### Run example Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Execute the example provided in the project. ```shell pnpm run example ``` -------------------------------- ### Install Dependencies and Generate Clients Source: https://github.com/solana-program/token-2022/blob/main/README.md Run these commands once to install dependencies and generate clients for the Token-2022 program. ```sh pnpm install # only need to run this once pnpm generate:clients ``` -------------------------------- ### Install Dependencies and Run Tests in JS Client Source: https://github.com/solana-program/token-2022/blob/main/clients/js/README.md Navigate to the client directory and execute these commands to install dependencies, build the client, and run tests. ```sh cd clients/js pnpm install pnpm build pnpm test ``` -------------------------------- ### Install @solana/spl-token with npm Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Install the library using npm. Ensure you are using @solana/web3.js version 1. ```shell npm install --save @solana/spl-token @solana/web3.js@1 ``` -------------------------------- ### Install dependencies and build JS libraries Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Install project dependencies using pnpm and build the JavaScript libraries. ```shell pnpm install pnpm run build ``` -------------------------------- ### Install older @solana/spl-token version Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Install version 0.1.8 of the library to use the older Token class. ```shell npm install @solana/spl-token@0.1.8 ``` -------------------------------- ### Install @solana/spl-token with yarn Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Install the library using yarn. Ensure you are using @solana/web3.js version 1. ```shell yarn add @solana/spl-token @solana/web3.js@1 ``` -------------------------------- ### Build SBF Programs and Start Local Validator Source: https://github.com/solana-program/token-2022/blob/main/README.md Build the necessary SBF programs and then restart the local test validator. These build commands only need to be run once. ```sh make build-sbf-program # you only need to run this once make build-sbf-confidential-elgamal-registry # you only need to run this once make restart-test-validator ``` -------------------------------- ### Build CLI Locally Source: https://github.com/solana-program/token-2022/blob/main/clients/cli/README.md Run this command to build the CLI locally. Ensure you have Cargo installed. ```sh cargo build ``` -------------------------------- ### Build and Test JavaScript Client Source: https://github.com/solana-program/token-2022/blob/main/clients/js/README.md Run this command from the repository root to build and test the JavaScript client. It starts a local validator if one isn't running. ```sh make test-js-clients-js ``` -------------------------------- ### Build Token 2022 Program Source: https://github.com/solana-program/token-2022/blob/main/README.md Builds the SBF (Simple Binary Format) program for Token 2022. Ensure you have the necessary Solana build tools installed. ```sh make build-sbf-program ``` -------------------------------- ### Get or Create Associated Token Account (ATA) with Token 2022 Source: https://context7.com/solana-program/token-2022/llms.txt Atomically fetch an existing associated token account or create it if it doesn't exist, using the Token 2022 program. Handles race conditions and validates existing accounts. ```typescript import { getOrCreateAssociatedTokenAccount, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const owner = new PublicKey('OwnerPubkeyHere11111111111111111111111111111'); const mint = new PublicKey('MintPubkeyHere111111111111111111111111111111'); const account = await getOrCreateAssociatedTokenAccount( connection, payer, mint, owner, false, 'confirmed', undefined, TOKEN_2022_PROGRAM_ID, ); console.log('Account address:', account.address.toBase58()); console.log('Balance:', account.amount.toString()); ``` -------------------------------- ### Build and Test Rust Client Source: https://github.com/solana-program/token-2022/blob/main/clients/rust/README.md Use these commands to build the SBF program and run tests for the Rust client from the repository root. ```sh make build-sbf-program ``` ```sh make test-clients-rust ``` -------------------------------- ### Build on-chain programs Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Build the SBF programs for the Token and Token-2022 functionalities. ```shell make build-sbf-program make build-sbf-confidential-elgamal-registry ``` -------------------------------- ### Build SBF Program for Testing Source: https://github.com/solana-program/token-2022/blob/main/clients/cli/README.md Build the Token-2022 program in SBF format for local testing. This command should be run from the repository root. ```sh cargo build-sbf --manifest-path program/Cargo.toml ``` -------------------------------- ### Create Wrapped Native Account (WSOL) Source: https://context7.com/solana-program/token-2022/llms.txt Creates and funds a wrapped SOL (WSOL) account, transferring a specified amount of lamports. This is useful for interacting with SOL as a token. ```typescript import { createWrappedNativeAccount, TOKEN_PROGRAM_ID, NATIVE_MINT } from '@solana/spl-token'; import { Connection, Keypair, clusterApiUrl, LAMPORTS_PER_SOL } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); // must be funded // Wrap 0.5 SOL into an ATA for the native mint const wsolAccount = await createWrappedNativeAccount( connection, payer, payer.publicKey, // owner 0.5 * LAMPORTS_PER_SOL, // lamports to wrap undefined, // keypair — undefined uses ATA { commitment: 'confirmed' }, TOKEN_PROGRAM_ID, NATIVE_MINT, ); console.log('wSOL account:', wsolAccount.toBase58()); ``` -------------------------------- ### createWrappedNativeAccount Source: https://context7.com/solana-program/token-2022/llms.txt Creates, initializes, and funds a wrapped native SOL (wSOL) token account, transferring `amount` lamports into it and calling `syncNative`. ```APIDOC ## createWrappedNativeAccount Creates, initializes, and funds a wrapped native SOL (wSOL) token account, transferring `amount` lamports into it and calling `syncNative`. ### Method ```typescript createWrappedNativeAccount( connection: Connection, payer: Signer, owner: PublicKey, amount: number, keypair?: Keypair, options?: ConfirmOptions, programId?: PublicKey, nativeMint?: PublicKey ): Promise ``` ### Parameters * **connection** (Connection) - Solana connection object. * **payer** (Signer) - The account paying for the transaction. * **owner** (PublicKey) - The owner of the wSOL account. * **amount** (number) - The amount of lamports to wrap into the wSOL account. * **keypair** (Keypair, optional) - The keypair for the wSOL account. If undefined, an Associated Token Account (ATA) will be used. * **options** (ConfirmOptions, optional) - Options for confirming the transaction. * **programId** (PublicKey, optional) - The Token Program ID. Defaults to `TOKEN_PROGRAM_ID`. * **nativeMint** (PublicKey, optional) - The native mint account. Defaults to `NATIVE_MINT`. ``` -------------------------------- ### Navigate to the JS client directory Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Change directory to the JavaScript client library within the repository. ```shell cd clients/js-legacy ``` -------------------------------- ### Navigate to the repository root Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Change directory to the root of the cloned repository. ```shell cd token-2022 ``` -------------------------------- ### Run tests Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Execute the test suite for the JavaScript libraries. ```shell pnpm run test ``` -------------------------------- ### Clone the token-2022 repository Source: https://github.com/solana-program/token-2022/blob/main/clients/js-legacy/README.md Clone the repository to build the on-chain programs from source. ```shell git clone https://github.com/solana-program/token-2022.git ``` -------------------------------- ### Token Groups: Initialize Group and Member Source: https://context7.com/solana-program/token-2022/llms.txt Initialize a new token group and register a member mint within that group. This enables on-chain NFT/fungible token grouping. ```APIDOC ## Token Groups — tokenGroupInitializeGroup / tokenGroupMemberInitialize The Token Group extension allows a mint to be declared a "collection" and for other mints to be registered as members of that collection, enabling NFT/fungible token grouping natively on-chain. ### Initialize Group ```typescript await tokenGroupInitializeGroupWithRentTransfer( connection, payer, groupMint, mintAuth, updateAuthority.publicKey, 100n, // max group members [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` ### Initialize Member ```typescript await tokenGroupMemberInitializeWithRentTransfer( connection, payer, memberMint, mintAuth, groupMint, updateAuthority.publicKey, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` ### Update Group Max Size ```typescript await tokenGroupUpdateGroupMaxSize( connection, payer, groupMint, updateAuthority, 500n, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` ``` -------------------------------- ### Build ElGamal Registry Program Source: https://github.com/solana-program/token-2022/blob/main/README.md Builds the SBF program for the ElGamal pubkey registry. This is a separate program within the repository. ```sh make build-sbf-confidential-elgamal-registry ``` -------------------------------- ### Initialize Token Group and Member Source: https://context7.com/solana-program/token-2022/llms.txt Initializes a token group, registers a member mint, and updates the group's maximum size. Ensure the program ID is correctly set for the TOKEN_2022_PROGRAM_ID. ```typescript import { tokenGroupInitializeGroupWithRentTransfer, tokenGroupMemberInitializeWithRentTransfer, tokenGroupUpdateGroupMaxSize, tokenGroupUpdateGroupAuthority, TOKEN_2022_PROGRAM_ID, } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const mintAuth = Keypair.generate(); const updateAuthority = Keypair.generate(); const groupMint = new PublicKey('GroupMintPubkey111111111111111111111111111'); const memberMint = new PublicKey('MemberMintPubkey11111111111111111111111111'); // Initialize the group with a max size of 100 members await tokenGroupInitializeGroupWithRentTransfer( connection, payer, groupMint, mintAuth, updateAuthority.publicKey, 100n, // max group members [], undefined, TOKEN_2022_PROGRAM_ID, ); // Register a member mint into the group await tokenGroupMemberInitializeWithRentTransfer( connection, payer, memberMint, mintAuth, groupMint, updateAuthority.publicKey, [], undefined, TOKEN_2022_PROGRAM_ID, ); // Expand group capacity await tokenGroupUpdateGroupMaxSize( connection, payer, groupMint, updateAuthority, 500n, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` -------------------------------- ### Lint JavaScript Client Source: https://github.com/solana-program/token-2022/blob/main/clients/js/README.md Run this command to lint the JavaScript client code. ```sh make lint-js-clients-js ``` -------------------------------- ### Build Programs and Restart Validator Source: https://github.com/solana-program/token-2022/blob/main/clients/js/README.md Commands to build Solana programs and restart the local test validator. These are prerequisites for running client tests. ```sh make build-sbf-program make build-sbf-confidential-elgamal-registry make restart-test-validator ``` -------------------------------- ### Test ElGamal Registry Program Source: https://github.com/solana-program/token-2022/blob/main/README.md Executes the test suite for the ElGamal pubkey registry program. Ensure all dependencies are met before running. ```sh make test-confidential-elgamal-registry ``` -------------------------------- ### Run Tests Source: https://github.com/solana-program/token-2022/blob/main/clients/cli/README.md Execute tests for the project using Cargo. This assumes the SBF program has been built. ```sh cargo test ``` -------------------------------- ### Solana Token-2022 CLI Usage Source: https://context7.com/solana-program/token-2022/llms.txt Commands for building Solana programs, starting/stopping a local test validator, generating clients, and running program tests using the provided CLI. ```sh # Build programs make build-sbf-program make build-sbf-confidential-elgamal-registry # Start local test validator (programs must be pre-built) make restart-test-validator # Generate JS and Rust clients from the IDL pnpm install pnpm generate:clients # Run program tests make test-program # Stop validator make stop-test-validator ``` -------------------------------- ### createMint Source: https://context7.com/solana-program/token-2022/llms.txt Creates and initializes a new SPL token mint on-chain using the Token 2022 program. This function allocates rent-exempt space and sets the mint authority and optional freeze authority. ```APIDOC ## createMint Creates and initializes a new SPL token mint on-chain, allocating rent-exempt space and setting the mint authority and optional freeze authority. ```typescript import { Connection, Keypair, clusterApiUrl } from '@solana/web3.js'; import { createMint, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); // funded keypair // Create a 6-decimal Token-2022 mint const mint = await createMint( connection, payer, // payer payer.publicKey, // mintAuthority payer.publicKey, // freezeAuthority (null to disable) 6, // decimals Keypair.generate(), // optional mint keypair { commitment: 'confirmed' }, TOKEN_2022_PROGRAM_ID, // use Token-2022 program for extension support ); console.log('Mint address:', mint.toBase58()); // => Mint address: ``` ``` -------------------------------- ### Initialize and Update Default Account State for Solana Tokens Source: https://context7.com/solana-program/token-2022/llms.txt Use `initializeDefaultAccountState` to set new token accounts to a frozen state, requiring manual thawing. Use `updateDefaultAccountState` to change this default behavior later. ```typescript import { initializeDefaultAccountState, updateDefaultAccountState, AccountState, TOKEN_2022_PROGRAM_ID, } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const freezeAuth = Keypair.generate(); const mint = new PublicKey('MintWithDefaultStatePubkey111111111111111111'); // All new token accounts start frozen await initializeDefaultAccountState( connection, payer, mint, AccountState.Frozen, undefined, TOKEN_2022_PROGRAM_ID, ); // Later: change default to initialized (unfrozen) await updateDefaultAccountState( connection, payer, mint, AccountState.Initialized, freezeAuth, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` -------------------------------- ### Initialize, Update, and Remove Solana Token Metadata Source: https://context7.com/solana-program/token-2022/llms.txt Use `tokenMetadataInitializeWithRentTransfer` to set initial token metadata. Use `tokenMetadataUpdateFieldWithRentTransfer` to add or modify fields, and `tokenMetadataRemoveKey` to delete them. `tokenMetadataUpdateAuthority` can transfer the authority to update metadata. ```typescript import { tokenMetadataInitialize, tokenMetadataInitializeWithRentTransfer, tokenMetadataUpdateField, tokenMetadataUpdateFieldWithRentTransfer, tokenMetadataRemoveKey, tokenMetadataUpdateAuthority, TOKEN_2022_PROGRAM_ID, } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const mintAuth = Keypair.generate(); const updateAuthority = payer.publicKey; const mint = new PublicKey('MintWithMetadataPubkey11111111111111111111'); // Initialize metadata (with automatic rent-exempt transfer if needed) await tokenMetadataInitializeWithRentTransfer( connection, payer, mint, updateAuthority, mintAuth, 'My Token', 'MTK', 'https://example.com/token.json', [], undefined, TOKEN_2022_PROGRAM_ID, ); // Add or update a custom metadata field await tokenMetadataUpdateFieldWithRentTransfer( connection, payer, mint, payer, 'background_color', '#FF5733', [], undefined, TOKEN_2022_PROGRAM_ID, ); // Remove a custom metadata key await tokenMetadataRemoveKey( connection, payer, mint, payer, 'background_color', true /* idempotent */, [], undefined, TOKEN_2022_PROGRAM_ID, ); // Transfer metadata update authority await tokenMetadataUpdateAuthority( connection, payer, mint, payer, new PublicKey('NewUpdateAuthority111111111111111111111111111'), [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` -------------------------------- ### Check JavaScript Client Formatting Source: https://github.com/solana-program/token-2022/blob/main/clients/js/README.md Use this command to check if the JavaScript client code adheres to the project's formatting standards. ```sh make format-check-js-clients-js ``` -------------------------------- ### Format Token 2022 Program Source: https://github.com/solana-program/token-2022/blob/main/README.md Checks the code formatting for the Token 2022 program against the project's standards. Use `make format-program` to auto-format. ```sh make format-check-program ``` -------------------------------- ### Clippy Check ElGamal Registry Program Source: https://github.com/solana-program/token-2022/blob/main/README.md Applies the Rust Clippy linter to the ElGamal pubkey registry program to identify potential issues and enforce coding best practices. ```sh make clippy-confidential-elgamal-registry ``` -------------------------------- ### Core Constants Source: https://context7.com/solana-program/token-2022/llms.txt Key program addresses and utility functions exported from the `@solana-program/token-2022` library. ```APIDOC ## Core Constants Key program addresses exported from `@solana-program/token-2022`. ```typescript import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, NATIVE_MINT, NATIVE_MINT_2022, programSupportsExtensions, } from '@solana/spl-token'; console.log(TOKEN_2022_PROGRAM_ID.toBase58()); // TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb // Guard: reject base program when extensions are needed if (!programSupportsExtensions(programId)) { throw new Error('Use TOKEN_2022_PROGRAM_ID for extensions'); } ``` ``` -------------------------------- ### Format Check ElGamal Registry Program Source: https://github.com/solana-program/token-2022/blob/main/README.md Verifies that the ElGamal pubkey registry program's code adheres to the project's formatting guidelines. ```sh make format-check-confidential-elgamal-registry ``` -------------------------------- ### Create a Token 2022 Mint Source: https://context7.com/solana-program/token-2022/llms.txt Use the `createMint` function to initialize a new SPL token mint on the Solana blockchain with Token 2022 program support. Ensure the payer is funded and specify mint/freeze authorities and decimals. ```typescript import { Connection, Keypair, clusterApiUrl } from '@solana/web3.js'; import { createMint, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); // funded keypair // Create a 6-decimal Token-2022 mint const mint = await createMint( connection, payer, payer.publicKey, payer.publicKey, 6, Keypair.generate(), { commitment: 'confirmed' }, TOKEN_2022_PROGRAM_ID, ); console.log('Mint address:', mint.toBase58()); // => Mint address: ``` -------------------------------- ### getMintLen / getAccountLen (ExtensionType) Source: https://context7.com/solana-program/token-2022/llms.txt Computes the byte length required for a mint or token account with specified extension types, needed when allocating on-chain space before initialization. ```APIDOC ## getMintLen / getAccountLen (ExtensionType) Computes the byte length required for a mint or token account with specified extension types, needed when allocating on-chain space before initialization. ### getMintLen #### Method ```typescript getMintLen(extensions: ExtensionType[]): number ``` ### getAccountLen #### Method ```typescript getAccountLen(extensions: ExtensionType[]): number ``` ### Parameters (for both getMintLen and getAccountLen) * **extensions** (ExtensionType[]) - An array of `ExtensionType` enums specifying the extensions to include in the length calculation. ``` -------------------------------- ### Calculate Mint and Account Lengths (Token 2022 Extensions) Source: https://context7.com/solana-program/token-2022/llms.txt Computes the required byte length for mint or token accounts based on specified extension types. This is crucial for allocating on-chain space before initialization. ```typescript import { ExtensionType, getMintLen, getAccountLen, TOKEN_2022_PROGRAM_ID, } from '@solana/spl-token'; import { Connection, Keypair, SystemProgram, Transaction, sendAndConfirmTransaction, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const mintKp = Keypair.generate(); // Calculate space for a mint with TransferFeeConfig + MetadataPointer const extensions = [ExtensionType.TransferFeeConfig, ExtensionType.MetadataPointer]; const mintLen = getMintLen(extensions); const lamports = await connection.getMinimumBalanceForRentExemption(mintLen); console.log('Mint byte length:', mintLen); // => 234 (varies by extension combo) const tx = new Transaction().add( SystemProgram.createAccount({ fromPubkey: payer.publicKey, newAccountPubkey: mintKp.publicKey, space: mintLen, lamports, programId: TOKEN_2022_PROGRAM_ID, }), ); await sendAndConfirmTransaction(connection, tx, [payer, mintKp]); ``` -------------------------------- ### Core Constants for Token 2022 Source: https://context7.com/solana-program/token-2022/llms.txt Import and log key program addresses for Token 2022 and related programs. Includes a check to ensure the Token-2022 program is used when extensions are required. ```typescript import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, NATIVE_MINT, NATIVE_MINT_2022, programSupportsExtensions, } from '@solana/spl-token'; console.log(TOKEN_2022_PROGRAM_ID.toBase58()); // TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb // Guard: reject base program when extensions are needed if (!programSupportsExtensions(programId)) { throw new Error('Use TOKEN_2022_PROGRAM_ID for extensions'); } ``` -------------------------------- ### Test Token 2022 Program Source: https://github.com/solana-program/token-2022/blob/main/README.md Runs tests for the Token 2022 program. This command executes the test suite to verify program functionality. ```sh make test-program ``` -------------------------------- ### Create and Update Interest Bearing Mints Source: https://context7.com/solana-program/token-2022/llms.txt Use these functions to create and update interest-bearing mints. The interest rate is stored on the mint and accrues over time. ```typescript import { createInterestBearingMint, updateRateInterestBearingMint, TOKEN_2022_PROGRAM_ID, } from '@solana/spl-token'; import { Connection, Keypair, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const mintAuth = Keypair.generate(); const rateAuth = Keypair.generate(); // Create a mint with 5% annual interest rate (500 basis points) const mint = await createInterestBearingMint( connection, payer, mintAuth.publicKey, // mintAuthority mintAuth.publicKey, // freezeAuthority rateAuth.publicKey, // rateAuthority 500, // initial rate (basis points / year) 6, // decimals Keypair.generate(), undefined, TOKEN_2022_PROGRAM_ID, ); console.log('Interest-bearing mint:', mint.toBase58()); // Later: update rate to 3% await updateRateInterestBearingMint( connection, payer, mint, rateAuth, 300, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` -------------------------------- ### Clippy Check Token 2022 Program Source: https://github.com/solana-program/token-2022/blob/main/README.md Runs Clippy, a Rust linter, on the Token 2022 program to catch common mistakes and improve code quality. ```sh make clippy-program ``` -------------------------------- ### Implement Token Transfer Hooks Source: https://context7.com/solana-program/token-2022/llms.txt Use these functions to initialize and manage transfer hooks for Token-2022. The hook program executes custom logic on each transfer. ```typescript import { initializeTransferHook, updateTransferHook, transferCheckedWithTransferHook, TOKEN_2022_PROGRAM_ID, } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const hookAuthority = Keypair.generate(); const hookProgramId = new PublicKey('HookProgramId111111111111111111111111111111'); const mint = new PublicKey('MintWithHookPubkey111111111111111111111111'); const source = new PublicKey('SourceTokenAccount1111111111111111111111111'); const destination = new PublicKey('DestinationTokenAccount111111111111111111111'); const owner = Keypair.generate(); // Attach hook to the mint (must be done before mint is initialized on-chain) await initializeTransferHook( connection, payer, mint, hookAuthority.publicKey, hookProgramId, undefined, TOKEN_2022_PROGRAM_ID, ); // Transfer — Token-2022 CPIs into hookProgramId on execution await transferCheckedWithTransferHook( connection, payer, source, mint, destination, owner, 500_000n, 6, [], undefined, TOKEN_2022_PROGRAM_ID, ); // Update hook program await updateTransferHook( connection, payer, mint, new PublicKey('NewHookProgram1111111111111111111111111111'), hookAuthority, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` -------------------------------- ### Enable and Disable CPI Guard for Solana Token Accounts Source: https://context7.com/solana-program/token-2022/llms.txt Use `enableCpiGuard` to prevent malicious programs from draining a token account via indirect calls. Use `disableCpiGuard` to remove this restriction. ```typescript import { enableCpiGuard, disableCpiGuard, TOKEN_2022_PROGRAM_ID, } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const owner = Keypair.generate(); const account = new PublicKey('UserTokenAccount1111111111111111111111111111'); // Prevent CPI programs from draining this account await enableCpiGuard( connection, payer, account, owner, [], undefined, TOKEN_2022_PROGRAM_ID, ); // Remove the guard await disableCpiGuard( connection, payer, account, owner, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` -------------------------------- ### Default Account State Source: https://context7.com/solana-program/token-2022/llms.txt Manage the initial state of newly created token accounts. You can set them to 'Frozen' by default, requiring a thaw operation, or to 'Initialized' (unfrozen). ```APIDOC ## Default Account State — initializeDefaultAccountState / updateDefaultAccountState The Default Account State extension allows a mint to set the default state for newly created token accounts to `Frozen`, requiring the freeze authority to thaw them before use (useful for KYC/allowlist workflows). ### initializeDefaultAccountState Initializes a new token account with a default state (e.g., `Frozen`). ### updateDefaultAccountState Updates the default state for new token accounts to a specified state (e.g., `Initialized`). #### Parameters for initializeDefaultAccountState: - `connection` (Connection): Solana connection object. - `payer` (Keypair): The account paying for the transaction and rent. - `mint` (PublicKey): The mint account for the token. - `accountState` (AccountState): The default state to set for new accounts (e.g., `AccountState.Frozen`). - `owner` (PublicKey, optional): The owner of the new token accounts. Defaults to the payer's public key. - `programId` (PublicKey): The Token 2022 program ID. #### Parameters for updateDefaultAccountState: - `connection` (Connection): Solana connection object. - `payer` (Keypair): The account paying for the transaction and rent. - `mint` (PublicKey): The mint account for the token. - `accountState` (AccountState): The new default state to set for new accounts (e.g., `AccountState.Initialized`). - `freezeAuthority` (PublicKey, optional): The freeze authority of the mint. - `multiSigners` (Signer[], optional): Additional signers for the transaction. - `programId` (PublicKey): The Token 2022 program ID. ``` -------------------------------- ### transferChecked Source: https://context7.com/solana-program/token-2022/llms.txt Transfers tokens while asserting the mint address and decimal places. This is a safer alternative to `transfer`. ```APIDOC ## transferChecked Transfers tokens while asserting the mint address and decimal places — the safer alternative to `transfer` that guards against sending to accounts of the wrong mint. ### Method ```typescript await transferChecked( connection: Connection, payer: Signer, source: PublicKey, mint: PublicKey, destination: PublicKey, owner: Signer | PublicKey, amount: bigint, decimals: number, multiSigners?: Signer[], options?: ConfirmOptions, programId?: PublicKey ): Promise ``` ### Parameters - **connection** (Connection) - The connection to the Solana cluster. - **payer** (Signer) - The account paying for the transaction. - **source** (PublicKey) - The source token account. - **mint** (PublicKey) - The public key of the mint account. - **destination** (PublicKey) - The destination token account. - **owner** (Signer | PublicKey) - The owner of the source token account. - **amount** (bigint) - The amount of tokens to transfer in raw units. - **decimals** (number) - The number of decimals the mint account has. Must match the mint's actual decimals. - **multiSigners** (Signer[], optional) - An array of multi-signers if the owner is a PublicKey. - **options** (ConfirmOptions, optional) - Options for confirming the transaction. - **programId** (PublicKey, optional) - The Token 2022 program ID. Defaults to `TOKEN_2022_PROGRAM_ID`. ``` -------------------------------- ### createAssociatedTokenAccount Source: https://context7.com/solana-program/token-2022/llms.txt Creates and initializes the canonical associated token account (ATA) for a given owner and mint using the Token 2022 program. Returns the ATA address. ```APIDOC ## createAssociatedTokenAccount Creates and initializes the canonical associated token account (ATA) for a given owner and mint. Returns the ATA address. ```typescript import { createAssociatedTokenAccount, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const owner = new PublicKey('OwnerPubkeyHere11111111111111111111111111111'); const mint = new PublicKey('MintPubkeyHere111111111111111111111111111111'); const tokenAccount = await createAssociatedTokenAccount( connection, payer, mint, owner, { commitment: 'confirmed' }, TOKEN_2022_PROGRAM_ID, ); console.log('ATA:', tokenAccount.toBase58()); ``` ``` -------------------------------- ### getOrCreateAssociatedTokenAccount Source: https://context7.com/solana-program/token-2022/llms.txt Fetches the associated token account if it exists, or creates and initializes it otherwise, using the Token 2022 program. This function handles race conditions atomically and throws errors for invalid mint or owner configurations. ```APIDOC ## getOrCreateAssociatedTokenAccount Fetches the associated token account if it already exists; creates and initializes it otherwise. Handles race conditions atomically. Throws `TokenInvalidMintError` / `TokenInvalidOwnerError` if the existing account doesn't match expectations. ```typescript import { getOrCreateAssociatedTokenAccount, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const owner = new PublicKey('OwnerPubkeyHere11111111111111111111111111111'); const mint = new PublicKey('MintPubkeyHere111111111111111111111111111111'); const account = await getOrCreateAssociatedTokenAccount( connection, payer, mint, owner, false, // allowOwnerOffCurve — set true for PDAs 'confirmed', undefined, TOKEN_2022_PROGRAM_ID, ); console.log('Account address:', account.address.toBase58()); console.log('Balance:', account.amount.toString()); ``` ``` -------------------------------- ### Enable and Disable Required Memo Transfers for Solana Tokens Source: https://context7.com/solana-program/token-2022/llms.txt Use `enableRequiredMemoTransfers` to enforce that all incoming transfers to an account include a memo instruction. Use `disableRequiredMemoTransfers` to remove this requirement. ```typescript import { enableRequiredMemoTransfers, disableRequiredMemoTransfers, TOKEN_2022_PROGRAM_ID, } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const owner = Keypair.generate(); const account = new PublicKey('UserTokenAccount1111111111111111111111111111'); // All incoming transfers must include a memo await enableRequiredMemoTransfers( connection, payer, account, owner, [], undefined, TOKEN_2022_PROGRAM_ID, ); // Disable requirement await disableRequiredMemoTransfers( connection, payer, account, owner, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` -------------------------------- ### Create Associated Token Account (ATA) with Token 2022 Source: https://context7.com/solana-program/token-2022/llms.txt Create the canonical associated token account for a given owner and mint using the Token 2022 program. This function returns the ATA address. ```typescript import { createAssociatedTokenAccount, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js'; const connection = new Connection(clusterApiUrl('devnet'), 'confirmed'); const payer = Keypair.generate(); const owner = new PublicKey('OwnerPubkeyHere11111111111111111111111111111'); const mint = new PublicKey('MintPubkeyHere111111111111111111111111111111'); const tokenAccount = await createAssociatedTokenAccount( connection, payer, mint, owner, { commitment: 'confirmed' }, TOKEN_2022_PROGRAM_ID, ); console.log('ATA:', tokenAccount.toBase58()); ``` -------------------------------- ### mintTo Source: https://context7.com/solana-program/token-2022/llms.txt Mints new tokens to a destination token account, increasing the supply. Requires the mint authority to sign. ```APIDOC ## mintTo Mints new tokens to a destination token account, increasing the supply. Requires the mint authority to sign. ### Method ```typescript await mintTo( connection: Connection, payer: Signer, mint: PublicKey, destination: PublicKey, authority: Signer | PublicKey, amount: bigint, multiSigners?: Signer[], options?: ConfirmOptions, programId?: PublicKey ): Promise ``` ### Parameters - **connection** (Connection) - The connection to the Solana cluster. - **payer** (Signer) - The account paying for the transaction. - **mint** (PublicKey) - The public key of the mint account. - **destination** (PublicKey) - The destination token account. - **authority** (Signer | PublicKey) - The mint authority (Signer or PublicKey + multiSigners). - **amount** (bigint) - The amount of tokens to mint in raw units. - **multiSigners** (Signer[], optional) - An array of multi-signers if the authority is a PublicKey. - **options** (ConfirmOptions, optional) - Options for confirming the transaction. - **programId** (PublicKey, optional) - The Token 2022 program ID. Defaults to `TOKEN_2022_PROGRAM_ID`. ``` -------------------------------- ### Token Metadata Source: https://context7.com/solana-program/token-2022/llms.txt Manage token metadata directly on the mint account, including name, symbol, URI, and custom key-value pairs. Supports initialization, updating fields, removing keys, and transferring the update authority. ```APIDOC ## Token Metadata — tokenMetadataInitialize / tokenMetadataUpdateField / tokenMetadataRemoveKey The Token Metadata extension stores token name, symbol, URI, and arbitrary key-value metadata directly on the mint account, eliminating the need for a separate metadata program. ### tokenMetadataInitialize / tokenMetadataInitializeWithRentTransfer Initializes the token metadata for a mint account. `tokenMetadataInitializeWithRentTransfer` handles rent-exempt transfer automatically if needed. ### tokenMetadataUpdateField / tokenMetadataUpdateFieldWithRentTransfer Adds or updates a metadata field (key-value pair) for a mint account. `tokenMetadataUpdateFieldWithRentTransfer` handles rent-exempt transfer automatically if needed. ### tokenMetadataRemoveKey Removes a specified metadata key from the mint account. ### tokenMetadataUpdateAuthority Transfers the authority to update token metadata to a new public key. #### Parameters for tokenMetadataInitialize/tokenMetadataInitializeWithRentTransfer: - `connection` (Connection): Solana connection object. - `payer` (Keypair): The account paying for the transaction and rent. - `mint` (PublicKey): The mint account to initialize metadata for. - `updateAuthority` (PublicKey): The public key of the metadata update authority. - `mintAuthority` (Keypair): The mint authority of the mint. - `name` (string): The name of the token. - `symbol` (string): The symbol of the token. - `uri` (string): The URI pointing to the token's metadata. - `multiSigners` (Signer[], optional): Additional signers for the transaction. - `programId` (PublicKey): The Token 2022 program ID. #### Parameters for tokenMetadataUpdateField/tokenMetadataUpdateFieldWithRentTransfer: - `connection` (Connection): Solana connection object. - `payer` (Keypair): The account paying for the transaction and rent. - `mint` (PublicKey): The mint account to update metadata for. - `owner` (Keypair): The owner of the mint account (or update authority). - `field` (string): The metadata field key to update. - `value` (string): The new value for the metadata field. - `multiSigners` (Signer[], optional): Additional signers for the transaction. - `programId` (PublicKey): The Token 2022 program ID. #### Parameters for tokenMetadataRemoveKey: - `connection` (Connection): Solana connection object. - `payer` (Keypair): The account paying for the transaction and rent. - `mint` (PublicKey): The mint account to remove metadata from. - `owner` (Keypair): The owner of the mint account (or update authority). - `key` (string): The metadata key to remove. - `idempotent` (boolean): If true, the operation will succeed even if the key is not found. - `multiSigners` (Signer[], optional): Additional signers for the transaction. - `programId` (PublicKey): The Token 2022 program ID. #### Parameters for tokenMetadataUpdateAuthority: - `connection` (Connection): Solana connection object. - `payer` (Keypair): The account paying for the transaction and rent. - `mint` (PublicKey): The mint account whose update authority is being changed. - `owner` (Keypair): The current update authority. - `newUpdateAuthority` (PublicKey): The public key of the new update authority. - `multiSigners` (Signer[], optional): Additional signers for the transaction. - `programId` (PublicKey): The Token 2022 program ID. ``` -------------------------------- ### Memo Transfers Source: https://context7.com/solana-program/token-2022/llms.txt Configure the Memo Transfer extension to enforce that all incoming transfers to an account include a memo instruction within the same transaction. ```APIDOC ## Memo Transfers — enableRequiredMemoTransfers / disableRequiredMemoTransfers The Memo Transfer extension requires that every incoming transfer to an account include a memo instruction in the same transaction, enabling audit trails and compliance. ### enableRequiredMemoTransfers Enables the requirement for memos on all incoming transfers to the specified account. ### disableRequiredMemoTransfers Disables the requirement for memos on incoming transfers. #### Parameters for enableRequiredMemoTransfers: - `connection` (Connection): Solana connection object. - `payer` (Keypair): The account paying for the transaction and rent. - `account` (PublicKey): The token account to apply the memo requirement to. - `owner` (PublicKey): The owner of the token account. - `multiSigners` (Signer[], optional): Additional signers for the transaction. - `programId` (PublicKey): The Token 2022 program ID. #### Parameters for disableRequiredMemoTransfers: - `connection` (Connection): Solana connection object. - `payer` (Keypair): The account paying for the transaction and rent. - `account` (PublicKey): The token account to disable the memo requirement for. - `owner` (PublicKey): The owner of the token account. - `multiSigners` (Signer[], optional): Additional signers for the transaction. - `programId` (PublicKey): The Token 2022 program ID. ``` -------------------------------- ### Transfer Hook Extension Source: https://context7.com/solana-program/token-2022/llms.txt Enables custom on-chain programs to execute logic during token transfers, such as enforcing royalties or allowlist checks. ```APIDOC ## initializeTransferHook ### Description Initializes the Transfer Hook extension for a mint. This must be done before the mint is initialized on-chain. ### Method `initializeTransferHook` ### Parameters - `connection` (Connection): The Solana connection object. - `payer` (Keypair): The account paying for the transaction. - `mint` (PublicKey): The mint account. - `hookAuthority` (PublicKey): The authority that can update or remove the transfer hook. - `hookProgramId` (PublicKey): The program ID of the transfer hook program. - `memo` (string[]): Optional memo for the transaction. - `programId` (PublicKey): The Token 2022 program ID. ### Request Example ```typescript await initializeTransferHook( connection, payer, mint, hookAuthority.publicKey, hookProgramId, undefined, TOKEN_2022_PROGRAM_ID, ); ``` ``` ```APIDOC ## transferCheckedWithTransferHook ### Description Transfers tokens with the Transfer Hook extension enabled. The associated hook program will be executed during the transfer. ### Method `transferCheckedWithTransferHook` ### Parameters - `connection` (Connection): The Solana connection object. - `payer` (Keypair): The account paying for the transaction. - `source` (PublicKey): The source token account. - `mint` (PublicKey): The mint account. - `destination` (PublicKey): The destination token account. - `owner` (Keypair): The owner of the source token account. - `amount` (bigint): The amount of tokens to transfer. - `decimals` (number): The number of decimals for the token. - `memo` (string[]): Optional memo for the transfer. - `multiSigners` (Keypair[]): Optional multi-signers. - `programId` (PublicKey): The Token 2022 program ID. ### Request Example ```typescript await transferCheckedWithTransferHook( connection, payer, source, mint, destination, owner, 500_000n, 6, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` ``` ```APIDOC ## updateTransferHook ### Description Updates the transfer hook program associated with a mint. ### Method `updateTransferHook` ### Parameters - `connection` (Connection): The Solana connection object. - `payer` (Keypair): The account paying for the transaction. - `mint` (PublicKey): The mint account. - `newHookProgramId` (PublicKey): The new program ID for the transfer hook. - `hookAuthority` (Keypair): The authority that can update or remove the transfer hook. - `multiSigners` (Keypair[]): Optional multi-signers. - `memo` (string[]): Optional memo for the transaction. - `programId` (PublicKey): The Token 2022 program ID. ### Request Example ```typescript await updateTransferHook( connection, payer, mint, new PublicKey('NewHookProgram1111111111111111111111111111'), hookAuthority, [], undefined, TOKEN_2022_PROGRAM_ID, ); ``` ``` -------------------------------- ### Scaled UI Amount: Update Multiplier Source: https://context7.com/solana-program/token-2022/llms.txt Apply a floating-point multiplier to the displayed UI amount of a token. This enables re-basing mechanics while keeping the raw balance constant. ```APIDOC ## Scaled UI Amount — updateMultiplier The Scaled UI Amount extension applies a floating-point multiplier to the displayed (UI) amount of a token, enabling re-basing mechanics like stock splits or rebase tokens while the raw balance stays constant. ### Update Multiplier ```typescript await updateMultiplier( connection, payer, mint, owner, 2.0, // new multiplier BigInt(Math.floor(Date.now() / 1000)), // effective Unix timestamp [], undefined, TOKEN_2022_PROGRAM_ID, ); // After this, a balance of 1,000,000 raw tokens displays as 2,000,000 to users ``` ```