### Run an Example's Start Script Source: https://github.com/anza-xyz/kit/blob/main/examples/README.md Navigate to an example's directory and run this command to start it. ```shell pnpm start ``` -------------------------------- ### Install Program Clients Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/index.mdx Install Kit-compatible clients for specific Solana programs. This example installs clients for the System, Memo, Token, and Compute Budget programs. ```package-install npm install @solana-program/system \ @solana-program/memo \ @solana-program/token \ @solana-program/compute-budget ``` -------------------------------- ### Install and Develop React App Source: https://github.com/anza-xyz/kit/blob/main/examples/react-app/README.md Installs dependencies, compiles JavaScript and TypeScript definitions, and starts the development server for hot-reloading. ```shell pnpm install pnpm turbo compile:js compile:typedefs pnpm dev ``` -------------------------------- ### Install @solana/wallet-account-signer Source: https://github.com/anza-xyz/kit/blob/main/packages/wallet-account-signer/README.md Install the package using pnpm. ```shell pnpm add @solana/wallet-account-signer ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/anza-xyz/kit/blob/main/CLAUDE.md Commands to install project dependencies, set up the test validator, and build all packages. ```shell pnpm install # Install dependencies pnpm test:setup # Install the Agave test validator (first time only) ./scripts/start-shared-test-validator.sh # Start shared test validator (needed for some tests) pnpm build # Build + test all packages ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/anza-xyz/kit/blob/main/examples/README.md Run this command to install all project dependencies. ```shell pnpm install ``` -------------------------------- ### Install Kit Main Library Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/index.mdx Install the main @solana/kit library. This package includes smaller, individual packages like @solana/rpc and @solana/transactions. ```package-install @solana/kit ``` -------------------------------- ### Install RPC Subscriptions Package Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/rpc-subscriptions.mdx Install the standalone `@solana/rpc-subscriptions` package to use Kit's RPC subscription client. ```bash npm install @solana/rpc-subscriptions # or yarn add @solana/rpc-subscriptions ``` -------------------------------- ### Install @solana/kit with npm Source: https://github.com/anza-xyz/kit/blob/main/README.md Use this command to install the Solana Kit SDK for Node.js or web applications. ```shell npm install --save @solana/kit ``` -------------------------------- ### Install @solana/plugin-interfaces Source: https://github.com/anza-xyz/kit/blob/main/packages/plugin-interfaces/README.md Install the package using npm. ```bash npm install @solana/plugin-interfaces ``` -------------------------------- ### Install Dependencies and Setup Test Validator Source: https://github.com/anza-xyz/kit/blob/main/CONTRIBUTING.md Commands to install project dependencies and set up the Agave test validator for running tests. ```shell pnpm install ``` ```shell pnpm test:setup ``` ```shell ./scripts/start-shared-test-validator.sh ``` -------------------------------- ### Install @solana/kit and tsx Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/getting-started/setup.mdx Install the @solana/kit library and tsx for running TypeScript code. ```bash npm install @solana/kit tsx # or yarn add @solana/kit tsx ``` -------------------------------- ### Install RPC Package Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/rpc.mdx Install the standalone @solana/rpc package for RPC client functionality. ```bash npm install @solana/rpc # or yarn add @solana/rpc ``` -------------------------------- ### Run Development Server Source: https://github.com/anza-xyz/kit/blob/main/docs/README.md Start the development server for the Kit project. Access the application at http://localhost:3000 in your browser. ```bash pnpm dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/anza-xyz/kit/blob/main/docs/README.md Install project dependencies using pnpm. Use the `--ignore-workspace` flag to separate documentation website dependencies from library dependencies. ```bash pnpm install --ignore-workspace ``` -------------------------------- ### Enable Mainnet-Beta Access Source: https://github.com/anza-xyz/kit/blob/main/examples/react-app/README.md Starts the development server or builds the application with Mainnet-Beta access enabled by setting the REACT_EXAMPLE_APP_ENABLE_MAINNET environment variable. ```shell REACT_EXAMPLE_APP_ENABLE_MAINNET=true pnpm dev ``` ```shell REACT_EXAMPLE_APP_ENABLE_MAINNET=true pnpm build ``` -------------------------------- ### Build React App for Deployment Source: https://github.com/anza-xyz/kit/blob/main/examples/react-app/README.md Installs dependencies and builds a static bundle for deployment to a web server. ```shell pnpm install pnpm turbo build ``` -------------------------------- ### Configure package.json scripts Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/getting-started/setup.mdx Add scripts to your package.json for starting the application and a local Solana validator. ```json { "name": "kit-tutorial", "version": "1.0.0", "scripts": { "start": "tsx src/index.ts", "validator": "solana-test-validator" }, "dependencies": { "@solana/kit": "^2.1.0", "tsx": "^4.19.3" } } ``` -------------------------------- ### Install Offchain Message Utilities Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/offchain-messages.mdx Install the standalone package for offchain message utilities. These utilities are also included within the `@solana/kit` library. ```bash npm install @solana/offchain-messages ``` -------------------------------- ### Import and Install Ed25519 Polyfill Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/keypairs.mdx Import and call the `install()` function from the polyfill package before any key operations. This shims Ed25519 support onto the `SubtleCrypto` interface. ```typescript import { install } from '@solana/webcrypto-ed25519-polyfill'; // Calling this will shim methods on `SubtleCrypto`, adding Ed25519 support. install(); // Now you can do this, in environments that do not otherwise support Ed25519. const keyPair = await crypto.subtle.generateKey({ name: 'Ed25519' }, false, ['sign']); ``` -------------------------------- ### Create SignableMessage Examples Source: https://github.com/anza-xyz/kit/blob/main/packages/signers/README.md Demonstrates creating `SignableMessage` instances from different inputs, including raw byte arrays, strings, and with pre-existing signatures. ```typescript const myMessage = createSignableMessage(new Uint8Array([1, 2, 3])); ``` ```typescript const myMessageFromText = createSignableMessage('Hello world!'); ``` ```typescript const myMessageWithSignatures = createSignableMessage('Hello world!', { [address('1234..5678')]: new Uint8Array([1, 2, 3]) as SignatureBytes, }); ``` -------------------------------- ### Install and Use Ed25519 Polyfill Source: https://github.com/anza-xyz/kit/blob/main/packages/webcrypto-ed25519-polyfill/README.md Import and call `install()` to enable Ed25519 support in environments where it's missing. This allows you to use `crypto.subtle.generateKey`, `crypto.subtle.exportKey`, `crypto.subtle.sign`, and `crypto.subtle.verify` with the 'Ed25519' algorithm. ```typescript import { install } from '@solana/webcrypto-ed25519-polyfill'; // Calling this will shim methods on `SubtleCrypto`, adding Ed25519 support. install(); // Now you can do this, in environments that do not otherwise support Ed25519. const keyPair = await crypto.subtle.generateKey({ name: 'Ed25519' }, false, ['sign']); const publicKeyBytes = await crypto.subtle.exportKey('raw', keyPair.publicKey); const data = new Uint8Array([1, 2, 3]); const signature = await crypto.subtle.sign({ name: 'Ed25519' }, keyPair.privateKey, data); if (await crypto.subtle.verify({ name: 'Ed25519' }, keyPair.publicKey, signature, data)) { console.log('Data was signed using the private key associated with this public key'); } else { throw new Error('Signature verification error'); } ``` -------------------------------- ### Build Transaction (Web3.js) Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/upgrade-guide.mdx Example of building a transaction in Web3.js by adding instructions and setting blockhash. ```typescript import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js'; import { createInitializeMintInstruction } from '@solana/spl-token'; const latestBlockhash = await connection.getLatestBlockhash(); const createAccount = SystemProgram.createAccount(createAccountInput); const initializeMint = createInitializeMintInstruction(initializeMintInput); const transaction = new Transaction({ feePayer, ...latestBlockhash }) .add(createAccount) .add(initializeMint); ``` -------------------------------- ### Develop a Single Package Source: https://github.com/anza-xyz/kit/blob/main/CONTRIBUTING.md Commands to navigate to a specific package, compile its code, and start the development watch process. ```shell cd packages/accounts pnpm turbo compile:js compile:typedefs pnpm dev ``` -------------------------------- ### Setup Local Test Solana Validator Source: https://github.com/anza-xyz/kit/blob/main/examples/README.md Execute this command in the monorepo root to set up a local test Solana validator. ```shell pnpm test:setup ``` -------------------------------- ### Set Up Project with RPC and Transaction APIs Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/index.mdx Set up your project by creating instances for RPC API, RPC Subscriptions API, and a send-and-confirm transaction strategy using primitives from @solana/kit. ```typescript import { createSolanaRpc, createSolanaRpcSubscriptions, sendAndConfirmTransactionFactory, } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); ``` -------------------------------- ### Tutorial Function with Client Creation Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/getting-started/signers.mdx Demonstrates how to use the updated createClient function within the tutorial. It fetches the client, retrieves the wallet's balance, and logs it to the console. This setup is necessary before crafting transactions. ```typescript import { Rpc, RpcSubscriptions, SolanaRpcApi, SolanaRpcSubscriptionsApi, TransactionSigner, MessageSigner, } from '@solana/kit'; export type Client = { rpc: Rpc; rpcSubscriptions: RpcSubscriptions; wallet: TransactionSigner & MessageSigner; }; export async function createClient() { return {} as Client; } // ---cut-before--- async function tutorial() { const client = await createClient(); const { value: balance } = await client.rpc.getBalance(client.wallet.address).send(); console.log(`Balance: ${balance} lamports.`); } ``` -------------------------------- ### Get Option Encoder Source: https://github.com/anza-xyz/kit/blob/main/packages/options/README.md Example of using getOptionEncoder to create an encoder for Option. ```ts const bytes = getOptionEncoder(getU32Encoder()).encode(some(42)); ``` -------------------------------- ### Sign Transaction Message with Fee Payer and Lifetime Source: https://github.com/anza-xyz/kit/blob/main/README.md This example shows how to sign a transaction message. It highlights that attempting to sign without a fee payer and lifetime will result in a type error, enforcing proper setup. ```typescript const feePayer = await generateKeyPair(); const feePayerAddress = await getAddressFromPublicKey(feePayer.publicKey); const transactionMessage = createTransactionMessage({ version: 'legacy' }); const transactionMessageWithFeePayer = setTransactionMessageFeePayer(feePayerAddress, transactionMessage); // Attempting to sign the transaction message without a lifetime will throw a type error const signedTransaction = await signTransaction([signer], transactionMessageWithFeePayer); // => "Property 'lifetimeConstraint' is missing in type" ``` -------------------------------- ### Create Solana Program Source: https://github.com/anza-xyz/kit/blob/main/README.md Use this command to initiate the creation of a new Solana program and generate associated clients. Follow the on-screen prompts for configuration. ```sh pnpm create solana-program ``` -------------------------------- ### Install Ed25519 Polyfill Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/keypairs.mdx Install the polyfill package using npm or yarn. This is the first step to enabling Ed25519 support. ```bash npm install @solana/webcrypto-ed25519-polyfill # or yarn add @solana/webcrypto-ed25519-polyfill ``` -------------------------------- ### Build CreateAccount Instruction Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/getting-started/instructions.mdx Use this to build the `CreateAccount` instruction. Ensure you have the necessary parameters like payer, new account details, space, lamports, and the program address. ```javascript // Build instructions. const createAccountIx = getCreateAccountInstruction({ payer: client.wallet, newAccount: mint, space: mintSize, lamports: mintRent, programAddress: TOKEN_PROGRAM_ADDRESS, }); } ``` -------------------------------- ### Creating and Using an RPC Client Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-spec/README.md Demonstrates the typical workflow for creating an RPC client instance, calling a method to get a pending request, and sending the request to the RPC server. ```APIDOC ## Usage Example ```ts const rpc = createSolanaRpc(mainnet('https://api.mainnet-beta.solana.com')); const response = await rpc .getLatestBlockhash({ commitment: 'confirmed' }) .send({ abortSignal: AbortSignal.timeout(10_000) }); ``` ### Description This example shows the three main steps involved in using the RPC client: 1. Creating an `Rpc` instance using `createSolanaRpc`. 2. Calling a supported RPC method (e.g., `getLatestBlockhash`) to obtain a `PendingRpcRequest`. 3. Sending the pending request using the `send` method, optionally with an `AbortSignal`. ``` -------------------------------- ### Create and Use Solana RPC Subscriptions Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-subscriptions-spec/README.md Demonstrates the typical workflow for creating a subscription instance, calling a subscription method, subscribing to notifications, and handling the received data. Includes error handling and cleanup. ```typescript const rpcSubscriptions = // Step 1 - Create a `RpcSubscriptions` instance. This may be stateful. createSolanaRpcSubscriptions(mainnet('wss://api.mainnet-beta.solana.com')); const response = await rpcSubscriptions // Step 2 - Call supported methods on it to produce `PendingRpcSubscriptionsRequest` objects. .slotNotifications({ commitment: 'confirmed' }) // Step 3 - Call the `subscribe()` method on those pending requests to trigger them. .subscribe({ abortSignal: AbortSignal.timeout(10_000) }); // Step 4 - Iterate over the result. try { for await (const slotNotification of slotNotifications) { console.log('Got a slot notification', slotNotification); } } catch (e) { console.error('The subscription closed unexpectedly', e); } finally { console.log('We have stopped listening for notifications'); } ``` -------------------------------- ### Example Transaction Query Result Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-graphql/README.md This is an example of the data structure returned by the nested transaction query, showing details for an SPL token transfer. ```json { data: { transaction: { message: { instructions: [ { amount: '50', authority: { address: 'AHPPMhzDQix9sKULBqeaQ5BUZgrKdz8tg6DzPxsofB12', lamports: 890880n, }, destination: { address: '2W8mUY75zxqwAcpirn75r3Cc7TStMirFyHwKqo13fmB1', mint: { address: '8poKMotB2cEYVv5sbjrdyssASZj1vwYCe7GJFeXo2QP7', decimals: 6, }, owner: { address: '7tRxJ2znbTFpwW9XaMMiDsXDudoPEUXRcpDpm8qjWgAZ', lamports: 890880n, } }, source: { address: 'BqFCPqXUm4cq6jaZZx1TDTvUR1wdEuNNwAHBEVR6mJhM', mint: { address: '8poKMotB2cEYVv5sbjrdyssASZj1vwYCe7GJFeXo2QP7', decimals: 6, }, owner: { address: '3dPmVLMD7PC5faZNyJUH9WFrUxAsbjydJfoozwmR1wDG', lamports: e890880n, } } }, /* .. */ ] } } } } ``` -------------------------------- ### Compare Web3.js Connection with Kit RPC Subscriptions Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/upgrade-guide.mdx Illustrates setting up a WebSocket connection and subscribing to account changes in Web3.js versus Kit. Kit utilizes `createSolanaRpcSubscriptions` for efficient event handling. ```typescript import { Connection, PublicKey } from '@solana/web3.js'; // Create a `Connection` object with a WebSocket endpoint. const connection = new Connection('https://api.devnet.solana.com', { wsEndpoint: 'wss://api.devnet.solana.com', commitment: 'confirmed', }); // Subscribe to RPC events and listen to notifications. const wallet = new PublicKey('1234..5678'); connection.onAccountChange(wallet, (accountInfo) => { console.log(accountInfo); }); ``` ```typescript import { address, createSolanaRpcSubscriptions } from '@solana/kit'; // Create an RPC subscriptions proxy object. const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); // Use an `AbortController` to cancel the subscriptions. const abortController = new AbortController(); // Subscribe to RPC events. const wallet = address('1234..5678'); const accountNotifications = await rpcSubscriptions .accountNotifications(wallet, { commitment: 'confirmed' }) .subscribe({ abortSignal: abortController.signal }); try { // Listen to event notifications. for await (const accountInfo of accountNotifications) { console.log(accountInfo); } } catch (e) { // Gracefully handle subscription disconnects. } ``` -------------------------------- ### Install Web Crypto Ed25519 Polyfill Source: https://github.com/anza-xyz/kit/blob/main/README.md Install the polyfill if your target runtime does not support Ed25519. This mimics the Web Crypto API for Ed25519 key pairs. ```typescript import { install } from '@solana/webcrypto-ed25519-polyfill'; import { generateKeyPair, signBytes, verifySignature } from '@solana/kit'; install(); const keyPair: CryptoKeyPair = await generateKeyPair(); /* Remaining logic */ ``` -------------------------------- ### getUnionCodec Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/codecs.mdx The `getUnionCodec` is a lower-level codec helper that can be used to encode/decode any TypeScript union. It accepts an array of codecs, a function to get the index from a value, and a function to get the index from bytes. ```APIDOC ## getUnionCodec ### Description Encodes and decodes TypeScript unions using a provided set of codecs and index-determining functions. ### Parameters - **codecs**: An array of codecs, each defining a variant of the union. - **getIndexFromValue**: A function that takes a union value and returns the index of the codec to use for encoding. - **getIndexFromBytes**: A function that takes a byte array and an offset, and returns the index of the codec to use for decoding. ### Request Example ```ts import { getUnionCodec, getU16Codec, getBooleanCodec, Codec } from '@solana/kit'; const codec: Codec = getUnionCodec( [getU16Codec(), getBooleanCodec()], (value) => (typeof value === 'number' ? 0 : 1), (bytes, offset) => (bytes.slice(offset).length > 1 ? 0 : 1), ); codec.encode(42); // Returns Uint8Array representing 42 codec.encode(true); // Returns Uint8Array representing true ``` ### Notes `getUnionEncoder` and `getUnionDecoder` functions are also available for separate encoding and decoding operations. ``` -------------------------------- ### Getting Transaction Signature Source: https://github.com/anza-xyz/kit/blob/main/packages/transactions/README.md Retrieves the unique signature for a transaction that has been signed by its fee payer. ```APIDOC ## getSignatureFromTransaction() ### Description Given a transaction signed by its fee payer, this method will return the `Signature` that uniquely identifies it. This string can be used to look up transactions at a later date, for example on a Solana block explorer. ### Method `getSignatureFromTransaction` ### Parameters #### Request Body - **tx** (Transaction) - Required - The transaction object. ### Request Example ```ts import { getSignatureFromTransaction } from '@solana/transactions'; const signature = getSignatureFromTransaction(tx); console.debug(`Inspect this transaction at https://explorer.solana.com/tx/${signature}`); ``` ``` -------------------------------- ### Sign Transactions with Kit Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/upgrade-guide.mdx This example demonstrates signing transactions using Kit's `generateKeyPair` and `signTransaction` functions. It utilizes `CryptoKeyPair` for secure key management. ```typescript import { compileTransaction, generateKeyPair, signTransaction } from '@solana/kit'; // ---cut-start--- import { TransactionMessage, TransactionMessageWithBlockhashLifetime, TransactionMessageWithFeePayer, } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithBlockhashLifetime; // ---cut-end--- const [payer, authority] = await Promise.all([generateKeyPair(), generateKeyPair()]); const transaction = compileTransaction(transactionMessage); const signedTransaction = await signTransaction([payer, authority], transaction); ``` -------------------------------- ### Create and Use Solana RPC Client Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-spec/README.md Demonstrates the three-step process of creating an RPC client, calling a method to get a pending request, and sending the request with an abort signal. ```typescript const rpc = // Step 1 - Create a `Rpc` instance. This may be stateful. createSolanaRpc(mainnet('https://api.mainnet-beta.solana.com')); const response = await rpc // Step 2 - Call supported methods on it to produce `PendingRpcRequest` objects. .getLatestBlockhash({ commitment: 'confirmed' }) // Step 3 - Call the `send()` method on those pending requests to trigger them. .send({ abortSignal: AbortSignal.timeout(10_000) }); ``` -------------------------------- ### Merge Bytes Example Source: https://github.com/anza-xyz/kit/blob/main/packages/codecs-core/README.md Concatenate multiple `Uint8Array` buffers into a single `Uint8Array` using `mergeBytes`. ```ts // Merge multiple Uint8Array buffers into one. mergeBytes([new Uint8Array([1, 2]), new Uint8Array([3, 4])]); // Uint8Array([1, 2, 3, 4]) ``` -------------------------------- ### getPublicKeyFromPrivateKey() Source: https://github.com/anza-xyz/kit/blob/main/packages/keys/README.md Given an extractable `CryptoKey` private key, gets the corresponding public key as a `CryptoKey`. ```APIDOC ## getPublicKeyFromPrivateKey() ### Description Given an extractable `CryptoKey` private key, gets the corresponding public key as a `CryptoKey`. ### Parameters - `privateKey` (CryptoKey) - The extractable private key. - `extractable` (boolean, optional) - Whether the public key should be extractable. Defaults to false. ### Returns - `Promise` - The corresponding public key as a `CryptoKey` object. ### Request Example ```ts import { createPrivateKeyFromBytes, getPublicKeyFromPrivateKey } from '@solana/keys'; const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true); const publicKey = await getPublicKeyFromPrivateKey(privateKey); const extractablePublicKey = await getPublicKeyFromPrivateKey(privateKey, true); ``` ``` -------------------------------- ### Create Transfer SOL Instruction (Web3.js) Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/upgrade-guide.mdx Demonstrates creating a SOL transfer instruction using Web3.js's SystemProgram. ```typescript import { PublicKey, SystemProgram } from '@solana/web3.js'; const transferSol = SystemProgram.transfer({ fromPubkey: new PublicKey('2222..2222'), toPubkey: new PublicKey('3333..3333'), lamports: 1_000_000_000, // 1 SOL. }); ``` -------------------------------- ### Build CreateAccount Instruction Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/getting-started/instructions.mdx Use `getCreateAccountInstruction` to build an instruction for allocating a new account on Solana. Ensure all required parameters like payer, new account details, lamports, space, and program address are provided. ```typescript // @filename: client.ts import { Rpc, RpcSubscriptions, SolanaRpcApi, SolanaRpcSubscriptionsApi, TransactionSigner, MessageSigner, } from '@solana/kit'; export type Client = { rpc: Rpc; rpcSubscriptions: RpcSubscriptions; wallet: TransactionSigner & MessageSigner; }; // @filename: create-mint.ts const payer = null as any; const newAccount = null as any; const lamports = null as any; const space = null as any; const programAddress = null as any; // ---cut-before--- import { getCreateAccountInstruction } from '@solana-program/system'; import type { Client } from './client'; export async function createMint(client: Client, options: { decimals?: number } = {}) { // Build instructions. const createAccountIx = getCreateAccountInstruction({ payer, newAccount, space, lamports, programAddress, }); } ``` -------------------------------- ### Implement and Use RpcApi Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-api/README.md Shows how to create an RpcApi instance with a defined API and how to call its methods, including sending a request and awaiting the result. ```typescript const rpc: Rpc = createExampleRpc(/* ... */); const something: Something = await rpc.getSomething(address('95DpK3y3GF7U8s1k4EvZ7xqyeCkhsHeZaE97iZpHUGMN')).send(); ``` -------------------------------- ### Contains Bytes Example Source: https://github.com/anza-xyz/kit/blob/main/packages/codecs-core/README.md Check if a `Uint8Array` contains another `Uint8Array` at a specific offset using `containsBytes`. ```ts // Check if a Uint8Array contains another Uint8Array at a given offset. containsBytes(new Uint8Array([1, 2, 3, 4]), new Uint8Array([2, 3]), 1); // true containsBytes(new Uint8Array([1, 2, 3, 4]), new Uint8Array([2, 3]), 2); // false ``` -------------------------------- ### Fixed-Size Codec Example Source: https://github.com/anza-xyz/kit/blob/main/packages/codecs-core/README.md Demonstrates a `FixedSizeCodec` which has a known `fixedSize` attribute indicating its encoded byte length. ```typescript const myCodec: FixedSizeCodec = getU32Codec(); myCodec.fixedSize; // 4 bytes. ``` -------------------------------- ### Efficiently Create Solana Mint Account Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/getting-started/instructions.mdx Prepare inputs and create a new Solana mint account efficiently by using `Promise.all` to execute potentially parallelizable operations like generating a keypair and fetching rent exemption balance. ```typescript // @filename: client.ts import { Rpc, RpcSubscriptions, SolanaRpcApi, SolanaRpcSubscriptionsApi, TransactionSigner, MessageSigner, } from '@solana/kit'; export type Client = { rpc: Rpc; rpcSubscriptions: RpcSubscriptions; wallet: TransactionSigner & MessageSigner; }; // @filename: create-mint.ts // ---cut-before--- import { generateKeyPairSigner } from '@solana/kit'; import { getCreateAccountInstruction } from '@solana-program/system'; import { getMintSize, TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import type { Client } from './client'; export async function createMint(client: Client, options: { decimals?: number } = {}) { // Prepare inputs. const mintSize = getMintSize(); const [mint, mintRent] = await Promise.all([ generateKeyPairSigner(), client.rpc.getMinimumBalanceForRentExemption(BigInt(mintSize)).send(), ]); ``` -------------------------------- ### Generate and Use KeyPairSigner Source: https://github.com/anza-xyz/kit/blob/main/packages/signers/README.md Demonstrates generating a KeyPairSigner and using it to sign messages and transactions. Ensure necessary imports are included. ```typescript import { pipe } from '@solana/functional'; import { generateKeyPairSigner } from '@solana/signers'; import { createTransactionMessage } from '@solana/transaction-messages'; import { compileTransaction } from '@solana/transactions'; // Generate a key pair signer. const mySigner = await generateKeyPairSigner(); mySigner.address; // Address; // Sign one or multiple messages. const myMessage = createSignableMessage('Hello world!'); const [messageSignatures] = await mySigner.signMessages([myMessage]); // Sign one or multiple transaction messages. const myTransactionMessage = pipe( createTransactionMessage({ version: 0 }), // Add instructions, fee payer, lifetime, etc. ); const myTransaction = compileTransaction(myTransactionMessage); const [transactionSignatures] = await mySigner.signTransactions([myTransaction]); ``` -------------------------------- ### Initializing the RPC-GraphQL Client Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-graphql/README.md Demonstrates how to initialize the RPC-GraphQL client using an existing RPC client. The `RpcGraphQL` type supports a `query` method for executing GraphQL queries. ```APIDOC ## Initializing the RPC-GraphQL Client To initialize the RPC-GraphQL client, use `createSolanaRpcGraphQL`. ```ts import { createSolanaRpc } from '@solana/rpc'; import { createSolanaRpcGraphQL } from '@solana/rpc-graphql'; // Create the RPC client const rpc = createSolanaRpc('https://api.devnet.solana.com'); // Create the RPC-GraphQL client const rpcGraphQL = createSolanaRpcGraphQL(rpc); ``` The `RpcGraphQL` type supports one method `query` which accepts a string query source and an optional `variableValues` parameter. ``` -------------------------------- ### Offset out of range error with negative preOffset Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/codecs.mdx Shows an example where a negative preOffset causes a SolanaError with code SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE. ```ts import { offsetCodec, resizeCodec, getU32Codec } from '@solana/kit'; const biggerU32Codec = resizeCodec(getU32Codec(), (size) => size + 4); // ---cut-before--- const u32InTheEndCodec = offsetCodec(biggerU32Codec, { preOffset: () => -4 }); u32InTheEndCodec.encode(0xffffffff); ``` -------------------------------- ### Get UTF-8 Codec Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/codecs.mdx Use `getUtf8Codec` to encode and decode UTF-8 strings. This codec does not enforce size boundaries. ```ts import { getUtf8Codec } from '@solana/kit'; // ---cut-before--- const codec = getUtf8Codec(); const bytes = codec.encode('hello'); // 0x68656c6c6f const value = codec.decode(bytes); // "hello" ``` -------------------------------- ### Initialize Solana RPC GraphQL Client Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-graphql/README.md Initialize the RPC-GraphQL client by first creating an RPC client and then passing it to `createSolanaRpcGraphQL`. ```typescript import { createSolanaRpc } from '@solana/rpc'; // Create the RPC client const rpc = createSolanaRpc('https://api.devnet.solana.com'); // Create the RPC-GraphQL client const rpcGraphQL = createSolanaRpcGraphQL(rpc); ``` -------------------------------- ### Compare Web3.js Connection with Kit RPC Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/upgrade-guide.mdx Demonstrates creating a connection and sending RPC requests in Web3.js versus Kit. Kit uses `createSolanaRpc` for a lightweight RPC proxy. ```typescript import { Connection, PublicKey } from '@solana/web3.js'; // Create a `Connection` object. const connection = new Connection('https://api.devnet.solana.com', { commitment: 'confirmed', }); // Send RPC requests. const wallet = new PublicKey('1234..5678'); const balance = await connection.getBalance(wallet); ``` ```typescript import { address, createSolanaRpc } from '@solana/kit'; // Create an RPC proxy object. const rpc = createSolanaRpc('https://api.devnet.solana.com'); // Send RPC requests. const wallet = address('1234..5678'); const { value: balance } = await rpc.getBalance(wallet).send(); ``` -------------------------------- ### Get BigInt Downcast Request Transformer Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-transformers/README.md Creates a transformer that converts all `BigInt` values within requests to `Number`. ```typescript import { getBigIntDowncastRequestTransformer } from '@solana/rpc-transformers'; const requestTransformer = getBigIntDowncastRequestTransformer(); ``` -------------------------------- ### Create Transfer SOL Instruction (Kit) Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/upgrade-guide.mdx Shows how to create a SOL transfer instruction using Kit's @solana-program/system library. Kit uses TransactionSigner objects for signers. ```typescript import { address, createNoopSigner } from '@solana/kit'; import { getTransferSolInstruction } from '@solana-program/system'; const transferSol = getTransferSolInstruction({ source: createNoopSigner(address('2222..2222')), destination: address('3333..3333'), amount: 1_000_000_000, // 1 SOL. }); ``` -------------------------------- ### Check if Bytes Contain Sub-Array Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/codecs.mdx The `containsBytes` function checks if a `Uint8Array` contains another `Uint8Array` starting at a specific offset. ```typescript import { containsBytes } from '@solana/kit'; // ---cut-before--- containsBytes(new Uint8Array([1, 2, 3, 4]), new Uint8Array([2, 3]), 1); // true containsBytes(new Uint8Array([1, 2, 3, 4]), new Uint8Array([2, 3]), 2); // false ``` -------------------------------- ### Create a new transaction message Source: https://github.com/anza-xyz/kit/blob/main/packages/transaction-messages/README.md Initializes an empty transaction message with the specified version. This is the starting point for building a transaction. ```typescript import { createTransactionMessage } from '@solana/transaction-messages'; const message = createTransactionMessage({ version: 0 }); ``` -------------------------------- ### GraphQL Query for Account Data with Caching Example Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-graphql/README.md Demonstrates a GraphQL query that fetches account data and its mint authority, illustrating how caching prevents duplicate requests for the same resource. ```graphql query { account(address: "J7iup799j5BVjKXACZycYef7WQ4x1wfzhUsc5v357yWQ") { lamports data(encoding: BASE_64) ... on MintAccount { mintAuthority { lamports data(encoding: BASE_64) } } } } ``` -------------------------------- ### Implement MessagePartialSigner Source: https://github.com/anza-xyz/kit/blob/main/packages/signers/README.md Example implementation of a partial message signer. Use this when you need to sign messages without altering their content. ```typescript const myMessagePartialSigner: MessagePartialSigner<'1234..5678'> = { address: address('1234..5678'), signMessages: async (messages: SignableMessage[]): Promise => { // My custom signing logic. }, }; ``` -------------------------------- ### Fetch Account Info with Kit Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/upgrade-guide.mdx Use Kit's `createSolanaRpc` and `getAccountInfo` for fetching account details. Ensure you have the RPC endpoint configured. ```typescript import { address } from '@solana/kit'; // ---cut-start--- import { createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); // ---cut-end--- const wallet = address('1234..5678'); const { value: account } = await rpc.getAccountInfo(wallet).send(); ``` -------------------------------- ### JavaScript RPC Call for Multiple Accounts Source: https://github.com/anza-xyz/kit/blob/main/packages/rpc-graphql/README.md Example of how RPC-GraphQL internally calls `getMultipleAccounts` when multiple account queries are present. ```javascript rpc.getMultipleAccounts([ 'J7iup799j5BVjKXACZycYef7WQ4x1wfzhUsc5v357yWQ', 'EVW3CoyogapBfQxBFFEKGMM1bn3JyoFiqkAJdw3FHX1b', ]); ``` -------------------------------- ### Create Sequential and Parallel Instruction Plans Source: https://github.com/anza-xyz/kit/blob/main/docs/content/docs/concepts/instruction-plans.mdx Use `sequentialInstructionPlan` and `parallelInstructionPlan` to compose complex operations from individual instructions. This example demonstrates a multi-step escrow transfer process. ```typescript import { Instruction, sequentialInstructionPlan, parallelInstructionPlan } from '@solana/kit'; const depositFromAlice = {} as unknown as Instruction; const depositFromBob = {} as unknown as Instruction; const activateVault = {} as unknown as Instruction; const withdrawToAlice = {} as unknown as Instruction; const withdrawToBob = {} as unknown as Instruction; // ---cut-before--- const instructionPlan = sequentialInstructionPlan([ parallelInstructionPlan([depositFromAlice, depositFromBob]), activateVault, parallelInstructionPlan([withdrawToAlice, withdrawToBob]), ]); ``` -------------------------------- ### Array U32 Size Prefix Example Source: https://github.com/anza-xyz/kit/blob/main/packages/codecs-data-structures/README.md Illustrates the default behavior of `getArrayCodec` using a u32 prefix for array size. ```plaintext getArrayCodec(getU8Codec()).encode([1, 2, 3]); // 0x03000000010203 // | └-- 3 items of 1 byte each. // └-- 4-byte prefix telling us to read 3 items. ```