# Getting started (/docs/getting-started) In this tutorial, we'll build a small Solana app with Kit. We'll create a devnet signer, fund it with devnet SOL, create a token mint, and read its data back β€” all with a plugin-composed Kit client. ## Install dependencies First, let's install Kit and the plugins for connecting to Solana via RPC and loading a signer. ```bash npm install @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ```bash pnpm add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ```bash yarn add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ```bash bun add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` Then install the program plugins for the Solana programs you want to interact with. For this tutorial, we'll use the Token program to create and read a token mint. ```bash npm install @solana-program/token ``` ```bash pnpm add @solana-program/token ``` ```bash yarn add @solana-program/token ``` ```bash bun add @solana-program/token ``` ## Create a devnet signer Before we start, let's create a signer that we can reuse across this tutorial. This one-time setup script grinds a small vanity address, makes the keypair extractable, and writes it to a local file in the same JSON format used by Solana CLI keypairs. ```ts twoslash title="create-signer.ts" import { grindKeyPairSigner, writeKeyPairSigner } from '@solana/kit'; const signer = await grindKeyPairSigner({ extractable: true, matches: /^kit/i, }); await writeKeyPairSigner(signer, './kit-getting-started-keypair.json'); console.log(`✨ Created devnet signer ${signer.address}`); console.log('πŸ” Wrote ./kit-getting-started-keypair.json'); console.log('βœ… Add this file to .gitignore before committing your project.'); ``` Run this script once, then remove it from your project. We'll keep the generated `kit-getting-started-keypair.json` file locally for the rest of this tutorial. Be sure to add it to `.gitignore` if you are planning on committing these changes. Already have a Solana CLI keypair? You can skip this script and use `signerFromFile('~/.config/solana/id.json')` instead. See [Setting Up Signers](/docs/guides/setting-up-signers) for more signer options. ## Create a client Now let's create a client connected to devnet and load the signer from the file we just wrote. ```ts twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signerFromFile } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(signerFromFile('./kit-getting-started-keypair.json')) .use(solanaDevnetRpc()) .use(tokenProgram()); ``` Here's what each piece does: * `createClient()` creates an empty Kit client that can be extended with plugins. * `.use(signerFromFile(...))` loads our keypair file and sets it as both the client's payer (who pays fees) and identity (who owns assets). * `.use(solanaDevnetRpc())` connects to devnet and adds RPC, subscriptions, airdrops, minimum balance helpers, and transaction sending. * `.use(tokenProgram())` adds typed access to the Token program's instructions and accounts. Because we just created a fresh devnet signer, it won't have any SOL yet. Let's fund it with a devnet airdrop before moving on. If you're reusing a signer that already has devnet SOL, you can skip this step. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signerFromFile } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(signerFromFile('./kit-getting-started-keypair.json')) .use(solanaDevnetRpc()) .use(tokenProgram()); // ---cut-before--- const airdropSignature = await client.airdrop(client.payer.address, lamports(1_000_000_000n)); console.log(`πŸ’Έ Funded ${client.payer.address} with 1 SOL`); if (airdropSignature) { console.log(`πŸ”Ž https://explorer.solana.com/tx/${airdropSignature}?cluster=devnet`); } ``` Airdrops are only available on test networks like devnet and localhost. Run the airdrop once, then remove or comment out those lines before continuing so we do not hit devnet faucet rate limits. If the airdrop fails, wait a moment and try again, or request devnet SOL from the [Solana Faucet](https://faucet.solana.com). ## Send a transaction Let's create a token mint onchain. In Solana, every transaction contains one or more instructions: small commands that tell programs what to do. Some tasks, like creating a mint, require multiple instructions that should stay together. Kit represents that kind of multi-step operation as an **instruction plan**. The Token program plugin gives us one of these plans via `client.token.instructions.createMint(...)`. Under the hood, it creates a new account for the provided mint address with enough lamports to be rent-exempt (system program's `createAccount` instruction) and initializes it as a Token program mint (token program's `initializeMint` instruction). We pass the new mint as a signer (since we initialize a new account), choose `9` decimals, and set our client identity as the mint authority. ```ts twoslash import { createClient, generateKeyPairSigner } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signerFromFile } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(signerFromFile('./kit-getting-started-keypair.json')) .use(solanaDevnetRpc()) .use(tokenProgram()); // ---cut-before--- const mint = await generateKeyPairSigner(); const createMintPlan = client.token.instructions.createMint({ newMint: mint, decimals: 9, mintAuthority: client.identity.address, }); const createMintResult = await client.sendTransaction([createMintPlan]); const createMintSignature = createMintResult.context.signature; console.log(`πŸŽ‰ Created token mint ${mint.address}`); console.log(`πŸ”Ž https://explorer.solana.com/tx/${createMintSignature}?cluster=devnet`); ``` `client.sendTransaction([...])` accepts an array of instructions and instruction plans and sends them as a single transaction. If one part fails, the whole transaction fails. This is the most common way to send transactions with a client, especially when we want to combine several instructions or plans. For simple one-off operations, program instruction helpers also include a `.sendTransaction()` shortcut. The following sends the same `createMint` instruction plan as a single transaction without explicitly calling `client.sendTransaction([...])`. ```ts twoslash import { createClient, generateKeyPairSigner } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signerFromFile } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(signerFromFile('./kit-getting-started-keypair.json')) .use(solanaDevnetRpc()) .use(tokenProgram()); const mint = await generateKeyPairSigner(); // ---cut-before--- const createMintResult = await client.token.instructions .createMint({ newMint: mint, decimals: 9, mintAuthority: client.identity.address, }) .sendTransaction(); ``` For error handling, priority fees, and more advanced patterns, see the [Sending Transactions](/docs/guides/sending-transactions) guide. ## Fetch an account Now let's read the mint account we just created. Program plugins provide typed fetch helpers that decode account data automatically. The `mintAccount.data` object gives us the full `Mint` structure with fields like `decimals`, `mintAuthority`, `supply`, and `freezeAuthority`. ```ts twoslash import { createClient, generateKeyPairSigner } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signerFromFile } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(signerFromFile('./kit-getting-started-keypair.json')) .use(solanaDevnetRpc()) .use(tokenProgram()); const mint = await generateKeyPairSigner(); // ---cut-before--- const mintAccount = await client.token.accounts.mint.fetch(mint.address); console.log('βœ… Mint account decoded'); console.log(` Address: ${mint.address}`); console.log(` Decimals: ${mintAccount.data.decimals}`); console.log(' Mint authority:', mintAccount.data.mintAuthority); console.log(` Supply: ${mintAccount.data.supply}`); ``` For raw account fetching and manual decoding, see the [Fetching Accounts](/docs/guides/fetching-accounts) guide. ## Full example Here's the complete script you can copy and run after creating `kit-getting-started-keypair.json`. ```ts twoslash import { createClient, generateKeyPairSigner, lamports } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signerFromFile } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(signerFromFile('./kit-getting-started-keypair.json')) .use(solanaDevnetRpc()) .use(tokenProgram()); // Run this once, then remove or comment it out to avoid devnet faucet rate limits. const airdropSignature = await client.airdrop(client.payer.address, lamports(1_000_000_000n)); console.log(`πŸ’Έ Funded ${client.payer.address} with 1 SOL`); if (airdropSignature) { console.log(`πŸ”Ž https://explorer.solana.com/tx/${airdropSignature}?cluster=devnet`); } const mint = await generateKeyPairSigner(); const createMintPlan = client.token.instructions.createMint({ newMint: mint, decimals: 9, mintAuthority: client.identity.address, }); const createMintResult = await client.sendTransaction([createMintPlan]); const createMintSignature = createMintResult.context.signature; console.log(`πŸŽ‰ Created token mint ${mint.address}`); console.log(`πŸ”Ž https://explorer.solana.com/tx/${createMintSignature}?cluster=devnet`); const mintAccount = await client.token.accounts.mint.fetch(mint.address); console.log('βœ… Mint account decoded'); console.log(` Address: ${mint.address}`); console.log(` Decimals: ${mintAccount.data.decimals}`); console.log(' Mint authority:', mintAccount.data.mintAuthority); console.log(` Supply: ${mintAccount.data.supply}`); ``` ## Next steps We've connected to devnet, funded a signer, created a token mint, and read its data. Here's where to go next: * [Setting Up Signers](/docs/guides/setting-up-signers) β€” load signers from keypair files, wallet standard, and more. * [Sending Transactions](/docs/guides/sending-transactions) β€” error handling, priority fees, and instruction plans. * [Fetching Accounts](/docs/guides/fetching-accounts) β€” program plugin fetch helpers, batch fetching, and decoding. * [Using Program Plugins](/docs/guides/using-program-plugins) β€” typed access to any Solana program. * [Plugins](/docs/plugins) β€” understand and extend the plugin system. # Installation (/docs) Kit is a JavaScript SDK for building Solana apps across environments like Node, the web, and React Native. It provides a comprehensive set of data types and helper functions, forming the foundation for interacting with Solana in JavaScript. Check out our [Upgrade guide](/docs/upgrade-guide) to see how Kit compares to Web3.js. ## Quick start Choose the client setup that fits your environment: ### Install packages Install Kit and the plugins for RPC connectivity and signer management. ```bash npm install @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ```bash pnpm add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ```bash yarn add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ```bash bun add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ### Install program plugins Install plugins for any Solana program you want to interact with. You can find a full list on the [Available Plugins](/docs/plugins/available-plugins) page. ```bash npm install @solana-program/system @solana-program/token ``` ```bash pnpm add @solana-program/system @solana-program/token ``` ```bash yarn add @solana-program/system @solana-program/token ``` ```bash bun add @solana-program/system @solana-program/token ``` ### Create your client ```ts twoslash import { createClient } from '@solana/kit'; import { solanaMainnetRpc } from '@solana/kit-plugin-rpc'; import { signerFromFile } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(signerFromFile('~/.config/solana/id.json')) .use(solanaMainnetRpc({ rpcUrl: 'https://api.mainnet-beta.solana.com' })) .use(systemProgram()) .use(tokenProgram()); // Here are some of the things you can do with your client: // client.rpc.getBalance(address).send(); // client.system.instructions.transferSol({...}).sendTransaction(); // client.token.accounts.mint.fetch(address); // client.sendTransaction(instructions); // And more... ``` This example loads the default Solana CLI keypair. See [Setting Up Signers](/docs/guides/setting-up-signers) for other production signer options such as using a wallet. ### Install packages Install Kit and the plugins for local RPC connectivity and signer management. ```bash npm install @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ```bash pnpm add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ```bash yarn add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ```bash bun add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer ``` ### Install program plugins Install plugins for any Solana program you want to interact with. You can find a full list on the [Available Plugins](/docs/plugins/available-plugins) page. ```bash npm install @solana-program/system @solana-program/token ``` ```bash pnpm add @solana-program/system @solana-program/token ``` ```bash yarn add @solana-program/system @solana-program/token ``` ```bash bun add @solana-program/system @solana-program/token ``` ### Start a test validator Make sure you have a local Solana validator running before using your client. ```shell solana-test-validator ``` ### Create your client ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(100_000_000_000n))) .use(systemProgram()) .use(tokenProgram()); // Signer is auto-generated and funded with SOL. // Here are some of the things you can do with your client: // client.rpc.getBalance(address).send(); // client.system.instructions.transferSol({...}).sendTransaction(); // client.token.accounts.mint.fetch(address); // client.sendTransaction(instructions); // And more... ``` ### Install packages Install Kit and the plugins for LiteSVM and signer management. ```bash npm install @solana/kit @solana/kit-plugin-litesvm @solana/kit-plugin-signer ``` ```bash pnpm add @solana/kit @solana/kit-plugin-litesvm @solana/kit-plugin-signer ``` ```bash yarn add @solana/kit @solana/kit-plugin-litesvm @solana/kit-plugin-signer ``` ```bash bun add @solana/kit @solana/kit-plugin-litesvm @solana/kit-plugin-signer ``` ### Install program plugins Install plugins for any Solana program you want to interact with. You can find a full list on the [Available Plugins](/docs/plugins/available-plugins) page. ```bash npm install @solana-program/system @solana-program/token ``` ```bash pnpm add @solana-program/system @solana-program/token ``` ```bash yarn add @solana-program/system @solana-program/token ``` ```bash bun add @solana-program/system @solana-program/token ``` ### Create your client ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { litesvm } from '@solana/kit-plugin-litesvm'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(litesvm()) .use(airdropSigner(lamports(100_000_000_000n))) .use(systemProgram()) .use(tokenProgram()); // Here are some of the things you can do with your client: // client.rpc.getBalance(address).send(); // client.system.instructions.transferSol({...}).sendTransaction(); // client.token.accounts.mint.fetch(address); // client.sendTransaction(instructions); // And more... ``` ### Install Kit ```bash npm install @solana/kit ``` ```bash pnpm add @solana/kit ``` ```bash yarn add @solana/kit ``` ```bash bun add @solana/kit ``` ### Install program libraries Install Kit-compatible libraries for any program you want to interact with. For example, to interact with the System program, install the `@solana-program/system` package. You can find a [list of available program plugins here](/docs/plugins/available-plugins). ```bash npm install @solana-program/system @solana-program/token ``` ```bash pnpm add @solana-program/system @solana-program/token ``` ```bash yarn add @solana-program/system @solana-program/token ``` ```bash bun add @solana-program/system @solana-program/token ``` ### Set up your project ```ts twoslash import { address, createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const { value: balance } = await rpc .getBalance(address('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb')) .send(); console.log(`Balance: ${balance} lamports`); ``` See [Kit Without a Client](/docs/advanced-guides/kit-without-a-client) for the full guide on sending transactions, signing, and more without a client. Ready to build? Check out the [Getting Started](/docs/getting-started) tutorial to build your first app, or explore the [Guides](/docs/guides) for specific topics. # Upgrade guide (/docs/upgrade-guide) import TreeShaking from './tree-shaking'; ## Why upgrade? Kit is a complete rewrite of [the Web3.js library](https://github.com/solana-labs/solana-web3.js/). It is designed to be more composable, customizable, and efficient than its predecessor. Its functional design enables the entire library to be tree-shaken, drastically reducing your bundle size. It also takes advantage of modern JavaScript features β€” such as native Ed25519 key support and `bigint` for large values β€” resulting in an even smaller bundle, better performance and most importantly, a reduced attack surface for your application. Unlike Web3.js, Kit doesn't rely on JavaScript classes or other non-tree-shakeable features. This brings us to our first key difference. ## Where's my `Connection` class? In Web3.js, the `Connection` class serves as a central entry point, making the library's API easier to discover via a single object. However, this comes at a cost: using the `Connection` class forces you to bundle every method it provides, even if you only use a few. As a result, your users must download the entire library, even when most of it goes unused. To avoid this, **Kit does not include a single entry-point class like `Connection`**. Instead, it offers a set of functions that you can import and use as needed. Two key functions replace most of the `Connection` class's functionality: `createSolanaRpc` and `createSolanaRpcSubscriptions`. The former, `createSolanaRpc`, returns an `Rpc` object for making RPC requests to a specified endpoint. [Read more about RPCs here](/docs/guides/rpc).
```ts title="Web3.js" 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); ``` ```ts twoslash title="Kit" 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(); ```
The latter, `createSolanaRpcSubscriptions`, returns an `RpcSubscriptions` object, which lets you to subscribe to events on the Solana network. [Read more about RPC Subscriptions here](/docs/guides/rpc-subscriptions).
```ts title="Web3.js" 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); }); ``` ```ts twoslash title="Kit" 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. } ```
Note that, although `Rpc` and `RpcSubscriptions` look like classes, they are actually [`Proxy` objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). This means they dynamically construct RPC requests or subscriptions based on method names and parameters. TypeScript is then used to provide type safety for the RPC API, making it easy to discover available RPC methods while keeping the library lightweight. Regardless of whether your RPC supports 1 method or 100, the bundle size remains unchanged. ## Introducing Kit clients The functional approach above gives you maximum treeshakability, but it can feel verbose compared to Web3.js's `Connection`. Kit addresses this with **plugin-based clients** β€” a single object that bundles the functionality you need while still letting you choose what goes in. You cherry-pick plugins, so you typically only bundle what you actually use.
```ts title="Web3.js" import { Connection, PublicKey } from '@solana/web3.js'; // Create a `Connection` object. const connection = new Connection('https://api.devnet.solana.com'); // Use the connection. const wallet = new PublicKey('1234..5678'); const balance = await connection.getBalance(wallet); ``` ```ts twoslash title="Kit" import { address, createClient, generateKeyPairSigner } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signer } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; // Create a client with the plugins you need. const payer = await generateKeyPairSigner(); const client = createClient().use(signer(payer)).use(solanaDevnetRpc()).use(systemProgram()); // Use the client. const wallet = address('1234..5678'); const { value: balance } = await client.rpc.getBalance(wallet).send(); ```
A Kit client is an immutable JavaScript object built by chaining `.use()` calls. Each plugin adds capabilities to the client β€” like signer roles, RPC access, transaction sending, or typed program instructions. Start with `createClient()` from `@solana/kit`, add signer plugins such as `signer(payer)`, then apply RPC bundles like `solanaDevnetRpc()` to install RPC, subscriptions, transaction planning, sending, and devnet airdrops. You may then extend it with program plugins like `systemProgram()` and `tokenProgram()` to add typed access to the accounts and instructions of those programs. The rest of this guide uses a client for the Kit examples. To learn more about the plugin system, see [Plugins](/docs/plugins). ## Fetching and decoding accounts Fetching onchain accounts is as simple as calling the appropriate RPC method on the client. Kit also provides helper functions like `fetchEncodedAccount`, which returns a `MaybeAccount` object with an `exists` boolean to indicate whether the account is present onchain:
```ts title="Web3.js" import { PublicKey } from '@solana/web3.js'; const wallet = new PublicKey('1234..5678'); const account = await connection.getAccountInfo(wallet); ``` ```ts twoslash title="Kit" import { address, assertAccountExists, fetchEncodedAccount } from '@solana/kit'; // ---cut-start--- import { createClient, generateKeyPairSigner } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signer } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const payer = await generateKeyPairSigner(); const client = createClient().use(signer(payer)).use(solanaDevnetRpc()).use(systemProgram()); // ---cut-end--- const wallet = address('1234..5678'); const account = await fetchEncodedAccount(client.rpc, wallet); assertAccountExists(account); account.data satisfies Uint8Array; ```
To decode raw account data, Kit provides a composable serialization library called **codecs**. You can define a codec for any account type by combining primitives: ```ts twoslash title="Kit" import { address, Address, addCodecSizePrefix, getAddressCodec, getStructCodec, getU32Codec, getU8Codec, getUtf8Codec, } from '@solana/kit'; type Person = { age: number; discriminator: number; name: string; wallet: Address; }; const personCodec = getStructCodec([ ['discriminator', getU8Codec()], // A single-byte account discriminator. ['wallet', getAddressCodec()], // A 32-byte account address. ['age', getU8Codec()], // An 8-bit unsigned integer. ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], // A UTF-8 string with a 32-bit length prefix. ]); const bytes = personCodec.encode({ age: 42, discriminator: 0, name: 'Alice', wallet: address('1234..5678'), }); ``` [You can read more about codecs here](/docs/advanced-guides/codecs). Once you have a codec, you can use `decodeAccount` to transform an encoded account into a decoded one: ```ts twoslash title="Kit" import { address, decodeAccount, fetchEncodedAccount } from '@solana/kit'; // ---cut-start--- import { Address, createSolanaRpc, addCodecSizePrefix, getAddressCodec, getStructCodec, getU32Codec, getU8Codec, getUtf8Codec, } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); type Person = { age: number; discriminator: number; name: string; wallet: Address; }; const personCodec = getStructCodec([ ['discriminator', getU8Codec()], ['wallet', getAddressCodec()], ['age', getU8Codec()], ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], ]); // ---cut-end--- const wallet = address('1234..5678'); const account = await fetchEncodedAccount(rpc, wallet); const decodedAccount = decodeAccount(account, personCodec); if (decodedAccount.exists) { decodedAccount.data satisfies Person; } ``` ## Using program libraries Fortunately, you don't need to create a custom codec for every account. Kit provides client libraries for many popular Solana programs, [generated via Codama](https://github.com/codama-idl/codama), ensuring a consistent structure across them. These libraries can be used as standalone imports or as client plugins. As client plugins, they add typed `.accounts` and `.instructions` namespaces to your client. For example, here's how to fetch and decode a `Nonce` account using the System program:
```ts title="Web3.js" import { NonceAccount, PublicKey } from '@solana/web3.js'; const wallet = new PublicKey('1234..5678'); const accountInfo = await connection.getAccountInfo(wallet); const nonce = NonceAccount.fromAccountData(accountInfo.data); ``` ```ts twoslash title="Kit" import { address } from '@solana/kit'; // ---cut-start--- import { createClient, generateKeyPairSigner } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signer } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const payer = await generateKeyPairSigner(); const client = createClient().use(signer(payer)).use(solanaDevnetRpc()).use(systemProgram()); // ---cut-end--- const nonce = await client.system.accounts.nonce.fetch(address('1234..5678')); ```
They can also be used as standalone functions without a client: ```ts twoslash title="Kit" import { address } from '@solana/kit'; import { fetchNonce } from '@solana-program/system'; // ---cut-start--- import { createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); // ---cut-end--- const account = await fetchNonce(rpc, address('1234..5678')); ``` [Check out the "Available plugins" page](/docs/plugins/available-plugins) for a list of available program libraries compatible with Kit. ## Creating instructions Program libraries also provide functions for creating instructions. With a client, you can create instructions through the program's typed namespace:
```ts title="Web3.js" 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. }); ``` ```ts twoslash title="Kit" import { address } from '@solana/kit'; // ---cut-start--- import { createClient, generateKeyPairSigner } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signer } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const payer = await generateKeyPairSigner(); const client = createClient().use(signer(payer)).use(solanaDevnetRpc()).use(systemProgram()); // ---cut-end--- const transferSol = client.system.instructions.transferSol({ source: client.payer, destination: address('3333..3333'), amount: 1_000_000_000, // 1 SOL. }); ```
Without a client, you can use the standalone instruction helpers directly. In this case, Kit uses `TransactionSigner` objects for accounts that need to sign. This allows signers to be extracted from built transactions later, enabling automatic transaction signing without manually tracking which keys need to sign. ```ts twoslash title="Kit" import { address, generateKeyPairSigner } from '@solana/kit'; import { getTransferSolInstruction } from '@solana-program/system'; const source = await generateKeyPairSigner(); const transferSol = getTransferSolInstruction({ source, destination: address('3333..3333'), amount: 1_000_000_000, // 1 SOL. }); ``` ## Sending transactions In Web3.js, sending a transaction involves creating a `Transaction` object, adding instructions, signing it, and sending it. Kit clients reduce this to a single call:
```ts title="Web3.js" import { Keypair, PublicKey, sendAndConfirmTransaction, SystemProgram, Transaction, } from '@solana/web3.js'; const payer = Keypair.generate(); const transaction = new Transaction().add( SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: new PublicKey('3333..3333'), lamports: 1_000_000_000, }), ); const signature = await sendAndConfirmTransaction(connection, transaction, [payer]); ``` ```ts twoslash title="Kit" import { address } from '@solana/kit'; // ---cut-start--- import { createClient, generateKeyPairSigner } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signer } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const payer = await generateKeyPairSigner(); const client = createClient().use(signer(payer)).use(solanaDevnetRpc()).use(systemProgram()); // ---cut-end--- const result = await client.system.instructions .transferSol({ source: client.payer, destination: address('3333..3333'), amount: 1_000_000_000, }) .sendTransaction(); const signature = result.context.signature; ```
With a client, building the transaction message, setting the fee payer, fetching a recent blockhash, signing, sending, and confirming are all handled for you. You can also send multiple instructions as a single atomic transaction using `client.sendTransaction([...])`: ```ts twoslash title="Kit" import { address } from '@solana/kit'; // ---cut-start--- import { createClient, generateKeyPairSigner } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signer } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const payer = await generateKeyPairSigner(); const client = createClient().use(signer(payer)).use(solanaDevnetRpc()).use(systemProgram()); // ---cut-end--- await client.sendTransaction([ client.system.instructions.transferSol({ source: client.payer, destination: address('3333..3333'), amount: 500_000_000, }), client.system.instructions.transferSol({ source: client.payer, destination: address('4444..4444'), amount: 500_000_000, }), ]); ``` For full control over each of these steps, you can build transactions manually. Kit uses an immutable transaction model where each helper returns a new transaction object with an updated type. The `pipe` function lets you chain these helpers together: ```ts twoslash title="Kit" import { appendTransactionMessageInstructions, assertIsTransactionWithBlockhashLifetime, createTransactionMessage, getSignatureFromTransaction, pipe, sendAndConfirmTransactionFactory, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, signTransactionMessageWithSigners, } from '@solana/kit'; import { getCreateAccountInstruction } from '@solana-program/system'; import { getInitializeMintInstruction, TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; // ---cut-start--- import { address, createSolanaRpc, createSolanaRpcSubscriptions, generateKeyPairSigner, } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); const space = null as unknown as Parameters[0]['space']; const lamports = null as unknown as Parameters[0]['lamports']; // ---cut-end--- // Create signers β€” Kit uses the native CryptoKeyPair API for secure key management. const [payer, mint] = await Promise.all([generateKeyPairSigner(), generateKeyPairSigner()]); // Create instructions β€” signers are attached directly to instructions. const createAccount = getCreateAccountInstruction({ payer, newAccount: mint, space, lamports, programAddress: TOKEN_PROGRAM_ADDRESS, }); const initializeMint = getInitializeMintInstruction({ mint: mint.address, mintAuthority: address('1234..5678'), decimals: 2, }); // Build the transaction message. const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(payer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions([createAccount, initializeMint], tx), ); // Sign β€” signers are extracted automatically from the transaction message. const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); // Send and confirm. assertIsTransactionWithBlockhashLifetime(signedTransaction); const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirm(signedTransaction, { commitment: 'confirmed' }); ``` A few things to note about the manual approach: * **Signers**: Kit uses `TransactionSigner` objects (highlighted above) instead of raw keypairs. Since signers are attached to instructions and the fee payer, `signTransactionMessageWithSigners` can sign the transaction automatically without needing to pass signers separately. [Read more about signers here](/docs/advanced-guides/signers). * **Immutability**: Each transaction helper returns a new object with a narrower type, ensuring that required fields (fee payer, lifetime, etc.) are set before the transaction can be signed or sent. The `pipe` function chains these transformations together. * **Signatures**: Transaction signatures are deterministically known before sending. The `getSignatureFromTransaction` helper extracts the signature from the signed transaction, and `sendAndConfirm` does not return it. ## Closing words We've now explored the key differences between Web3.js and Kit, giving you a solid foundation for upgrading your project. Since Kit is a complete rewrite, there's no simple step-by-step migration guide, and the process may take some time. To ease the transition, Kit provides a `@solana/compat` package, which allows for incremental migration. This package includes functions that convert core types β€” such as public keys and transactions β€” between Web3.js and Kit. This means you can start integrating Kit without having to refactor your entire project at once. ```ts twoslash title="Kit" import { Keypair, PublicKey } from '@solana/web3.js'; import { createSignerFromKeyPair } from '@solana/kit'; import { fromLegacyKeypair, fromLegacyPublicKey, fromLegacyTransactionInstruction, fromVersionedTransaction, } from '@solana/compat'; // ---cut-start--- const transactionInstruction = null as unknown as Parameters< typeof fromLegacyTransactionInstruction >[0]; const versionedTransaction = null as unknown as Parameters[0]; // ---cut-end--- // Convert `PublicKeys`. const address = fromLegacyPublicKey(new PublicKey('1234..5678')); // Convert `Keypairs`. const cryptoKeypair = await fromLegacyKeypair(Keypair.generate()); const signer = await createSignerFromKeyPair(cryptoKeypair); // Convert `TransactionInstruction`. const instruction = fromLegacyTransactionInstruction(transactionInstruction); // Convert `VersionedTransaction`. const transaction = fromVersionedTransaction(versionedTransaction); ``` If you're using a Kit client, the upgrade is even more straightforward β€” the client-based API is conceptually closer to Web3.js's `Connection` model while still giving you the benefits of Kit's modular architecture. Check out the [Getting Started](/docs/getting-started) tutorial to see the client-based approach in action or explore [Plugins](/docs/plugins) to learn more about the plugin system. # Codecs (/docs/advanced-guides/codecs) ## Introduction Kit includes a powerful serialisation system called Codecs. Whether you're working with account data, instruction arguments, or custom binary layouts, Codecs give you the tools to transform structured data into bytes β€” and back again. Codecs are composable, type-safe, and environment-agnostic. They are designed to provide a flexible and consistent foundation for handling binary data across the Solana stack. ## Installation Codecs are **included within the `@solana/kit` library** but you may also install them using their standalone package. ```bash npm install @solana/codecs ``` ```bash pnpm add @solana/codecs ``` ```bash yarn add @solana/codecs ``` ```bash bun add @solana/codecs ``` Note that the `@solana/codecs` package itself is composed of several smaller packages, each providing a different set of codec helpers. Here's the list of all packages containing codecs, should you need to install them individually: | Package | Description | | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | | [`@solana/kit`](https://www.npmjs.com/package/@solana/kit) | Includes `@solana/codecs`. | | [`@solana/codecs`](https://www.npmjs.com/package/@solana/codecs) | Includes all codecs packages below. | | [`@solana/codecs-core`](https://www.npmjs.com/package/@solana/codecs-core) | Core types and utilities for building codecs. | | [`@solana/codecs-numbers`](https://www.npmjs.com/package/@solana/codecs-numbers) | Codecs for numbers of various sizes and characteristics. | | [`@solana/codecs-strings`](https://www.npmjs.com/package/@solana/codecs-strings) | Codecs for strings of various encodings and size strategies. | | [`@solana/codecs-data-structures`](https://www.npmjs.com/package/@solana/codecs-data-structures) | Codecs for a variety of data structures such as objects, enums, arrays, maps, etc. | | [`@solana/options`](https://www.npmjs.com/package/@solana/options) | Codecs for Rust-like `Options` in JavaScript. | ## What is a Codec? A Codec is an object that knows how to encode a any type into a `Uint8Array` and how to decode a `Uint8Array` back into that value. No matter which serialization strategy we use, Codecs abstract away its implementation and offer a simple encode and decode interface. They are also highly composable, allowing us to build complex data structures from simple building blocks. Here's a quick example that encodes and decodes a simple `Person` type. ```ts twoslash import { Codec, addCodecSizePrefix, getUtf8Codec, getU32Codec, getStructCodec, ReadonlyUint8Array, } from '@solana/kit'; // ---cut-before--- // Use composable codecs to build complex data structures. type Person = { name: string; age: number }; const getPersonCodec = (): Codec => getStructCodec([ ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], ['age', getU32Codec()], ]); // Use your own codecs to encode and decode data. const personCodec = getPersonCodec(); const encodedPerson = personCodec.encode({ name: 'John', age: 42 }); const decodedPerson = personCodec.decode(encodedPerson); ``` ## Composing codecs The easiest way to create your own codecs is to compose the [various codecs](#available-codecs) at your disposal. For instance, consider the following codecs available: * `getStructCodec`: Creates a codec for objects with named fields. * `getU32Codec`: Creates a codec for unsigned 32-bit integers. * `getUtf8Codec`: Creates a codec for UTF-8 strings. * `addCodecSizePrefix`: Creates a codec that prefixes the encoded data with its length. * `getBooleanCodec`: Creates a codec for booleans using a single byte. By combining them together we can create a custom codec for the following `Person` type. ```ts twoslash import { Codec, addCodecSizePrefix, getUtf8Codec, getU32Codec, getStructCodec, getBooleanCodec, } from '@solana/kit'; // ---cut-before--- type Person = { name: string; age: number; verified: boolean; }; const getPersonCodec = (): Codec => getStructCodec([ ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], ['age', getU32Codec()], ['verified', getBooleanCodec()], ]); ``` This function returns a `Codec` object which contains both an `encode` and `decode` function that can be used to convert a `Person` type to and from a `Uint8Array`. ```ts twoslash import { Codec, addCodecSizePrefix, getUtf8Codec, getU32Codec, getStructCodec, getBooleanCodec, } from '@solana/kit'; type Person = { name: string; age: number; verified: boolean }; const getPersonCodec = (): Codec => getStructCodec([ ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], ['age', getU32Codec()], ['verified', getBooleanCodec()], ]); // ---cut-before--- const personCodec = getPersonCodec(); const bytes = personCodec.encode({ name: 'John', age: 42, verified: true }); const person = personCodec.decode(bytes); ``` There is a significant library of composable codecs at your disposal, enabling you to compose complex types. Check out the [available codecs](#available-codecs) section for more information. If you need a custom codec that cannot be composed from existing ones, you can always create your own as we will see in the ["Creating custom codecs"](#creating-custom-codecs) section below. ## Separate encoders and decoders Whilst Codecs can both encode and decode, it is possible to only focus on encoding or decoding data, enabling the unused logic to be tree-shaken. For instance, here's our previous example using Encoders only to encode a `Person` type. ```ts twoslash import { Encoder, addEncoderSizePrefix, getUtf8Encoder, getU32Encoder, getStructEncoder, getBooleanEncoder, } from '@solana/kit'; type Person = { name: string; age: number; verified: boolean }; // ---cut-before--- const getPersonEncoder = (): Encoder => getStructEncoder([ ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())], ['age', getU32Encoder()], ['verified', getBooleanEncoder()], ]); const bytes = getPersonEncoder().encode({ name: 'John', age: 42, verified: true }); ``` The same can be done for decoding the `Person` type by using Decoders like so. ```ts twoslash import { Decoder, addDecoderSizePrefix, getUtf8Decoder, getU32Decoder, getStructDecoder, getBooleanDecoder, } from '@solana/kit'; type Person = { name: string; age: number; verified: boolean }; const bytes = null as unknown as Uint8Array; // ---cut-before--- const getPersonDecoder = (): Decoder => getStructDecoder([ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())], ['age', getU32Decoder()], ['verified', getBooleanDecoder()], ]); const person = getPersonDecoder().decode(bytes); ``` ## Combining encoders and decoders Separating Codecs into Encoders and Decoders is particularly good practice for library maintainers as it allows their users to tree-shake any of the encoders and/or decoders they don't need. However, we may still want to offer a codec helper for users who need both for convenience. That's why this library offers a `combineCodec` helper that creates a `Codec` instance from a matching `Encoder` and `Decoder`. ```ts twoslash import { Codec, Encoder, Decoder, combineCodec } from '@solana/kit'; type Person = { name: string; age: number; verified: boolean }; const getPersonEncoder = null as unknown as () => Encoder; const getPersonDecoder = null as unknown as () => Decoder; // ---cut-before--- const getPersonCodec = (): Codec => combineCodec(getPersonEncoder(), getPersonDecoder()); ``` This means library maintainers can offer Encoders, Decoders and Codecs for all their types whilst staying efficient and tree-shakeable. In summary, we recommend the following pattern when creating codecs for library types. ```ts type MyType = /* ... */; const getMyTypeEncoder = (): Encoder => { /* ... */ }; const getMyTypeDecoder = (): Decoder => { /* ... */ }; const getMyTypeCodec = (): Codec => combineCodec( getMyTypeEncoder(), getMyTypeDecoder(), ); ``` ## Different `From` and `To` types When creating codecs, the encoded type is allowed to be looser than the decoded type. A good example of that is the u64 number codec: ```ts twoslash import { Codec, getU64Codec } from '@solana/kit'; // ---cut-before--- const u64Codec: Codec = getU64Codec(); ``` As you can see, the first type parameter is looser since it accepts numbers or big integers, whereas the second type parameter only accepts big integers. That's because when *encoding* a u64 number, you may provide either a `bigint` or a `number` for convenience. However, when you decode a u64 number, you will always get a `bigint` because not all u64 values can fit in a JavaScript `number` type. ```ts twoslash import { getU64Codec } from '@solana/kit'; const u64Codec = getU64Codec(); // ---cut-before--- const bytes = u64Codec.encode(42); const value = u64Codec.decode(bytes); // BigInt(42) ``` This relationship between the type we encode β€œFrom” and decode β€œTo” can be generalized in TypeScript as `To extends From`. Here's another example using an object with default values. You can read more about the [transformCodec](#transform-codec) helper below. ```ts twoslash import { Codec, Encoder, Decoder, transformEncoder, getStructEncoder, getStructDecoder, addEncoderSizePrefix, addDecoderSizePrefix, getUtf8Encoder, getUtf8Decoder, getU32Encoder, getU32Decoder, combineCodec, } from '@solana/kit'; // ---cut-before--- type Person = { name: string; age: number }; type PersonInput = { name: string; age?: number }; const getPersonEncoder = (): Encoder => transformEncoder( getStructEncoder([ ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())], ['age', getU32Encoder()], ]), (input) => ({ ...input, age: input.age ?? 42 }), ); const getPersonDecoder = (): Decoder => getStructDecoder([ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())], ['age', getU32Decoder()], ]); const getPersonCodec = (): Codec => combineCodec(getPersonEncoder(), getPersonDecoder()); ``` ## Fixed-size and variable-size codecs It is also worth noting that Codecs can either be of fixed size or variable size. `FixedSizeCodecs` have a `fixedSize` number attribute that tells us exactly how big their encoded data is in bytes. ```ts twoslash import { FixedSizeCodec, getU32Codec } from '@solana/kit'; // ---cut-before--- const myCodec = getU32Codec(); myCodec satisfies FixedSizeCodec; myCodec.fixedSize; // 4 bytes. ``` On the other hand, `VariableSizeCodecs` do not know the size of their encoded data in advance. Instead, they will grab that information either from the provided encoded data or from the value to encode. For the former, we can simply access the length of the `Uint8Array`. For the latter, it provides a `getSizeFromValue` that tells us the encoded byte size of the provided value. ```ts twoslash import { VariableSizeCodec, getUtf8Codec, getU32Codec, addCodecSizePrefix } from '@solana/kit'; // ---cut-before--- const myCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); myCodec satisfies VariableSizeCodec; myCodec.getSizeFromValue('hello world'); // 4 + 11 bytes. ``` Also note that, if the `VariableSizeCodec` is bounded by a maximum size, it can be provided as a `maxSize` number attribute. The following type guards are available to identify and/or assert the size of codecs: `isFixedSize`, `isVariableSize`, `assertIsFixedSize` and `assertIsVariableSize`. Finally, note that the same is true for `Encoders` and `Decoders`. * A `FixedSizeEncoder` has a `fixedSize` number attribute. * A `VariableSizeEncoder` has a `getSizeFromValue` function and an optional `maxSize` number attribute. * A `FixedSizeDecoder` has a `fixedSize` number attribute. * A `VariableSizeDecoder` has an optional `maxSize` number attribute. ## Creating custom codecs If composing codecs isn't enough for you, you may implement your own codec logic by using the `createCodec` function. This function requires an object with a `read` and a `write` function telling us how to read from and write to an existing byte array. The `read` function accepts the `bytes` to decode from and the `offset` at each we should start reading. It returns an array with two items: * The first item should be the decoded value. * The second item should be the next offset to read from. ```ts twoslash import { createCodec, Offset } from '@solana/kit'; const write = null as unknown as Parameters>[0]['write']; const fixedSize = null as unknown as 1; // ---cut-before--- createCodec({ read(bytes, offset) { const value = bytes[offset]; return [value, offset + 1]; }, write, fixedSize, }); ``` Reciprocally, the `write` function accepts the `value` to encode, the array of `bytes` to write the encoded value to and the `offset` at which it should be written. It should encode the given value, insert it in the byte array, and provide the next offset to write to as the return value. ```ts twoslash import { createCodec } from '@solana/kit'; const read = null as unknown as Parameters>[0]['read']; const fixedSize = null as unknown as 1; // ---cut-before--- createCodec({ write(value: number, bytes, offset) { bytes.set([value], offset); return offset + 1; }, read, fixedSize, }); ``` Additionally, we must specify the size of the codec. If we are defining a `FixedSizeCodec`, we must simply provide the `fixedSize` number attribute. For `VariableSizeCodecs`, we must provide the `getSizeFromValue` function as described in the previous section. ```ts twoslash import { createCodec } from '@solana/kit'; type Config = Parameters>[0]; const read = null as unknown as Config['read']; const write = null as unknown as Config['write']; // ---cut-before--- // FixedSizeCodec. createCodec({ fixedSize: 1, read, write, }); // VariableSizeCodec. createCodec({ getSizeFromValue: (value: string) => value.length, read, write, }); ``` Here's a concrete example of a custom codec that encodes any unsigned integer in a single byte. Since a single byte can only store integers from 0 to 255, if any other integer is provided it will take its modulo 256 to ensure it fits in a single byte. Because it always requires a single byte, that codec is a `FixedSizeCodec` of size `1`. ```ts twoslash import { createCodec } from '@solana/kit'; const getModuloU8Codec = () => createCodec({ fixedSize: 1, read(bytes, offset) { const value = bytes[offset]; return [value, offset + 1]; }, write(value, bytes, offset) { bytes.set([value % 256], offset); return offset + 1; }, }); ``` Note that, it is also possible to create custom encoders and decoders separately by using the `createEncoder` and `createDecoder` functions respectively and then use the `combineCodec` function on them just like we were doing with composed codecs. This approach is recommended to library maintainers as it allows their users to tree-shake any of the encoders and/or decoders they don't need. Here's our previous modulo u8 example but split into separate `Encoder`, `Decoder` and `Codec` instances. ```ts twoslash import { createEncoder, createDecoder, combineCodec } from '@solana/kit'; const getModuloU8Encoder = () => createEncoder({ fixedSize: 1, write(value, bytes, offset) { bytes.set([value % 256], offset); return offset + 1; }, }); const getModuloU8Decoder = () => createDecoder({ fixedSize: 1, read(bytes, offset) { const value = bytes[offset]; return [value, offset + 1]; }, }); const getModuloU8Codec = () => combineCodec(getModuloU8Encoder(), getModuloU8Decoder()); ``` Here's another example returning a `VariableSizeCodec`. This one transforms a simple string composed of characters from `a` to `z` to a buffer of numbers from `1` to `26` where `0` bytes are spaces. ```ts twoslash import { createEncoder, createDecoder, combineCodec } from '@solana/kit'; const alphabet = ' abcdefghijklmnopqrstuvwxyz'; const getCipherEncoder = () => createEncoder({ getSizeFromValue: (value) => value.length, write(value, bytes, offset) { const bytesToAdd = [...value].map((char) => alphabet.indexOf(char)); bytes.set(bytesToAdd, offset); return offset + bytesToAdd.length; }, }); const getCipherDecoder = () => createDecoder({ read(bytes, offset) { const value = [...bytes.slice(offset)].map((byte) => alphabet.charAt(byte)).join(''); return [value, bytes.length]; }, }); const getCipherCodec = () => combineCodec(getCipherEncoder(), getCipherDecoder()); ``` ## Available codecs ### Core utilities
[addCodecSentinel](#add-codec-sentinel) \ [addCodecSizePrefix](#add-codec-size-prefix) \ [containsBytes](#contains-bytes) \ [fixBytes](#fix-bytes) \ [fixCodecSize](#fix-codec-size) \ [mergeBytes](#merge-bytes) \ [offsetCodec](#offset-codec) \ [padBytes](#pad-bytes) \ [padLeftCodec](#pad-left-codec) \ [padRightCodec](#pad-right-codec) \ [resizeCodec](#resize-codec) \ [reverseCodec](#reverse-codec) \ [transformCodec](#transform-codec)
### Numbers
[getI8Codec](#get-i8-codec) \ [getI16Codec](#get-i16-codec) \ [getI32Codec](#get-i32-codec) \ [getI64Codec](#get-i64-codec) \ [getI128Codec](#get-i128-codec) \ [getF32Codec](#get-f32-codec) \ [getF64Codec](#get-f64-codec) \ [getShortU16Codec](#get-short-u16-codec) \ [getU8Codec](#get-u8-codec) \ [getU16Codec](#get-u16-codec) \ [getU32Codec](#get-u32-codec) \ [getU64Codec](#get-u64-codec) \ [getU128Codec](#get-u128-codec)
### Strings
[getBase10Codec](#get-base10-codec) \ [getBase16Codec](#get-base16-codec) \ [getBase58Codec](#get-base58-codec) \ [getBase64Codec](#get-base64-codec) \ [getBaseXCodec](#get-baseX-codec) \ [getBaseXResliceCodec](#get-baseX-reslice-codec) \ [getUtf8Codec](#get-utf8-codec)
### Data structures
[getArrayCodec](#get-array-codec) \ [getBitArrayCodec](#get-bit-array-codec) \ [getBooleanCodec](#get-boolean-codec) \ [getBytesCodec](#get-bytes-codec) \ [getConstantCodec](#get-constant-codec) \ [getDiscriminatedUnionCodec](#get-discriminated-union-codec) \ [getEnumCodec](#get-enum-codec) \ [getHiddenPrefixCodec](#get-hidden-prefix-codec) \ [getHiddenSuffixCodec](#get-hidden-suffix-codec) \ [getLiteralUnionCodec](#get-literal-union-codec) \ [getMapCodec](#get-map-codec) \ [getNullableCodec](#get-nullable-codec) \ [getOptionCodec](#get-option-codec) \ [getPatternMatchCodec](#get-pattern-match-codec) \ [getPredicateCodec](#get-predicate-codec) \ [getSetCodec](#get-set-codec) \ [getStructCodec](#get-struct-codec) \ [getTupleCodec](#get-tuple-codec) \ [getUnionCodec](#get-union-codec) \ [getUnitCodec](#get-unit-codec)
## Core utilities listing \[!toc] ### addCodecSentinel \[!toc] One way of delimiting the size of a codec is to use sentinels. The `addCodecSentinel` function allows us to add a sentinel to the end of the encoded data and to read until that sentinel is found when decoding. It accepts any codec and a `Uint8Array` sentinel responsible for delimiting the encoded data. ```ts twoslash import { addCodecSentinel, getUtf8Codec } from '@solana/kit'; // ---cut-before--- const codec = addCodecSentinel(getUtf8Codec(), new Uint8Array([255, 255])); codec.encode('hello'); // 0x68656c6c6fffff // | β””-- Our sentinel. // β””-- Our encoded string. ``` Note that the sentinel *must not* be present in the encoded data and *must* be present in the decoded data for this to work. If this is not the case, dedicated errors will be thrown. ```ts twoslash import { addCodecSentinel, getUtf8Codec } from '@solana/kit'; // ---cut-before--- const sentinel = new Uint8Array([108, 108]); // 'll' const codec = addCodecSentinel(getUtf8Codec(), sentinel); codec.encode('hello'); // Throws: sentinel is in encoded data. codec.decode(new Uint8Array([1, 2, 3])); // Throws: sentinel missing in decoded data. ``` Separate `addEncoderSentinel` and `addDecoderSentinel` functions are also available. ```ts twoslash import { addEncoderSentinel, addDecoderSentinel, getUtf8Encoder, getUtf8Decoder, } from '@solana/kit'; const sentinel = null as unknown as Uint8Array; // ---cut-before--- const bytes = addEncoderSentinel(getUtf8Encoder(), sentinel).encode('hello'); const value = addDecoderSentinel(getUtf8Decoder(), sentinel).decode(bytes); ``` ### addCodecSizePrefix \[!toc] The `addCodecSizePrefix` function allows us to store the byte size of any codec as a number prefix, enabling us to contain variable-size codecs to their actual size. When encoding, the size of the encoded data is stored before the encoded data itself. When decoding, the size is read first to know how many bytes to read next. For example, say we want to represent a variable-size base-58 string using a `u32` size prefix. Here's how we can use the `addCodecSizePrefix` function to achieve that. ```ts twoslash import { addCodecSizePrefix, getBase58Codec, getU32Codec } from '@solana/kit'; // ---cut-before--- const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec()); getU32Base58Codec().encode('hello world'); // 0x0b00000068656c6c6f20776f726c64 // | β””-- Our encoded base-58 string. // β””-- Our encoded u32 size prefix. ``` You may also use the `addEncoderSizePrefix` and `addDecoderSizePrefix` functions to separate your codec logic like so: ```ts twoslash import { addEncoderSizePrefix, addDecoderSizePrefix, getBase58Encoder, getBase58Decoder, getU32Encoder, getU32Decoder, combineCodec, } from '@solana/kit'; // ---cut-before--- const getU32Base58Encoder = () => addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()); const getU32Base58Decoder = () => addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()); const getU32Base58Codec = () => combineCodec(getU32Base58Encoder(), getU32Base58Decoder()); ``` ### containsBytes \[!toc] Checks if a `Uint8Array` contains another `Uint8Array` at a given offset. ```ts twoslash 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 ``` ### fixBytes \[!toc] Pads or truncates a `Uint8Array` so it has the specified length. ```ts twoslash import { fixBytes } from '@solana/kit'; // ---cut-before--- fixBytes(new Uint8Array([1, 2]), 4); // Uint8Array([1, 2, 0, 0]) fixBytes(new Uint8Array([1, 2, 3, 4]), 2); // Uint8Array([1, 2]) ``` ### fixCodecSize \[!toc] The `fixCodecSize` function allows us to bind the size of a given codec to the given fixed size. For instance, say we wanted to represent a base-58 string that uses exactly 32 bytes when decoded. Here's how we can use the `fixCodecSize` helper to achieve that. ```ts twoslash import { fixCodecSize, getBase58Codec } from '@solana/kit'; // ---cut-before--- const get32BytesBase58Codec = () => fixCodecSize(getBase58Codec(), 32); ``` You may also use the `fixEncoderSize` and `fixDecoderSize` functions to separate your codec logic like so: ```ts twoslash import { fixEncoderSize, fixDecoderSize, getBase58Encoder, getBase58Decoder, combineCodec, } from '@solana/kit'; // ---cut-before--- const get32BytesBase58Encoder = () => fixEncoderSize(getBase58Encoder(), 32); const get32BytesBase58Decoder = () => fixDecoderSize(getBase58Decoder(), 32); const get32BytesBase58Codec = () => combineCodec(get32BytesBase58Encoder(), get32BytesBase58Decoder()); ``` ### mergeBytes \[!toc] Concatenates an array of `Uint8Arrays` into a single `Uint8Array`. ```ts twoslash import { mergeBytes } from '@solana/kit'; // ---cut-before--- const bytes1 = new Uint8Array([0x01, 0x02]); const bytes2 = new Uint8Array([]); const bytes3 = new Uint8Array([0x03, 0x04]); const bytes = mergeBytes([bytes1, bytes2, bytes3]); // ^ [0x01, 0x02, 0x03, 0x04] ``` ### offsetCodec \[!toc] The `offsetCodec` function is a powerful codec primitive that allows us to move the offset of a given codec forward or backwards. It accepts one or two functions that takes the current offset and returns a new offset. To understand how this works, let's take the following `biggerU32Codec` example which encodes a `u32` number inside an 8-byte buffer by using the [resizeCodec](#resize-codec) helper. ```ts twoslash import { resizeCodec, getU32Codec } from '@solana/kit'; // ---cut-before--- const biggerU32Codec = resizeCodec(getU32Codec(), (size) => size + 4); biggerU32Codec.encode(0xffffffff); // 0xffffffff00000000 // | β””-- Empty buffer space caused by the resizeCodec function. // β””-- Our encoded u32 number. ``` Now, let's say we want to move the offset of that codec 2 bytes forward so that the encoded number sits in the middle of the buffer. To achieve, this we can use the `offsetCodec` helper and provide a `preOffset` function that moves the "pre-offset" of the codec 2 bytes forward. ```ts twoslash import { offsetCodec, resizeCodec, getU32Codec } from '@solana/kit'; const biggerU32Codec = resizeCodec(getU32Codec(), (size) => size + 4); // ---cut-before--- const u32InTheMiddleCodec = offsetCodec(biggerU32Codec, { preOffset: ({ preOffset }) => preOffset + 2, }); u32InTheMiddleCodec.encode(0xffffffff); // 0x0000ffffffff0000 // β””-- Our encoded u32 number is now in the middle of the buffer. ``` We refer to this offset as the "pre-offset" because, once the inner codec is encoded or decoded, an additional offset will be returned which we refer to as the "post-offset". That "post-offset" is important as, unless we are reaching the end of our codec, it will be used by any further codecs to continue encoding or decoding data. By default, that "post-offset" is simply the addition of the "pre-offset" and the size of the encoded or decoded inner data. ```ts twoslash import { offsetCodec, resizeCodec, getU32Codec } from '@solana/kit'; const biggerU32Codec = resizeCodec(getU32Codec(), (size) => size + 4); // ---cut-before--- const u32InTheMiddleCodec = offsetCodec(biggerU32Codec, { preOffset: ({ preOffset }) => preOffset + 2, }); u32InTheMiddleCodec.encode(0xffffffff); // 0x0000ffffffff0000 // | | β””-- Post-offset. // | β””-- New pre-offset: The original pre-offset + 2. // β””-- Pre-offset: The original pre-offset before we adjusted it. ``` However, you may also provide a `postOffset` function to adjust the "post-offset". For instance, let's push the "post-offset" 2 bytes forward as well such that any further codecs will start doing their job at the end of our 8-byte `u32` number. ```ts twoslash import { offsetCodec, resizeCodec, getU32Codec } from '@solana/kit'; const biggerU32Codec = resizeCodec(getU32Codec(), (size) => size + 4); // ---cut-before--- const u32InTheMiddleCodec = offsetCodec(biggerU32Codec, { preOffset: ({ preOffset }) => preOffset + 2, postOffset: ({ postOffset }) => postOffset + 2, }); u32InTheMiddleCodec.encode(0xffffffff); // 0x0000ffffffff0000 // | | | β””-- New post-offset: The original post-offset + 2. // | | β””-- Post-offset: The original post-offset before we adjusted it. // | β””-- New pre-offset: The original pre-offset + 2. // β””-- Pre-offset: The original pre-offset before we adjusted it. ``` Both the `preOffset` and `postOffset` functions offer the following attributes: * `bytes`: The entire byte array being encoded or decoded. * `preOffset`: The original and unaltered pre-offset. * `wrapBytes`: A helper function that wraps the given offset around the byte array length. E.g. `wrapBytes(-1)` will refer to the last byte of the byte array. Additionally, the post-offset function also provides the following attributes: * `newPreOffset`: The new pre-offset after the pre-offset function has been applied. * `postOffset`: The original and unaltered post-offset. Note that you may also decide to ignore these attributes to achieve absolute offsets. However, relative offsets are usually recommended as they won't break your codecs when composed with other codecs. ```ts twoslash import { offsetCodec, resizeCodec, getU32Codec } from '@solana/kit'; const biggerU32Codec = resizeCodec(getU32Codec(), (size) => size + 4); // ---cut-before--- const u32InTheMiddleCodec = offsetCodec(biggerU32Codec, { preOffset: () => 2, postOffset: () => 8, }); u32InTheMiddleCodec.encode(0xffffffff); // 0x0000ffffffff0000 ``` Also note that any negative offset or offset that exceeds the size of the byte array will throw a `SolanaError` of code `SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE`. ```ts twoslash 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); // throws new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE) ``` To avoid this, you may use the `wrapBytes` function to wrap the offset around the byte array length. For instance, here's how we can use the `wrapBytes` function to move the pre-offset 4 bytes from the end of the byte array. ```ts twoslash import { offsetCodec, resizeCodec, getU32Codec } from '@solana/kit'; const biggerU32Codec = resizeCodec(getU32Codec(), (size) => size + 4); // ---cut-before--- const u32InTheEndCodec = offsetCodec(biggerU32Codec, { preOffset: ({ wrapBytes }) => wrapBytes(-4), }); u32InTheEndCodec.encode(0xffffffff); // 0x00000000ffffffff ``` As you can see, the `offsetCodec` helper allows you to jump all over the place with your codecs. This non-linear approach to encoding and decoding data allows you to achieve complex serialization strategies that would otherwise be impossible. The `offsetEncoder` and `offsetDecoder` functions can also be used to split your codec logic into tree-shakeable functions. ```ts twoslash import { offsetEncoder, resizeEncoder, getU32Encoder, offsetDecoder, resizeDecoder, getU32Decoder, combineCodec, } from '@solana/kit'; const biggerU32Encoder = resizeEncoder(getU32Encoder(), (size) => size + 4); const biggerU32Decoder = resizeDecoder(getU32Decoder(), (size) => size + 4); // ---cut-before--- const getU32InTheMiddleEncoder = () => offsetEncoder(biggerU32Encoder, { preOffset: ({ preOffset }) => preOffset + 2 }); const getU32InTheMiddleDecoder = () => offsetDecoder(biggerU32Decoder, { preOffset: ({ preOffset }) => preOffset + 2 }); const getU32InTheMiddleCodec = () => combineCodec(getU32InTheMiddleEncoder(), getU32InTheMiddleDecoder()); ``` ### padBytes \[!toc] Pads a `Uint8Array` with zeroes (to the right) to the specified length. ```ts twoslash import { padBytes } from '@solana/kit'; // ---cut-before--- padBytes(new Uint8Array([1, 2]), 4); // Uint8Array([1, 2, 0, 0]) padBytes(new Uint8Array([1, 2, 3, 4]), 2); // Uint8Array([1, 2, 3, 4]) ``` ### padLeftCodec \[!toc] The `padLeftCodec` helper can be used to add padding to the left of a given codec. It accepts an `offset` number that tells us how big the padding should be. ```ts twoslash import { padLeftCodec, getU16Codec } from '@solana/kit'; // ---cut-before--- const leftPaddedCodec = padLeftCodec(getU16Codec(), 4); leftPaddedCodec.encode(0xffff); // 0x00000000ffff // | β””-- Our encoded u16 number. // β””-- Our 4-byte padding. ``` Note that the `padLeftCodec` function is a simple wrapper around the `offsetCodec` and `resizeCodec` functions. For more complex padding strategies, you may want to use the [offsetCodec](#offset-codec) and [resizeCodec](#resize-codec) functions directly instead. Encoder-only and decoder-only helpers are available for these padding functions. ```ts twoslash import { padLeftEncoder, padLeftDecoder, getU16Encoder, getU16Decoder, combineCodec, } from '@solana/kit'; // ---cut-before--- const getMyPaddedEncoder = () => padLeftEncoder(getU16Encoder(), 6); const getMyPaddedDecoder = () => padLeftDecoder(getU16Decoder(), 6); const getMyPaddedCodec = () => combineCodec(getMyPaddedEncoder(), getMyPaddedDecoder()); ``` ### padRightCodec \[!toc] The `padRightCodec` helper can be used to add padding to the right of a given codec. It accepts an `offset` number that tells us how big the padding should be. ```ts twoslash import { padRightCodec, getU16Codec } from '@solana/kit'; // ---cut-before--- const rightPaddedCodec = padRightCodec(getU16Codec(), 4); rightPaddedCodec.encode(0xffff); // 0xffff00000000 // | β””-- Our 4-byte padding. // β””-- Our encoded u16 number. ``` Note that the `padRightCodec` function is a simple wrapper around the `offsetCodec` and `resizeCodec` functions. For more complex padding strategies, you may want to use the [offsetCodec](#offset-codec) and [resizeCodec](#resize-codec) functions directly instead. Encoder-only and decoder-only helpers are available for these padding functions. ```ts twoslash import { padRightEncoder, padRightDecoder, getU16Encoder, getU16Decoder, combineCodec, } from '@solana/kit'; // ---cut-before--- const getMyPaddedEncoder = () => padRightEncoder(getU16Encoder(), 6); const getMyPaddedDecoder = () => padRightDecoder(getU16Decoder(), 6); const getMyPaddedCodec = () => combineCodec(getMyPaddedEncoder(), getMyPaddedDecoder()); ``` ### resizeCodec \[!toc] The `resizeCodec` helper re-defines the size of a given codec by accepting a function that takes the current size of the codec and returns a new size. This works for both fixed-size and variable-size codecs. ```ts twoslash import { resizeCodec, getU32Codec, getUtf8Codec } from '@solana/kit'; // ---cut-before--- // Fixed-size codec. const getBiggerU32Codec = () => resizeCodec(getU32Codec(), (size) => size + 4); getBiggerU32Codec().encode(42); // 0x2a00000000000000 // | β””-- Empty buffer space caused by the resizeCodec function. // β””-- Our encoded u32 number. // Variable-size codec. const getBiggerUtf8Codec = () => resizeCodec(getUtf8Codec(), (size) => size + 4); getBiggerUtf8Codec().encode('ABC'); // 0x41424300000000 // | β””-- Empty buffer space caused by the resizeCodec function. // β””-- Our encoded string. ``` Note that the `resizeCodec` function doesn't change any encoded or decoded bytes, it merely tells the `encode` and `decode` functions how big the `Uint8Array` should be before delegating to their respective `write` and `read` functions. In fact, this is completely bypassed when using the `write` and `read` functions directly. For instance: ```ts twoslash import { resizeCodec, getU32Codec } from '@solana/kit'; // ---cut-before--- const getBiggerU32Codec = () => resizeCodec(getU32Codec(), (size) => size + 4); // Using the encode function. getBiggerU32Codec().encode(42); // 0x2a00000000000000 // Using the lower-level write function. const myCustomBytes = new Uint8Array(4); getBiggerU32Codec().write(42, myCustomBytes, 0); // 0x2a000000 ``` So when would it make sense to use the `resizeCodec` function? This function is particularly useful when combined with the [offsetCodec](#offset-codec) function. Whilst `offsetCodec` may help us push the offset forward β€” e.g. to skip some padding β€” it won't change the size of the encoded data which means the last bytes will be truncated by how much we pushed the offset forward. The `resizeCodec` function can be used to fix that. For instance, here's how we can use the `resizeCodec` and the `offsetCodec` functions together to create a struct codec that includes some padding. ```ts twoslash import { getStructCodec, getUtf8Codec, getU32Codec, offsetCodec, resizeCodec, fixCodecSize, } from '@solana/kit'; // ---cut-before--- const personCodec = getStructCodec([ ['name', fixCodecSize(getUtf8Codec(), 8)], // There is a 4-byte padding between name and age. [ 'age', offsetCodec( resizeCodec(getU32Codec(), (size) => size + 4), { preOffset: ({ preOffset }) => preOffset + 4 }, ), ], ]); personCodec.encode({ name: 'Alice', age: 42 }); // 0x416c696365000000000000002a000000 // | | β””-- Our encoded u32 (42). // | β””-- The 4-bytes of padding we are skipping. // β””-- Our 8-byte encoded string ("Alice"). ``` Note that this can be achieved using the [padLeftCodec](#pad-left-codec) helper which is implemented that way. The `resizeEncoder` and `resizeDecoder` functions can also be used to split your codec logic into tree-shakeable functions. ```ts twoslash import { resizeEncoder, resizeDecoder, getU32Encoder, getU32Decoder, combineCodec, } from '@solana/kit'; // ---cut-before--- const getBiggerU32Encoder = () => resizeEncoder(getU32Encoder(), (size) => size + 4); const getBiggerU32Decoder = () => resizeDecoder(getU32Decoder(), (size) => size + 4); const getBiggerU32Codec = () => combineCodec(getBiggerU32Encoder(), getBiggerU32Decoder()); ``` ### reverseCodec \[!toc] The `reverseCodec` helper reverses the bytes of the provided `FixedSizeCodec`. ```ts twoslash import { reverseCodec, getU64Codec } from '@solana/kit'; // ---cut-before--- const getBigEndianU64Codec = () => reverseCodec(getU64Codec()); ``` Note that number codecs can already do that for you via their `endian` option. ```ts twoslash import { getU64Codec, Endian } from '@solana/kit'; // ---cut-before--- const getBigEndianU64Codec = () => getU64Codec({ endian: Endian.Big }); ``` The `reverseEncoder` and `reverseDecoder` functions can also be used to achieve that. ```ts twoslash import { reverseEncoder, reverseDecoder, getU64Encoder, getU64Decoder, combineCodec, } from '@solana/kit'; // ---cut-before--- const getBigEndianU64Encoder = () => reverseEncoder(getU64Encoder()); const getBigEndianU64Decoder = () => reverseDecoder(getU64Decoder()); const getBigEndianU64Codec = () => combineCodec(getBigEndianU64Encoder(), getBigEndianU64Decoder()); ``` ### transformCodec \[!toc] It is possible to transform a `Codec` to a `Codec` by providing two mapping functions: one that goes from `T` to `U` and one that does the opposite. For instance, here's how you would map a `u32` integer into a `string` representation of that number. ```ts twoslash import { transformCodec, getU32Codec } from '@solana/kit'; // ---cut-before--- const getStringU32Codec = () => transformCodec( getU32Codec(), (integerAsString: string): number => parseInt(integerAsString), (integer: number): string => integer.toString(), ); getStringU32Codec().encode('42'); // new Uint8Array([42]) getStringU32Codec().decode(new Uint8Array([42])); // "42" ``` If a `Codec` has [different From and To types](#different-from-and-to-types), say `Codec`, and we want to map it to `Codec`, we must provide functions that map from `NewFrom` to `OldFrom` and from `OldTo` to `NewTo`. To illustrate that, let's take our previous `getStringU32Codec` example but make it use a `getU64Codec` codec instead as it returns a `Codec`. Additionally, let's make it so our `getStringU64Codec` function returns a `Codec` so that it also accepts numbers when encoding values. Here's what our mapping functions look like: ```ts twoslash import { transformCodec, getU64Codec } from '@solana/kit'; // ---cut-before--- const getStringU64Codec = () => transformCodec( getU64Codec(), (integerInput: number | string): number | bigint => typeof integerInput === 'string' ? BigInt(integerInput) : integerInput, (integer: bigint): string => integer.toString(), ); ``` Note that the second function that maps the decoded type is optional. That means, you can omit it to simply update or loosen the type to encode whilst keeping the decoded type the same. This is particularly useful to provide default values to object structures. For instance, here's how we can map a `Person` codec to give a default value to its `age` attribute. ```ts twoslash import { transformCodec, getStructCodec, Codec } from '@solana/kit'; // ---cut-before--- type Person = { name: string; age: number }; type PersonInput = { name: string; age?: number }; // ---cut-start--- const getPersonCodec = null as unknown as () => Codec; // ---cut-end--- const getPersonWithDefaultValueCodec = (): Codec => transformCodec( getPersonCodec(), (person: PersonInput): Person => ({ ...person, age: person.age ?? 42 }), ); ``` Similar helpers exist to map `Encoder` and `Decoder` instances allowing you to separate your codec logic into tree-shakeable functions. Here's our `getStringU32Codec` written that way. ```ts twoslash import { transformEncoder, transformDecoder, getU32Encoder, getU32Decoder, combineCodec, } from '@solana/kit'; // ---cut-before--- const getStringU32Encoder = () => transformEncoder(getU32Encoder(), (integerAsString: string): number => parseInt(integerAsString), ); const getStringU32Decoder = () => transformDecoder(getU32Decoder(), (integer: number): string => integer.toString()); const getStringU32Codec = () => combineCodec(getStringU32Encoder(), getStringU32Decoder()); ``` ## Numbers listing \[!toc] ### getI8Codec \[!toc] Encodes and decodes **signed 8-bit integers**. It supports values from -127 (`-2^7`) to 128 (`2^7 - 1`). Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. ```ts twoslash import { getI8Codec } from '@solana/kit'; // ---cut-before--- const codec = getI8Codec(); const bytes = codec.encode(-42); // 0xd6 const value = codec.decode(bytes); // -42 ``` `getI8Encoder` and `getI8Decoder` functions are also available. ### getI16Codec \[!toc] Encodes and decodes **signed 16-bit integers**. It supports values from -32,768 (`-2^15`) to 32,767 (`2^15 - 1`). Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getI16Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getI16Codec(); const bytes = codec.encode(-42); // 0xd6ff const value = codec.decode(bytes); // -42 // Big-endian. const beCodec = getI16Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(-42); // 0xffd6 const beValue = beCodec.decode(bytes); // -42 ``` `getI16Encoder` and `getI16Decoder` functions are also available. ### getI32Codec \[!toc] Encodes and decodes **signed 32-bit integers**. It supports values from -2,147,483,648 (`-2^31`) to 2,147,483,647 (`2^31 - 1`). Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getI32Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getI32Codec(); const bytes = codec.encode(-42); // 0xd6ffffff const value = codec.decode(bytes); // -42 // Big-endian. const beCodec = getI32Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(-42); // 0xffffffd6 const beValue = beCodec.decode(bytes); // -42 ``` `getI32Encoder` and `getI32Decoder` functions are also available. ### getI64Codec \[!toc] Encodes and decodes **signed 64-bit integers**. It supports values from `-2^63` to `2^63 - 1`. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getI64Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getI64Codec(); const bytes = codec.encode(-42); // 0xd6ffffffffffffff const value = codec.decode(bytes); // BigInt(-42) // Big-endian. const beCodec = getI64Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(-42); // 0xffffffffffffffd6 const beValue = beCodec.decode(bytes); // BigInt(-42) ``` `getI64Encoder` and `getI64Decoder` functions are also available. ### getI128Codec \[!toc] Encodes and decodes **signed 128-bit integers**. It supports values from `-2^127` to `2^127 - 1`. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getI128Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getI128Codec(); const bytes = codec.encode(-42); // 0xd6ffffffffffffffffffffffffffffff const value = codec.decode(bytes); // BigInt(-42) // Big-endian. const beCodec = getI128Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(-42); // 0xffffffffffffffffffffffffffffffd6 const beValue = beCodec.decode(bytes); // BigInt(-42) ``` `getI128Encoder` and `getI128Decoder` functions are also available. ### getF32Codec \[!toc] Encodes and decodes **32-bit floating-point numbers**. Due to the [IEEE 754](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) floating-point representation, some precision loss may occur. Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getF32Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getF32Codec(); const bytes = codec.encode(-1.5); // 0x0000c0bf const value = codec.decode(bytes); // -1.5 // Big-endian. const beCodec = getF32Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(-1.5); // 0xbfc00000 const beValue = beCodec.decode(bytes); // -1.5 ``` `getF32Encoder` and `getF32Decoder` functions are also available. ### getF64Codec \[!toc] Encodes and decodes **64-bit floating-point numbers**. Due to the [IEEE 754](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) floating-point representation, some precision loss may occur. Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getF64Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getF64Codec(); const bytes = codec.encode(-1.5); // 0x000000000000f8bf const value = codec.decode(bytes); // -1.5 // Big-endian. const beCodec = getF64Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(-1.5); // 0xbff8000000000000 const beValue = beCodec.decode(bytes); // -1.5 ``` `getF64Encoder` and `getF64Decoder` functions are also available. ### getShortU16Codec \[!toc] Encodes and decodes **unsigned integer using 1 to 3 bytes** based on the encoded value. It supports values from 0 to 4,194,303 (`2^22 - 1`). The larger the value, the more bytes it uses. * If the value is `<= 0x7f` (127), it is stored in a **single byte** and the first bit is set to `0` to indicate the end of the value. * Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern. * This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value. In other words, the encoding scheme follows this structure: ```txt 0XXXXXXX <- Values 0 to 127 (1 byte) 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes) 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes) ``` Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. ```ts twoslash import { getShortU16Codec } from '@solana/kit'; // ---cut-before--- const codec = getShortU16Codec(); const bytes1 = codec.encode(42); // 0x2a const bytes2 = codec.encode(128); // 0x8001 const bytes3 = codec.encode(16384); // 0x808001 codec.decode(bytes1); // 42 codec.decode(bytes2); // 128 codec.decode(bytes3); // 16384 ``` `getShortU16Encoder` and `getShortU16Decoder` functions are also available. ### getU8Codec \[!toc] Encodes and decodes **unsigned 8-bit integers**. It supports values from 0 to 255 (`2^8 - 1`). Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. ```ts twoslash import { getU8Codec } from '@solana/kit'; // ---cut-before--- const codec = getU8Codec(); const bytes = codec.encode(42); // 0x2a const value = codec.decode(bytes); // 42 ``` `getU8Encoder` and `getU8Decoder` functions are also available. ### getU16Codec \[!toc] Encodes and decodes **unsigned 16-bit integers**. It supports values from 0 to 65,535 (`2^16 - 1`). Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getU16Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getU16Codec(); const bytes = codec.encode(42); // 0x2a00 const value = codec.decode(bytes); // 42 // Big-endian. const beCodec = getU16Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(42); // 0x002a const beValue = beCodec.decode(bytes); // 42 ``` `getU16Encoder` and `getU16Decoder` functions are also available. ### getU32Codec \[!toc] Encodes and decodes **unsigned 32-bit integers**. It supports values from 0 to 4,294,967,295 (`2^32 - 1`). Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getU32Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getU32Codec(); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 // Big-endian. const beCodec = getU32Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(42); // 0x0000002a const beValue = beCodec.decode(bytes); // 42 ``` `getU32Encoder` and `getU32Decoder` functions are also available. ### getU64Codec \[!toc] Encodes and decodes **unsigned 64-bit integers**. It supports values from 0 to `2^64 - 1`. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getU64Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getU64Codec(); const bytes = codec.encode(42); // 0x2a00000000000000 const value = codec.decode(bytes); // 42 // Big-endian. const beCodec = getU64Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(42); // 0x000000000000002a const beValue = beCodec.decode(bytes); // 42 ``` `getU64Encoder` and `getU64Decoder` functions are also available. ### getU128Codec \[!toc] Encodes and decodes **unsigned 128-bit integers**. It supports values from 0 to `2^128 - 1`. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. Endianness can be specified using the `endian` option. The default is `Endian.Little`. ```ts twoslash import { getU128Codec, Endian } from '@solana/kit'; // ---cut-before--- // Little-endian. const codec = getU128Codec(); const bytes = codec.encode(42); // 0x2a000000000000000000000000000000 const value = codec.decode(bytes); // 42 // Big-endian. const beCodec = getU128Codec({ endian: Endian.Big }); const beBytes = beCodec.encode(42); // 0x0000000000000000000000000000002a const beValue = beCodec.decode(bytes); // 42 ``` `getU128Encoder` and `getU128Decoder` functions are also available. ## Strings listing \[!toc] ### getBase10Codec \[!toc] Encodes and decodes **Base 10 strings**. ```ts twoslash import { getBase10Codec } from '@solana/kit'; // ---cut-before--- const codec = getBase10Codec(); const bytes = codec.encode('1024'); // 0x0400 const value = codec.decode(bytes); // "1024" ``` This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. To add size constraints to your codec, you may use utility functions such as [`fixCodecSize`](#fix-codec-size), [`addCodecSizePrefix`](#add-codec-size-prefix) or [`addCodecSentinel`](#add-codec-sentinel). ```ts twoslash import { getBase10Codec, fixCodecSize, addCodecSizePrefix, getU32Codec, addCodecSentinel, } from '@solana/kit'; // ---cut-before--- fixCodecSize(getBase10Codec(), 4).encode('1024'); // 0x04000000 (padded to 4 bytes) addCodecSizePrefix(getBase10Codec(), getU32Codec()).encode('1024'); // 0x020000000400 // | β””-- The 2 bytes of content. // β””-- 4-byte prefix telling us to read 2 bytes. addCodecSentinel(getBase10Codec(), new Uint8Array([0xff, 0xff])).encode('1024'); // 0x0400ffff // | β””-- The sentinel signaling the end of the content. // β””-- The 2 bytes of content. ``` `getBase10Encoder` and `getBase10Decoder` functions are also available. ### getBase16Codec \[!toc] Encodes and decodes **Base 16 strings**. ```ts twoslash import { getBase16Codec } from '@solana/kit'; // ---cut-before--- const codec = getBase16Codec(); const bytes = codec.encode('deadface'); // 0xdeadface const value = codec.decode(bytes); // "deadface" ``` This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. To add size constraints to your codec, you may use utility functions such as [`fixCodecSize`](#fix-codec-size), [`addCodecSizePrefix`](#add-codec-size-prefix) or [`addCodecSentinel`](#add-codec-sentinel). ```ts twoslash import { getBase16Codec, fixCodecSize, addCodecSizePrefix, getU32Codec, addCodecSentinel, } from '@solana/kit'; // ---cut-before--- fixCodecSize(getBase16Codec(), 2).encode('deadface'); // 0xdead (truncated to 2 bytes) addCodecSizePrefix(getBase16Codec(), getU32Codec()).encode('deadface'); // 0x04000000deadface // | β””-- The 4 bytes of content. // β””-- 4-byte prefix telling us to read 4 bytes. addCodecSentinel(getBase16Codec(), new Uint8Array([0xff, 0xff])).encode('deadface'); // 0xdeadfaceffff // | β””-- The sentinel signaling the end of the content. // β””-- The 4 bytes of content. ``` `getBase16Encoder` and `getBase16Decoder` functions are also available. ### getBase58Codec \[!toc] Encodes and decodes **Base 58 strings**. ```ts twoslash import { getBase58Codec } from '@solana/kit'; // ---cut-before--- const codec = getBase58Codec(); const bytes = codec.encode('heLLo'); // 0x1b6a3070 const value = codec.decode(bytes); // "heLLo" ``` This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. To add size constraints to your codec, you may use utility functions such as [`fixCodecSize`](#fix-codec-size), [`addCodecSizePrefix`](#add-codec-size-prefix) or [`addCodecSentinel`](#add-codec-sentinel). ```ts twoslash import { getBase58Codec, fixCodecSize, addCodecSizePrefix, getU32Codec, addCodecSentinel, } from '@solana/kit'; // ---cut-before--- fixCodecSize(getBase58Codec(), 2).encode('heLLo'); // 0x1b6a (truncated to 2 bytes) addCodecSizePrefix(getBase58Codec(), getU32Codec()).encode('heLLo'); // 0x040000001b6a3070 // | β””-- The 4 bytes of content. // β””-- 4-byte prefix telling us to read 4 bytes. addCodecSentinel(getBase58Codec(), new Uint8Array([0xff, 0xff])).encode('heLLo'); // 0x1b6a3070ffff // | β””-- The sentinel signaling the end of the content. // β””-- The 4 bytes of content. ``` `getBase58Encoder` and `getBase58Decoder` functions are also available. ### getBase64Codec \[!toc] Encodes and decodes **Base 64 strings**. ```ts twoslash import { getBase64Codec } from '@solana/kit'; // ---cut-before--- const codec = getBase64Codec(); const bytes = codec.encode('hello+world'); // 0x85e965a3ec28ae57 const value = codec.decode(bytes); // "hello+world" ``` This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. To add size constraints to your codec, you may use utility functions such as [`fixCodecSize`](#fix-codec-size), [`addCodecSizePrefix`](#add-codec-size-prefix) or [`addCodecSentinel`](#add-codec-sentinel). ```ts twoslash import { getBase64Codec, fixCodecSize, addCodecSizePrefix, getU32Codec, addCodecSentinel, } from '@solana/kit'; // ---cut-before--- fixCodecSize(getBase64Codec(), 4).encode('hello+world'); // 0x85e965a3 (truncated to 4 bytes) addCodecSizePrefix(getBase64Codec(), getU32Codec()).encode('hello+world'); // 0x0400000085e965a3ec28ae57 // | β””-- The 8 bytes of content. // β””-- 4-byte prefix telling us to read 8 bytes. addCodecSentinel(getBase64Codec(), new Uint8Array([0xff, 0xff])).encode('hello+world'); // 0x85e965a3ec28ae57ffff // | β””-- The sentinel signaling the end of the content. // β””-- The 8 bytes of content. ``` `getBase64Encoder` and `getBase64Decoder` functions are also available. ### getBaseXCodec \[!toc] The `getBaseXCodec` accepts a custom `alphabet` of `X` characters and **creates a base-X codec using that alphabet**. It does so by iteratively dividing by `X` and handling leading zeros. ```ts twoslash import { getBaseXCodec } from '@solana/kit'; // ---cut-before--- const codec = getBaseXCodec('0ehlo'); const bytes = codec.encode('hello'); // 0x05bd const value = codec.decode(bytes); // "hello" ``` This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. To add size constraints to your codec, you may use utility functions such as [`fixCodecSize`](#fix-codec-size), [`addCodecSizePrefix`](#add-codec-size-prefix) or [`addCodecSentinel`](#add-codec-sentinel). ```ts twoslash import { getBaseXCodec, fixCodecSize, addCodecSizePrefix, getU32Codec, addCodecSentinel, } from '@solana/kit'; // ---cut-before--- const codec = getBaseXCodec('0ehlo'); fixCodecSize(codec, 4).encode('hello'); // 0x05bd0000 (padded to 4 bytes) addCodecSizePrefix(codec, getU32Codec()).encode('hello'); // 0x0200000005bd // | β””-- The 2 bytes of content. // β””-- 4-byte prefix telling us to read 2 bytes. addCodecSentinel(codec, new Uint8Array([0xff, 0xff])).encode('hello'); // 0x05bdffff // | β””-- The sentinel signaling the end of the content. // β””-- The 2 bytes of content. ``` `getBaseXEncoder` and `getBaseXDecoder` functions are also available. ### getBaseXResliceCodec \[!toc] The `getBaseXResliceCodec` accepts a custom `alphabet` of `X` characters and **creates a base-X codec using that alphabet**. It does so by re-slicing bytes into custom chunks of bits that are then mapped to the provided `alphabet`. The number of bits per chunk is also provided as the second argument and should typically be set to `log2(alphabet.length)`. This is typically used to create codecs whose alphabet's length is a power of 2 such as base-16 or base-64. ```ts twoslash import { getBaseXResliceCodec } from '@solana/kit'; // ---cut-before--- const codec = getBaseXResliceCodec('elho', 2); const bytes = codec.encode('hellolol'); // 0x4aee const value = codec.decode(bytes); // "hellolol" ``` This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. To add size constraints to your codec, you may use utility functions such as [`fixCodecSize`](#fix-codec-size), [`addCodecSizePrefix`](#add-codec-size-prefix) or [`addCodecSentinel`](#add-codec-sentinel). ```ts twoslash import { getBaseXResliceCodec, fixCodecSize, addCodecSizePrefix, getU32Codec, addCodecSentinel, } from '@solana/kit'; // ---cut-before--- const codec = getBaseXResliceCodec('elho', 2); fixCodecSize(codec, 4).encode('hellolol'); // 0x4aee0000 (padded to 4 bytes) addCodecSizePrefix(codec, getU32Codec()).encode('hellolol'); // 0x020000004aee // | β””-- The 2 bytes of content. // β””-- 4-byte prefix telling us to read 2 bytes. addCodecSentinel(codec, new Uint8Array([0xff, 0xff])).encode('hellolol'); // 0x4aeeffff // | β””-- The sentinel signaling the end of the content. // β””-- The 2 bytes of content. ``` `getBaseXResliceEncoder` and `getBaseXResliceDecoder` functions are also available. ### getUtf8Codec \[!toc] Encodes and decodes **UTF-8 strings**. ```ts twoslash import { getUtf8Codec } from '@solana/kit'; // ---cut-before--- const codec = getUtf8Codec(); const bytes = codec.encode('hello'); // 0x68656c6c6f const value = codec.decode(bytes); // "hello" ``` This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. To add size constraints to your codec, you may use utility functions such as [`fixCodecSize`](#fix-codec-size), [`addCodecSizePrefix`](#add-codec-size-prefix) or [`addCodecSentinel`](#add-codec-sentinel). ```ts twoslash import { getUtf8Codec, fixCodecSize, addCodecSizePrefix, getU32Codec, addCodecSentinel, } from '@solana/kit'; // ---cut-before--- fixCodecSize(getUtf8Codec(), 4).encode('hello'); // 0x68656c6c (truncated to 4 bytes) addCodecSizePrefix(getUtf8Codec(), getU32Codec()).encode('hello'); // 0x0500000068656c6c6f // | β””-- The 5 bytes of content. // β””-- 4-byte prefix telling us to read 5 bytes. addCodecSentinel(getUtf8Codec(), new Uint8Array([0xff, 0xff])).encode('hello'); // 0x68656c6c6fffff // | β””-- The sentinel signaling the end of the content. // β””-- The 5 bytes of content. ``` `getUtf8Encoder` and `getUtf8Decoder` functions are also available. ## Data structures listing \[!toc] ### getArrayCodec \[!toc] The `getArrayCodec` function accepts any codec of type `T` and returns a codec of type `Array`. ```ts twoslash import { getArrayCodec, getU8Codec } from '@solana/kit'; // ---cut-before--- const codec = getArrayCodec(getU8Codec()); const bytes = codec.encode([1, 2, 3]); // 0x03000000010203 const array = codec.decode(bytes); // [1, 2, 3] ``` By default, the size of the array is stored as a `u32` prefix before encoding the items. ```ts twoslash import { getArrayCodec, getU8Codec } from '@solana/kit'; // ---cut-before--- getArrayCodec(getU8Codec()).encode([1, 2, 3]); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. ``` However, you may use the `size` option to configure this behaviour. It can be one of the following three strategies: * `Codec`: When a number codec is provided, that codec will be used to encode and decode the size prefix. * `number`: When a number is provided, the codec will expect a fixed number of items in the array. An error will be thrown when trying to encode an array of a different length. * `"remainder"`: When the string `"remainder"` is passed as a size, the codec will use the remainder of the bytes to encode/decode its items. This means the size is not stored or known in advance but simply inferred from the rest of the buffer. For instance, if we have an array of `u16` numbers and 10 bytes remaining, we know there are 5 items in this array. ```ts twoslash import { getArrayCodec, getU8Codec, getU16Codec } from '@solana/kit'; // ---cut-before--- getArrayCodec(getU8Codec(), { size: getU16Codec() }).encode([1, 2, 3]); // 0x0300010203 // | β””-- 3 items of 1 byte each. // β””-- 2-byte prefix telling us to read 3 items. getArrayCodec(getU8Codec(), { size: 3 }).encode([1, 2, 3]); // 0x010203 // β””-- 3 items of 1 byte each. There must always be 3 items in the array. getArrayCodec(getU8Codec(), { size: 'remainder' }).encode([1, 2, 3]); // 0x010203 // β””-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes. ``` `getArrayEncoder` and `getArrayDecoder` functions are also available. ### getBitArrayCodec \[!toc] The `getBitArrayCodec` function returns a codec that encodes and decodes an array of booleans such that each boolean is represented by a single bit. It requires the size of the codec in bytes and an optional `backward` flag that can be used to reverse the order of the bits. ```ts twoslash import { getBitArrayCodec } from '@solana/kit'; // ---cut-before--- const booleans = [true, false, true, false, true, false, true, false]; getBitArrayCodec(1).encode(booleans); // 0xaa or 0b10101010 getBitArrayCodec(1, { backward: true }).encode(booleans); // 0x55 or 0b01010101 ``` `getBitArrayEncoder` and `getBitArrayDecoder` functions are also available. ### getBooleanCodec \[!toc] The `getBooleanCodec` function returns a `Codec` that stores the boolean as `0` or `1` using a `u8` number by default. ```ts twoslash import { getBooleanCodec } from '@solana/kit'; // ---cut-before--- const codec = getBooleanCodec(); const bytes = codec.encode(true); // 0x01 const value = codec.decode(bytes); // true ``` You may configure that behaviour by providing an explicit number codec as the `size` option of the `getBooleanCodec` function. That number codec will then be used to encode and decode the values `0` and `1` accordingly. ```ts twoslash import { getBooleanCodec, getU16Codec, getU32Codec } from '@solana/kit'; // ---cut-before--- getBooleanCodec({ size: getU16Codec() }).encode(false); // 0x0000 getBooleanCodec({ size: getU16Codec() }).encode(true); // 0x0100 getBooleanCodec({ size: getU32Codec() }).encode(false); // 0x00000000 getBooleanCodec({ size: getU32Codec() }).encode(true); // 0x01000000 ``` `getBooleanEncoder` and `getBooleanDecoder` functions are also available. ### getBytesCodec \[!toc] The `getBytesCodec` function returns a `Codec` meaning it converts `Uint8Arrays` to and from… `Uint8Arrays`! Whilst this might seem a bit useless, it can be useful when composed into other codecs. For example, you could use it in a struct codec to say that a particular field should be left unserialised. ```ts twoslash import { getBytesCodec } from '@solana/kit'; // ---cut-before--- const codec = getBytesCodec(); const bytes = codec.encode(new Uint8Array([42])); // 0x2a const value = codec.decode(bytes); // 0x2a ``` The `getBytesCodec` function will encode and decode `Uint8Arrays` using as many bytes as necessary. If you'd like to restrict the number of bytes used by this codec, you may combine it with utilities such as [`fixCodecSize`](#fix-codec-size), [`addCodecSizePrefix`](#add-codec-size-prefix) or [`addCodecSentinel`](#add-codec-sentinel). ```ts twoslash import { getBytesCodec, fixCodecSize, addCodecSizePrefix, getU32Codec, addCodecSentinel, } from '@solana/kit'; // ---cut-before--- const value = new Uint8Array([42, 43]); // 0x2a2b fixCodecSize(getBytesCodec(), 4).encode(value); // 0x2a2b0000 (padded to 4 bytes) addCodecSizePrefix(getBytesCodec(), getU32Codec()).encode(value); // 0x020000002a2b // | β””-- The 2 bytes of content. // β””-- 4-byte prefix telling us to read 2 bytes. addCodecSentinel(getBytesCodec(), new Uint8Array([0xff, 0xff])).encode(value); // 0x2a2bffff // | β””-- The sentinel signaling the end of the content. // β””-- The 2 bytes of content. ``` `getBytesEncoder` and `getBytesDecoder` functions are also available. ### getConstantCodec \[!toc] The `getConstantCodec` function accepts any `Uint8Array` and returns a `Codec`. When encoding, it will set the provided `Uint8Array` as-is. When decoding, it will assert that the next bytes contain the provided `Uint8Array` and move the offset forward. ```ts twoslash import { getConstantCodec } from '@solana/kit'; // ---cut-before--- const codec = getConstantCodec(new Uint8Array([1, 2, 3])); codec.encode(undefined); // 0x010203 codec.decode(new Uint8Array([1, 2, 3])); // undefined codec.decode(new Uint8Array([1, 2, 4])); // Throws an error. ``` `getConstantEncoder` and `getConstantDecoder` functions are also available. ### getDiscriminatedUnionCodec \[!toc] In Rust, enums are powerful data types whose variants can be one of the following: * An empty variant β€” e.g. `enum Message { Quit }`. * A tuple variant β€” e.g. `enum Message { Write(String) }`. * A struct variant β€” e.g. `enum Message { Move { x: i32, y: i32 } }`. Whilst we do not have such powerful enums in JavaScript, we can emulate them in TypeScript using a union of objects such that each object is differentiated by a specific field. **We call this a discriminated union**. We use a special field named `__kind` to distinguish between the different variants of a discriminated union. Additionally, since all variants are objects, we can use a `fields` property to wrap the array of tuple variants. Here is an example. ```ts twoslash type Message = | { __kind: 'quit' } // Empty variant. | { __kind: 'write'; fields: [string] } // Tuple variant. | { __kind: 'move'; x: number; y: number }; // Struct variant. ``` The `getDiscriminatedUnionCodec` function helps us encode and decode these discriminated unions. It requires the discriminator and codec of each variant as a first argument. Similarly to the [getStructCodec](#get-struct-codec), these are defined as an array of variant tuples where the first item is the discriminator of the variant and the second item is its codec. Since empty variants do not have data to encode, they simply use the [getUnitCodec](#get-unit-codec) which does nothing. Here is how we can create a discriminated union codec for our previous example. ```ts twoslash import { getDiscriminatedUnionCodec, getUnitCodec, getStructCodec, getTupleCodec, getUtf8Codec, getU32Codec, addCodecSizePrefix, getI32Codec, } from '@solana/kit'; // ---cut-before--- const messageCodec = getDiscriminatedUnionCodec([ // Empty variant. ['quit', getUnitCodec()], // Tuple variant. [ 'write', getStructCodec([ ['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])], ]), ], // Struct variant. [ 'move', getStructCodec([ ['x', getI32Codec()], ['y', getI32Codec()], ]), ], ]); ``` And here's how we can use such a codec to encode discriminated unions. Notice that by default, they use a `u8` number prefix to distinguish between the different types of variants. ```ts twoslash import { getDiscriminatedUnionCodec, getUnitCodec, getStructCodec, getTupleCodec, getUtf8Codec, getU32Codec, addCodecSizePrefix, getI32Codec, } from '@solana/kit'; const messageCodec = getDiscriminatedUnionCodec([ // Empty variant. ['quit', getUnitCodec()], // Tuple variant. [ 'write', getStructCodec([ ['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])], ]), ], // Struct variant. [ 'move', getStructCodec([ ['x', getI32Codec()], ['y', getI32Codec()], ]), ], ]); // ---cut-before--- messageCodec.encode({ __kind: 'quit' }); // 0x00 // β””-- 1-byte discriminator (Index 0 β€” the "quit" variant). messageCodec.encode({ __kind: 'write', fields: ['Hi'] }); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte discriminator (Index 1 β€” the "write" variant). messageCodec.encode({ __kind: 'move', x: 5, y: 6 }); // 0x020500000006000000 // | | β””-- Field y (6). // | β””-- Field x (5). // β””-- 1-byte discriminator (Index 2 β€” the "move" variant). ``` However, you may provide a number codec as the `size` option of the `getDiscriminatedUnionCodec` function to customise that behaviour. ```ts twoslash import { getDiscriminatedUnionCodec, getUnitCodec, getStructCodec, getTupleCodec, getUtf8Codec, getU32Codec, addCodecSizePrefix, getI32Codec, } from '@solana/kit'; const quitCodec = getUnitCodec(); const writeCodec = getStructCodec([ ['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])], ]); const moveCodec = getStructCodec([ ['x', getI32Codec()], ['y', getI32Codec()], ]); // ---cut-before--- const u32MessageCodec = getDiscriminatedUnionCodec( [ ['quit', quitCodec], ['write', writeCodec], ['move', moveCodec], ], { size: getU32Codec() }, ); u32MessageCodec.encode({ __kind: 'quit' }); // 0x00000000 // β””------β”˜ 4-byte discriminator (Index 0). u32MessageCodec.encode({ __kind: 'write', fields: ['Hi'] }); // 0x01000000020000004869 // β””------β”˜ 4-byte discriminator (Index 1). u32MessageCodec.encode({ __kind: 'move', x: 5, y: 6 }); // 0x020000000500000006000000 // β””------β”˜ 4-byte discriminator (Index 2). ``` You may also customize the discriminator property β€” which defaults to `__kind` β€” by providing the desired property name as the `discriminator` option like so: ```ts twoslash import { getDiscriminatedUnionCodec, getUnitCodec, getStructCodec, getTupleCodec, getUtf8Codec, getU32Codec, addCodecSizePrefix, getI32Codec, } from '@solana/kit'; const quitCodec = getUnitCodec(); const writeCodec = getStructCodec([ ['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])], ]); const moveCodec = getStructCodec([ ['x', getI32Codec()], ['y', getI32Codec()], ]); // ---cut-before--- const messageCodec = getDiscriminatedUnionCodec( [ ['quit', quitCodec], ['write', writeCodec], ['move', moveCodec], ], { discriminator: 'message' }, ); messageCodec.encode({ message: 'quit' }); messageCodec.encode({ message: 'write', fields: ['Hi'] }); messageCodec.encode({ message: 'move', x: 5, y: 6 }); ``` Note that, the discriminator value of a variant may be any scalar value β€” such as `number`, `bigint`, `boolean`, a JavaScript `enum`, etc. For instance, the following is also valid: ```ts twoslash import { getDiscriminatedUnionCodec, getUnitCodec, getStructCodec, getTupleCodec, getUtf8Codec, getU32Codec, addCodecSizePrefix, getI32Codec, } from '@solana/kit'; const quitCodec = getUnitCodec(); const writeCodec = getStructCodec([ ['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])], ]); const moveCodec = getStructCodec([ ['x', getI32Codec()], ['y', getI32Codec()], ]); // ---cut-before--- enum Message { Quit, Write, Move, } const messageCodec = getDiscriminatedUnionCodec([ [Message.Quit, quitCodec], [Message.Write, writeCodec], [Message.Move, moveCodec], ]); messageCodec.encode({ __kind: Message.Quit }); messageCodec.encode({ __kind: Message.Write, fields: ['Hi'] }); messageCodec.encode({ __kind: Message.Move, x: 5, y: 6 }); ``` `getDiscriminatedUnionEncoder` and `getDiscriminatedUnionDecoder` functions are also available. ### getEnumCodec \[!toc] The `getEnumCodec` function accepts a JavaScript enum constructor and returns a codec for encoding and decoding values of that enum. ```ts twoslash import { getEnumCodec } from '@solana/kit'; // ---cut-before--- enum Direction { Left, Right, } const codec = getEnumCodec(Direction); const bytes = codec.encode(Direction.Left); // 0x00 const direction = codec.decode(bytes); // Direction.Left ``` When encoding an enum, you may either provide the value of the enum variant β€” e.g. `Direction.Left` β€” or its key β€” e.g. `'Left'`. ```ts twoslash import { getEnumCodec } from '@solana/kit'; enum Direction { Left, Right, } // ---cut-before--- getEnumCodec(Direction).encode(Direction.Left); // 0x00 getEnumCodec(Direction).encode(Direction.Right); // 0x01 getEnumCodec(Direction).encode('Left'); // 0x00 getEnumCodec(Direction).encode('Right'); // 0x01 ``` By default, a `u8` number is being used to store the enum value. However, a number codec may be passed as the `size` option to configure that behaviour. ```ts twoslash import { getEnumCodec, getU32Codec } from '@solana/kit'; enum Direction { Left, Right, } // ---cut-before--- const u32DirectionCodec = getEnumCodec(Direction, { size: getU32Codec() }); u32DirectionCodec.encode(Direction.Left); // 0x00000000 u32DirectionCodec.encode(Direction.Right); // 0x01000000 ``` This function also works with lexical enums β€” e.g. `enum Direction { Left = '←' }` β€” explicit numerical enums β€” e.g. `enum Speed { Left = 50 }` β€” and hybrid enums with a mix of both. ```ts twoslash import { getEnumCodec } from '@solana/kit'; // ---cut-before--- enum Numbers { One, Five = 5, Six, Nine = 'nine', } getEnumCodec(Numbers).encode(Numbers.One); // 0x00 getEnumCodec(Numbers).encode(Numbers.Five); // 0x01 getEnumCodec(Numbers).encode(Numbers.Six); // 0x02 getEnumCodec(Numbers).encode(Numbers.Nine); // 0x03 getEnumCodec(Numbers).encode('One'); // 0x00 getEnumCodec(Numbers).encode('Five'); // 0x01 getEnumCodec(Numbers).encode('Six'); // 0x02 getEnumCodec(Numbers).encode('Nine'); // 0x03 ``` Notice how, by default, the index of the enum variant is used to encode the value of the enum. For instance, in the example above, `Numbers.Five` is encoded as `0x01` even though its value is `5`. This is also true for lexical enums. However, when dealing with numerical enums that have explicit values, you may use the `useValuesAsDiscriminators` option to encode the value of the enum variant instead of its index. ```ts twoslash import { getEnumCodec } from '@solana/kit'; // ---cut-before--- enum Numbers { One, Five = 5, Six, Nine = 9, } const codec = getEnumCodec(Numbers, { useValuesAsDiscriminators: true }); codec.encode(Numbers.One); // 0x00 codec.encode(Numbers.Five); // 0x05 codec.encode(Numbers.Six); // 0x06 codec.encode(Numbers.Nine); // 0x09 codec.encode('One'); // 0x00 codec.encode('Five'); // 0x05 codec.encode('Six'); // 0x06 codec.encode('Nine'); // 0x09 ``` Note that when using the `useValuesAsDiscriminators` option on an enum that contains a lexical value, an error will be thrown. ```ts twoslash import { getEnumCodec } from '@solana/kit'; // ---cut-before--- enum Lexical { One, Two = 'two', } getEnumCodec(Lexical, { useValuesAsDiscriminators: true }); // Throws an error. ``` `getEnumEncoder` and `getEnumDecoder` functions are also available. ### getHiddenPrefixCodec \[!toc] The `getHiddenPrefixCodec` function allow us to prepend a list of hidden `Codec` to a given codec. When encoding, the hidden codecs will be encoded before the main codec and the offset will be moved accordingly. When decoding, the hidden codecs will be decoded but only the result of the main codec will be returned. This is particularly helpful when creating data structures that include constant values that should not be included in the final type. ```ts twoslash import { getHiddenPrefixCodec, getConstantCodec, getU16Codec } from '@solana/kit'; // ---cut-before--- const codec = getHiddenPrefixCodec(getU16Codec(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); codec.encode(42); // 0x0102030405062a00 // | | β””-- Our main u16 codec (value = 42). // | β””-- Our second hidden prefix codec. // β””-- Our first hidden prefix codec. codec.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 42, 0])); // 42 ``` `getHiddenPrefixEncoder` and `getHiddenPrefixDecoder` functions are also available. ### getHiddenSuffixCodec \[!toc] The `getHiddenSuffixCodec` function allow us to append a list of hidden `Codec` to a given codec. When encoding, the hidden codecs will be encoded after the main codec and the offset will be moved accordingly. When decoding, the hidden codecs will be decoded but only the result of the main codec will be returned. This is particularly helpful when creating data structures that include constant values that should not be included in the final type. ```ts twoslash import { getHiddenSuffixCodec, getConstantCodec, getU16Codec } from '@solana/kit'; // ---cut-before--- const codec = getHiddenSuffixCodec(getU16Codec(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); codec.encode(42); // 0x2a00010203040506 // | | β””-- Our second hidden suffix codec. // | β””-- Our first hidden suffix codec. // β””-- Our main u16 codec (value = 42). codec.decode(new Uint8Array([42, 0, 1, 2, 3, 4, 5, 6])); // 42 ``` `getHiddenSuffixEncoder` and `getHiddenSuffixDecoder` functions are also available. ### getLiteralUnionCodec \[!toc] The `getLiteralUnionCodec` function accepts an array of literal values β€” such as `string`, `number`, `boolean`, etc. β€” and returns a codec that encodes and decodes such values by using their index in the array. It uses TypeScript unions to represent all the possible values. ```ts twoslash import { getLiteralUnionCodec, FixedSizeCodec } from '@solana/kit'; // ---cut-before--- const codec = getLiteralUnionCodec(['left', 'right', 'up', 'down']); codec satisfies FixedSizeCodec<'left' | 'right' | 'up' | 'down'>; const bytes = codec.encode('left'); // 0x00 const value = codec.decode(bytes); // 'left' ``` It uses a `u8` number by default to store the index of the value. However, you may provide a number codec as the `size` option of the `getLiteralUnionCodec` function to customise that behaviour. ```ts twoslash import { getLiteralUnionCodec, getU32Codec } from '@solana/kit'; // ---cut-before--- const codec = getLiteralUnionCodec(['left', 'right', 'up', 'down'], { size: getU32Codec(), }); codec.encode('left'); // 0x00000000 codec.encode('right'); // 0x01000000 codec.encode('up'); // 0x02000000 codec.encode('down'); // 0x03000000 ``` `getLiteralUnionEncoder` and `getLiteralUnionDecoder` functions are also available. ### getMapCodec \[!toc] The `getMapCodec` function accepts two codecs of type `K` and `V` and returns a codec of type `Map`. ```ts twoslash import { getMapCodec, getU8Codec, getUtf8Codec, fixCodecSize } from '@solana/kit'; // ---cut-before--- const keyCodec = fixCodecSize(getUtf8Codec(), 8); const valueCodec = getU8Codec(); const codec = getMapCodec(keyCodec, valueCodec); const bytes = codec.encode(new Map([['alice', 42]])); // 0x01000000616c6963650000002a const map = codec.decode(bytes); // new Map([["alice", 42]]) ``` Each entry (key/value pair) is encoded one after the other with the key first and the value next. By default, the size of the map is stored as a `u32` prefix before encoding the entries. ```ts twoslash import { getMapCodec, getU8Codec, getUtf8Codec, fixCodecSize } from '@solana/kit'; // ---cut-before--- const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 8), getU8Codec()); const myMap = new Map(); myMap.set('alice', 42); myMap.set('bob', 5); codec.encode(myMap); // 0x02000000616c6963650000002a626f62000000000005 // | | | | β””-- 2nd entry value (5). // | | | β””-- 2nd entry key ("bob"). // | | β””-- 1st entry value (42). // | β””-- 1st entry key ("alice"). // β””-- 4-byte prefix telling us to read 2 map entries. ``` However, you may use the `size` option to configure this behaviour. It can be one of the following three strategies: * `Codec`: When a number codec is provided, that codec will be used to encode and decode the size prefix. * `number`: When a number is provided, the codec will expect a fixed number of entries in the map. An error will be thrown when trying to encode a map of a different length. * `"remainder"`: When the string `"remainder"` is passed as a size, the codec will use the remainder of the bytes to encode/decode its entries. This means the size is not stored or known in advance but simply inferred from the rest of the buffer. For instance, if we have a map of `u16` numbers and 10 bytes remaining, we know there are 5 entries in this map. ```ts twoslash import { getMapCodec, getU8Codec, getU16Codec, fixCodecSize, getUtf8Codec } from '@solana/kit'; // ---cut-before--- const keyCodec = fixCodecSize(getUtf8Codec(), 8); const valueCodec = getU8Codec(); const myMap = new Map(); myMap.set('alice', 42); myMap.set('bob', 5); getMapCodec(keyCodec, valueCodec, { size: getU16Codec() }).encode(myMap); // 0x0200616c6963650000002a626f62000000000005 // | | β””-- Second entry. // | β””-- First entry. // β””-- 2-byte prefix telling us to read 2 entries. getMapCodec(keyCodec, valueCodec, { size: 3 }).encode(myMap); // 0x616c6963650000002a626f62000000000005 // | β””-- Second entry. // β””-- First entry. // There must always be 2 entries in the map. getMapCodec(keyCodec, valueCodec, { size: 'remainder' }).encode(myMap); // 0x616c6963650000002a626f62000000000005 // | β””-- Second entry. // β””-- First entry. // The size is inferred from the remainder of the bytes. ``` `getMapEncoder` and `getMapDecoder` functions are also available. ### getNullableCodec \[!toc] The `getNullableCodec` function accepts a codec of type `T` and returns a codec of type `T | null`. It stores whether or not the item exists as a boolean prefix using a `u8` by default. ```ts twoslash import { getNullableCodec, getU32Codec, addCodecSizePrefix, getUtf8Codec } from '@solana/kit'; // ---cut-before--- const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); getNullableCodec(stringCodec).encode('Hi'); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (true β€” The item exists). getNullableCodec(stringCodec).encode(null); // 0x00 // β””-- 1-byte prefix (false β€” The item is null). ``` You may provide a number codec as the `prefix` option of the `getNullableCodec` function to configure how to store the boolean prefix. ```ts twoslash import { getNullableCodec, getU32Codec, addCodecSizePrefix, getUtf8Codec } from '@solana/kit'; const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); // ---cut-before--- const u32NullableStringCodec = getNullableCodec(stringCodec, { prefix: getU32Codec(), }); u32NullableStringCodec.encode('Hi'); // 0x01000000020000004869 // β””------β”˜ 4-byte prefix (true). u32NullableStringCodec.encode(null); // 0x00000000 // β””------β”˜ 4-byte prefix (false). ``` Additionally, if the item is a `FixedSizeCodec`, you may set the `noneValue` option to `"zeroes"` to also make the returned nullable codec a `FixedSizeCodec`. To do so, it will pad `null` values with zeroes to match the length of existing values. ```ts twoslash import { getNullableCodec, fixCodecSize, getUtf8Codec } from '@solana/kit'; // ---cut-before--- const fixedNullableStringCodec = getNullableCodec( fixCodecSize(getUtf8Codec(), 8), // Only works with fixed-size items. { noneValue: 'zeroes' }, ); fixedNullableStringCodec.encode('Hi'); // 0x014869000000000000 // | β””-- 8-byte utf8 string content ("Hi"). // β””-- 1-byte prefix (true β€” The item exists). fixedNullableStringCodec.encode(null); // 0x000000000000000000 // | β””-- 8-byte of padding to make a fixed-size codec. // β””-- 1-byte prefix (false β€” The item is null). ``` The `noneValue` option can also be set to an explicit byte array to use as the padding for `null` values. Note that, in this case, the returned codec will not be a `FixedSizeCodec` as the byte array representing `null` values may be of any length. ```ts twoslash import { getNullableCodec, getUtf8Codec } from '@solana/kit'; // ---cut-before--- const codec = getNullableCodec(getUtf8Codec(), { noneValue: new Uint8Array([255]), // 0xff means null. }); codec.encode('Hi'); // 0x014869 // | β””-- 2-byte utf8 string content ("Hi"). // β””-- 1-byte prefix (true β€” The item exists). codec.encode(null); // 0x00ff // | β””-- 1-byte representing null (0xff). // β””-- 1-byte prefix (false β€” The item is null). ``` The `prefix` option of the `getNullableCodec` function can also be set to `null`, meaning no prefix will be used to determine whether the item exists. In this case, the codec will rely on the `noneValue` option to determine whether the item is `null`. ```ts twoslash import { getNullableCodec, getU16Codec } from '@solana/kit'; // ---cut-before--- const codecWithZeroNoneValue = getNullableCodec(getU16Codec(), { noneValue: 'zeroes', // 0x0000 means null. prefix: null, }); codecWithZeroNoneValue.encode(42); // 0x2a00 codecWithZeroNoneValue.encode(null); // 0x0000 const codecWithCustomNoneValue = getNullableCodec(getU16Codec(), { noneValue: new Uint8Array([255]), // 0xff means null. prefix: null, }); codecWithCustomNoneValue.encode(42); // 0x2a00 codecWithCustomNoneValue.encode(null); // 0xff ``` Note that if `prefix` is set to `null` and no `noneValue` is provided, the codec assumes that the item exists if and only if some remaining bytes are available to decode. This could be useful to describe data structures that may or may not have additional data to the end of the buffer. ```ts const codec = getNullableCodec(getU16Codec(), { prefix: null }); codec.encode(42); // 0x2a00 codec.encode(null); // Encodes nothing. codec.decode(new Uint8Array([42, 0])); // 42 codec.decode(new Uint8Array([])); // null ``` To recap, here are all the possible configurations of the `getNullableCodec` function, using a `u16` codec as an example. | `encode(42)` / `encode(null)` | No `noneValue` (default) | `noneValue: "zeroes"` | Custom `noneValue` (`0xff`) | | ----------------------------- | ------------------------ | --------------------------- | --------------------------- | | `u8` prefix (default) | `0x012a00` / `0x00` | `0x012a00` / `0x000000` | `0x012a00` / `0x00ff` | | Custom `prefix` (`u16`) | `0x01002a00` / `0x0000` | `0x01002a00` / `0x00000000` | `0x01002a00` / `0x0000ff` | | No `prefix` | `0x2a00` / `0x` | `0x2a00` / `0x0000` | `0x2a00` / `0xff` | Note that you might be interested in the Rust-like alternative version of nullable codecs, available as the [getOptionCodec](#get-option-codec) function. `getNullableEncoder` and `getNullableDecoder` functions are also available. ### getOptionCodec \[!toc] The `getOptionCodec` function accepts a codec of type `T` and returns a codec of type `Option` β€” as defined in the [`@solana/options`](https://github.com/anza-xyz/kit/tree/main/packages/options) package. Note that, when encoding, `T` or `null` may also be provided directly as input and will be interpreted as `Some(T)` or `None` respectively. However, when decoding, the output will always be an `Option` type. It stores whether or not the item exists as a boolean prefix using a `u8` by default. ```ts twoslash import { getOptionCodec, getU32Codec, addCodecSizePrefix, getUtf8Codec, some, none, } from '@solana/kit'; // ---cut-before--- const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); getOptionCodec(stringCodec).encode('Hi'); getOptionCodec(stringCodec).encode(some('Hi')); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (Some). getOptionCodec(stringCodec).encode(null); getOptionCodec(stringCodec).encode(none()); // 0x00 // β””-- 1-byte prefix (None). ``` You may provide a number codec as the `prefix` option of the `getOptionCodec` function to configure how to store the boolean prefix. ```ts twoslash import { getOptionCodec, getU32Codec, addCodecSizePrefix, getUtf8Codec, some, none, } from '@solana/kit'; const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); // ---cut-before--- const u32OptionStringCodec = getOptionCodec(stringCodec, { prefix: getU32Codec(), }); u32OptionStringCodec.encode(some('Hi')); // 0x01000000020000004869 // β””------β”˜ 4-byte prefix (Some). u32OptionStringCodec.encode(none()); // 0x00000000 // β””------β”˜ 4-byte prefix (None). ``` Additionally, if the item is a `FixedSizeCodec`, you may set the `noneValue` option to `"zeroes"` to also make the returned Option codec a `FixedSizeCodec`. To do so, it will pad `None` values with zeroes to match the length of existing values. ```ts twoslash import { getOptionCodec, fixCodecSize, getUtf8Codec, some, none } from '@solana/kit'; // ---cut-before--- const codec = getOptionCodec( fixCodecSize(getUtf8Codec(), 8), // Only works with fixed-size items. { noneValue: 'zeroes' }, ); codec.encode(some('Hi')); // 0x014869000000000000 // | β””-- 8-byte utf8 string content ("Hi"). // β””-- 1-byte prefix (Some). codec.encode(none()); // 0x000000000000000000 // | β””-- 8-byte of padding to make a fixed-size codec. // β””-- 1-byte prefix (None). ``` The `noneValue` option can also be set to an explicit byte array to use as the padding for `None` values. Note that, in this case, the returned codec will not be a `FixedSizeCodec` as the byte array representing `None` values may be of any length. ```ts twoslash import { getOptionCodec, getUtf8Codec, some, none } from '@solana/kit'; // ---cut-before--- const codec = getOptionCodec(getUtf8Codec(), { noneValue: new Uint8Array([255]), // 0xff means None. }); codec.encode(some('Hi')); // 0x014869 // | β””-- 2-byte utf8 string content ("Hi"). // β””-- 1-byte prefix (Some). codec.encode(none()); // 0x00ff // | β””-- 1-byte representing None (0xff). // β””-- 1-byte prefix (None). ``` The `prefix` option of the `getOptionCodec` function can also be set to `null`, meaning no prefix will be used to determine whether the item exists. In this case, the codec will rely on the `noneValue` option to determine whether the item is `None`. ```ts twoslash import { getOptionCodec, getU16Codec, some, none } from '@solana/kit'; // ---cut-before--- const codecWithZeroNoneValue = getOptionCodec(getU16Codec(), { noneValue: 'zeroes', // 0x0000 means None. prefix: null, }); codecWithZeroNoneValue.encode(some(42)); // 0x2a00 codecWithZeroNoneValue.encode(none()); // 0x0000 const codecWithCustomNoneValue = getOptionCodec(getU16Codec(), { noneValue: new Uint8Array([255]), // 0xff means None. prefix: null, }); codecWithCustomNoneValue.encode(some(42)); // 0x2a00 codecWithCustomNoneValue.encode(none()); // 0xff ``` Note that if `prefix` is set to `null` and no `noneValue` is provided, the codec assume that the item exists if and only if some remaining bytes are available to decode. This could be useful to describe data structures that may or may not have additional data to the end of the buffer. ```ts twoslash import { getOptionCodec, getU16Codec, some, none } from '@solana/kit'; // ---cut-before--- const codec = getOptionCodec(getU16Codec(), { prefix: null }); codec.encode(some(42)); // 0x2a00 codec.encode(none()); // Encodes nothing. codec.decode(new Uint8Array([42, 0])); // some(42) codec.decode(new Uint8Array([])); // none() ``` To recap, here are all the possible configurations of the `getOptionCodec` function, using a `u16` codec as an example. | `encode(some(42))` / `encode(none())` | No `noneValue` (default) | `noneValue: "zeroes"` | Custom `noneValue` (`0xff`) | | ------------------------------------- | ------------------------ | --------------------------- | --------------------------- | | `u8` prefix (default) | `0x012a00` / `0x00` | `0x012a00` / `0x000000` | `0x012a00` / `0x00ff` | | Custom `prefix` (`u16`) | `0x01002a00` / `0x0000` | `0x01002a00` / `0x00000000` | `0x01002a00` / `0x0000ff` | | No `prefix` | `0x2a00` / `0x` | `0x2a00` / `0x0000` | `0x2a00` / `0xff` | `getOptionEncoder` and `getOptionDecoder` functions are also available. ### getPatternMatchCodec \[!toc] The `getPatternMatchCodec` function returns a codec that selects which variant codec to use based on pattern matching. It generalises [`getPredicateCodec`](#get-predicate-codec) from two variants to any number of variants. It accepts an array of `[encodePredicate, decodePredicate, codec]` triples, where: * An encode predicate, that takes the value to encode and returns a boolean * A decode predicate, that takes a `ReadonlyUint8Array` and returns a boolean * A codec, that will be used when the corresponding predicate returns `true` Predicates are tested in order and the first match is used. If no predicate matches, a `SolanaError` is thrown. ```ts twoslash import { getPatternMatchCodec, getU8Codec, getU16Codec, getU32Codec, Codec } from '@solana/kit'; // ---cut-before--- const codec: Codec = getPatternMatchCodec([ [ (value: number | bigint) => value < 256, bytes => bytes.length === 1, getU8Codec(), ], [ (value: number | bigint) => value < 2 ** 16, bytes => bytes.length === 2, getU16Codec(), ], [ (value: number | bigint) => value < 2 ** 32, bytes => bytes.length <= 4, getU32Codec(), ], ]); const u8Bytes = codec.encode(42) // 0x2a, encoded as u8 codec.decode(u8Bytes) // 42, decoded as u8 const u16Bytes = codec.encode(1000) // 0xe803, encoded as u16 codec.decode(u16Bytes) // 1000, decoded as u16 const u32Bytes = codec.encode(100_000) // 0xa0860100, encoded as u32 codec.decode(u32Bytes) // 100_000, decoded as u32 ``` `getPatternMatchEncoder` and `getPatternMatchDecoder` functions are also available. ### getPredicateCodec \[!toc] The `getPredicateCodec` function returns a codec that switches between two different codecs, based on a predicate. It accepts the following arguments: * An encode predicate, that takes a value of a given type and returns a boolean * A decode predicate, that takes a `ReadOnlyUint8Array` and returns a boolean * A codec, that will be used to encode if the encode predicate is true and will be used to decode if the decode predicate is true * A codec, that will be used to encode if the encode predicate is false and will be used to decode if the decode predicate is false ```ts twoslash import { getPredicateCodec, getU8Codec, getU32Codec, Codec } from '@solana/kit'; // ---cut-before--- const codec: Codec = getPredicateCodec( (value: number) => value < 256, bytes => bytes.length === 1, getU8Codec(), getU32Codec(), ); const u8Bytes = codec.encode(42) // 0x2a, used u8 codec codec.decode(u8Bytes) // 42, used u8 codec const u32Bytes = codec.encode(1000) // 0xE8030000, used u32 codec codec.decode(u32Bytes) // 1000, used u32 codec ``` `getPredicateEncoder` and `getPredicateDecoder` functions are also available. ### getSetCodec \[!toc] The `getSetCodec` function accepts any codec of type `T` and returns a codec of type `Set`. ```ts twoslash import { getSetCodec, getU8Codec } from '@solana/kit'; // ---cut-before--- const codec = getSetCodec(getU8Codec()); const bytes = codec.encode(new Set([1, 2, 3])); // 0x03000000010203 const value = codec.decode(bytes); // new Set([1, 2, 3]) ``` By default, the size of the set is stored as a `u32` prefix before encoding the items. ```ts twoslash import { getSetCodec, getU8Codec } from '@solana/kit'; // ---cut-before--- getSetCodec(getU8Codec()).encode(new Set([1, 2, 3])); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. ``` However, you may use the `size` option to configure this behaviour. It can be one of the following three strategies: * `Codec`: When a number codec is provided, that codec will be used to encode and decode the size prefix. * `number`: When a number is provided, the codec will expect a fixed number of items in the set. An error will be thrown when trying to encode a set of a different length. * `"remainder"`: When the string `"remainder"` is passed as a size, the codec will use the remainder of the bytes to encode/decode its items. This means the size is not stored or known in advance but simply inferred from the rest of the buffer. For instance, if we have a set of `u16` numbers and 10 bytes remaining, we know there are 5 items in this set. ```ts twoslash import { getSetCodec, getU8Codec, getU16Codec } from '@solana/kit'; // ---cut-before--- getSetCodec(getU8Codec(), { size: getU16Codec() }).encode(new Set([1, 2, 3])); // 0x0300010203 // | β””-- 3 items of 1 byte each. // β””-- 2-byte prefix telling us to read 3 items. getSetCodec(getU8Codec(), { size: 3 }).encode(new Set([1, 2, 3])); // 0x010203 // β””-- 3 items of 1 byte each. There must always be 3 items in the set. getSetCodec(getU8Codec(), { size: 'remainder' }).encode(new Set([1, 2, 3])); // 0x010203 // β””-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes. ``` `getSetEncoder` and `getSetDecoder` functions are also available. ### getStructCodec \[!toc] The `getStructCodec` function accepts any number of field codecs and returns a codec for an object containing all these fields. Each provided field is an array such that the first item is the name of the field and the second item is the codec used to encode and decode that field type. ```ts twoslash import { getStructCodec, getU8Codec, getUtf8Codec, addCodecSizePrefix, Codec, getU32Codec, } from '@solana/kit'; // ---cut-before--- type Person = { name: string; age: number }; const personCodec: Codec = getStructCodec([ ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], ['age', getU8Codec()], ]); const bytes = personCodec.encode({ name: 'alice', age: 42 }); // 0x05000000616c6963652a // | β””-- Age field. // β””-- Name field. const person = personCodec.decode(bytes); // { name: "alice", age: 42 } ``` `getStructEncoder` and `getStructDecoder` functions are also available. ### getTupleCodec \[!toc] The `getTupleCodec` function accepts any number of codecs β€” `T`, `U`, `V`, etc. β€” and returns a tuple codec of type `[T, U, V, …]` such that each item is in the order of the provided codecs. ```ts twoslash import { getTupleCodec, getU8Codec, getU64Codec, addCodecSizePrefix, getUtf8Codec, getU32Codec, } from '@solana/kit'; // ---cut-before--- const tupleCodec = getTupleCodec([ addCodecSizePrefix(getUtf8Codec(), getU32Codec()), getU8Codec(), getU64Codec(), ]); const bytes = tupleCodec.encode(['alice', 42, 123]); // 0x05000000616c6963652a7b00000000000000 // | | β””-- 3rd item (123). // | β””-- 2nd item (42). // β””-- 1st item ("alice"). const value = tupleCodec.decode(bytes); // ["alice", 42, 123] ``` `getTupleEncoder` and `getTupleDecoder` functions are also available. ### getUnionCodec \[!toc] The `getUnionCodec` is a lower-lever codec helper that can be used to encode/decode any TypeScript union. It accepts the following arguments: * An array of codecs, each defining a variant of the union. * A `getIndexFromValue` function which, given a value of the union, returns the index of the codec that should be used to encode that value. * A `getIndexFromBytes` function which, given the byte array to decode at a given offset, returns the index of the codec that should be used to decode the next bytes. ```ts twoslash import { getUnionCodec, getU16Codec, getBooleanCodec, Codec } from '@solana/kit'; // ---cut-before--- const codec: Codec = getUnionCodec( [getU16Codec(), getBooleanCodec()], (value) => (typeof value === 'number' ? 0 : 1), (bytes, offset) => (bytes.slice(offset).length > 1 ? 0 : 1), ); codec.encode(42); // 0x2a00 codec.encode(true); // 0x01 ``` `getUnionEncoder` and `getUnionDecoder` functions are also available. ### getUnitCodec \[!toc] The `getUnitCodec` function returns a `Codec` that encodes `undefined` into an empty `Uint8Array` and returns `undefined` without consuming any bytes when decoding. This is more of a low-level codec that can be used internally by other codecs. For instance, this is how [getDiscriminatedUnionCodec](#get-discriminated-union-codec) describes the codecs of empty variants. ```ts twoslash import { getUnitCodec } from '@solana/kit'; const anyBytes = null as unknown as Uint8Array; // ---cut-before--- getUnitCodec().encode(undefined); // Empty Uint8Array getUnitCodec().decode(anyBytes); // undefined ``` `getUnitEncoder` and `getUnitDecoder` functions are also available. # Errors (/docs/advanced-guides/errors) ## Introduction The ecosystem of packages based on Kit's error system benefit from strongly typed error data, and descriptive error messages. Its error messages get scrubbed from your production bundles, which means that the library of error messages can grow indefinitely without adding a single byte to your app. ## Installation Errors are **included within the `@solana/kit` library** but you may also install them using their standalone package. ```bash npm install @solana/errors ``` ```bash pnpm add @solana/errors ``` ```bash yarn add @solana/errors ``` ```bash bun add @solana/errors ``` ## What is a `SolanaError`? A `SolanaError` is a class made of three components: * An error **code**; found in the union named [`SolanaErrorCode`](/api/type-aliases/SolanaErrorCode) * An error **message** * Optional error **context** Here's an example of some code that responds to various errors, taking advantage of the error context offered by each one: ```ts twoslash import { Transaction, TransactionWithBlockhashLifetime, sendAndConfirmTransactionFactory, } from '@solana/kit'; const sendAndConfirmTransaction = null as unknown as ReturnType< typeof sendAndConfirmTransactionFactory >; const transaction = null as unknown as Transaction & TransactionWithBlockhashLifetime; // ---cut-before--- import { assertIsSendableTransaction, isSolanaError, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, } from '@solana/kit'; try { assertIsSendableTransaction(transaction); await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) { console.error(`Missing signatures for ${e.context.addresses.join(', ')}`); } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT)) { console.error( `Transaction exceeds size limit of ${e.context.transactionSizeLimit} bytes. ` + `Actual size: ${e.context.transactionSize}`, ); } throw e; } ``` ## Catching errors When you encounter an error, you can determine whether it is a `SolanaError` or not using the `isSolanaError()` function: ```ts twoslash import { isSolanaError } from '@solana/kit'; try { // ... } catch (e) { if (isSolanaError(e)) { // A Solana error was thrown } else { // Something else went wrong } } ``` When you have a strategy for handling a *particular* error, you can supply that error's code as the second argument. This will both identify that error by code and refine the type of the `SolanaError` such that the shape of its `context` property becomes known to TypeScript. ```ts twoslash import { SolanaError } from '@solana/kit'; const e = null as unknown as SolanaError; // ---cut-before--- import { isSolanaError, SolanaErrorCode, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, } from '@solana/kit'; try { // ... } catch (e) { if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) { // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ console.error( // Now TypeScript knows the shape of this error's context `Missing signatures for these addresses: [${e.context.addresses.join(', ')}]`, // ^^^^^^^^^ ); } else { // Something else went wrong } } ``` Some Solana errors have, as their root cause, another Solana error. One such example is during transaction simulation (preflight): ```ts twoslash import { Base64EncodedWireTransaction, Rpc, SendTransactionApi } from '@solana/kit'; const rpc = null as unknown as Rpc; const wireTransaction = null as unknown as Base64EncodedWireTransaction; // ---cut-before--- import { isSolanaError, SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, } from '@solana/kit'; try { const result = await rpc.sendTransaction(wireTransaction, { encoding: 'base64', skipPreflight: false, }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE)) { // Simulation failed, but why? const underlyingError = e.cause; if ( isSolanaError( underlyingError, SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED, ) ) { // Now we know the root cause of the simulation failure, and can advise the user } } } ``` ## Failed transaction errors When a transaction fails to send, Kit raises one of two high-level error codes that wrap whatever actually went wrong with extra context useful for debugging. ### `SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION` This is the error you get back when sending a single transaction fails. The message itself indicates whether the failure happened during preflight or after the transaction was submitted; the context exposes the underlying error, simulation logs, the preflight result when available, and the full `TransactionPlanResult` for deeper inspection. ```ts twoslash import { SolanaError } from '@solana/kit'; const error = null as unknown as SolanaError; // ---cut-before--- import { isSolanaError, SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION } from '@solana/kit'; if (isSolanaError(error, SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION)) { console.error(error.message); // Includes "(preflight)" or the transaction signature. console.error('Cause:', error.cause); // The underlying error that triggered the failure. console.error('Logs:', error.context.logs); // Program logs, when available. console.error('Preflight:', error.context.preflightData); // Simulation result, when available. } ``` The full `TransactionPlanResult` is also attached as `error.context.transactionPlanResult`, but it is non-enumerable so it does not pollute serialized errors. Cast it to [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult) when you need to walk the tree. ### `SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS` The plural variant is raised when sending more than one transaction fails. Its context exposes a `failedTransactions` array β€” one entry per failure, with the underlying error, its position in the plan, simulation logs, and preflight data β€” plus the same non-enumerable `transactionPlanResult`. ```ts twoslash import { SolanaError } from '@solana/kit'; const error = null as unknown as SolanaError; // ---cut-before--- import { isSolanaError, SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS } from '@solana/kit'; if (isSolanaError(error, SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS)) { for (const { error: cause, index, logs } of error.context.failedTransactions) { console.error(`Transaction #${index + 1} failed:`, cause.message); if (logs) console.error('Logs:', logs); } } ``` Each individual `error` in the array has already been unwrapped from any preflight wrapper, so you can branch on its code directly the same way you would for a standalone `SolanaError`. ## Walking transaction plan results Both failed-transaction errors above expose a `transactionPlanResult` you can inspect, and any successful multi-transaction send returns one directly. A [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult) is a tree that mirrors the original plan, with one of three statuses at each leaf β€” `successful`, `failed`, or `canceled`. Kit ships a small set of helpers for working with these trees without writing your own recursion. [`flattenTransactionPlanResult`](/api/functions/flattenTransactionPlanResult) collapses the tree into an array of leaf results, in the order they appear: ```ts twoslash import { TransactionPlanResult } from '@solana/kit'; const result = null as unknown as TransactionPlanResult; // ---cut-before--- import { flattenTransactionPlanResult } from '@solana/kit'; for (const single of flattenTransactionPlanResult(result)) { if (single.status === 'successful') { console.log('βœ…', single.context.signature); } else if (single.status === 'failed') { console.error('❌', single.error.message); } else { console.warn('⏭️', 'canceled'); } } ``` [`summarizeTransactionPlanResult`](/api/functions/summarizeTransactionPlanResult) bucketizes the leaves into successful, failed, and canceled arrays, plus a single `successful` boolean for the overall outcome: ```ts twoslash import { TransactionPlanResult } from '@solana/kit'; const result = null as unknown as TransactionPlanResult; // ---cut-before--- import { summarizeTransactionPlanResult } from '@solana/kit'; const summary = summarizeTransactionPlanResult(result); console.log(`${summary.successfulTransactions.length} ok`); console.log(`${summary.failedTransactions.length} failed`); console.log(`${summary.canceledTransactions.length} canceled`); ``` [`getFirstFailedSingleTransactionPlanResult`](/api/functions/getFirstFailedSingleTransactionPlanResult) is a convenience for when you only care about the first failure in a tree β€” useful for surfacing a single root cause in error UI: ```ts twoslash import { TransactionPlanResult } from '@solana/kit'; const result = null as unknown as TransactionPlanResult; // ---cut-before--- import { getFirstFailedSingleTransactionPlanResult } from '@solana/kit'; const failed = getFirstFailedSingleTransactionPlanResult(result); console.error('First failure:', failed.error.message); ``` By default, executors throw [`SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN`](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN) on any failure. If you would rather inspect a partial result without a `try`/`catch`, [`passthroughFailedTransactionPlanExecution`](/api/functions/passthroughFailedTransactionPlanExecution) catches that error and returns the embedded `TransactionPlanResult` instead. ```ts twoslash import { TransactionPlanResult } from '@solana/kit'; const sendTransactionsPromise = null as unknown as Promise; // ---cut-before--- import { passthroughFailedTransactionPlanExecution } from '@solana/kit'; const result = await passthroughFailedTransactionPlanExecution(sendTransactionsPromise); ``` ## Program-specific errors Codama-generated program packages export their own error helpers so you can identify and format program-specific failures. The pattern is consistent across packages: an `isXError(error, transactionMessage)` type guard, a `getXErrorMessage(code)` formatter, and an enum-shaped `XError` for individual codes (where `X` is the program name, e.g. `System` for `@solana-program/system`). ```ts twoslash import { SolanaError, TransactionMessage } from '@solana/kit'; const error = null as unknown as SolanaError; const transactionMessage = null as unknown as TransactionMessage; // ---cut-before--- import { getSystemErrorMessage, isSystemError } from '@solana-program/system'; if (isSystemError(error, transactionMessage)) { console.error(`System program error: ${getSystemErrorMessage(error.context.code)}`); console.error(`Failed instruction index: ${error.context.index}`); } ``` When sending a transaction or transaction plan, the program-specific error usually lives a few hops down the chain β€” typically as the `cause` of `SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION` or as one of the `failedTransactions[i].error` entries on the plural variant. Pair the helpers above with the failed-transaction errors documented earlier to surface actionable error messages to your users. ## Error messages ### In development mode When your bundler sets the constant `__DEV__` to `true`, every error message will be included in the bundle. As such, you will be able to read them in plain language wherever they appear. The size of your JavaScript bundle will increase significantly with the inclusion of every error message in development mode. Be sure to build your bundle with `__DEV__` set to `false` when you go to production. ### In production mode When your bundler sets the constant `__DEV__` to `false`, error messages will be stripped from the bundle to save space. Only the error code will appear in the message when an error is encountered. Follow the instructions in the error message to convert the error code back to the human-readable error message. For instance, to recover the error text for the error with code `7050005`: ```shell $ pnpm dlx @solana/errors decode -- 7050005 [Decoded] Solana error code #7050005 - Insufficient funds for fee ``` ```shell $ npx @solana/errors decode -- 7050005 [Decoded] Solana error code #7050005 - Insufficient funds for fee ``` ```shell $ yarn dlx @solana/errors decode -- 7050005 [Decoded] Solana error code #7050005 - Insufficient funds for fee ``` ```shell $ bunx @solana/errors decode -- 7050005 [Decoded] Solana error code #7050005 - Insufficient funds for fee ``` # Advanced Guides (/docs/advanced-guides) These guides go deep on the core building blocks Kit is built from β€” transactions, signers, instruction plans, errors, codecs, keypairs, and more. Each one is a reference you can dip into when you want to understand exactly how something works under the hood. The [Guides](/docs/guides) section covers the practical, task-oriented workflows most applications need day to day, and [plugin-based clients](/docs/plugins) take care of much of this automatically. Reach for the Advanced Guides when you are debugging an unexpected behavior, building a custom plugin, working without a client, or simply curious about what is happening underneath. You can read these guides in any order β€” start with the topic that is closest to what you are working on. # Instruction Plans (/docs/advanced-guides/instruction-plans) ## Introduction Instruction plans describe operations that go beyond a single instruction and may even span multiple transactions. They define a set of instructions that must be executed following a specific order. For instance, imagine we wanted to create an instruction plan for a simple escrow transfer between Alice and Bob. First, both would need to deposit their assets into a vault. This could happen in any order. Then and only then, the vault can be activated to switch the assets. Alice and Bob can now both withdraw each other's assets (again, in any order). Here's how we could describe an instruction plan for such an operation. ```ts twoslash 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]), ]); ``` As you can see, instruction plans don't concern themselves with: * Adding structural instructions β€” e.g. compute budget limits and prices. * Building transaction messages from these instructions. That is, planning how many can fit into a single instruction, adding a fee payer, a lifetime, etc. * Compiling, signing and sending transactions to the network. Instead, they solely focus on describing operations and delegate all that to two components introduced in this package: * **Transaction planner**: builds transaction messages from an instruction plan and returns an appropriate transaction plan. * **Transaction plan executor**: compiles, signs and sends transaction plans and returns a detailed result of this operation. ```ts twoslash import { TransactionPlanner, TransactionPlanExecutor, InstructionPlan } from '@solana/kit'; const instructionPlan = {} as unknown as InstructionPlan; const transactionPlanner = {} as unknown as TransactionPlanner; const transactionPlanExecutor = {} as unknown as TransactionPlanExecutor; // ---cut-before--- // Plan instructions into transactions. const transactionPlan = await transactionPlanner(instructionPlan); // Execute transactions. const transactionPlanResult = await transactionPlanExecutor(transactionPlan); ``` This separation of concerns not only improves the developer experience but also allows program maintainers to offer helper functions that go beyond a single instruction, while leaving their consumers to decide how they want these operations to materialise. ## Installation Instruction plans are **included within the `@solana/kit` library** but you may also install them using their standalone package. ```bash npm install @solana/instruction-plans ``` ```bash pnpm add @solana/instruction-plans ``` ```bash yarn add @solana/instruction-plans ``` ```bash bun add @solana/instruction-plans ``` ## Creating instruction plans This package offers several helpers to help you compose your own instruction plans. Let's have a look at them. ### Single instructions The most trivial way to create an instruction plan is to use the `singleInstructionPlan` helper to create a plan with only one instruction. ```ts twoslash import { singleInstructionPlan, Instruction } from '@solana/kit'; const transferSol = {} as unknown as Instruction; // ---cut-before--- const instructionPlan = singleInstructionPlan(transferSol); ``` ### Sequential plans The `sequentialInstructionPlan` helper allows you to create plans from other plans that must be executed sequentially. Therefore, in the example below, we guarantee that Bob will receive assets from Alice before sending them to Carla. ```ts twoslash import { singleInstructionPlan, sequentialInstructionPlan, Instruction } from '@solana/kit'; const transferFromAliceToBob = {} as unknown as Instruction; const transferFromBobToCarla = {} as unknown as Instruction; // ---cut-before--- const instructionPlan = sequentialInstructionPlan([ singleInstructionPlan(transferFromAliceToBob), singleInstructionPlan(transferFromBobToCarla), ]); ``` Note that the `sequentialInstructionPlan` helper also accept `Instruction` objects directly and automatically wraps them in `singleInstructionPlans`. Therefore the following is equivalent to the previous example. ```ts twoslash import { sequentialInstructionPlan, Instruction } from '@solana/kit'; const transferFromAliceToBob = {} as unknown as Instruction; const transferFromBobToCarla = {} as unknown as Instruction; // ---cut-before--- const instructionPlan = sequentialInstructionPlan([transferFromAliceToBob, transferFromBobToCarla]); ``` A `nonDivisibleSequentialInstructionPlan` helper is also available to define sequential plans whose inner instructions should all be executed atomically. That is, either in a single transaction or in a transaction bundle when not possible. ```ts twoslash import { nonDivisibleSequentialInstructionPlan, Instruction } from '@solana/kit'; const createAccount = {} as unknown as Instruction; const initializeMint = {} as unknown as Instruction; // ---cut-before--- const instructionPlan = nonDivisibleSequentialInstructionPlan([createAccount, initializeMint]); ``` In this example, we know that both instruction will either succeed or fail together. ### Parallel plans The `parallelInstructionPlan` function can be used to create plans from other plans that can be executed in parallel. This means direct children of this plan can be executed in separate parallel transactions without consequence. For instance, in the example below, Alice can transfer assets to both Bob and Carla in any order without affecting the final outcome. ```ts twoslash import { singleInstructionPlan, parallelInstructionPlan, Instruction } from '@solana/kit'; const transferFromAliceToBob = {} as unknown as Instruction; const transferFromAliceToCarla = {} as unknown as Instruction; // ---cut-before--- const instructionPlan = parallelInstructionPlan([ singleInstructionPlan(transferFromAliceToBob), singleInstructionPlan(transferFromAliceToCarla), ]); ``` The `parallelInstructionPlan` also accepts `Instruction` object directly and therefore the previous example can be simplified as: ```ts twoslash import { parallelInstructionPlan, Instruction } from '@solana/kit'; const transferFromAliceToBob = {} as unknown as Instruction; const transferFromAliceToCarla = {} as unknown as Instruction; // ---cut-before--- const instructionPlan = parallelInstructionPlan([transferFromAliceToBob, transferFromAliceToCarla]); ``` ### Message packer plans Message packer plans are a bit special. They can dynamically pack instructions into transaction messages. This is particularly useful when packing instructions whose size will vary based on the available space left on the transaction message being packed. For instance, imagine a `write` instruction on a program that gradually write data from instructions into a buffer account. The instruction data used in this case will ideally be as long as the transaction message can fit. Using the `getLinearMessagePackerInstructionPlan` helper, we can create an instruction plan that does just that. ```ts twoslash import { getLinearMessagePackerInstructionPlan, Instruction } from '@solana/kit'; const dataToWrite = {} as unknown as Uint8Array; const getWriteInstruction = {} as unknown as (params: { offset: number; data: Uint8Array; }) => Instruction; // ---cut-before--- const instructionPlan = getLinearMessagePackerInstructionPlan({ totalLength: dataToWrite.length, getInstruction: (offset, length) => getWriteInstruction({ offset, data: dataToWrite.slice(offset, offset + length), }), }); ``` As you can see, the `getLinearMessagePackerInstructionPlan` helper accepts a `totalLength` attribute representing the total amount of bytes we eventually want to write to the buffer. The purpose of the `getInstruction` function is then to generate these `write` instructions at the provided positions. There also exists a `getReallocMessagePackerInstructionPlan` helper that works similarly but whose purpose is to pack multiple realloc instructions to help resize an account. ```ts twoslash import { getReallocMessagePackerInstructionPlan, Instruction } from '@solana/kit'; const additionalDataSize = {} as unknown as number; const getExtendInstruction = {} as unknown as (params: { length: number }) => Instruction; // ---cut-before--- const instructionPlan = getReallocMessagePackerInstructionPlan({ totalSize: additionalDataSize, getInstruction: (size) => getExtendInstruction({ length: size }), }); ``` Whilst these helpers are fairly situational, you can create any custom message packer as long as you implement the following interfaces. ```ts twoslash import { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/kit'; // ---cut-before--- type MessagePackerInstructionPlan = { getMessagePacker: () => MessagePacker; kind: 'messagePacker'; }; type MessagePacker = { done: () => boolean; packMessageToCapacity: ( transactionMessage: TransactionMessage & TransactionMessageWithFeePayer, ) => TransactionMessage & TransactionMessageWithFeePayer; }; ``` Most of your custom logic will live in the `packMessageToCapacity` function whose purpose is to pack the provided message with as many instruction datas as possible or throw when it isn't achievable. The `done` function lets us know if there is any instruction data left to pack. See [`MessagePacker`](/api/type-aliases/MessagePacker) for more information. ### Combining plans It is worth noting that more complex operations can be created by combining plans together. For instance, the following plan will: * Create two accounts in parallel, one Buffer account and one Metadata account. * The Buffer account will be written to via multiple parallel `write` instructions. * The Metadata account will be created and initialized atomically. * Once both of these accounts are created, the data in the Buffer account will be used to set the data in the Metadata account before being closed. ```ts twoslash import { sequentialInstructionPlan, nonDivisibleSequentialInstructionPlan, parallelInstructionPlan, Instruction, MessagePackerInstructionPlan, } from '@solana/kit'; const createAccount1 = {} as unknown as Instruction; const createAccount2 = {} as unknown as Instruction; const initializeBuffer = {} as unknown as Instruction; const initializeMetadata = {} as unknown as Instruction; const setMetadataFromBuffer = {} as unknown as Instruction; const closeBuffer = {} as unknown as Instruction; const writeMessagePacker = {} as unknown as MessagePackerInstructionPlan; // ---cut-before--- const instructionPlan = sequentialInstructionPlan([ parallelInstructionPlan([ sequentialInstructionPlan([ createAccount1, initializeBuffer, parallelInstructionPlan([writeMessagePacker]), ]), nonDivisibleSequentialInstructionPlan([createAccount2, initializeMetadata]), ]), setMetadataFromBuffer, closeBuffer, ]); ``` ## Planning instructions Once we have an instruction plan, the first step is to build transaction messages from it in the most optimal way whilst satisfying all the constraints defined in the instruction plan. This is the role of **transaction planners**. ### Transaction planners Transaction planners are defined as simple abortable functions that transform a given instruction plan into a set of built transaction messages called a **transaction plan**. ```ts twoslash import { TransactionPlanner, InstructionPlan } from '@solana/kit'; const transactionPlanner = {} as unknown as TransactionPlanner; const instructionPlan = {} as unknown as InstructionPlan; const abortSignal = {} as unknown as AbortSignal; // ---cut-before--- const transactionPlan = await transactionPlanner(instructionPlan, { abortSignal }); ``` ### Creating a transaction planner To spin up a transaction planner, you may use the `createTransactionPlanner` helper. This helper requires a `createTransactionMessage` function that tells us how each new transaction message should be created before being packed with instructions. For instance, in the example below we create a new planner such that each planned transaction message will be using version 0 and using the `payer` signer as a fee payer. ```ts twoslash import { createTransactionPlanner, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, TransactionSigner, } from '@solana/kit'; const payer = {} as unknown as TransactionSigner; // ---cut-before--- const transactionPlanner = createTransactionPlanner({ createTransactionMessage: () => pipe( createTransactionMessage({ version: 0 }), (message) => setTransactionMessageFeePayerSigner(payer, message), // ... ), }); ``` Additionally, the `onTransactionMessageUpdated` function may be provided to update transaction messages during the planning process. This function will be called whenever a transaction message is updated β€” e.g. when new instructions are added. It accepts the updated transaction message and must return a transaction message back, even if no changes were made. In the example below, we check if the packed transaction contains an instruction that transfers SOL and, if so, add a guard instruction that ensures no more than 1 SOL is transferred. ```ts twoslash import { appendTransactionMessageInstruction, createTransactionPlanner, TransactionMessage, Instruction, } from '@solana/kit'; const createTransactionMessage = {} as unknown as Parameters< typeof createTransactionPlanner >[0]['createTransactionMessage']; const containsTransferSolInstruction = {} as unknown as (message: TransactionMessage) => boolean; const transferSolGuardInstruction = {} as unknown as Instruction; // ---cut-before--- const transactionPlanner = createTransactionPlanner({ createTransactionMessage, onTransactionMessageUpdated: (message) => { if (containsTransferSolInstruction(message)) { return appendTransactionMessageInstruction( transferSolGuardInstruction, message, ) as unknown as typeof message; } return message; }, }); ``` Check out the [Recipes section](#recipes) at this end of this guide for ideas of what can be achieved with this API. ### Transaction plans Since transaction planners output transaction plans, it may be useful to see what these look like. They work similarly to instruction plans but they wrap transaction messages instead of instructions and do not contain message packers. * [`singleTransactionPlan`](/api/functions/singleTransactionPlan). Wraps a built transaction message. * [`sequentialTransactionPlan`](/api/functions/sequentialTransactionPlan): Wraps other transaction plans that must be executed sequentially. * [`nonDivisibleSequentialTransactionPlan `](/api/functions/nonDivisibleSequentialTransactionPlan): Wraps other transaction plans that must be executed sequentially and atomically. Since atomicity is at the transaction level, this suggests transaction bundles should be used if possible. Otherwise, the plan should fail to execute. * [`parallelTransactionPlan`](/api/functions/parallelTransactionPlan): Wraps other transaction plans that may be executed in parallel. ```ts twoslash import { singleTransactionPlan, sequentialTransactionPlan, parallelTransactionPlan, TransactionMessage, TransactionMessageWithFeePayer, } from '@solana/kit'; const messageA = {} as unknown as TransactionMessage & TransactionMessageWithFeePayer; const messageB = {} as unknown as TransactionMessage & TransactionMessageWithFeePayer; const messageC = {} as unknown as TransactionMessage & TransactionMessageWithFeePayer; // ---cut-before--- const transactionPlan = parallelTransactionPlan([ sequentialTransactionPlan([singleTransactionPlan(messageA), singleTransactionPlan(messageB)]), singleTransactionPlan(messageC), ]); ``` ### Advanced transaction planners Whilst the `createTransactionPlanner` helper is designed to suit most projects, it may not suit yours. If so, you may create your own by offering a function that satisfy the following signature. ```ts twoslash import { InstructionPlan, TransactionPlan } from '@solana/kit'; // ---cut-before--- type TransactionPlanner = ( instructionPlan: InstructionPlan, config?: { abortSignal?: AbortSignal }, ) => Promise; ``` ## Executing transactions Now that we have obtained a transaction plan from our instruction plan, the next and final step is to send these transactions using a **transaction plan executor**. ### Transaction plan executors Transaction plan executors are defined as abortable functions that transform a given transaction plan into a mirrored data structure that contains the execution status of each transaction. That data structure is called a **transaction plan result**. ```ts twoslash import { TransactionPlanExecutor, TransactionPlan } from '@solana/kit'; const transactionPlanExecutor = {} as unknown as TransactionPlanExecutor; const transactionPlan = {} as unknown as TransactionPlan; const abortSignal = {} as unknown as AbortSignal; // ---cut-before--- const transactionPlanResult = await transactionPlanExecutor(transactionPlan, { abortSignal }); ``` ### Creating a transaction plan executor To spin up a transaction plan executor, you may use the `createTransactionPlanExecutor` helper. This helper requires an `executeTransactionMessage` function that tells us how each transaction message should be executed when encountered during the execution process. The `executeTransactionMessage` callback receives the following arguments: * **`context`**: A mutable object for storing data during execution β€” see the [next section](#the-execution-context) for details. * **`message`**: The transaction message to execute. * **`config`**: An optional configuration object that may include an `abortSignal`. The callback must return the context object that the successful result should carry β€” at minimum, an object containing the transaction `signature`. Anything stored on the mutable `context` argument but left out of the return value is preserved as well, with the returned value taking precedence. For instance, in the example below we create a new executor such that each transaction message will be assigned the latest blockhash lifetime before being signed and sent to the network using the provided RPC client. ```ts twoslash import { sendAndConfirmTransactionFactory, createTransactionPlanExecutor, getSignatureFromTransaction, Rpc, SolanaRpcApi, RpcSubscriptions, SolanaRpcSubscriptionsApi, setTransactionMessageLifetimeUsingBlockhash, signTransactionMessageWithSigners, assertIsSendableTransaction, assertIsTransactionWithBlockhashLifetime, TransactionMessage, TransactionMessageWithFeePayer, } from '@solana/kit'; const rpc = {} as unknown as Rpc; const rpcSubscriptions = {} as unknown as RpcSubscriptions; // ---cut-before--- const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); const transactionPlanExecutor = createTransactionPlanExecutor({ executeTransactionMessage: async (context, message) => { const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const messageWithBlockhash = setTransactionMessageLifetimeUsingBlockhash( latestBlockhash, message, ); context.message = messageWithBlockhash; const transaction = await signTransactionMessageWithSigners(messageWithBlockhash); context.transaction = transaction; const signature = getSignatureFromTransaction(transaction); assertIsSendableTransaction(transaction); assertIsTransactionWithBlockhashLifetime(transaction); await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); return { signature, transaction }; }, }); ``` ### The execution context The `context` object passed to the `executeTransactionMessage` callback is a mutable object that you can populate incrementally as execution progresses. This context is preserved in the resulting `SingleTransactionPlanResult` regardless of the outcome β€” successful, failed, or canceled. This is particularly useful for debugging failures or building recovery plans. If an error is thrown at any point in the callback, any attributes you've already saved to the context will still be available in the `FailedSingleTransactionPlanResult`. The context object supports three optional base properties that have semantic meaning: * **`message`**: The transaction message after any modifications (e.g., after setting a lifetime). * **`transaction`**: The signed transaction ready to be sent. * **`signature`**: The transaction signature. For successful results, provide it in the context returned by your callback; for failed results, it is derived automatically from any `transaction` stored on the context. You can also add any custom properties you need: ```ts twoslash import { createTransactionPlanExecutor, getSignatureFromTransaction, setTransactionMessageLifetimeUsingBlockhash, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, assertIsSendableTransaction, assertIsTransactionWithBlockhashLifetime, Rpc, SolanaRpcApi, RpcSubscriptions, SolanaRpcSubscriptionsApi, } from '@solana/kit'; const rpc = {} as unknown as Rpc; const rpcSubscriptions = {} as unknown as RpcSubscriptions; const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); // ---cut-before--- const transactionPlanExecutor = createTransactionPlanExecutor({ executeTransactionMessage: async (context, message) => { // Store the start time (custom context). context.startedAt = Date.now(); const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const messageWithBlockhash = setTransactionMessageLifetimeUsingBlockhash( latestBlockhash, message, ); // Store the message about to be signed. context.message = messageWithBlockhash; const transaction = await signTransactionMessageWithSigners(messageWithBlockhash); // Store the transaction about to be sent. context.transaction = transaction; assertIsSendableTransaction(transaction); assertIsTransactionWithBlockhashLifetime(transaction); await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); // Return the successful context, including the confirmation time (custom context). return { confirmedAt: Date.now(), signature: getSignatureFromTransaction(transaction), transaction, }; }, }); ``` When accessing the context from a result, you can retrieve both the base properties and your custom properties: ```ts twoslash import { SingleTransactionPlanResult, TransactionPlanResultContextWithSignature, isSuccessfulSingleTransactionPlanResult, isFailedSingleTransactionPlanResult, } from '@solana/kit'; const result = {} as unknown as SingleTransactionPlanResult< TransactionPlanResultContextWithSignature & { startedAt: number } >; // ---cut-before--- if (isSuccessfulSingleTransactionPlanResult(result)) { console.log(result.context.signature); // Always available for successful results. console.log(result.context.transaction); // Available if you stored it. console.log(result.context.startedAt); // Custom context property. } if (isFailedSingleTransactionPlanResult(result)) { console.log(result.error); // The error that caused the failure. console.log(result.context.message); // Available if stored before the failure. console.log(result.context.transaction); // Available if stored before the failure. console.log(result.context.startedAt); // Custom context property. } ``` Check out the [Recipes section](#recipes) at this end of this guide for ideas of what can be achieved with this API. ### Transaction plan results When you execute a transaction plan, you get back a `TransactionPlanResult` that tells you what happened during execution. This result object has the same tree structure as your original transaction plan, but includes execution information for each transaction message. Each transaction message in your plan can have one of three execution outcomes: * **Successful** - The transaction was sent and confirmed. You get the original planned message, a context object containing the signature (and optionally the transaction), plus any custom context data. * **Failed** - The transaction encountered an error. You get the original planned message, the error that caused the failure, and a context object with any data accumulated before the failure. * **Canceled** - The transaction was skipped because an earlier transaction failed or the operation was aborted. You get the original planned message with any context data accumulated before cancellation. The result structure mirrors your transaction plan structure: * Single transaction messages become `SingleTransactionPlanResult` with the original `plannedMessage` plus execution status * Sequential plans become `SequentialTransactionPlanResult` containing child results * Parallel plans become `ParallelTransactionPlanResult` containing child results Each `SingleTransactionPlanResult` has a `status` property that is a string literal (`'successful'`, `'failed'`, or `'canceled'`), and properties like `context`, `error` live at the top level of each variant. ```ts twoslash import { parallelTransactionPlan, singleTransactionPlan, parallelTransactionPlanResult, successfulSingleTransactionPlanResult, failedSingleTransactionPlanResult, isSuccessfulSingleTransactionPlanResult, isFailedSingleTransactionPlanResult, SolanaError, Signature, TransactionMessage, TransactionMessageWithFeePayer, Transaction, } from '@solana/kit'; const messageA = {} as unknown as TransactionMessage & TransactionMessageWithFeePayer; const messageB = {} as unknown as TransactionMessage & TransactionMessageWithFeePayer; const transactionA = {} as unknown as Transaction; const signatureA = {} as unknown as Signature; const error = {} as unknown as SolanaError; // ---cut-before--- // If your transaction plan looked like this: const plan = parallelTransactionPlan([ singleTransactionPlan(messageA), singleTransactionPlan(messageB), ]); // Your result may look like this: const result = parallelTransactionPlanResult([ successfulSingleTransactionPlanResult(messageA, { signature: signatureA, transaction: transactionA }), failedSingleTransactionPlanResult(messageB, error), ]); // Access the signature from a successful result: if (isSuccessfulSingleTransactionPlanResult(result.plans[0])) { console.log(result.plans[0].context.signature); console.log(result.plans[0].context.transaction); // If available } // Access the error from a failed result: if (isFailedSingleTransactionPlanResult(result.plans[1])) { console.log(result.plans[1].error); console.log(result.plans[1].context.signature); // If available console.log(result.plans[1].context.transaction); // If available } ``` ### Working with transaction plan results The `flattenTransactionPlanResult` function collapses a result tree into a flat array of all [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult) instances, regardless of how they are nested in parallel or sequential structures. ```ts twoslash import { flattenTransactionPlanResult, TransactionPlanResult } from '@solana/kit'; const result = {} as unknown as TransactionPlanResult; // ---cut-before--- for (const single of flattenTransactionPlanResult(result)) { if (single.status === 'successful') { console.log('βœ…', single.context.signature); } else if (single.status === 'failed') { console.error('❌', single.error.message); } else { console.warn('⚠️ Transaction was canceled'); } } ``` The `summarizeTransactionPlanResult` function provides a higher-level view by bucketing all single results into `successfulTransactions`, `failedTransactions`, and `canceledTransactions` arrays. It also exposes a `successful` boolean that is `true` only when there are no failures or cancellations. ```ts twoslash import { summarizeTransactionPlanResult, TransactionPlanResult } from '@solana/kit'; const result = {} as unknown as TransactionPlanResult; // ---cut-before--- const summary = summarizeTransactionPlanResult(result); if (summary.successful) { console.log(`All ${summary.successfulTransactions.length} transactions confirmed`); } else { console.warn( `${summary.failedTransactions.length} failed, ${summary.canceledTransactions.length} canceled`, ); } ``` ### Failed transaction executions When a transaction plan executor β€” created via the `createTransactionPlanExecutor` helper β€” encounters a failed transaction, it will cancel all remaining transactions in the plan. The executor will then throw a `SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN` error code. This error contains a `transactionPlanResult` property (accessible as a non-enumerable property) that provides detailed information about which transactions succeeded, failed, or were canceled. ```ts twoslash import { TransactionPlan, TransactionPlanExecutor, SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN, isSolanaError, TransactionPlanResult, } from '@solana/kit'; const transactionPlan = {} as unknown as TransactionPlan; const transactionPlanExecutor = {} as unknown as TransactionPlanExecutor; // ---cut-before--- try { const result = await transactionPlanExecutor(transactionPlan); } catch (error) { if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN)) { // Access the failed `TransactionPlanResult` to understand what happened. const result = error.context.transactionPlanResult as TransactionPlanResult; } } ``` ### Advanced transaction plan executors Whilst the `createTransactionPlanExecutor` helper is designed to suit most projects, it may not suit yours. If so, you may create your own by offering a function that satisfies the following signature. ```ts twoslash import { TransactionPlan, TransactionPlanResult } from '@solana/kit'; // ---cut-before--- type TransactionPlanExecutor = ( transactionPlan: TransactionPlan, config?: { abortSignal?: AbortSignal }, ) => Promise; ``` This allows you to implement custom execution strategies, such as using transaction bundles for atomic execution or adding custom transaction prioritization. Bundled clients such as `solanaRpc` and `litesvm` install ready-to-use planner and executor implementations on the client. See [Available plugins](/docs/plugins/available-plugins) for the full list, and [Sending multiple transactions](/docs/guides/sending-multiple-transactions) for the consumer-facing API they expose. ## Recipes Here are some common patterns and recipes for using instruction plans effectively. ### Setting priority fees You can set priority fees by using the [`setTransactionMessageComputeUnitPrice`](/api/functions/setTransactionMessageComputeUnitPrice) helper from `@solana/kit` in your `createTransactionMessage` function. See [Configuring compute and priority fees](/docs/advanced-guides/transactions#configuring-priority-fees) for the full set of fee setters, including the v1 [`setTransactionMessagePriorityFeeLamports`](/api/functions/setTransactionMessagePriorityFeeLamports) variant. ```ts twoslash import { createTransactionPlanner, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, TransactionSigner, } from '@solana/kit'; const payer = {} as unknown as TransactionSigner; // ---cut-before--- import { setTransactionMessageComputeUnitPrice } from '@solana/kit'; // [!code ++] const transactionPlanner = createTransactionPlanner({ createTransactionMessage: () => pipe( createTransactionMessage({ version: 0 }), (message) => setTransactionMessageFeePayerSigner(payer, message), // [!code ++:2] // Set priority fees to 0.01 lamports per compute unit. (message) => setTransactionMessageComputeUnitPrice(10_000n, message), ), }); ``` ### Estimating compute units You can estimate and set compute units and other resource limits dynamically by using a two-step process: * First, add provisory resource limits (if missing) in your transaction planner. * Then, estimate and update them right before sending the transaction. The [`fillTransactionMessageProvisoryResourceLimits`](/api/functions/fillTransactionMessageProvisoryResourceLimits) helper from `@solana/kit` reserves the limits by setting them to a provisory value of `0`, so the planner can account for the resulting compute budget instructions when packing transaction messages. See [Estimating compute units](/docs/advanced-guides/transactions#configuring-resource-limit-estimation) for the full estimator API. ```ts twoslash import { createTransactionPlanner, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, TransactionSigner, } from '@solana/kit'; const payer = {} as unknown as TransactionSigner; // ---cut-before--- import { fillTransactionMessageProvisoryResourceLimits } from '@solana/kit'; // [!code ++] const transactionPlanner = createTransactionPlanner({ createTransactionMessage: () => pipe( createTransactionMessage({ version: 0 }), (message) => setTransactionMessageFeePayerSigner(payer, message), (message) => fillTransactionMessageProvisoryResourceLimits(message), // [!code ++] ), }); ``` Then, pair [`estimateResourceLimitsFactory`](/api/functions/estimateResourceLimitsFactory) with [`estimateAndSetResourceLimitsFactory`](/api/functions/estimateAndSetResourceLimitsFactory) in your transaction plan executor to estimate the resource limits right before sending the transaction. ```ts twoslash import { sendAndConfirmTransactionFactory, createTransactionPlanExecutor, getSignatureFromTransaction, Rpc, SolanaRpcApi, RpcSubscriptions, SolanaRpcSubscriptionsApi, setTransactionMessageLifetimeUsingBlockhash, signTransactionMessageWithSigners, assertIsSendableTransaction, assertIsTransactionWithBlockhashLifetime, TransactionMessage, TransactionMessageWithFeePayer, } from '@solana/kit'; const rpc = {} as unknown as Rpc; const rpcSubscriptions = {} as unknown as RpcSubscriptions; // ---cut-before--- // [!code ++:4] import { estimateAndSetResourceLimitsFactory, estimateResourceLimitsFactory, } from '@solana/kit'; const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); // [!code ++:2] const estimateResourceLimits = estimateResourceLimitsFactory({ rpc }); const estimateAndSetResourceLimits = estimateAndSetResourceLimitsFactory(estimateResourceLimits); const transactionPlanExecutor = createTransactionPlanExecutor({ executeTransactionMessage: async (context, message) => { const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const messageWithBlockhash = setTransactionMessageLifetimeUsingBlockhash( latestBlockhash, message, ); context.message = messageWithBlockhash; const estimatedMessage = await estimateAndSetResourceLimits(messageWithBlockhash); // [!code ++] context.message = estimatedMessage; // [!code ++] const transaction = await signTransactionMessageWithSigners(estimatedMessage); context.transaction = transaction; const signature = getSignatureFromTransaction(transaction); assertIsSendableTransaction(transaction); assertIsTransactionWithBlockhashLifetime(transaction); await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); return { signature, transaction }; }, }); ``` ### Durable nonce executor You may create transaction plans that use durable nonces for offline transaction signing by using the `setTransactionMessageLifetimeUsingDurableNonce` helper in your transaction planner. ```ts twoslash import { createTransactionPlanner, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, TransactionSigner, } from '@solana/kit'; const payer = {} as unknown as TransactionSigner; const config = {} as unknown as Parameters< typeof setTransactionMessageLifetimeUsingDurableNonce >['0']; const nonce = config.nonce; const nonceAccountAddress = config.nonceAccountAddress; const nonceAuthorityAddress = config.nonceAuthorityAddress; // ---cut-before--- import { setTransactionMessageLifetimeUsingDurableNonce } from '@solana/kit'; // [!code ++] const transactionPlanner = createTransactionPlanner({ createTransactionMessage: () => { return pipe( createTransactionMessage({ version: 0 }), (message) => setTransactionMessageFeePayerSigner(payer, message), // [!code ++:5] (message) => setTransactionMessageLifetimeUsingDurableNonce( { nonce, nonceAccountAddress, nonceAuthorityAddress }, message, ), ); }, }); ``` Then, make sure to use the `sendAndConfirmDurableNonceTransactionFactory` helper in your transaction plan executor in order to use the appropriate confirmation strategy for your transactions. ```ts twoslash import { createTransactionPlanExecutor, getSignatureFromTransaction, Rpc, SolanaRpcApi, RpcSubscriptions, SolanaRpcSubscriptionsApi, signTransactionMessageWithSigners, assertIsSendableTransaction, TransactionMessage, TransactionMessageWithFeePayer, assertIsTransactionWithDurableNonceLifetime, } from '@solana/kit'; const rpc = {} as unknown as Rpc; const rpcSubscriptions = {} as unknown as RpcSubscriptions; // ---cut-before--- // [!code ++:4] import { assertIsTransactionMessageWithDurableNonceLifetime, sendAndConfirmDurableNonceTransactionFactory, } from '@solana/kit'; // [!code ++:4] const sendAndConfirmDurableNonceTransaction = sendAndConfirmDurableNonceTransactionFactory({ rpc, rpcSubscriptions, }); const transactionPlanExecutor = createTransactionPlanExecutor({ executeTransactionMessage: async (context, message) => { assertIsTransactionMessageWithDurableNonceLifetime(message); // [!code ++] context.message = message; const transaction = await signTransactionMessageWithSigners(message); context.transaction = transaction; const signature = getSignatureFromTransaction(transaction); assertIsSendableTransaction(transaction); assertIsTransactionWithDurableNonceLifetime(transaction); await sendAndConfirmDurableNonceTransaction(transaction, { commitment: 'confirmed' }); // [!code ++] return { signature, transaction }; }, }); ``` # Key pairs (/docs/advanced-guides/keypairs) ## Introduction Kit uses the primitives built-in to JavaScript’s Web Crypto API to perform cryptography. This keeps your applications small, and confers to them the security and performance characteristics of the runtime's native cryptography functions. Ed25519 keys created or imported using the native APIs are compatible with all of Kit's cryptographic features. Kit also offers several helpers to generate, import, and transform key material. Keys are a low-level primitive. While it's important to know how they work, in a Solana application it's often more appropriate to deal with key material in terms of the accounts and wallets that sign a transaction or message. The [Signers](/docs/advanced-guides/signers) API offers an ergonomic way to build and sign transactions using accounts and their associated keys. ## Installation Key management functions are **included within the `@solana/kit` library** but you may also install them using their standalone package. ```bash npm install @solana/keys ``` ```bash pnpm add @solana/keys ``` ```bash yarn add @solana/keys ``` ```bash bun add @solana/keys ``` When deploying your application to a JavaScript runtime that lacks support for the Ed25519 digital signature algorithm, [import our polyfill](#polyfill) before invoking any operations that create or make use of `CryptoKey` objects. ## What is a key pair? A key pair is a data type composed of 256-bits of random data (the private key) and a Cartesian point (the public key) on the curve that is used to cryptographically sign and verify Solana transactions. The interface definition of `CryptoKeyPair` is: ```ts interface CryptoKeyPair { privateKey: CryptoKey; publicKey: CryptoKey; } ``` Together, these keys represent an address on Solana and its owner. The 256-bit address is derived from the coordinates of the public key itself. ## What is a key? A key is an object native to the JavaScript runtime that supports the [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) interface. You can use a `CryptoKey` with the native [`SubtleCrypto` API](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) to sign messages and to verify signatures. Kit builds on these capabilities to enable the use of `CryptoKey` objects to sign and verify Solana transactions and off-chain messages. ## Managing keys ### Generating new keys You can use the native [`SubtleCrypto#generateKey`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) API, or the [`generateKeyPair()`](/api/functions/generateKeyPair) helper to create a new random key pair. ```ts twoslash const keyPair = await crypto.subtle.generateKey( /* algorithm */ { name: 'Ed25519' }, /* extractable */ false, /* usages */ ['sign', 'verify'], ); ``` ```ts twoslash import { generateKeyPair } from '@solana/kit'; const keyPair = await generateKeyPair(); ``` This is useful in cases where you need to sign for the creation of a new account with a random address, using an ephemeral key pair that can be discarded after the account is created and assigned to a program. ### Importing a key You can create a `CryptoKeyPair` using the 64 bytes of a pre-generated key. This is possible to do with the native [`SubtleCrypto#importKey`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey) API, but it is more convenient to use the helpers in Kit. ```ts twoslash import { createKeyPairFromBytes } from '@solana/kit'; const keyPair = await createKeyPairFromBytes( new Uint8Array([ /* 32 bytes representing the private key */ /* 32 bytes representing the public key */ ]), ); ``` In cases where you have only the 32 bytes representing the private key but not its associated public key, you can use a different function that will automatically derive the public key from the private key. ```ts twoslash import { createKeyPairFromPrivateKeyBytes } from '@solana/kit'; const keyPair = await createKeyPairFromPrivateKeyBytes( new Uint8Array([ /* 32 bytes representing the private key */ ]), ); ``` ### Storing keys `CryptoKey` objects can be stored locally by runtimes that support the [IndexedDB API](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API). Given an instance of an `IDBDatabase` with an object store called `'MyKeyPairStore'`: ```ts twoslash const db = await new Promise((resolve, reject) => { const request = indexedDB.open('MyDatabase', 1); request.onupgradeneeded = (e) => { const db = (e.target as IDBOpenDBRequest).result; db.createObjectStore('MyKeyPairStore'); }; request.onsuccess = (e) => { resolve((e.target as IDBOpenDBRequest).result); }; request.onerror = (e) => { reject((e.target as IDBOpenDBRequest).error); }; }); ``` You can store a key pair like this: ```ts twoslash const db = null as unknown as IDBDatabase; const keyPair = null as unknown as CryptoKeyPair; // ---cut-before--- const transaction = db.transaction('MyKeyPairStore', 'readwrite'); const store = transaction.objectStore('MyKeyPairStore'); await new Promise((resolve, reject) => { const request = store.put(keyPair, 'myStoredKey'); request.onsuccess = () => resolve(); request.onerror = () => reject(request.error); }); ``` And then later retrieve it like this: ```ts twoslash const db = null as unknown as IDBDatabase; // ---cut-before--- const transaction = db.transaction('MyKeyPairStore', 'readonly'); const store = transaction.objectStore('MyKeyPairStore'); const loadedKeyPair = await new Promise((resolve, reject) => { const request = store.get('myStoredKey'); request.onsuccess = () => { if (request.result) { resolve(request.result); } else { reject(new Error('Key not found')); } }; request.onerror = () => reject(request.error); }); ``` Keys stored in IndexedDB are local to the host, are subject to its [storage limits and eviction criteria](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API#storage_limits_and_eviction_criteria), and can not be accessed from a domain other than the one that stored them when the host is a web browser. Keys that are evicted from storage or erased by the user can generally not be recovered. ### Exporting a key You can obtain the 32 bytes of any public key like this: ```ts twoslash const keyPair = null as unknown as CryptoKeyPair; // ---cut-before--- const publicKeyBytes = new Uint8Array(await crypto.subtle.exportKey('raw', keyPair.publicKey)); ``` Exporting private key material requires a specially constructed `CryptoKey` with its extractable property set to `true`. ```ts twoslash const keyPair = await crypto.subtle.generateKey( /* algorithm */ { name: 'Ed25519' }, /* extractable */ true, // ^^^^ /* usages */ ['sign', 'verify'], ); ``` You can then use that `CryptoKey` with the [`SubtleCrypto#exportKey`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey) API. The last 32 bytes of a PKCS#8 export of the key are the private key bytes. ```ts twoslash const keyPair = null as unknown as CryptoKeyPair; // ---cut-before--- const exportedPrivateKey = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey); const privateKeyBytes = new Uint8Array(exportedPrivateKey, exportedPrivateKey.byteLength - 32, 32); ``` Exporting private key material in JavaScript is not recommended, and you should take extreme care when doing so. Private key bytes exported through these APIs are vulnerable to theft (eg. by code running in your JavaScript sandbox) and accidental logging (eg. to the console or to a third-party logger). ## Using private keys A private key is a `CryptoKey` whose `type` property is set to `'private'` and whose `usages` property includes `'sign'`. Private keys can be used by their owner to produce a digital signature of a specific message. You can think of a signature as representing the key owner's approval of, agreement to, or endorsement of the message. Private key owners must never share the key with anyone. ### Signing messages Any data that you can serialize as a `Uint8Array` can be signed with a `CryptoKey`. ```ts twoslash import { ReadonlyUint8Array } from '@solana/kit'; // ---cut-before--- import { getU32Encoder, getUtf8Encoder } from '@solana/kit'; const messageFromText = getUtf8Encoder().encode('πŸŽ‰'); const messageFromU32 = getU32Encoder().encode(0xdeadbeef); const messageOfBytes = new Uint8Array([1, 2, 3]); ``` Supply a message and a private key to the [`signBytes()`](/api/functions/signBytes) function to obtain a 64-byte digital signature. ```ts twoslash const bobsKeyPair = null as unknown as CryptoKeyPair; // ---cut-before--- import { getUtf8Encoder, signBytes } from '@solana/kit'; const message = getUtf8Encoder().encode('The meeting is at 6:00pm'); const bobsSignature = await signBytes(bobsKeyPair.privateKey, message); console.log(bobsSignature); // @log: Uint8Array(64) [79, 43, 140, 65, 177, 35, 169, 61, 62, 228, 190, 202, 205, 143, 4, 35, 83, 228, 47, 76, 68, 62, 125, 140, 21, 102, 182, 105, 24, 238, 67, 40, 179, 255, 247, 136, 95, 119, 46, 244, 44, 224, 100, 111, 68, 110, 189, 224, 159, 144, 197, 181, 210, 132, 101, 226, 120, 200, 0, 102, 104, 65, 216, 3] ``` The same message and private key might produce a different signature every time you call this function. Some runtimes produce randomized signatures as per [draft-irtf-cfrg-det-sigs-with-noise](https://datatracker.ietf.org/doc/draft-irtf-cfrg-det-sigs-with-noise/) while others produce deterministic signatures as per [RFC 8032](https://www.rfc-editor.org/rfc/rfc8032). ### Signing transactions In Kit, private keys are used to digitally sign transactions on behalf of account owners, to approve spending, transfers, and modifications to account data on the blockchain. ```ts twoslash import { Transaction, TransactionWithLifetime } from '@solana/kit'; const transaction = null as unknown as Transaction & TransactionWithLifetime; const bobsKeyPair = null as unknown as CryptoKeyPair; // ---cut-before--- import { signTransaction } from '@solana/kit'; const signedTransaction = await signTransaction([bobsKeyPair], transaction); ``` In practice, it's rare to sign transactions like this. Typically, you create a transaction message in your application, specify which accounts are required to sign it using the [Signers API](/docs/advanced-guides/signers), and then call [`signTransactionMessageWithSigners`](/api/functions/signTransactionMessageWithSigners) to turn it into a signed `Transaction`. ## Using public keys A public key is a `CryptoKey` whose `type` property is set to `'public'` and whose `usages` property includes `'verify'`. Solana uses public keys to verify that modifications to account data and balances through transactions are approved of by those who hold the private keys required to authorize such modifications. Kit generally only uses public keys to derive the address of their associated accounts, but it can also use public keys to enable your programs to verify arbitrary messages. ### Verifying signatures The public key associated with a given private key can be used by anyone to verify that a message was signed by the holder of the associated private key, as described above. The verification function requires the original message, a digital signature, and the public key associated with the owner who is believed to have produced that signature. Successful verification implies that the contents of the message signed by the owner are identical to the contents of the message that was given to the verification function. Key owners are free to share their public key with anyone they would like to grant the ability to verify their digital signatures. If someone sends us a message and signature that they claim to be from the example above, we could use Bob's public key to verify that the signature was in fact the one produced by Bob and that the message was not modified in transit. ```ts twoslash import { SignatureBytes } from '@solana/kit'; const bobsPublicKey = null as unknown as CryptoKey; const supposedlyBobsSignature = null as unknown as SignatureBytes; // ---cut-before--- import { getUtf8Encoder, verifySignature } from '@solana/kit'; const verificationSucceeded = await verifySignature( bobsPublicKey, supposedlyBobsSignature, getUtf8Encoder().encode('The meeting is at 6:00pm'), ); if (!verificationSucceeded) { throw new Error( 'Either the message was modified, the signature was not produced by Bob, or both', ); } ``` Verification protects equally against false claims of who produced the signature as it does against false claims about what message was signed. Both of these will return `false`; {/* prettier-ignore */} ```ts twoslash import { SignatureBytes } from '@solana/kit'; const bobsPublicKey = null as unknown as CryptoKey; const bobsSignature = null as unknown as SignatureBytes; const mallorysSignature = null as unknown as SignatureBytes; const signature = null as unknown as SignatureBytes; // ---cut-before--- import { getUtf8Encoder, verifySignature } from '@solana/kit'; // False claim that Bob signed the message when it was in fact Mallory await verifySignature( bobsPublicKey, mallorysSignature, //^^^^^^^^^^^^^^^^^ getUtf8Encoder().encode('The meeting is at 6:00pm'), ); // False claim about the contents of the message await verifySignature( bobsPublicKey, bobsSignature, getUtf8Encoder().encode('The meeting is at 6:00am'), // ^^^^^^ ); ``` ### Deriving addresses The Solana address associated with any public key can be derived using the [`getAddressFromPublicKey()`](/api/functions/getAddressFromPublicKey) function. ```ts twoslash const keyPair = null as unknown as CryptoKeyPair; // ---cut-before--- import { getAddressFromPublicKey } from '@solana/kit'; const address = await getAddressFromPublicKey(keyPair.publicKey); ``` ## Signatures The [`SignatureBytes`](/api/type-aliases/SignatureBytes) type represents a 64-byte Ed25519 signature, and the [`Signature`](/api/type-aliases/Signature) type represents such a signature as a base58-encoded string. When you acquire a string that you expect to be a base58-encoded signature (eg. of a transaction) from an untrusted network API or user input you can assert it is in fact a base58-encoded byte array of sufficient length using the [`assertIsSignature()`](/api/functions/assertIsSignature) function. ```ts twoslash // @noErrors: 1308 import { GetSignatureStatusesApi, Rpc } from '@solana/kit'; const rpc = null as unknown as Rpc; const signatureInput = null as unknown as HTMLInputElement; // ---cut-before--- import { assertIsSignature } from '@solana/kit'; // Imagine a function that asserts whether a user-supplied signature is valid or not. function handleSubmit() { // We know only that what the user typed conforms to the `string` type. const signature: string = signatureInput.value; try { // If this type assertion function doesn't throw, then // Typescript will upcast `signature` to `Signature`. assertIsSignature(signature); // At this point, `signature` is a `Signature` that can be used with the RPC. const { value: [status], } = await rpc.getSignatureStatuses([signature]).send(); } catch (e) { // `signature` turned out not to be a base58-encoded signature } } ``` Similarly, you can use the [`isSignature()`](/api/functions/isSignature) type guard. It will return `true` if the input string conforms to the `Signature` type and will refine the type for use in your program from that point onward. This method does not throw in the opposite case. ```ts twoslash import { GetSignatureStatusesApi, Rpc } from '@solana/kit'; const rpc = null as unknown as Rpc; const signature = ''; function setError(s: string) {} function setSignatureStatus( s: ReturnType['value'][number], ) {} // ---cut-before--- import { isSignature } from '@solana/kit'; if (isSignature(signature)) { // At this point, `signature` has been refined to a // `Signature` that can be used with the RPC. const { value: [status], } = await rpc.getSignatureStatuses([signature]).send(); setSignatureStatus(status); } else { setError(`${signature} is not a transaction signature`); } ``` The [`signature()`](/api/functions/signature) helper combines *asserting* that a string is an Ed25519 signature with *coercing* it to the `Signature` type. It's best used with untrusted input. ```ts import { signature } from '@solana/kit'; const signature = signature(userSuppliedSignature); const { value: [status], } = await rpc.getSignatureStatuses([signature]).send(); ``` ## Runtime Support All major JavaScript runtimes support the Ed25519 digital signature algorithm required by Solana. | | Runtime | Min version | Since | | -------------------: | -------------------- | ------------- | -------- | | **Desktop browsers** | Chrome | v137 | May 2025 | | | Edge | v137 | May 2025 | | | Firefox | v130 | Sep 2024 | | | Safari | v17 | Sep 2023 | | **Mobile browsers** | Android browser | v137 | May 2025 | | | Firefox for Android | v139 | May 2025 | | | Mobile Safari | iOS 17 | Sep 2023 | | **Server runtimes** | Bun | v1.2.6 | Mar 2025 | | | Cloudflare `workerd` | v1.20230419.0 | Apr 2023 | | | Deno | v1.26.1 | Oct 2022 | | | Node.js | v18.4.0 | Jun 2022 | | | Vercel Edge | v2.3.0 | May 2023 | For additional up-to-date details on runtimes' implementation status, visit [https://github.com/WICG/webcrypto-secure-curves/issues/20](https://github.com/WICG/webcrypto-secure-curves/issues/20). ### Ed25519 Polyfill To use keys in a runtime without Ed25519 digital signature algorithm support, install the following polyfill. ```bash npm install @solana/webcrypto-ed25519-polyfill ``` ```bash pnpm add @solana/webcrypto-ed25519-polyfill ``` ```bash yarn add @solana/webcrypto-ed25519-polyfill ``` ```bash bun add @solana/webcrypto-ed25519-polyfill ``` Then import and install it before invoking any operations that create or make use of `CryptoKey` objects. ```ts twoslash 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']); ``` Wherever you call `install()`, make sure the call is made only once, and before any key operation requiring Ed25519 support is performed. Because the polyfill's implementation of Ed25519 key generation exists in userspace, it can't guarantee that the keys you generate with it are non-exportable. Untrusted code running in your JavaScript context may still be able to gain access to and/or exfiltrate secret key material. Native `CryptoKeys` can be stored in IndexedDB, but the keys created by this polyfill can not. This is because, unlike native `CryptoKeys`, our polyfilled key objects can not implement the [structured clone algorithm](https://www.w3.org/TR/WebCryptoAPI/#cryptokey-interface-clone). # Kit without a client (/docs/advanced-guides/kit-without-a-client) This guide shows how to achieve the same capabilities a [Kit client](/docs/plugins) gives you, but using Kit's primitives directly. The page is organized as a reference: each section takes one piece of what a fully composed client offers and shows the manual equivalent, so you can pick and choose the exact bits you need. ## When to skip the client Going client-less is the right choice when you want the smallest possible bundles, full control over every step of the transaction lifecycle, or when you are writing library code that should not assume a Kit client. The cost is a little more boilerplate and a less prescriptive structure. The client model, on the other hand, gives you consistent ergonomics and a curated set of plugin interfaces other plugins can build on. If you need ergonomics on top of a curated set of primitives, consider [creating a custom plugin bundle](/docs/plugins/creating-custom-plugins) instead. A bundle plugin is just a regular plugin that composes several smaller ones, so you keep the client model while owning exactly which primitives are wired up. ## Set up RPC Kit ships two factories for talking to a Solana RPC node: `createSolanaRpc` for HTTP requests and `createSolanaRpcSubscriptions` for the WebSocket channel. Both return typed proxies with the full Solana JSON-RPC API surface available on them. ```ts twoslash import { createSolanaRpc, createSolanaRpcSubscriptions } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); ``` The objects returned by these factories are exactly what `client.rpc` and `client.rpcSubscriptions` expose under the hood, so any code that takes an `Rpc` or `RpcSubscriptions` works in either setup. See [RPC requests](/docs/guides/rpc) and [RPC subscriptions](/docs/guides/rpc-subscriptions) for the user-facing API. ## Create a signer The most common way to create a signer is to generate a fresh in-memory keypair with `generateKeyPairSigner`. The returned object is a `KeyPairSigner` that satisfies both the `TransactionSigner` and `MessageSigner` interfaces. ```ts twoslash import { generateKeyPairSigner } from '@solana/kit'; const signer = await generateKeyPairSigner(); ``` If you already have a keypair stored as a JSON byte array β€” for example, a Solana CLI keypair file β€” you can rebuild a signer from it with `createKeyPairSignerFromBytes`. See [Setting up signers](/docs/guides/setting-up-signers) for the broader signer setup story and [Advanced guides β€” Signers](/docs/advanced-guides/signers) for the underlying signer interfaces. ```ts twoslash import { createKeyPairSignerFromBytes } from '@solana/kit'; import { readFileSync } from 'node:fs'; const bytes = JSON.parse(readFileSync('keypair.json', 'utf-8')) as number[]; const signer = await createKeyPairSignerFromBytes(new Uint8Array(bytes)); ``` ## Build a transaction message Kit transaction messages are immutable: each helper returns a new object with a narrower type, so TypeScript can enforce that required fields are set before the message is signed or sent. The `pipe` helper threads a value through a sequence of transformations and lets the type narrow at each step. ```ts twoslash import { appendTransactionMessageInstructions, createTransactionMessage, Instruction, pipe, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, } from '@solana/kit'; // ---cut-start--- import { createSolanaRpc, generateKeyPairSigner } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const signer = await generateKeyPairSigner(); const instructionA = {} as Instruction; const instructionB = {} as Instruction; // ---cut-end--- const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions([instructionA, instructionB], tx), ); ``` This is the same composition the bundled clients use internally. See [Advanced guides β€” Transactions](/docs/advanced-guides/transactions) for the full transaction message API, including durable-nonce lifetimes and other configuration helpers. ## Estimate compute units Setting explicit resource limits (the compute unit limit, and on version 1 transactions the loaded accounts data size limit) close to what your transaction actually consumes increases the chance of inclusion, packs more transactions per block, and reduces priority fees. Kit ships everything you need for this without leaving `@solana/kit`: `estimateResourceLimitsFactory` simulates the message to estimate the compute unit limit (and the loaded accounts data size limit for version 1 transactions), and `estimateAndSetResourceLimitsFactory` wraps that estimator to write the result back onto the message in one step. ```ts twoslash import { estimateAndSetResourceLimitsFactory, estimateResourceLimitsFactory, TransactionMessage, TransactionMessageWithFeePayer, } from '@solana/kit'; // ---cut-start--- import { createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const transactionMessage = {} as TransactionMessage & TransactionMessageWithFeePayer; // ---cut-end--- const estimateResourceLimits = estimateResourceLimitsFactory({ rpc }); const estimateAndSetResourceLimits = estimateAndSetResourceLimitsFactory(estimateResourceLimits); const transactionMessageWithLimits = await estimateAndSetResourceLimits(transactionMessage); ``` Bundled clients such as `solanaRpc` and `litesvm` already do this for you when sending transactions. ## Sign the transaction Once a transaction message is fully configured, `signTransactionMessageWithSigners` extracts every signer attached to it (the fee payer plus any signer-typed instruction inputs) and produces a signed `Transaction`. ```ts twoslash import { signTransactionMessageWithSigners, TransactionMessage, TransactionMessageWithFeePayer, } from '@solana/kit'; // ---cut-start--- const transactionMessage = {} as TransactionMessage & TransactionMessageWithFeePayer; // ---cut-end--- const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); ``` Two assertions are typically useful at this point: `assertIsSendableTransaction` verifies the transaction has every required signature and fits within the size limit, and `assertIsTransactionWithBlockhashLifetime` narrows the lifetime so it can be passed to `sendAndConfirmTransactionFactory` below. The transaction identifier on Solana is the fee payer's signature, which is fully determined as soon as the fee payer signs β€” `getSignatureFromTransaction(signedTransaction)` returns that identifier directly, without needing to send the transaction first. ## Send and confirm a transaction `sendAndConfirmTransactionFactory` builds a function that sends a signed transaction and waits for the configured commitment. It needs both an `rpc` and an `rpcSubscriptions` because confirmation listens to slot and signature notifications. ```ts twoslash import { SendableTransaction, sendAndConfirmTransactionFactory, Transaction, TransactionWithBlockhashLifetime, } from '@solana/kit'; // ---cut-start--- import { createSolanaRpc, createSolanaRpcSubscriptions } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); const signedTransaction = {} as Transaction & SendableTransaction & TransactionWithBlockhashLifetime; // ---cut-end--- const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); await sendAndConfirmTransaction(signedTransaction, { commitment: 'confirmed' }); ``` For durable-nonce transactions, use `sendAndConfirmDurableNonceTransactionFactory` instead, which knows how to confirm against a nonce account instead of a recent blockhash. If you don't need confirmation at all, `sendTransactionWithoutConfirmingFactory` returns a fire-and-forget sender. All three return `Promise`; pair them with `getSignatureFromTransaction` to obtain the signature for logging or display. ## Fetch and decode accounts To read onchain state, `fetchEncodedAccount` wraps `getAccountInfo` and returns a `MaybeEncodedAccount` whose shape is consistent regardless of whether the account exists. `assertAccountExists` narrows the result so the rest of your code can rely on a fully populated account. ```ts twoslash import { address, assertAccountExists, fetchEncodedAccount } from '@solana/kit'; // ---cut-start--- import { createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); // ---cut-end--- const account = await fetchEncodedAccount( rpc, address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'), ); assertAccountExists(account); account.data satisfies Uint8Array; ``` For typed reads, the `@solana-program/*` packages export `fetchX` and `decodeX` standalone helpers that take any `Rpc` and return decoded `Account` values without needing a Kit client. See [Fetching accounts](/docs/guides/fetching-accounts) for the full helper line-up and [Codecs](/docs/advanced-guides/codecs) for decoding raw bytes when no helper is available. ## Next steps * [Plugins](/docs/plugins) β€” opt back in to the client model when you want it. * [Plugins β€” Creating custom plugins](/docs/plugins/creating-custom-plugins) β€” wrap a curated set of primitives into a reusable bundle. * [Advanced guides β€” Transactions](/docs/advanced-guides/transactions) β€” the full transaction message API. * [Advanced guides β€” Signers](/docs/advanced-guides/signers) β€” the signer interfaces in depth. # Offchain messages (/docs/advanced-guides/offchain-messages) ## Introduction Any time you want one or more parties to approve of something that is not governed by an onchain program, you can prepare a message for them to sign offchain. Such messages can contain arbitrary contents, like the text of a plain-language contract, or some data encoded as text. Each offchain message contains a list of one or more signers that must provide a signature over that encoded message. Only when all of the required signers provide an authentic signature over the message are its contents considered to be ratified. You can use Kit to create, sign, verify, encode, and decode offchain messages. ## Installation Offchain message utilities are **included within the `@solana/kit` library** but you may also install them using their standalone packages. To install the offchain message utilities: ```bash npm install @solana/offchain-messages ``` ```bash pnpm add @solana/offchain-messages ``` ```bash yarn add @solana/offchain-messages ``` ```bash bun add @solana/offchain-messages ``` ## What is an offchain message? An offchain message consists of some UTF-8 message text, and a list of one or more required signers. The message is considered ratified when all of the signers provide a signature over the encoded message. Here is an example of a contract being proposed by one person as an offchain message, and ratified by another. ```ts twoslash const ursulaKeypair = null as unknown as CryptoKeyPair; // ---cut-before--- import { Address, createSignerFromKeyPair, getOffchainMessageEnvelopeEncoder, OffchainMessage, partiallySignOffchainMessageWithSigners, } from '@solana/kit'; // Ursula creates the contract as an offchain message. const ursulaSigner = await createSignerFromKeyPair(ursulaKeypair); const offchainMessage: OffchainMessage = { content: "Ursula grants Ariel three days as a human, in exchange for Ariel's voice, on the " + 'condition that Ariel secures a kiss of true love from Prince Eric before the third ' + 'sunset to remain human permanently. If Ariel fails, she reverts to a mermaid and ' + "becomes Ursula's property.", requiredSignatories: [ ursulaSigner, { address: 'ARiEL3q7uXvN9yZK8s2a5GfpHmQdR7cBv' as Address }, ], version: 1, }; // Ursula partially signs the message, producing an offchain message envelope. const offchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage); // Ursula encodes the offchain message envelope to share with Ariel. const offchainMessageEnvelopeBytes = getOffchainMessageEnvelopeEncoder().encode(offchainMessageEnvelope); ``` ```ts twoslash import { ReadonlyUint8Array } from '@solana/kit'; const arielKeypair = null as unknown as CryptoKeyPair; const offchainMessageEnvelopeBytes = null as unknown as ReadonlyUint8Array; // ---cut-before--- import { getOffchainMessageEnvelopeCodec, signOffchainMessageEnvelope } from '@solana/kit'; // Ariel decodes the offchain message envelope received from Ursula. const offchainMessageEnvelope = getOffchainMessageEnvelopeCodec().decode(offchainMessageEnvelopeBytes); // To ratify the contract, she signs the message. const fullySignedOffchainMessageEnvelope = await signOffchainMessageEnvelope([arielKeypair], offchainMessageEnvelope); // Ariel encodes the fully signed offchain message envelope to share with Ursula. const fullySignedOffchainMessageEnvelopeBytes = getOffchainMessageEnvelopeCodec().encode(fullySignedOffchainMessageEnvelope); ``` ```ts twoslash import { ReadonlyUint8Array, OffchainMessageEnvelope } from '@solana/kit'; const offchainMessageEnvelope = null as unknown as OffchainMessageEnvelope; const receivedOffchainMessageEnvelopeBytes = null as unknown as ReadonlyUint8Array; // ---cut-before--- import { bytesEqual, getOffchainMessageEnvelopeDecoder, isSolanaError, verifyOffchainMessageEnvelope, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE, } from '@solana/kit'; // Upon receipt of the signed message envelope bytes from Ariel, Ursula decodes them. const receivedOffchainMessageEnvelope = getOffchainMessageEnvelopeDecoder().decode(receivedOffchainMessageEnvelopeBytes); // For good measure, Ursula verifies that the message bytes are the exact ones she sent. if (!bytesEqual(receivedOffchainMessageEnvelope.content, offchainMessageEnvelope.content)) { throw new Error('I do not accept this modified contract'); } // Ursula then verifies the signatures on the envelope. try { await verifyOffchainMessageEnvelope(receivedOffchainMessageEnvelope); console.log('We have a deal!'); } catch(e) { if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE)) { console.error('We do not have a deal!'); } else { throw e; } } ``` ## Building offchain messages Use the [`OffchainMessage`](/api/type-aliases/OffchainMessage) type to help you create an offchain message. ### Specifying the version Specify the `version` property to select the schema and capabilities of the message. The latest version is version `1` which corresponds to the specification found in [sRFC 3](https://github.com/solana-foundation/SRFCs/discussions/3). ```ts twoslash // @noErrors: 2322 import { address, OffchainMessage } from '@solana/kit'; const offchainMessage: OffchainMessage = { // [!code ++:1] version: 1, /* ... */ }; ``` The format and construction of v0 messages is beyond the scope of this guide. You can read the v0 specification [here](https://docs.solanalabs.com/proposals/off-chain-message-signing). ### Required signatories Each message must specify a list of addresses belonging to accounts that must sign the message in order for it to be considered valid. #### Using a signer \[!toc] You can declare one or more required signatories using a [`MessageSigner`](/api/interfaces/MessageSigner). ```ts twoslash const myKeyPair = null as unknown as CryptoKeyPair; // ---cut-before--- // @noErrors: 2322 import { createSignerFromKeyPair, OffchainMessage } from '@solana/kit'; const messageSigner = await createSignerFromKeyPair(myKeyPair); const offchainMessage: OffchainMessage = { version: 1, // [!code ++:1] requiredSignatories: [messageSigner], /* ... */ }; ``` When you do so, the message will have the capability to self-sign using the [`signOffchainMessageWithSigners`](/api/functions/signOffchainMessageWithSigners) method. Follow the [instructions for signing offchain message envelopes with `CryptoKeyPairs`](#signing-offchain-message-envelopes) to sign it. #### Using an address \[!toc] You can declare one or more required signatories for whom you don't control the private key using the addresses of their accounts. ```ts twoslash const myKeyPair = null as unknown as CryptoKeyPair; // ---cut-before--- // @noErrors: 2322 import { address, OffchainMessage } from '@solana/kit'; const offchainMessage: OffchainMessage = { version: 1, // [!code ++:1] requiredSignatories: [{ address: address('EkMpZ4tPqt7LgNCWjbNQ4WhuzFuitdwp8JPxSbCWXy9x') }], /* ... */ }; ``` ### Defining the message content Each message must contain some non-empty UTF-8 text the signatories must agree upon. #### Using text \[!toc] The content can be a string of UTF-8 text. ```ts twoslash const myKeyPair = null as unknown as CryptoKeyPair; // ---cut-before--- import { address, createSignerFromKeyPair, OffchainMessage } from '@solana/kit'; const messageSigner = await createSignerFromKeyPair(myKeyPair); const offchainMessage: OffchainMessage = { version: 1, requiredSignatories: [ messageSigner, { address: address('r5FsobNdd53imrHH4rrdAt1MNkkJUjNPBTNqvKe9igR') }, ], // [!code ++:1] content: 'πŸ₯“ Crispy bacon is better than floppy bacon.', }; ``` #### Using data \[!toc] You can also encode arbitrary data as text using an encoding such as base-64. ```ts twoslash import { ReadonlyUint8Array } from '@solana/kit'; const bytes = null as unknown as ReadonlyUint8Array; const myKeyPair = null as unknown as CryptoKeyPair; // ---cut-before--- import { address, createSignerFromKeyPair, getBase64Decoder, OffchainMessage } from '@solana/kit'; const messageSigner = await createSignerFromKeyPair(myKeyPair); const offchainMessage: OffchainMessage = { version: 1, requiredSignatories: [ messageSigner, { address: address('r5FsobNdd53imrHH4rrdAt1MNkkJUjNPBTNqvKe9igR') }, ], // [!code ++:1] content: getBase64Decoder().decode(bytes), }; ``` ## Signing offchain messages In order to be considered ratified an offchain message must be signed by all of the private keys belonging to accounts that are required signatories of the message. * [`FullySignedOffchainMessageEnvelope`](/api/type-aliases/FullySignedOffchainMessageEnvelope): An offchain message that is signed by all of its required signatories. * [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope): A compiled offchain message encoded as bytes, paired with a map between its required signatory addresses and their provided signatures, if any. Offchain messages whose signers are specified using `MessageSigner` objects have the ability to self-sign. This is because signers encapsulate both the address of the signing account as well as an implementation of the signing algorithm for the private key associated with that account. The [`signOffchainMessageWithSigners`](/api/functions/signOffchainMessageWithSigners) method will return a new signed offchain message envelope of type `FullySignedOffchainMessageEnvelope`. ```ts twoslash import { OffchainMessage } from '@solana/kit'; const offchainMessage = null as unknown as OffchainMessage; // ---cut-before--- import { SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING, isSolanaError, signOffchainMessageWithSigners, } from '@solana/kit'; try { const fullySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(offchainMessage); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING)) { console.error('Missing signers for the following addresses:', e.context.addresses); } else { throw e; } } ``` This function will throw if the offchain message does not carry a `MessageSigner` implementation for every required signer. To partially sign a message that you know to carry a strict subset of the required `MessageSigners`, use the [`partiallySignOffchainMessageWithSigners`](/api/functions/partiallySignOffchainMessageWithSigners) method. Building offchain messages using `MessageSigners` is the recommended way to create self-signable offchain messages. To sign with a `CryptoKey` directly, you first have to compile the offchain message. ```ts twoslash import { OffchainMessage } from '@solana/kit'; const offchainMessage = null as unknown as OffchainMessage; // ---cut-before--- import { compileOffchainMessageEnvelope } from '@solana/kit'; const offchainMessageEnvelope = compileOffchainMessageEnvelope(offchainMessage); ``` This produces an unsigned offchain message envelope. Follow the [instructions for signing offchain message envelopes with `CryptoKeyPairs`](#signing-offchain-message-envelopes) to sign it. If the version of the offchain message is known, use the compile function specific to that version, such as [`compileOffchainMessageV1Envelope`](/api/functions/compileOffchainMessageV1Envelope). This will prevent you from bundling compilers you don't need, saving space in your JavaScript bundle. ## Signing offchain message envelopes Wherever you have a `OffchainMessageEnvelope` instead of an `OffchainMessage` you can add or replace a signature using the `signOffchainMessageEnvelope` method and one or more `CryptoKeyPairs`. ```ts twoslash import { OffchainMessageEnvelope } from '@solana/kit'; const keyPair = null as unknown as CryptoKeyPair; const offchainMessageEnvelope = null as unknown as OffchainMessageEnvelope; // ---cut-before--- import { SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING, isSolanaError, signOffchainMessageEnvelope, } from '@solana/kit'; try { const fullySignedOffchainMessageEnvelope = await signOffchainMessageEnvelope( [keyPair], offchainMessageEnvelope, ); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING)) { console.error('Missing signers for the following addresses:', e.context.addresses); } else { throw e; } } ``` This function will throw if the resultant offchain message envelope is missing a signature for one of the offchain message's required signers. To partially sign an offchain message envelope, use the [`partiallySignOffchainMessageEnvelope`](/api/functions/partiallySignOffchainMessageEnvelope) method. ## Verifying an offchain message Given an offchain message envelope, you can verify that it has been signed by all of its required signatories using the [`verifyOffchainMessageEnvelope`](/api/functions/verifyOffchainMessageEnvelope) method. ```ts twoslash import { OffchainMessageEnvelope } from '@solana/kit'; const receivedOffchainMessageEnvelope = null as unknown as OffchainMessageEnvelope; // ---cut-before--- import { isSolanaError, verifyOffchainMessageEnvelope, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE, } from '@solana/kit'; try { await verifyOffchainMessageEnvelope(receivedOffchainMessageEnvelope); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE)) { if (e.context.signatoriesWithInvalidSignatures.length) { console.error( 'The signatures for the following addresses are invalid', e.context.signatoriesWithInvalidSignatures, ); } if (e.context.signatoriesWithMissingSignatures.length) { console.error( 'The following required signatories have not signed this message', e.context.signatoriesWithMissingSignatures, ); } } else { throw e; } } ``` Verifying an offchain message will tell you if its content has been signed by all required signatories, but it will *not* ensure that the content of the message nor its list of required signatories is what you expect it to be. Take special care to inspect the content of the message before accepting it. If you have the original bytes of the message, you can compare them to the `content` of the envelope you are verifying. Otherwise, see [deserializing offchain messages](#deserializing-offchain-messages) for instructions on how to decode the envelope's `content` for inspection. ## Serializing offchain messages If you would like to share an offchain message envelope with someone, you can serialize it to bytes using an encoder. ```ts twoslash import { OffchainMessageEnvelope } from '@solana/kit'; const offchainMessageEnvelope = null as unknown as OffchainMessageEnvelope; // ---cut-before--- import { getOffchainMessageEnvelopeEncoder } from '@solana/kit'; const offchainMessageEnvelopeBytes = getOffchainMessageEnvelopeEncoder().encode(offchainMessageEnvelope); ``` ## Deserializing offchain messages Decoding the bytes of an encoded offchain message envelope yields an `OffchainMessageEnvelope` object. This takes the form of a compiled offchain message encoded as [`OffchainMessageBytes`](/api/type-aliases/OffchainMessageBytes), paired with a map between its required signatory addresses and their provided signatures, if any. ```ts twoslash import { ReadonlyUint8Array } from '@solana/kit'; const offchainMessageEnvelopeBytes = null as unknown as ReadonlyUint8Array; // ---cut-before--- import { getOffchainMessageEnvelopeDecoder } from '@solana/kit'; const offchainMessageEnvelope = getOffchainMessageEnvelopeDecoder().decode( offchainMessageEnvelopeBytes, ); ``` Decoding the bytes of the offchain message envelope will yield an object containing an offchain message in its **compiled** form – a message in a form suitable for signing and transmitting over a network. Decompiling a compiled message will yield an `OffchainMessage` object. This is the most common form of offchain message that you will encounter when using Kit to build an application. ```ts twoslash import { OffchainMessageEnvelope } from '@solana/kit'; const offchainMessageEnvelope = null as unknown as OffchainMessageEnvelope; // ---cut-before--- import { getOffchainMessageDecoder } from '@solana/kit'; const offchainMessage = getOffchainMessageDecoder().decode(offchainMessageEnvelope.content); ``` # Reactive stores (/docs/advanced-guides/reactive-stores) Kit ships two framework-agnostic reactive state containers - a **reactive action store** for on-demand async work and a **reactive stream store** for live notification streams. Both expose a tiny `subscribe` / `getState` contract that drops into any reactive system: React's `useSyncExternalStore`, Svelte stores, Vue's `shallowRef`, Solid's `from()`, or a hand-rolled render loop. The [`@solana/react`](/docs/guides/react) hooks are thin `useSyncExternalStore` wrappers over exactly these stores. If you are not using React - or you want imperative control the hooks don't expose - reach for the stores directly. Everything on this page is available from `@solana/kit`. ## Action stores A `ReactiveActionStore` wraps an async function as a reactive state machine. Each `dispatch()` runs the function and drives a `{ data, error, status }` snapshot through `idle β†’ running β†’ success` (or `error`). `data` and `error` persist through subsequent `running` states, so a view can keep rendering the last result while a retry is in flight (stale-while-revalidate). A `success` clears `error`, and a `reset()` clears `data` and `error`. Any Kit RPC request is an action source: call `.reactiveStore()` on it to get a store that re-fires the same request on every `dispatch()`. ```ts twoslash import { createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); // The store starts `idle`. The arguments are baked into the request, so each // dispatch() re-fires the same getLatestBlockhash call. const store = rpc.getLatestBlockhash().reactiveStore(); const unsubscribe = store.subscribe(() => { const { data, error, status } = store.getState(); if (status === 'success') { console.log('Blockhash:', data.value.blockhash); } else if (status === 'error') { console.error(error); } }); store.dispatch(); // fire the first attempt ``` ### The store API | Member | What it does | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | | `dispatch(...args)` | Fire-and-forget. Returns synchronously and never throws - failures land on state as `{ status: 'error' }`. Use from event handlers. | | `dispatchAsync(...args)` | Promise-returning. Resolves with the result, rejects with the thrown error (or an `AbortError` when superseded / reset). | | `getState()` | The current `{ data, error, status }` snapshot. Stable identity between changes. | | `subscribe(listener)` | Registers a change listener; returns an unsubscribe function. The listener takes no argument - read the latest via `getState()`. | | `reset()` | Aborts any in-flight dispatch and returns the store to `idle`, clearing `data` and `error`. | | `withSignal(signal)` | A wrapper exposing `dispatch` / `dispatchAsync` bound to a caller-provided `AbortSignal`. | Each `dispatch()` aborts the previous in-flight call, so only the most recent dispatch can mutate state - a stale response can never clobber a newer one. Use `withSignal` to attach your own cancellation source. A fresh timeout per attempt: ```ts twoslash import { createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const store = rpc.getLatestBlockhash().reactiveStore(); // Fresh 5-second clock on every attempt: store.withSignal(AbortSignal.timeout(5_000)).dispatch(); ``` ### Binding to your view The `subscribe` / `getState` pair works with reactive UI frameworks. Wire the blockhash store to a "fetch" button: ```ts twoslash import { createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const store = rpc.getLatestBlockhash().reactiveStore(); const button = document.querySelector('button')!; const output = document.querySelector('#out')!; button.addEventListener('click', () => store.dispatch()); const unsubscribe = store.subscribe(() => { const state = store.getState(); output.textContent = state.status === 'success' ? state.data.value.blockhash : state.status; }); // On teardown: unsubscribe(); ``` ```svelte {#if $blockhash.status === 'success'}

{$blockhash.data.value.blockhash}

{:else}

{$blockhash.status}

{/if} ```
```vue ```
Another common use case is to call `dispatch` on mount for data loading. React splits these into two hooks over the same store: [`useRequest`](/docs/guides/react/core-hooks#userequest) fires on mount, [`useAction`](/docs/guides/react/core-hooks#useaction) fires on demand. ### Wrapping any async function `.reactiveStore()` is sugar for RPC requests. For anything else - a `fetch`, your own SDK etc., you can build a store with `createReactiveActionStore`. The wrapped function receives the per-dispatch `AbortSignal` first, then whatever you pass to `dispatch`: ```ts twoslash import { createReactiveActionStore } from '@solana/kit'; const store = createReactiveActionStore(async (signal: AbortSignal, accountId: string) => { const response = await fetch(`/api/accounts/${accountId}`, { signal }); return response.json(); }); store.subscribe(() => console.log(store.getState())); store.dispatch('abc...'); // forwarded to the wrapped function after the signal ``` The signal is aborted automatically when a newer `dispatch()` supersedes this one or when `reset()` is called, so a function that threads it into its I/O cancels cleanly. ## Stream stores A `ReactiveStreamStore` holds the latest value from an ongoing stream. Where an action store fires on demand, a stream store opens a connection with `connect()` and updates its snapshot every time a notification arrives. Its status vocabulary is `idle β†’ loading β†’ loaded` (or `error`). `data` and `error` are preserved across `loading`, so a reconnect can render stale data while it re-establishes. Any Kit RPC subscription is a stream source - call `.reactiveStore()` on it. ```ts twoslash import { createSolanaRpcSubscriptions } from '@solana/kit'; const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); const store = rpcSubscriptions.slotNotifications().reactiveStore(); const unsubscribe = store.subscribe(() => { const { data, status } = store.getState(); if (status === 'loaded') { console.log('Current slot:', data.slot); } }); store.connect(); // open the stream ``` ### The store API | Member | What it does | | --------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `connect()` | Opens the stream (aborting any active connection) and transitions to `loading`, then `loaded` / `error`. | | `getState()` | The current `{ data, error, status }` snapshot. Stable identity between changes. | | `subscribe(listener)` | Registers a change listener; returns an unsubscribe function. Read the latest via `getState()`. | | `reset()` | Aborts the active connection and returns the store to `idle`, clearing `data` and `error`. | | `withSignal(signal)` | A wrapper exposing `connect()` bound to a caller-provided `AbortSignal` - a per-connection timeout or a shared kill switch. | Unlike an action store, a stream store is opened once and left running; `reset()` tears it down. A subsequent `connect()` always opens a fresh stream. ### Binding to your view The contract is the same `subscribe` / `getState` pair, but it is important to call `reset()` on teardown to clean up the stream. Wire the slot store to a live display: ```ts twoslash import { createSolanaRpcSubscriptions } from '@solana/kit'; const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); const store = rpcSubscriptions.slotNotifications().reactiveStore(); const output = document.querySelector('#slot')!; const unsubscribe = store.subscribe(() => { const state = store.getState(); output.textContent = state.status === 'loaded' ? String(state.data.slot) : state.status; }); store.connect(); // On teardown: unsubscribe(); store.reset(); ``` ```svelte {#if $slot.status === 'loaded'}

Slot: {$slot.data.slot}

{:else}

{$slot.status}

{/if} ```
```vue ```
### Wrapping any stream For a stream that is not a Kit subscription, you can build a store with `createReactiveStoreFromDataPublisherFactory`. You give it a factory that produces a fresh `DataPublisher` on every `connect()`, plus the channel names to read data and errors from. The factory receives the per-connection `AbortSignal`; thread it into the transport so the connection itself tears down on reset, not just the store's listeners. ```ts twoslash import { createReactiveStoreFromDataPublisherFactory } from '@solana/kit'; const store = createReactiveStoreFromDataPublisherFactory({ createDataPublisher: (signal) => { const socket = new WebSocket('wss://example.com/feed'); signal.addEventListener('abort', () => socket.close()); // A `DataPublisher` exposes `on(channel, subscriber, { signal })`. Forward the // payload you care about from each channel - here, the message text. return Promise.resolve({ on(channelName, subscriber, options) { if (channelName === 'message') { const handler = (event: MessageEvent) => subscriber(event.data); socket.addEventListener('message', handler, options); return () => socket.removeEventListener('message', handler); } // channelName === 'error' here β€” surface a real Error rather than the raw DOM event. const handler = () => subscriber(new Error('WebSocket connection error')); socket.addEventListener('error', handler, options); return () => socket.removeEventListener('error', handler); }, }); }, dataChannelName: 'message', errorChannelName: 'error', }); store.subscribe(() => { const snapshot = store.getState(); if (snapshot.status === 'loaded') console.log('Latest:', snapshot.data); }); // Fresh 30-second clock per connection attempt: store.withSignal(AbortSignal.timeout(30_000)).connect(); ``` The factory runs on every `connect()`, so a torn-down stream can be reopened without losing subscribers or the last known value. ### Consuming a store as an async iterable The `subscribe` / `getState` contract is *push*-based: the store calls you when something changes. Some consumers are *pull*-based instead: they drive a stream by `for await`-ing an `AsyncIterable`. TanStack Query's `experimental_streamedQuery` is the canonical example, and it's exactly how Kit's [`useSubscriptionQuery`](/docs/guides/react/query#usesubscriptionquery) routes a subscription through the query cache. `bridgeStoreToAsyncIterable` adapts any `ReactiveStreamStore` to that contract. It only *observes* the store, so you connect and reset the store yourself; the bridge just subscribes, yields values, and unsubscribes when the loop ends: ```ts import { bridgeStoreToAsyncIterable, createSolanaRpcSubscriptions } from '@solana/kit'; const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); const store = rpcSubscriptions.slotNotifications().reactiveStore(); const controller = new AbortController(); // You own the connection β€” bind it to the same signal so an abort tears it down. store.withSignal(controller.signal).connect(); try { for await (const notification of bridgeStoreToAsyncIterable(store, controller.signal)) { console.log('Current slot:', notification.slot); } } catch (e) { console.error('The subscription errored', e); } finally { store.reset(); } // Elsewhere β€” end the loop cleanly: controller.abort(); ``` Because it reads through a store, it inherits the store's snapshot model: it **seeds from the current value** (a value already present when the loop starts is delivered, so the order of `connect()` and iteration doesn't matter), it is **latest-wins** (a store only ever holds the newest value, so if several notifications land between pulls only the freshest is yielded), a store `error` **throws** out of the `for await`, and aborting the signal **ends the loop cleanly** (an abort is teardown, not failure). Because a subscription never ends on its own, the signal is how the loop terminates β€” bind it to the store's connection so the abort tears the underlying stream down too. An optional third `shouldYield` predicate gates each value before it is yielded β€” return `false` to drop it. This is a different thing from an RPC subscription's own async iterable. `await rpcSubscriptions.slotNotifications().subscribe({abortSignal})` also gives you an `AsyncIterable`, but that one vends messages **straight off the transport** β€” it does not go through a store, so there's no `idle`/`loading`/`loaded`/`error` snapshot, no stale-while-revalidate, and it queues every message rather than keeping only the latest. Use `.subscribe()` when you want the raw transport stream; use `bridgeStoreToAsyncIterable` when you want a store's unified lifecycle exposed as an iterable. ## Fetch once, then stay live A common pattern is "load a value, then keep it current" - fetch an account balance once, then track it through subscription notifications. Doing this by hand is fiddly: the initial fetch and the first few notifications can arrive out of order, and a late initial response must not overwrite a newer notification. `createReactiveStoreWithInitialValueAndSlotTracking` solves exactly this. It pairs an action source (the one-shot read) with a stream source (the live updates) and deduplicates the two by slot, so the store always holds the value observed at the highest slot. The result is an ordinary `ReactiveStreamStore` - `connect()` to start, and bind it with the same `subscribe` / `getState` pattern as any stream store. This is the primitive behind React's [`useTrackedData`](/docs/guides/react/core-hooks#usetrackeddata). ```ts twoslash import { address, createReactiveStoreWithInitialValueAndSlotTracking, createSolanaRpc, createSolanaRpcSubscriptions, } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); const myAddress = address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'); const balanceStore = createReactiveStoreWithInitialValueAndSlotTracking({ initialValueSource: rpc.getBalance(myAddress, { commitment: 'confirmed' }), initialValueMapper: (lamports) => lamports, streamSource: rpcSubscriptions.accountNotifications(myAddress), streamValueMapper: ({ lamports }) => lamports, }); const unsubscribe = balanceStore.subscribe(() => { const state = balanceStore.getState(); if (state.status === 'loaded') { console.log(`Balance at slot ${state.data.context.slot}:`, state.data.value); } }); balanceStore.connect(); ``` Both sources must yield `SolanaRpcResponse` envelopes so their slots can be compared; the two mappers project each source's value into the unified item type the store holds. The loaded `data` is itself a `SolanaRpcResponse`, so `data.context.slot` tells you the slot the current value was observed at. # Signers (/docs/advanced-guides/signers) ## Introduction Signers are an abstraction that combines an account with an implementation that computes signatures on behalf of that account. No matter what actually computes the signature – a wallet app, a network API, the `SubtleCrypto` API, or a userspace implementation – so long as it implements the correct signer interface for your intended purpose, you can use it with all of Kit's signer-aware functions. Signers are designed to make it easier to build, sign, and send transactions by taking the guesswork out of which accounts' key pairs need to sign a transaction. Signer-aware APIs allow you to associate signer objects with each transaction instruction that requires them, enabling Kit's transaction planning, signing, and sending functions to automatically collect and invoke them. ## Installation Signers are **included within the `@solana/kit` library** but you may also install them using their standalone package. ```bash npm install @solana/signers ``` ```bash pnpm add @solana/signers ``` ```bash yarn add @solana/signers ``` ```bash bun add @solana/signers ``` ## What is a signer? All signers are wrappers around an [`Address`](/api/type-aliases/Address). This means that most APIs that require an `Address` can be made to accept a signer. Each specific type of signer adds one or more capabilities, such as the ability to sign a message or a transaction on behalf of the account with that address. Some even add the ability to sign *and* send a transaction, which is common for wallets that you use in your browser or on your phone. ```ts twoslash // @noErrors: 2769 import { createSignableMessage, createTransactionMessage, generateKeyPairSigner, pipe, setTransactionMessageFeePayerSigner, signTransactionMessageWithSigners, } from '@solana/kit'; // Generate a key pair signer. const mySigner = await generateKeyPairSigner(); mySigner.address; // The address of the account // Sign one or multiple messages. const myMessage = createSignableMessage('Hello world!'); const [messageSignatures] = await mySigner.signMessages([myMessage]); // ^^^^^^^^ // Sign to pay fees for a transaction message const myTransactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(mySigner, m), // ^^^^^^^^ // Add instructions, lifetime, etc. ); const signedTransaction = await signTransactionMessageWithSigners(myTransactionMessage); ``` As you can see, this provides a consistent API regardless of how things are being signed behind the scenes. If tomorrow we need to use a browser wallet instead, we'd simply need to swap the `generateKeyPairSigner()` function with the signer factory of our choice. ## Types of signers This package offers a total of five different types of signers that may be used in combination when applicable. Three of them allow us to sign transactions whereas the other two are used for regular message signing. They are separated into three categories: * **Partial signers**: Given a message or transaction, provide one or more signatures for it. These signers are not able to modify the given data which allows us to run many of them in parallel. * **Modifying signers**: Can choose to modify a message or transaction before signing it with zero or more private keys. Because modifying a message or transaction invalidates any pre-existing signatures over it, modifying signers must do their work before any other signer. * **Sending signers**: Given a transaction, signs it and sends it immediately to the blockchain. When applicable, the signer may also decide to modify the provided transaction before signing it. This interface accommodates wallets that simply cannot sign a transaction without sending it at the same time. This category of signers does not apply to regular messages. Thus, we end up with the following interfaces. | | Partial signers | Modifying signers | Sending signers | | ---------------------------------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | [`TransactionSigner`](/api/type-aliases/TransactionSigner) | [`TransactionPartialSigner`](/api/type-aliases/TransactionPartialSigner) | [`TransactionModifyingSigner`](/api/type-aliases/TransactionModifyingSigner) | [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner) | | [`MessageSigner`](/api/type-aliases/MessageSigner) | [`MessagePartialSigner`](/api/type-aliases/MessagePartialSigner) | [`MessageModifyingSigner`](/api/type-aliases/MessageModifyingSigner) | N/A | We will go through each of these five signer interfaces and their respective characteristics in the documentation below. ## Signing transactions ### Partial signers [`TransactionPartialSigner`](/api/type-aliases/TransactionPartialSigner) is an interface that signs an array of [`Transactions`](/api/type-aliases/Transaction) without modifying their content. It defines a `signTransactions` function that returns a [`SignatureDictionary`](/api/type-aliases/SignatureDictionary) for each provided transaction. Such signature dictionaries are expected to be merged with the existing ones if any. ```ts twoslash // @noErrors: 2355 import { address, SignatureDictionary, Transaction, TransactionPartialSigner } from '@solana/kit'; // ---cut-before--- const myTransactionPartialSigner: TransactionPartialSigner<'1234..5678'> = { address: address('1234..5678'), signTransactions: async (transactions): Promise => { // My custom signing logic. }, }; ``` **Characteristics**: * **Parallel**. It returns a signature dictionary for each provided transaction without modifying them, making it possible for multiple partial signers to sign the same transaction in parallel. * **Flexible order**. The order in which we use these signers for a given transaction doesn’t matter. ### Modifying signers [`TransactionModifyingSigner`](/api/type-aliases/TransactionModifyingSigner) is an interface that potentially modifies the provided [`Transactions`](/api/type-aliases/Transaction) before signing them. E.g. this enables wallets to inject additional instructions into the transaction before signing them. For each transaction, instead of returning a [`SignatureDictionary`](/api/type-aliases/SignatureDictionary), its `modifyAndSignTransactions` function returns an updated [`Transaction`](/api/type-aliases/Transaction) with a potentially modified set of instructions and signature dictionary. ```ts twoslash // @noErrors: 2355 import { address, Transaction, TransactionModifyingSigner, TransactionWithinSizeLimit, TransactionWithLifetime, } from '@solana/kit'; // ---cut-before--- const myTransactionModifyingSigner: TransactionModifyingSigner<'1234..5678'> = { address: address('1234..5678'), modifyAndSignTransactions: async ( transactions: readonly Transaction[], ): Promise => { // My custom signing logic. }, }; ``` **Characteristics**: * **Sequential**. Contrary to partial signers, these cannot be executed in parallel as each call can modify the provided transactions. * **First signers**. For a given transaction, a modifying signer must always be used before a partial signer as the former will likely modify the transaction and thus impact the outcome of the latter. * **Potential conflicts**. If more than one modifying signer is provided, the second signer may invalidate the signature of the first one. However, modifying signers may decide not to modify a transaction based on the existence of signatures for that transaction. ### Sending signers [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner) is an interface that signs one or multiple transactions before sending them immediately to the blockchain. It defines a `signAndSendTransactions` function that returns the transaction signature (i.e. its identifier) for each provided [`Transaction`](/api/type-aliases/Transaction). This interface is required for PDA wallets and other types of wallets that don't provide an interface for signing transactions without sending them. Note that it is also possible for such signers to modify the provided transactions before signing and sending them. This enables use cases where the modified transactions cannot be shared with the app and thus must be sent directly. ```ts twoslash // @noErrors: 2355 import { address, SignatureBytes, Transaction, TransactionSendingSigner } from '@solana/kit'; // ---cut-before--- const myTransactionSendingSigner: TransactionSendingSigner<'1234..5678'> = { address: address('1234..5678'), signAndSendTransactions: async (transactions: Transaction[]): Promise => { // My custom signing logic. }, }; ``` **Characteristics**: * **Single signer**. Since this signer also sends the provided transactions, we can only use a single [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner) for a given set of transactions. * **Last signer**. Trivially, that signer must also be the last one used. * **Potential conflicts**. Since signers may decide to modify the given transactions before sending them, they may invalidate previous signatures. However, signers may decide not to modify a transaction based on the existence of signatures for that transaction. * **Potential confirmation**. Whilst this is not required by this interface, it is also worth noting that most wallets will also wait for the transaction to be confirmed (typically with a `confirmed` commitment) before notifying the app that they are done. ## Signing messages ### Signable messages [`SignableMessage`](/api/type-aliases/SignableMessage) defines a message with any of the signatures that might have already been provided by other signers. This interface allows modifying signers to decide on whether or not they should modify the provided message depending on whether or not signatures already exist for such message. It also helps create a more consistent API by providing a structure analogous to transactions which also keep track of their signature dictionary. ```ts twoslash import { SignatureDictionary } from '@solana/kit'; // ---cut-before--- type SignableMessage = { content: Uint8Array; signatures: SignatureDictionary; // Record }; ``` You can use the [`createSignableMessage`](/api/functions/createSignableMessage) function to create a [`SignableMessage`](/api/type-aliases/SignableMessage) from a `Uint8Array` or UTF-8 string. It optionally accepts a signature dictionary if the message already contains signatures. ```ts twoslash import { address, createSignableMessage, SignatureBytes } from '@solana/kit'; // ---cut-before-- const myMessage = createSignableMessage(new Uint8Array([1, 2, 3])); const myMessageFromText = createSignableMessage('Hello world!'); const myMessageWithSignatures = createSignableMessage('Hello world!', { [address('1234..5678')]: new Uint8Array([1, 2, 3]) as SignatureBytes, }); ``` ### Partial signers [`MessagePartialSigner`](/api/type-aliases/MessagePartialSigner) is an interface that signs an array of [`SignableMessages`](/api/type-aliases/SignableMessage) without modifying their content. It defines a `signMessages` function that returns a [`SignatureDictionary`](/api/type-aliases/SignatureDictionary) for each provided message. Such signature dictionaries are expected to be merged with the existing ones if any. ```ts twoslash // @noErrors: 2355 import { address, MessagePartialSigner, SignableMessage, SignatureDictionary } from '@solana/kit'; // ---cut-before--- const myMessagePartialSigner: MessagePartialSigner<'1234..5678'> = { address: address('1234..5678'), signMessages: async (messages: SignableMessage[]): Promise => { // My custom signing logic. }, }; ``` **Characteristics**: * **Parallel**. When multiple signers sign the same message, we can perform this operation in parallel to obtain all their signatures. * **Flexible order**. The order in which we use these signers for a given message doesn’t matter. ### Modifying signers [`MessageModifyingSigner`](/api/type-aliases/MessageModifyingSigner) is an interface that potentially modifies the content of the provided [`SignableMessages`](/api/type-aliases/SignableMessage) before signing them. E.g. this enables wallets to prefix or suffix nonces to the messages they sign. For each message, instead of returning a [`SignatureDictionary`](/api/type-aliases/SignatureDictionary), its `modifyAndSignMessages` function returns its updated [`SignableMessage`](/api/type-aliases/SignableMessage) with a potentially modified content and signature dictionary. ```ts twoslash // @noErrors: 2355 import { address, MessageModifyingSigner, SignableMessage } from '@solana/kit'; // ---cut-before--- const myMessageModifyingSigner: MessageModifyingSigner<'1234..5678'> = { address: address('1234..5678'), modifyAndSignMessages: async (messages: SignableMessage[]): Promise => { // My custom signing logic. }, }; ``` **Characteristics**: * **Sequential**. Contrary to partial signers, these cannot be executed in parallel as each call can modify the content of the message. * **First signers**. For a given message, a modifying signer must always be used before a partial signer as the former will likely modify the message and thus impact the outcome of the latter. * **Potential conflicts**. If more than one modifying signer is provided, the second signer may invalidate the signature of the first one. However, modifying signers may decide not to modify a message based on the existence of signatures for that message. ## Available signers ### No-op signers For a given address, a no-op signer can be created to offer an implementation of both the `MessagePartialSigner` and `TransactionPartialSigner` interfaces such that they do not sign anything. Namely, signing a transaction or a message with a `NoopSigner` will return an empty `SignatureDictionary`. This signer may be useful: * For testing purposes. * For indicating that a given account is a signer and taking the responsibility to provide the signature for that account ourselves. For instance, if we need to send the transaction to a server that will sign it and send it for us. ```ts twoslash import { address, SignableMessage, Transaction, TransactionWithinSizeLimit, TransactionWithLifetime, } from '@solana/kit'; const myMessage = null as unknown as SignableMessage; const myTransaction = null as unknown as Transaction & TransactionWithinSizeLimit & TransactionWithLifetime; // ---cut-before--- import { createNoopSigner } from '@solana/kit'; const myNoopSigner = createNoopSigner(address('1234..5678')); const [myMessageSignatures] = await myNoopSigner.signMessages([myMessage]); // <- Empty signature dictionary. const [myTransactionSignatures] = await myNoopSigner.signTransactions([myTransaction]); // <- Empty signature dictionary. ``` ### Key pair signers A key pair signer uses a `CryptoKeyPair` to sign messages and transactions. It implements both the `MessagePartialSigner` and `TransactionPartialSigner` interfaces and keeps track of the `CryptoKeyPair` instance used to sign messages and transactions.
[createSignerFromKeyPair](#create-signer-from-key-pair) [generateKeyPairSigner](#generate-key-pair-signer) [createKeyPairSignerFromBytes](#create-key-pair-signer-from-bytes) [createKeyPairSignerFromPrivateKeyBytes](#create-key-pair-signer-from-private-key-bytes)
#### createSignerFromKeyPair \[!toc] Creates a `KeyPairSigner` from a provided Crypto KeyPair. The `signMessages` and `signTransactions` functions of the returned signer will use the private key of the provided key pair to sign messages and transactions. Note that both the `signMessages` and `signTransactions` implementations are parallelized, meaning that they will sign all provided messages and transactions in parallel. ```ts twoslash import { createSignerFromKeyPair, generateKeyPair, KeyPairSigner } from '@solana/kit'; const myKeyPair: CryptoKeyPair = await generateKeyPair(); const myKeyPairSigner: KeyPairSigner = await createSignerFromKeyPair(myKeyPair); ``` #### generateKeyPairSigner \[!toc] A convenience function that generates a new Crypto KeyPair and immediately creates a `KeyPairSigner` from it. ```ts twoslash import { generateKeyPairSigner } from '@solana/kit'; const myKeyPairSigner = await generateKeyPairSigner(); ``` #### createKeyPairSignerFromBytes \[!toc] A convenience function that creates a new KeyPair from a 64-bytes `Uint8Array` secret key and immediately creates a `KeyPairSigner` from it. ```ts twoslash import fs from 'fs'; import { createKeyPairSignerFromBytes } from '@solana/kit'; // Get bytes from local keypair file. const keypairFile = fs.readFileSync('~/.config/solana/id.json'); const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString())); // Create a KeyPairSigner from the bytes. const signer = await createKeyPairSignerFromBytes(keypairBytes); ``` #### createKeyPairSignerFromPrivateKeyBytes \[!toc] A convenience function that creates a new KeyPair from a 32-bytes `Uint8Array` private key and immediately creates a `KeyPairSigner` from it. ```ts twoslash import { createKeyPairSignerFromPrivateKeyBytes, getUtf8Encoder } from '@solana/kit'; const message = getUtf8Encoder().encode('Hello, World!'); const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message)); const derivedSigner = await createKeyPairSignerFromPrivateKeyBytes(seed); ``` ### Wallet account signers Wallet account signers bridge between [Wallet Standard](https://github.com/wallet-standard/wallet-standard) accounts and Kit's signer interfaces. They live in the [`@solana/wallet-account-signer`](https://www.npmjs.com/package/@solana/wallet-account-signer) package and let any wallet that exposes the standard Solana features participate in signing transactions and messages. ```bash npm install @solana/wallet-account-signer ``` ```bash pnpm add @solana/wallet-account-signer ``` ```bash yarn add @solana/wallet-account-signer ``` ```bash bun add @solana/wallet-account-signer ```
[createSignerFromWalletAccount](#create-signer-from-wallet-account) [createTransactionSignerFromWalletAccount](#create-transaction-signer-from-wallet-account) [createTransactionSendingSignerFromWalletAccount](#create-transaction-sending-signer-from-wallet-account) [createMessageSignerFromWalletAccount](#create-message-signer-from-wallet-account)
#### createSignerFromWalletAccount \[!toc] Inspects the wallet account's available features and returns a single signer object combining whichever capabilities the wallet supports β€” `modifyAndSignTransactions`, `signAndSendTransactions`, and/or `modifyAndSignMessages`. Use this when you do not know in advance which features a wallet exposes. ```ts twoslash import { UiWalletAccount } from '@wallet-standard/ui'; const walletAccount = null as unknown as UiWalletAccount; // ---cut-before--- import { createSignerFromWalletAccount } from '@solana/wallet-account-signer'; const signer = createSignerFromWalletAccount(walletAccount, 'solana:devnet'); ``` #### createTransactionSignerFromWalletAccount \[!toc] Returns a [`TransactionModifyingSigner`](/api/type-aliases/TransactionModifyingSigner) that signs transactions with the wallet via the `solana:signTransaction` feature. The signer is allowed to modify the transaction before signing, which lets the wallet inject guard instructions or priority fees if it wants to. ```ts twoslash import { UiWalletAccount } from '@wallet-standard/ui'; const walletAccount = null as unknown as UiWalletAccount; // ---cut-before--- import { createTransactionSignerFromWalletAccount } from '@solana/wallet-account-signer'; const signer = createTransactionSignerFromWalletAccount(walletAccount, 'solana:devnet'); ``` #### createTransactionSendingSignerFromWalletAccount \[!toc] Returns a [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner) that uses the `solana:signAndSendTransaction` feature to sign and immediately submit the transaction to the network. This is the right shape for wallets that do not let the dapp inspect or relay the signed transaction itself. ```ts twoslash import { UiWalletAccount } from '@wallet-standard/ui'; const walletAccount = null as unknown as UiWalletAccount; // ---cut-before--- import { createTransactionSendingSignerFromWalletAccount } from '@solana/wallet-account-signer'; const signer = createTransactionSendingSignerFromWalletAccount(walletAccount, 'solana:devnet'); ``` #### createMessageSignerFromWalletAccount \[!toc] Returns a [`MessageModifyingSigner`](/api/type-aliases/MessageModifyingSigner) that signs arbitrary messages via the `solana:signMessage` feature. This is the wallet-backed counterpart to a key pair signer's message-signing capability. ```ts twoslash import { UiWalletAccount } from '@wallet-standard/ui'; const walletAccount = null as unknown as UiWalletAccount; // ---cut-before--- import { createMessageSignerFromWalletAccount } from '@solana/wallet-account-signer'; const signer = createMessageSignerFromWalletAccount(walletAccount); ``` ## Signing with signers Kit provides helper functions that use [`TransactionSigner`](/api/type-aliases/TransactionSigner) objects to sign and optionally send transactions. There are two families of signing functions: * **Transaction message functions** extract signers from the transaction message β€” either from the fee payer or from account metas β€” and handle compilation and signing automatically. * **Transaction functions** accept an explicit array of signers alongside a compiled [`Transaction`](/api/type-aliases/Transaction), giving you full control over which signers are used. ### Signing transaction messages The following functions extract [`TransactionSigners`](/api/type-aliases/TransactionSigner) from a transaction message's account metas, compile the message into a [`Transaction`](/api/type-aliases/Transaction), and use those signers to sign it. #### partiallySignTransactionMessageWithSigners \[!toc] Signs a transaction message without requiring all signatures to be present. This is useful when you know the message only carries a subset of the required signers and you plan to add more signatures later. ```ts twoslash import { TransactionMessage, TransactionMessageWithFeePayer, TransactionMessageWithSigners, } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners; // ---cut-before--- import { partiallySignTransactionMessageWithSigners } from '@solana/kit'; const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage); ``` This function ignores any [`TransactionSendingSigners`](/api/type-aliases/TransactionSendingSigner) in the message since it does not send the transaction. Use [`signAndSendTransactionMessageWithSigners`](#sign-and-send-transaction-message-with-signers) if you need to sign and send in a single step. #### signTransactionMessageWithSigners \[!toc] Signs a transaction message and asserts that all required signatures are present. The returned transaction satisfies the [`FullySignedTransaction`](/api/type-aliases/FullySignedTransaction) type. ```ts twoslash import { TransactionMessage, TransactionMessageWithFeePayer, TransactionMessageWithSigners, } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners; // ---cut-before--- import { signTransactionMessageWithSigners } from '@solana/kit'; const fullySignedTransaction = await signTransactionMessageWithSigners(transactionMessage); ``` This function will throw if the transaction message does not carry a [`TransactionSigner`](/api/type-aliases/TransactionSigner) implementation for every required signer. To partially sign a message that you know to carry a strict subset of the required signers, use [`partiallySignTransactionMessageWithSigners`](#partially-sign-transaction-message-with-signers). #### signAndSendTransactionMessageWithSigners \[!toc] Signs a transaction message and sends it to the network via the [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner) found in the message's account metas. Returns the transaction signature as [`SignatureBytes`](/api/type-aliases/SignatureBytes). ```ts twoslash import { TransactionMessage, TransactionMessageWithFeePayer, TransactionMessageWithSigners, TransactionMessageWithSingleSendingSigner, } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners & TransactionMessageWithSingleSendingSigner; // ---cut-before--- import { signAndSendTransactionMessageWithSigners } from '@solana/kit'; const signature = await signAndSendTransactionMessageWithSigners(transactionMessage); ``` The message must contain exactly one resolvable [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner). You can check this ahead of time using [`isTransactionMessageWithSingleSendingSigner`](/api/functions/isTransactionMessageWithSingleSendingSigner) to provide a fallback strategy: ```ts twoslash // @noErrors: 2345 import { Rpc, RpcSubscriptions, SolanaRpcApi, SolanaRpcSubscriptionsApi, TransactionMessage, TransactionMessageWithBlockhashLifetime, TransactionMessageWithFeePayer, TransactionMessageWithSigners, } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage & TransactionMessageWithBlockhashLifetime & TransactionMessageWithFeePayer & TransactionMessageWithSigners; const rpc = null as unknown as Rpc; const rpcSubscriptions = null as unknown as RpcSubscriptions; // ---cut-before--- import { isTransactionMessageWithSingleSendingSigner, sendAndConfirmTransactionFactory, signAndSendTransactionMessageWithSigners, signTransactionMessageWithSigners, } from '@solana/kit'; if (isTransactionMessageWithSingleSendingSigner(transactionMessage)) { // A sending signer is available β€” sign and send in one step. const signature = await signAndSendTransactionMessageWithSigners(transactionMessage); } else { // No sending signer β€” sign locally and use sendAndConfirmTransaction. const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); await sendAndConfirm(signedTransaction, { commitment: 'confirmed' }); } ``` ### Signing compiled transactions When you already have a compiled [`Transaction`](/api/type-aliases/Transaction) and an explicit set of signers β€” for example, when signers are not embedded in the transaction message or when working with an externally provided transaction β€” you can use the following lower-level functions. #### partiallySignTransactionWithSigners \[!toc] Signs a compiled transaction using the provided [`TransactionModifyingSigners`](/api/type-aliases/TransactionModifyingSigner) and [`TransactionPartialSigners`](/api/type-aliases/TransactionPartialSigner) without requiring all signatures to be present. ```ts twoslash import { Transaction, TransactionWithLifetime, TransactionPartialSigner, TransactionModifyingSigner, } from '@solana/kit'; const compiledTransaction = null as unknown as Transaction & TransactionWithLifetime; const signerA = null as unknown as TransactionPartialSigner; const signerB = null as unknown as TransactionPartialSigner; // ---cut-before--- import { partiallySignTransactionWithSigners } from '@solana/kit'; const signedTransaction = await partiallySignTransactionWithSigners( [signerA, signerB], compiledTransaction, ); ``` This function ignores any [`TransactionSendingSigners`](/api/type-aliases/TransactionSendingSigner) in the provided array. Use [`signAndSendTransactionWithSigners`](#sign-and-send-transaction-with-signers) if you need to sign and send. #### signTransactionWithSigners \[!toc] Signs a compiled transaction using the provided signers and asserts that all required signatures are present. The returned transaction satisfies the [`FullySignedTransaction`](/api/type-aliases/FullySignedTransaction) type. ```ts twoslash import { Transaction, TransactionWithLifetime, TransactionPartialSigner } from '@solana/kit'; const compiledTransaction = null as unknown as Transaction & TransactionWithLifetime; const signerA = null as unknown as TransactionPartialSigner; const signerB = null as unknown as TransactionPartialSigner; // ---cut-before--- import { signTransactionWithSigners } from '@solana/kit'; const fullySignedTransaction = await signTransactionWithSigners( [signerA, signerB], compiledTransaction, ); ``` This function will throw if the resultant transaction is missing a signature for one of its required signers. To partially sign, use [`partiallySignTransactionWithSigners`](#partially-sign-transaction-with-signers). #### signAndSendTransactionWithSigners \[!toc] Signs a compiled transaction using the provided signers and sends it to the network via the [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner) found in the array. Returns the transaction signature as [`SignatureBytes`](/api/type-aliases/SignatureBytes). ```ts twoslash import { Transaction, TransactionWithLifetime, TransactionPartialSigner, TransactionSendingSigner, } from '@solana/kit'; const compiledTransaction = null as unknown as Transaction & TransactionWithLifetime; const partialSigner = null as unknown as TransactionPartialSigner; const sendingSigner = null as unknown as TransactionSendingSigner; // ---cut-before--- import { signAndSendTransactionWithSigners } from '@solana/kit'; const signature = await signAndSendTransactionWithSigners( [partialSigner, sendingSigner], compiledTransaction, ); ``` The provided signers must contain exactly one resolvable [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner). You can validate this ahead of time using [`assertContainsResolvableTransactionSendingSigner`](#assert-contains-resolvable-transaction-sending-signer). #### assertContainsResolvableTransactionSendingSigner \[!toc] Asserts that an array of signers contains at least one [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner) that can be unambiguously resolved. This is useful for validating your signers before calling [`signAndSendTransactionWithSigners`](#sign-and-send-transaction-with-signers). ```ts twoslash import { TransactionSigner } from '@solana/kit'; const mySigners = null as unknown as TransactionSigner[]; // ---cut-before--- import { assertContainsResolvableTransactionSendingSigner } from '@solana/kit'; // Throws if no resolvable sending signer is found or if // multiple sending-only signers conflict with each other. assertContainsResolvableTransactionSendingSigner(mySigners); ``` ### How composite signers are resolved When a signer implements multiple interfaces (e.g. both [`TransactionPartialSigner`](/api/type-aliases/TransactionPartialSigner) and [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner)), the signing functions automatically resolve it to the most appropriate role: 1. **[`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner)** β€” Used if no other signer exclusively implements the sending interface. Only one sending signer can be active. 2. **[`TransactionModifyingSigner`](/api/type-aliases/TransactionModifyingSigner)** β€” Used if no other signer exclusively implements the modifying interface. Modifying signers run sequentially before all others. 3. **[`TransactionPartialSigner`](/api/type-aliases/TransactionPartialSigner)** β€” The fallback. Partial signers run in parallel after all modifying signers have finished. This means a composite signer is always demoted to the least powerful interface that avoids conflicts with other signers. # Transaction Introspection (/docs/advanced-guides/transaction-introspection) ## Introduction When you fetch a confirmed transaction with `getTransaction`, the RPC hands you a compiled, wire-shaped payload: account references are numeric indices, instruction data is encoded as a string, and the instructions emitted by cross-program invocations live in a separate `meta.innerInstructions` field. Codama auto-generated (e.g.`@solana-program/*`) clients β€” `identifyXyzProgramInstruction`, `parseMyProgramInstruction`, and other helpers β€” want Kit [`Instruction`](/api/interfaces/Instruction) objects with resolved [`AccountMeta`](/api/interfaces/AccountMeta)s and raw bytes. The `@solana/transaction-introspection` package bridges that gap. It decodes a `getTransaction` response into a [`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage), resolves every account index against the static keys plus the addresses loaded from address lookup tables, normalizes the inner CPI instructions, and returns instructions in the exact form the `@solana-program/*` clients can `identify` and `parse` directly. It supports `legacy`, `v0`, and `v1` transactions. This guide picks up where [Deserializing transactions](/docs/advanced-guides/transactions#deserializing-transactions) leaves off. ## Installation These utilities are **included within the `@solana/kit` library** but you may also install them using their standalone package. ```bash npm install @solana/transaction-introspection ``` ```bash pnpm add @solana/transaction-introspection ``` ```bash yarn add @solana/transaction-introspection ``` ```bash bun add @solana/transaction-introspection ``` ## Decoding an RPC response [`decodeTransactionFromRpcResponse`](/api/functions/decodeTransactionFromRpcResponse) turns a `getTransaction` response into a [`DecodedRpcTransaction`](/api/type-aliases/DecodedRpcTransaction): the `compiledMessage` (always carrying the recent blockhash in `lifetimeToken`), the `loadedAddresses` pulled from `meta`, and β€” for `base64` and `base58` encodings only β€” a re-encodable `transaction`. ```ts twoslash import { createSolanaRpc, signature } from '@solana/kit'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const txid = '5pX...'; // ---cut-before--- import { decodeTransactionFromRpcResponse } from '@solana/kit'; const rpcTx = await rpc .getTransaction(signature(txid), { commitment: 'confirmed', encoding: 'base64', maxSupportedTransactionVersion: 0, }) .send(); if (!rpcTx) { throw new Error(`Transaction ${txid} not found`); } const { compiledMessage, loadedAddresses, transaction } = decodeTransactionFromRpcResponse(rpcTx); ``` Prefer `encoding: 'base64'` when bandwidth allows β€” it is the most compact, the wire bytes round-trip cleanly through the Kit codecs, and the return type statically guarantees a non-optional `transaction`. `encoding: 'base58'` behaves the same way, and `encoding: 'json'` is accepted too, though it omits `transaction` because the server has already decompiled the wire format. `encoding: 'jsonParsed'` is **not** supported. Its instructions arrive pre-parsed by the server and lack the raw bytes the `@solana-program/*` `parseXInstruction` clients need, so passing one throws `SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION`. To receive a `v0` or `v1` transaction at all, you must set `maxSupportedTransactionVersion` on the `getTransaction` call. Without it the server rejects anything past `legacy`. ## Walking every instruction [`walkInstructions`](/api/functions/walkInstructions) is the main API. It returns every instruction in a confirmed transaction as an array of [`TracedInstruction`](/api/type-aliases/TracedInstruction)s, in the order an explorer displays them: each outer instruction followed immediately by the inner instructions its CPIs produced. Because each entry is itself a resolved Kit `Instruction`, you can pass it straight to [`isInstructionForProgram`](/api/functions/isInstructionForProgram) and to the auto-generated `identifyXInstruction` / `parseXInstruction` helpers. Here we tally every USDC transfer in a transaction β€” outer instructions and inner CPI alike β€” using the `@solana-program/token` client to parse each `TransferChecked` and filter by mint: ```ts twoslash import { createSolanaRpc, signature } from '@solana/kit'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const txid = '5pX...'; // ---cut-before--- import { address, decodeTransactionFromRpcResponse, isInstructionForProgram, isInstructionWithAccounts, isInstructionWithData, walkInstructions, } from '@solana/kit'; import { identifyTokenInstruction, parseTransferCheckedInstruction, TOKEN_PROGRAM_ADDRESS, TokenInstruction, } from '@solana-program/token'; const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const rpcTx = await rpc .getTransaction(signature(txid), { commitment: 'confirmed', encoding: 'base64', maxSupportedTransactionVersion: 0, }) .send(); if (!rpcTx) { throw new Error(`Transaction ${txid} not found`); } const { compiledMessage, loadedAddresses } = decodeTransactionFromRpcResponse(rpcTx); let totalTransferred = 0n; for (const ix of walkInstructions({ compiledMessage, loadedAddresses, meta: rpcTx.meta })) { // Narrow to the Token program, then to instructions that carry data and accounts. if (!isInstructionForProgram(ix, TOKEN_PROGRAM_ADDRESS)) continue; if (!isInstructionWithData(ix) || !isInstructionWithAccounts(ix)) continue; if (identifyTokenInstruction(ix) !== TokenInstruction.TransferChecked) continue; const { accounts, data } = parseTransferCheckedInstruction(ix); if (accounts.mint.address !== usdcMint) continue; totalTransferred += data.amount; console.log( ix.trace.kind === 'outer' ? `Transfer Checked at outer[${ix.trace.index}]` : `CPI transfer checked at inner[${ix.trace.outerIndex}/${ix.trace.innerIndex}]`, ); } console.log(`Total transferred (base units): ${totalTransferred}`); ``` The CPI transfers β€” those a router or DEX program made on your behalf β€” are caught alongside the top-level ones precisely because `walkInstructions` interleaves the inner instructions from `meta.innerInstructions`. Each entry carries a `trace` property typed as [`InstructionTrace`](/api/type-aliases/InstructionTrace), a discriminated union that records where the instruction sits: * `{ kind: 'outer', index }` β€” a top-level instruction in the compiled message. * `{ kind: 'inner', outerIndex, innerIndex, stackHeight? }` β€” an instruction emitted via cross-program invocation. `stackHeight` is the CPI depth, included only when the RPC reports it. The same pattern works with any codama-generated `@solana-program/*` client. Swap in `@solana-program/system` to tally lamports moved by every `TransferSol`, outer or inner: ```ts twoslash import { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime, LoadedAddresses, MetaWithInnerInstructions, } from '@solana/kit'; const compiledMessage = null as unknown as CompiledTransactionMessage & CompiledTransactionMessageWithLifetime; const loadedAddresses = null as unknown as LoadedAddresses; const meta = null as unknown as MetaWithInnerInstructions; // ---cut-before--- import { isInstructionForProgram, isInstructionWithAccounts, isInstructionWithData, walkInstructions, } from '@solana/kit'; import { identifySystemInstruction, parseTransferSolInstruction, SYSTEM_PROGRAM_ADDRESS, SystemInstruction, } from '@solana-program/system'; let totalLamports = 0n; for (const ix of walkInstructions({ compiledMessage, loadedAddresses, meta })) { if (!isInstructionForProgram(ix, SYSTEM_PROGRAM_ADDRESS)) continue; if (!isInstructionWithData(ix) || !isInstructionWithAccounts(ix)) continue; if (identifySystemInstruction(ix) !== SystemInstruction.TransferSol) continue; totalLamports += parseTransferSolInstruction(ix).data.amount; } ``` Pass `meta?.loadedAddresses` (or the `loadedAddresses` returned by `decodeTransactionFromRpcResponse`) for `v0` transactions that load accounts from address lookup tables. This package never makes an RPC call to resolve lookup tables itself β€” it uses the addresses the validator already recorded in `meta`. Without them, only the static accounts are available to resolve indices, and any instruction referencing a looked-up account index throws `SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE`. Omitting `meta` entirely returns only the outer instructions. ## Resolving instructions without walking If you do not need the interleaved outer-and-inner ordering, the lower-level helpers expose each piece on its own. [`getInstructionsFromCompiledTransactionMessage`](/api/functions/getInstructionsFromCompiledTransactionMessage) returns just the outer instructions as [`ResolvedInstruction`](/api/type-aliases/ResolvedInstruction)s. [`getInnerInstructionsFromMeta`](/api/functions/getInnerInstructionsFromMeta) returns just the inner instructions (decoding their base58 data and resolving indices against a supplied `AccountMeta` list). [`getAccountMetasFromCompiledTransactionMessage`](/api/functions/getAccountMetasFromCompiledTransactionMessage) builds the ordered `AccountMeta` list both rely on. ```ts twoslash import { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime, LoadedAddresses, MetaWithInnerInstructions, } from '@solana/kit'; const compiledMessage = null as unknown as CompiledTransactionMessage & CompiledTransactionMessageWithLifetime; const loadedAddresses = null as unknown as LoadedAddresses; const meta = null as unknown as MetaWithInnerInstructions; // ---cut-before--- import { getAccountMetasFromCompiledTransactionMessage, getInnerInstructionsFromMeta, getInstructionsFromCompiledTransactionMessage, } from '@solana/kit'; const outerInstructions = getInstructionsFromCompiledTransactionMessage( compiledMessage, loadedAddresses, ); const accountMetas = getAccountMetasFromCompiledTransactionMessage( compiledMessage, loadedAddresses, ); const innerInstructions = getInnerInstructionsFromMeta(meta, accountMetas); ``` The account metas are returned in the runtime's resolution order β€” writable signers, readonly signers, writable non-signers, readonly non-signers, then the ALT-loaded writable and readonly addresses β€” so inner-instruction indices line up against the very same list. If you only need the flat ordered address list, map over the result with `accountMetas.map((m) => m.address)`. ## Notes * **Version support.** `legacy`, `v0`, and `v1` compiled messages all resolve identically β€” account indices, inner instructions, and ALT-loaded addresses behave the same across versions. * **`jsonParsed` is rejected.** Use `base64`, `base58`, or `json`. Any unrecognized response shape throws `SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE`. * **`TracedInstruction` is a `ResolvedInstruction`.** No separate filter helper is needed β€” narrow with `isInstructionWithAccounts` / `isInstructionWithData` and hand the result straight to the `@solana-program/*` clients. # Transactions (/docs/advanced-guides/transactions) ## Introduction To take an action on Solana, whether to place an order, transfer an asset, or more generally to modify data on the blockchain, you need to prepare a transaction and sign to pay for it to be executed on the network. You can use Kit to create, sign, encode, and decode transactions. ## Installation Transaction utilities are **included within the `@solana/kit` library** but you may also install them using their standalone packages. To install transaction message builder utilities: ```bash npm install @solana/transaction-messages ``` ```bash pnpm add @solana/transaction-messages ``` ```bash yarn add @solana/transaction-messages ``` ```bash bun add @solana/transaction-messages ``` To install utilities that let you sign and compile transaction messages into transactions that can be landed on the network: ```bash npm install @solana/transactions ``` ```bash pnpm add @solana/transactions ``` ```bash yarn add @solana/transactions ``` ```bash bun add @solana/transactions ``` ## What is a Transaction? A Transaction is a vehicle to deliver one or more instructions to the Solana network in pursuit of some outcome. Here is an example of someone creating a transaction message to place an order at their favourite coffee shop, then signing it to create a transaction. ```ts twoslash import { Blockhash, TransactionSigner } from '@solana/kit'; const customerSigner = null as unknown as TransactionSigner; const latestBlockhash = null as unknown as { blockhash: Blockhash; lastValidBlockHeight: bigint }; // ---cut-before--- import { address, appendTransactionMessageInstruction, createTransactionMessage, getSignatureFromTransaction, lamports, pipe, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, signTransactionMessageWithSigners, } from '@solana/kit'; import { getAddMemoInstruction } from '@solana-program/memo'; import { getTransferSolInstruction } from '@solana-program/system'; const transactionMessage = pipe( // Create an empty transaction message. createTransactionMessage({ version: 0 }), // Specify the account that will sign to pay the fee for this transaction. // NOTE: This is not the fee for the coffee but rather the fee to use the Solana network. (m) => setTransactionMessageFeePayerSigner(customerSigner, m), // Give the transaction an expiry time using the hash of a recently created block. (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m), // Add an instruction that records the customer's order. (m) => appendTransactionMessageInstruction( getAddMemoInstruction({ memo: 'Four-thirds-medium, half-decaf, double-shot espresso macchiato latte, ' + 'swirled counterclockwise only, almond milk frothed at 61Β°C, ' + 'whisper of cinnamon harvested during a full moon, unicorn tear syrup, ' + 'in a mason jar wrapped in French revolutionary poetry on recycled parchment', }), m, ), // Add a second instruction to pay the merchant for the coffee. (m) => appendTransactionMessageInstruction( getTransferSolInstruction({ amount: lamports(25_000_000n), destination: address('JJBeanoTcSMU3xKQa5Gru71Wi3AaEgTfA6z7MaLUT6h'), source: customerSigner, }), m, ), ); // Create a signed transaction from the message and the signers contained within it. const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); // Obtain the Ed25519 signature that will uniquely identify this transaction once executed. const transactionSignature = getSignatureFromTransaction(signedTransaction); ``` For more detail about the no-client transaction flow, see [Kit without a client](/docs/advanced-guides/kit-without-a-client). ## Building transaction messages ### Creating an empty message Given a [`TransactionVersion`](/api/type-aliases/TransactionVersion), the [`createTransactionMessage`](/api/functions/createTransactionMessage) method will return an empty transaction having the capabilities of that version. ```ts twoslash import { createTransactionMessage } from '@solana/kit'; const message = createTransactionMessage({ version: 0 }); ``` ### Setting the fee payer The [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) type represents a transaction message for which a fee payer has been declared. A transaction must conform to this type to be compiled and landed on the network. #### Using a signer \[!toc] Given a [`TransactionSigner`](/api/type-aliases/TransactionSigner), this method will return a new transaction message having the same type as the one supplied plus the [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) type. Additionally, the resulting message will have the capability to self-sign using the [`signTransactionMessageWithSigners`](/api/functions/signTransactionMessageWithSigners) function. ```ts twoslash import { TransactionMessage } from '@solana/kit'; const keyPair = null as unknown as CryptoKeyPair; const transactionMessage = null as unknown as TransactionMessage; // ---cut-before--- import { createSignerFromKeyPair, setTransactionMessageFeePayerSigner } from '@solana/kit'; const mySigner = await createSignerFromKeyPair(keyPair); const transactionMessagePaidByMe = setTransactionMessageFeePayerSigner( mySigner, transactionMessage, ); ``` #### Using an address \[!toc] Given a base58-encoded address of a system account, this method will return a new transaction message having the same type as the one supplied plus the [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) type. ```ts twoslash import { TransactionMessage } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage; // ---cut-before--- import { address, setTransactionMessageFeePayer } from '@solana/kit'; const myAddress = address('mpngsFd4tmbUfzDYJayjKZwZcaR7aWb2793J6grLsGu'); const transactionMessagePaidByMe = setTransactionMessageFeePayer(myAddress, transactionMessage); ``` ### Defining the lifetime A signed transaction can be only be landed on the network if certain conditions are met: * It includes the hash of a recent block * Or it includes the value of an unused nonce known to the network These conditions define a transaction's lifetime, after which it can no longer be landed, even if signed. The lifetime must be added to the transaction message before it is compiled to be sent. #### Using a recent blockhash \[!toc] The [`TransactionMessageWithBlockhashLifetime`](/api/interfaces/TransactionMessageWithBlockhashLifetime) type represents a transaction message whose expiry is tied to the age of a block. Such a transaction can only be landed on the network if the current block height of the network is less than or equal to the value of `TransactionMessageWithBlockhashLifetime.lifetimeConstraint.lastValidBlockHeight`. Given a blockhash and the last block height at which that blockhash is considered usable to land transactions, the [`setTransactionMessageLifetimeUsingBlockhash`](/api/functions/setTransactionMessageLifetimeUsingBlockhash) method will return a new transaction message having the same type as the one supplied plus the [`TransactionMessageWithBlockhashLifetime`](/api/interfaces/TransactionMessageWithBlockhashLifetime) type. ```ts twoslash import { Rpc, GetLatestBlockhashApi, TransactionMessage } from '@solana/kit'; const rpc = null as unknown as Rpc; const transactionMessage = null as unknown as TransactionMessage; // ---cut-before--- import { setTransactionMessageLifetimeUsingBlockhash } from '@solana/kit'; const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const txMessageWithBlockhashLifetime = setTransactionMessageLifetimeUsingBlockhash( latestBlockhash, transactionMessage, ); ``` #### Using a durable nonce \[!toc] The [`TransactionMessageWithDurableNonceLifetime`](/api/interfaces/TransactionMessageWithDurableNonceLifetime) type represents a transaction message whose lifetime is defined by the value of a nonce account onchain. Such a transaction can only be landed on the network if the nonce value in the transaction message matches the one in the nonce account at the time the transaction executes. Given a nonce, the account where the value of the nonce is stored, and the address of the account authorized to consume that nonce, this method will return a new transaction having the same type as the one supplied plus the [`TransactionMessageWithDurableNonceLifetime`](/api/interfaces/TransactionMessageWithDurableNonceLifetime) type. ```ts twoslash import { TransactionMessage, address, Rpc, GetAccountInfoApi } from '@solana/kit'; const rpc = null as unknown as Rpc; const transactionMessage = null as unknown as TransactionMessage; // ---cut-before--- import { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from '@solana/kit'; import { fetchNonce } from '@solana-program/system'; const nonceAccountAddress = address('EGtMh4yvXswwHhwVhyPxGrVV2TkLTgUqGodbATEPvojZ'); const nonceAuthorityAddress = address('4KD1Rdrd89NG7XbzW3xsX9Aqnx2EExJvExiNme6g9iAT'); const { data: { blockhash }, } = await fetchNonce(rpc, nonceAccountAddress); const nonce = blockhash as string as Nonce; const durableNonceTransactionMessage = setTransactionMessageLifetimeUsingDurableNonce( { nonce, nonceAccountAddress, nonceAuthorityAddress }, transactionMessage, ); ``` In particular, this method *prepends* an instruction to the transaction message designed to consume (or β€˜advance’) the nonce in the same transaction whose lifetime is defined by it. ```ts twoslash import { TransactionMessageWithDurableNonceLifetime } from '@solana/kit'; const durableNonceTransactionMessage = null as unknown as TransactionMessageWithDurableNonceLifetime< 'EGtMh4yvXswwHhwVhyPxGrVV2TkLTgUqGodbATEPvojZ', '4KD1Rdrd89NG7XbzW3xsX9Aqnx2EExJvExiNme6g9iAT' >; // ---cut-before--- const [ // An 'advance nonce' instruction gets prepended to the instruction list advanceNonceInstruction, ...otherInstructions ] = durableNonceTransactionMessage.instructions; ``` ### Adding instructions There are three types that correspond to the different parts of an instruction. Any given instruction may conform to one or more of these types, but must conform in every case to the `Instruction` type. * [`Instruction`](/api/interfaces/Instruction): An instruction having a `programAddress` property that is the base58-encoded address of the program to invoke. * [`InstructionWithAccounts`](/api/interfaces/InstructionWithAccounts): An instruction that specifies a list of accounts that a program may read from, write to, or require be signers of the transaction itself. Objects that conform to this type have an `accounts` property that is an array of `AccountMeta | AccountLookupMeta` in the order the instruction requires. * [`InstructionWithData`](/api/interfaces/InstructionWithData): An instruction that supplies some data as input to the program. Objects that conform to this type have a `data` property that can be any type of `Uint8Array`. Given an instruction, the [`appendTransactionMessageInstruction`](/api/functions/appendTransactionMessageInstruction) method will return a new transaction message with that instruction having been added to the end of the list of existing instructions. ```ts twoslash import { TransactionMessage } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage; // ---cut-before--- import { address, appendTransactionMessageInstruction, getUtf8Encoder } from '@solana/kit'; import { getAddMemoInstruction } from '@solana-program/memo'; const memoTransactionMessage = appendTransactionMessageInstruction( getAddMemoInstruction({ memo: 'Hello world!' }), transactionMessage, ); ``` To add an instruction to the beginning of the list instead, see [`prependTransactionMessageInstruction`](/api/functions/prependTransactionMessageInstruction) To add an array of instructions to a transaction message, see [`appendTransactionMessageInstructions`](/api/functions/appendTransactionMessageInstructions) and [`prependTransactionMessageInstructions`](/api/functions/prependTransactionMessageInstructions). ## Configuring compute and priority fees Every transaction has a compute budget β€” a maximum number of compute units (CUs) it is allowed to consume. The Solana network also lets you attach a priority fee to influence inclusion ordering. Kit exposes these as first-class configuration setters on the transaction message, so you do not need to add or update Compute Budget program instructions yourself. ### Setting the compute unit limit The compute unit limit caps how many CUs the transaction may consume. Setting it close to what your transaction actually uses increases the chance of inclusion, packs more transactions per block, and reduces the amount of priority fees you pay. ```ts twoslash import { TransactionMessage } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage; // ---cut-before--- import { setTransactionMessageComputeUnitLimit } from '@solana/kit'; const transactionMessageWithLimit = setTransactionMessageComputeUnitLimit( 50_000, transactionMessage, ); ``` To remove the limit, pass `undefined` as the first argument. The matching reader [`getTransactionMessageComputeUnitLimit`](/api/functions/getTransactionMessageComputeUnitLimit) returns the limit currently set on a message, or `undefined` if none is set. ### Estimating compute units A good way to size a transaction's compute units and other resource limits is to simulate it and use the result. Kit ships [`estimateResourceLimitsFactory`](/api/functions/estimateResourceLimitsFactory) for the simulation step and [`estimateAndSetResourceLimitsFactory`](/api/functions/estimateAndSetResourceLimitsFactory) for the common case of estimating and writing the result back onto the message in one call. Alongside the compute unit limit, these also estimate the loaded accounts data size limit, which is required for version 1 transactions. ```ts twoslash import { Rpc, SimulateTransactionApi, TransactionMessage, TransactionMessageWithFeePayer, } from '@solana/kit'; const rpc = null as unknown as Rpc; const transactionMessage = null as unknown as TransactionMessage & TransactionMessageWithFeePayer; // ---cut-before--- import { estimateAndSetResourceLimitsFactory, estimateResourceLimitsFactory, } from '@solana/kit'; const estimateResourceLimits = estimateResourceLimitsFactory({ rpc }); const estimateAndSetResourceLimits = estimateAndSetResourceLimitsFactory(estimateResourceLimits); const transactionMessageWithLimits = await estimateAndSetResourceLimits(transactionMessage); ``` The estimator simulates the transaction with the maximum allowed limits so the simulation itself never runs out of budget; the returned values are the compute units actually consumed and, for version 1 transactions, the loaded accounts data size. `estimateAndSetResourceLimitsFactory` only updates a limit if no explicit value is already set or if the existing value is the provisory `0` value, leaving manually configured limits untouched. When constructing a message that you intend to estimate later, [`fillTransactionMessageProvisoryResourceLimits`](/api/functions/fillTransactionMessageProvisoryResourceLimits) reserves space for the limits by setting them to a provisory value of `0`. ### Setting the priority fee Priority fees boost the chance that your transaction is included sooner. The exact knob depends on the transaction version: legacy and v0 transactions express priority fees as a price per compute unit, while v1 transactions express them as a single total amount in lamports. ```ts twoslash import { TransactionMessage } from '@solana/kit'; const v0TransactionMessage = null as unknown as TransactionMessage & { version: 0 }; const v1TransactionMessage = null as unknown as TransactionMessage & { version: 1 }; // ---cut-before--- import { setTransactionMessageComputeUnitPrice, setTransactionMessagePriorityFeeLamports, } from '@solana/kit'; // Legacy or v0: 10,000 micro-lamports per compute unit. const v0WithPriorityFee = setTransactionMessageComputeUnitPrice(10_000n, v0TransactionMessage); // v1: 50,000 lamports total, regardless of compute unit usage. const v1WithPriorityFee = setTransactionMessagePriorityFeeLamports(50_000n, v1TransactionMessage); ``` Both setters accept `undefined` to clear the configuration. The matching readers [`getTransactionMessageComputeUnitPrice`](/api/functions/getTransactionMessageComputeUnitPrice) and [`getTransactionMessagePriorityFeeLamports`](/api/functions/getTransactionMessagePriorityFeeLamports) return the current value or `undefined` when none is set. Bundled clients such as `solanaRpc` and `litesvm` estimate the compute unit limit when sending transactions for you. Reach for the setters above when you build messages by hand or when you want to override what a client would do automatically. ## Compressing transaction messages Every transaction message must include a reference to the account addresses it will read from and write to. One alternative to storing these addresses in the message itself is to store them in an onchain account called an **address lookup table**. This lets you save space in the message by replacing many 32-byte account addresses with one or more 32-byte address lookup table account addresses then a 1-byte index into those tables for each address. Addresses that are required signers of a transaction message can not be looked up in an address lookup table; they must be encoded in the message in the conventional way. Given a transaction message and a mapping of lookup tables to the ordered addresses stored in them, the [`compressTransactionMessageUsingAddressLookupTables`](/api/functions/compressTransactionMessageUsingAddressLookupTables) function will return a new transaction message with the same instructions but with all non-signer accounts that are found in the given lookup tables represented by an [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta) instead of an [`AccountMeta`](/api/interfaces/AccountMeta). ```ts twoslash import { AddressesByLookupTableAddress, Rpc, GetAccountInfoApi, TransactionMessage, } from '@solana/kit'; const rpc = null as unknown as Rpc; const transactionMessage = null as unknown as Extract; // ---cut-before--- import { address, compressTransactionMessageUsingAddressLookupTables } from '@solana/kit'; import { fetchAddressLookupTable } from '@solana-program/address-lookup-table'; const lookupTableAddress = address('4QwSwNriKPrz8DLW4ju5uxC2TN5cksJx6tPUPj7DGLAW'); const { data: { addresses }, } = await fetchAddressLookupTable(rpc, lookupTableAddress); const addressesByAddressLookupTable: AddressesByLookupTableAddress = { [lookupTableAddress]: addresses, }; const compressedTransactionMessage = compressTransactionMessageUsingAddressLookupTables( transactionMessage, addressesByAddressLookupTable, ); ``` Consider how compressing transaction messages creates more space for instructions. This might enable you to prepare more complex transactions, or to execute the same number of instructions over fewer transactions thereby saving on network fees. This technique can not be applied to transaction messages having the version `'legacy'`. ## Signing transaction messages In order to be executed a transaction message must be signed by all of the private keys belonging to accounts that are required signers of the transaction, and must not exceed the size allowable by the network. You may encounter these types when using functions that send transactions. * [`FullySignedTransaction`](/api/type-aliases/FullySignedTransaction): A transaction that is signed by all of its required signers. * [`TransactionWithinSizeLimit`](/api/type-aliases/TransactionWithinSizeLimit): A transaction that is under or equal to the maximum size limit for transactions on the Solana network. * [`SendableTransaction`](/api/type-aliases/SendableTransaction): A union of `FullySignedTransaction` and `TransactionWithinSizeLimit` Transaction messages whose signers are specified using `TransactionSigner` objects have the ability to self-sign. This is because signers encapsulate both the address of the signing account as well as an implementation of the signing algorithm for the private key associated with that account. The [`signTransactionMessageWithSigners`](/api/functions/signTransactionMessageWithSigners) method will return a new signed transaction of type `FullySignedTransaction`. ```ts twoslash import { TransactionMessage, TransactionMessageWithFeePayer, TransactionMessageWithSigners, } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners; // ---cut-before--- import { SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, isSolanaError, signTransactionMessageWithSigners, } from '@solana/kit'; try { const fullySignedTransaction = await signTransactionMessageWithSigners(transactionMessage); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) { console.error('Missing signers for the following addresses:', e.context.addresses); } else { throw e; } } ``` This function will throw if the transaction message does not carry a `TransactionSigner` implementation for every required signer. To partially sign a message that you know to carry a strict subset of the required `TransactionSigners`, use the [`partiallySignTransactionMessageWithSigners`](/api/functions/partiallySignTransactionMessageWithSigners) method. If exactly one of the `TransactionSigners` in the message is a [`TransactionSendingSigner`](/api/type-aliases/TransactionSendingSigner) then you can use the [`signAndSendTransactionMessageWithSigners`](/api/functions/signAndSendTransactionMessageWithSigners) method to sign and send the transaction in a single step. For a comprehensive guide on all signing functions β€” including the lower-level [`partiallySignTransactionWithSigners`](/api/functions/partiallySignTransactionWithSigners), [`signTransactionWithSigners`](/api/functions/signTransactionWithSigners), and [`signAndSendTransactionWithSigners`](/api/functions/signAndSendTransactionWithSigners) functions that accept an explicit array of signers and a compiled transaction β€” see the [Signing with signers](/docs/advanced-guides/signers#signing-with-signers) section. Building transaction messages using `TransactionSigners` is the recommended way to create self-signable transaction messages. To sign with a `CryptoKey` directly, you first have to compile the transaction message. ```ts twoslash import { TransactionMessage, TransactionMessageWithFeePayer, TransactionMessageWithSigners, } from '@solana/kit'; const transactionMessage = null as unknown as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners; // ---cut-before--- import { compileTransaction } from '@solana/kit'; const transaction = compileTransaction(transactionMessage); ``` This produces an unsigned transaction. Follow the [instructions for signing transactions with `CryptoKeyPairs`](#signing-transactions) to sign it. ## Signing transactions Wherever you have a `Transaction` instead of a `TransactionMessage` you can add or replace a signature using the [`signTransaction`](/api/functions/signTransaction) method and one or more `CryptoKeyPairs`. ```ts twoslash import { Transaction, TransactionWithLifetime } from '@solana/kit'; const keyPair = null as unknown as CryptoKeyPair; const transaction = null as unknown as Transaction & TransactionWithLifetime; // ---cut-before--- import { SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, isSolanaError, signTransaction, } from '@solana/kit'; try { const fullySignedTransaction = await signTransaction([keyPair], transaction); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) { console.error('Missing signers for the following addresses:', e.context.addresses); } else { throw e; } } ``` This function will throw if the resultant transaction is missing a signature for one of the transaction's required signers. To partially sign a transaction, use the [`partiallySignTransaction`](/api/functions/partiallySignTransaction) method. If you have [`TransactionSigner`](/api/type-aliases/TransactionSigner) objects rather than raw `CryptoKeyPairs`, you can use [`signTransactionWithSigners`](/api/functions/signTransactionWithSigners) and [`partiallySignTransactionWithSigners`](/api/functions/partiallySignTransactionWithSigners) instead. See the [Signing with signers](/docs/advanced-guides/signers#signing-compiled-transactions) section for details. ## Serializing transactions If you would like to send a transaction to the network manually, you must first serialize it in a particular way. The [`Base64EncodedWireTransaction`](/api/type-aliases/Base64EncodedWireTransaction) represents the wire format of a transaction as a base64-encoded string. Given a transaction, the [`getBase64EncodedWireTransaction`](/api/functions/getBase64EncodedWireTransaction) method returns the transaction as a string that conforms to the `Base64EncodedWireTransaction` type. ```ts twoslash import { Transaction, Rpc, SendTransactionApi } from '@solana/kit'; const rpc = null as unknown as Rpc; const signedTransaction = null as unknown as Transaction; // ---cut-before--- import { getBase64EncodedWireTransaction, signTransaction } from '@solana/kit'; const serializedTransaction = getBase64EncodedWireTransaction(signedTransaction); const signature = await rpc.sendTransaction(serializedTransaction, { encoding: 'base64' }).send(); ``` Typically you would not serialize and send transactions to the network manually. See [Kit without a client](/docs/advanced-guides/kit-without-a-client) for the full no-client transaction flow. ## Deserializing transactions You can fetch the raw bytes of a transaction from the network using an RPC server. ```ts twoslash import { createSolanaRpc, getBase64Encoder, Signature } from '@solana/kit'; const rpc = createSolanaRpc('...'); // ---cut-before--- const response = await rpc .getTransaction( '3atZVDiLEjXmddxLbH2AWHtFdXmHRocnA4vNyvkPRcd7WnzCtoVshFCvGtxfGYWs9C6ptucY6Jd84BerDnzQpJEH' as Signature, { encoding: 'base64' }, ) .send(); if (!response) { throw new Error('Could not find transaction'); } const { transaction: [base64EncodedTransaction], } = response; const transactionBytes = getBase64Encoder().encode(base64EncodedTransaction); ``` Decoding the wire transaction bytes yields a `Transaction` object. This takes the form of a transaction message encoded as a byte array, and a list of signatures of those bytes created by those who must authorize the message and pay for it to be executed on Solana. ```ts twoslash import { ReadonlyUint8Array } from '@solana/kit'; const transactionBytes = new Uint8Array() as ReadonlyUint8Array; // ---cut-before--- import { getTransactionDecoder } from '@solana/kit'; const transaction = getTransactionDecoder().decode(transactionBytes); ``` Decoding the network wire format bytes of the message will yield a transaction message in its **compiled** form – a message in a form suitable for execution on the network. Encountering a compiled message in your application is rare, but it's important to know that they exist. ```ts twoslash import { Transaction } from '@solana/kit'; const transaction = null as unknown as Transaction; // ---cut-before--- import { getCompiledTransactionMessageDecoder } from '@solana/kit'; const compiledTransactionMessage = getCompiledTransactionMessageDecoder().decode( transaction.messageBytes, ); ``` Finally, decompiling a compiled message will yield a `TransactionMessage` object. This is the most common form of transaction message that you will encounter when using Kit to build an application. ```ts twoslash import { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from '@solana/kit'; const compiledTransactionMessage = null as unknown as CompiledTransactionMessage & CompiledTransactionMessageWithLifetime; // ---cut-before--- import { decompileTransactionMessage } from '@solana/kit'; const transactionMessage = decompileTransactionMessage(compiledTransactionMessage); ``` You can not fully reconstruct a source message from a compiled message without extra information. In particular, supporting details about the lifetime constraint and the concrete addresses of accounts sourced from account lookup tables are lost to compilation, but can be supplied in the `config` argument of the `decompileTransactionMessage` or `decompileTransactionMessageFetchingLookupTables` methods. To resolve a confirmed transaction's instructions β€” including the inner instructions emitted by cross-program invocations β€” into a form the `@solana-program/*` clients can `identify` and `parse` directly, see [Transaction introspection](/docs/advanced-guides/transaction-introspection). # Fetching accounts (/docs/guides/fetching-accounts) Reading data from Solana usually means fetching one or more accounts and decoding their data into something your application can use. This guide walks through the helpers Kit provides at each step, from the raw RPC call all the way to typed account objects. ## Fetch raw account data The `fetchEncodedAccount` helper wraps the `getAccountInfo` RPC method and returns a `MaybeEncodedAccount`. The result always has the same shape regardless of whether the account exists, which makes it easier to handle than the raw RPC response. ```ts twoslash import { address, fetchEncodedAccount } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const wallet = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const account = await fetchEncodedAccount(client.rpc, wallet); ``` When the account exists, you get back its address, lamports, owner program, and a `data` field containing the raw bytes as a `Uint8Array`. When it does not, the same object is returned with `exists: false` and just the address. ## Handle missing accounts A `MaybeEncodedAccount` is a discriminated union: TypeScript narrows the type once you check `account.exists`. You can branch on that flag, or use `assertAccountExists` when you would rather throw if the account is not present. ```ts twoslash import { address, assertAccountExists, fetchEncodedAccount } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const wallet = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const account = await fetchEncodedAccount(client.rpc, wallet); assertAccountExists(account); // `account` is now `EncodedAccount`, with `data` typed as `Uint8Array`. account.data satisfies Uint8Array; ``` Asserting up front lets the rest of your function rely on a fully populated account, which is convenient for scripts and tests. In application code, branching on `account.exists` is usually a better fit so you can show a sensible empty state. When working with several accounts at once, `assertAccountsExist(accounts)` performs the same check across an entire array in one call. ## Fetch multiple accounts When you need several accounts at once, `fetchEncodedAccounts` batches them into a single `getMultipleAccounts` RPC request and returns a parallel array of `MaybeEncodedAccount` values. ```ts twoslash import { address, fetchEncodedAccounts } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const accounts = await fetchEncodedAccounts(client.rpc, [ address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'), address('Ay1zdJ3VDbhrAtkRiqBUJgKLHYbgFZN5BXk7svtMowif'), ]); ``` Each returned account already carries its own address, so you do not need to zip arrays together to figure out which result belongs to which input. The same `exists` flag works on every entry, and `assertAccountsExist(accounts)` is the multi-account counterpart of `assertAccountExists`. ## Decode accounts manually Once you have an encoded account, the `decodeAccount` helper turns it into a typed `Account` (or `MaybeAccount`) by running its `data` through any `Decoder`. The [Codecs guide](/docs/advanced-guides/codecs) covers how to build these decoders. ```ts twoslash import { address, decodeAccount, fetchEncodedAccount } from '@solana/kit'; import { addDecoderSizePrefix, Decoder, getStructDecoder, getU32Decoder, getU8Decoder, getUtf8Decoder, } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- type Person = { name: string; age: number }; const personDecoder: Decoder = getStructDecoder([ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())], ['age', getU8Decoder()], ]); const wallet = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const encodedAccount = await fetchEncodedAccount(client.rpc, wallet); const decodedAccount = decodeAccount(encodedAccount, personDecoder); ``` `decodeAccount` preserves the `MaybeAccount` shape: a missing account stays missing, and a present account gets its `data` swapped from raw bytes to your decoded type. This means you can keep narrowing with `account.exists` exactly like before. ## Decode using program helpers For most popular Solana programs you will not need to write a decoder yourself. The `@solana-program/*` packages include generated helpers that handle decoding for every account they define, exposed as `decodeX`, `fetchX`, and `fetchMaybeX` functions where `X` is the account name. ```ts twoslash import { address } from '@solana/kit'; import { fetchMint } from '@solana-program/token'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const mint = await fetchMint(client.rpc, address('So11111111111111111111111111111111111111112')); mint.data.decimals; // typed as `number` ``` Each program package follows the same naming convention: `fetchMint` and `fetchMaybeMint` for the `Mint` account, `fetchToken` and `fetchMaybeToken` for the `Token` account, and so on. The standalone `decodeMint` and `decodeToken` helpers work on encoded accounts you have already fetched. If you would rather access these through a typed `client.token.accounts.*` namespace, see the [Using program plugins](/docs/guides/using-program-plugins) guide. ## Subscribe to account changes If you need live updates rather than a one-off read, pair an account fetch with an account subscription. The subscription notifies you whenever the account's data changes onchain, and the same address is used in both calls. ```ts twoslash import { address } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const wallet = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const accountNotifications = await client.rpcSubscriptions .accountNotifications(wallet, { commitment: 'confirmed' }) .subscribe({ abortSignal: AbortSignal.timeout(60_000) }); for await (const notification of accountNotifications) { console.log('Account changed:', notification.value); } ``` See the [RPC subscriptions](/docs/guides/rpc-subscriptions) guide for more on cancellation, error handling, and the async iterator model. ## Choose the right fetch helper Each helper trades a different amount of structure and convenience. The table below summarizes when each one shines. | Helper | Returns | Best for | | ------------------------------------- | --------------------------------- | -------------------------------------- | | `client.rpc.getAccountInfo(...)` | raw RPC response | one-off reads with custom encoding | | `client.rpc.getMultipleAccounts(...)` | raw RPC response | bulk reads with custom encoding | | `fetchEncodedAccount(...)` | `MaybeEncodedAccount` | unified handling of single accounts | | `fetchEncodedAccounts(...)` | `MaybeEncodedAccount[]` | unified batch reads | | `decodeAccount(...)` | `Account` / `MaybeAccount` | turning raw bytes into typed data | | `fetchMint`, `fetchToken`, ... | `Account` / `MaybeAccount` | typed reads for known program accounts | | `accountNotifications(...)` | async iterator of account updates | live updates instead of one-off reads | In practice you can pick any of them in isolation, or combine them to match the access pattern you need. ## Next steps * [Codecs](/docs/advanced-guides/codecs) β€” learn how to build custom decoders. * [RPC requests](/docs/guides/rpc) β€” explore the rest of the RPC API. * [Using program plugins](/docs/guides/using-program-plugins) β€” read typed accounts through `client.token.accounts.mint.fetch(...)` and friends. # Guides (/docs/guides) The pages in this section cover the most common tasks you will run into when building Solana applications with Kit. Each guide focuses on a single topic and can be read independently, so you can dip in when a specific question comes up rather than reading them in order. ## How to use these guides If you are completely new to Kit, start with the [Getting started](/docs/getting-started) tutorial. It walks through a small end-to-end project so the rest of the documentation has something concrete to reference. Once you have shipped your first transaction, the guides below are designed to be your day-to-day companion. They focus on practical workflows β€” composing a client, sending transactions, fetching accounts, testing locally, and so on β€” and link to the [Advanced guides](/docs/advanced-guides) when you want to learn what is happening under the hood. # RPC subscriptions (/docs/guides/rpc-subscriptions) RPC subscriptions let your application receive live updates from the network instead of polling for them. They are delivered over a WebSocket endpoint and surface as async iterators in Kit, which fit naturally into modern JavaScript control flow. Kit aims to support every method documented in the [Solana RPC WebSocket methods](https://solana.com/docs/rpc/websocket) docs. As with HTTP RPC, you can either browse the methods in the official documentation or rely on TypeScript autocompletion in your editor. ## Installation You will typically install Kit alongside the RPC plugin package, which provides both HTTP and WebSocket connectivity. ```bash npm install @solana/kit @solana/kit-plugin-rpc ``` ```bash pnpm add @solana/kit @solana/kit-plugin-rpc ``` ```bash yarn add @solana/kit @solana/kit-plugin-rpc ``` ```bash bun add @solana/kit @solana/kit-plugin-rpc ``` If you only need subscriptions and prefer not to use a Kit client, the lower-level `createSolanaRpcSubscriptions` function is available directly from `@solana/kit`. ## Create a subscriptions client The bundle plugins from `@solana/kit-plugin-rpc` install both `client.rpc` and `client.rpcSubscriptions` in one step. You do not need to manage two separate transports. ```ts twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); ``` By default, the WebSocket endpoint is derived from the HTTP endpoint by swapping `http`/`https` for `ws`/`wss`. If your provider hosts the two endpoints at different URLs, pass `rpcSubscriptionsUrl` explicitly in the plugin configuration. ## Subscribe to slot notifications Subscriptions return an async iterator. The most idiomatic way to consume one is a `for await` loop, which keeps reading notifications until the underlying subscription ends. ```ts twoslash // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const slotNotifications = await client.rpcSubscriptions .slotNotifications() .subscribe({ abortSignal: AbortSignal.timeout(10_000) }); for await (const notification of slotNotifications) { console.log('The network advanced to slot', notification.slot); } ``` The `.subscribe({ abortSignal })` step is mandatory because every subscription must be tied to an `AbortSignal`. This forces you to think up front about when the subscription should end and prevents leaks. ## Cancel subscriptions You may want to cancel a subscription before it ends naturally β€” for example, when a component unmounts in a UI. Pass an `AbortController` so that calling `.abort()` from anywhere in your code stops the iterator gracefully. ```ts twoslash // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const abortController = new AbortController(); const slotNotifications = await client.rpcSubscriptions .slotNotifications() .subscribe({ abortSignal: abortController.signal }); // Stop receiving notifications after the user navigates away. abortController.abort(); ``` `AbortSignal.timeout(ms)` is a convenient shortcut when you simply want a fixed duration. For one-off subscriptions, that single line is often all you need. ## Subscribe to account changes Account subscriptions notify you whenever an account's data changes onchain. The shape of the notification mirrors the response of `getAccountInfo`, so the same encoding and commitment options apply. ```ts twoslash import { address } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const wallet = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const accountNotifications = await client.rpcSubscriptions .accountNotifications(wallet, { commitment: 'confirmed' }) .subscribe({ abortSignal: AbortSignal.timeout(60_000) }); for await (const notification of accountNotifications) { console.log('Account changed:', notification.value); } ``` If you only need a one-off read of an account, [`fetchEncodedAccount`](/docs/guides/fetching-accounts) is usually a better fit. Use subscriptions for live, ongoing updates. ## Handle disconnects and errors Long-lived subscriptions can disconnect for many reasons β€” flaky networks, server restarts, or connection limits β€” and errors can be raised at any point during iteration. Wrap the iteration in a `try`/`catch` so your application can react gracefully. ```ts twoslash import { address } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const wallet = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const accountNotifications = await client.rpcSubscriptions .accountNotifications(wallet, { commitment: 'confirmed' }) .subscribe({ abortSignal: AbortSignal.timeout(60_000) }); try { for await (const notification of accountNotifications) { console.log('Account changed:', notification.value); } } catch (error) { // Reconnect, log, surface a UI error, etc. } ``` Depending on your application, you may want to recreate the subscription with a fresh `AbortSignal` after a disconnect, possibly using a small backoff to avoid thrashing the server. ## Use subscriptions without a client If you do not need a Kit client, you can build an `RpcSubscriptions` object directly with `createSolanaRpcSubscriptions`. This is the lower-level building block the plugins use under the hood. ```ts twoslash import { createSolanaRpcSubscriptions, mainnet } from '@solana/kit'; const rpcSubscriptions = createSolanaRpcSubscriptions(mainnet('wss://api.mainnet-beta.solana.com')); const slotNotifications = await rpcSubscriptions .slotNotifications() .subscribe({ abortSignal: AbortSignal.timeout(10_000) }); ``` This is useful when you want maximum tree-shaking, when you are writing a library that should not assume a client, or when you only need a tiny subset of the subscriptions API. ## Choose a WebSocket endpoint For light development or personal use, the public WebSocket endpoints maintained by the Solana Foundation work the same way as their HTTP counterparts. * `wss://api.mainnet-beta.solana.com` * `wss://api.testnet.solana.com` * `wss://api.devnet.solana.com` In production, your HTTP and WebSocket endpoints should match β€” both clusters and providers β€” to avoid subtle mismatches between the data each transport returns. Most RPC providers offer paired endpoints; consult their documentation for the exact URLs they expect you to use. ## Next steps * [RPC requests](/docs/guides/rpc) β€” read state and submit one-off requests over HTTP. * [Fetching accounts](/docs/guides/fetching-accounts) β€” pair subscriptions with a baseline read. * [Sending transactions](/docs/guides/sending-transactions) β€” submit work to the network. # RPC requests (/docs/guides/rpc) Solana applications interact with the network through a JSON-RPC server. RPC requests are how your code reads onchain state, simulates transactions, and submits transactions to be processed. Kit ships a fully typed RPC client and exposes it on Kit clients via plugins, so the same RPC API is available whether you compose a client or use the lower-level building blocks directly. Kit aims to support every method documented in the [Solana RPC HTTP methods](https://solana.com/docs/rpc/http) docs. You can either browse the methods in the official documentation or rely on TypeScript autocompletion in your editor. ## Installation You will typically install Kit alongside the RPC plugin package. ```bash npm install @solana/kit @solana/kit-plugin-rpc ``` ```bash pnpm add @solana/kit @solana/kit-plugin-rpc ``` ```bash yarn add @solana/kit @solana/kit-plugin-rpc ``` ```bash bun add @solana/kit @solana/kit-plugin-rpc ``` The `@solana/kit-plugin-rpc` package contains the plugins that install RPC connectivity on a client. The `@solana/kit` package contains the lower-level RPC primitives those plugins are built on top of, so you can also use it standalone if you prefer not to use a client. ## Create an RPC client The most convenient way to make RPC requests is to compose a Kit client with one of the bundle plugins, which install both `client.rpc` and `client.rpcSubscriptions` in one call. ```ts twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); ``` The bundle plugins also wire up minimum balance computation, transaction planning, and transaction sending, which you will use in the other guides. If you only need to make read-only RPC requests, you can drop the signer plugin and use `solanaRpcConnection(...)` instead, which only installs `client.rpc` and `client.rpcSubscriptions`. ## Send your first RPC request Once you have an RPC client, you build a request by calling the corresponding method on `client.rpc` and finalize it with `.send()`. Most RPC responses come back wrapped in a `{ context, value }` object, so destructuring `value` is a common pattern. ```ts twoslash import { address } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const wallet = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const { value: balance } = await client.rpc.getBalance(wallet).send(); ``` Although `client.rpc` looks like a regular object, it is actually a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) that constructs RPC requests on demand. TypeScript provides type safety for every method based on the API installed by your plugin, which makes the available methods discoverable from your editor while keeping the bundle small. ## Use cluster-specific RPC bundles The `@solana/kit-plugin-rpc` package ships several bundle plugins, each tailored to a specific use case. The cluster-typed variants type the RPC API to match what is available on that cluster, which prevents accidents like calling `airdrop` against mainnet at compile time. | Plugin | Default endpoint | Adds to the client | | ----------------------- | ------------------------------- | ----------------------------------------------------------- | | `solanaRpc(config)` | provided via `rpcUrl` | RPC, subscriptions, planning, sending | | `solanaMainnetRpc(...)` | provided via `rpcUrl` | mainnet-typed RPC, subscriptions, planning, sending | | `solanaDevnetRpc(...)` | `https://api.devnet.solana.com` | devnet-typed RPC, subscriptions, planning, sending, airdrop | | `solanaLocalRpc(...)` | `http://127.0.0.1:8899` | localnet RPC, subscriptions, planning, sending, airdrop | If you need to talk to a custom RPC provider, pass its URL through `solanaRpc({ rpcUrl: '...' })` or `solanaMainnetRpc({ rpcUrl: '...' })`. The other settings on `SolanaRpcConfig` cover advanced options such as transport configuration and transaction planner overrides. ## Pass request options Most RPC methods accept a configuration object as their final argument. This is where you control things like the requested commitment level, encoding, or pagination, depending on the method. ```ts twoslash import { address } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); // ---cut-end--- const wallet = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const { value: balance } = await client.rpc.getBalance(wallet, { commitment: 'confirmed' }).send(); ``` The `.send(...)` call itself accepts an optional `abortSignal` that lets you cancel the request in flight. ## Use RPC without a client If you do not need a Kit client, you can build an `Rpc` object directly with `createSolanaRpc`. This is useful when you want maximum tree-shaking, when you are writing a library that should not assume a client, or when you simply want to keep your dependency surface small. ```ts twoslash import { address, createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const wallet = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const { value: balance } = await rpc.getBalance(wallet).send(); ``` The standalone `Rpc` object exposes the exact same API as `client.rpc`, so any code that takes an `Rpc` will work in either setup. See the [Kit without a client](/docs/advanced-guides/kit-without-a-client) guide for more on this approach. ## Choose an RPC endpoint For light development or personal use, the public RPC endpoints maintained by the Solana Foundation are a fine starting point. * `https://api.mainnet-beta.solana.com` * `https://api.testnet.solana.com` * `https://api.devnet.solana.com` These endpoints are heavily rate-limited and should not be used for anything close to production traffic. When you ship to production, lease an RPC node from a provider or [run your own](https://docs.anza.xyz/operations/setup-an-rpc-node). Some RPC providers also expose extra methods on top of the standard JSON-RPC API; many of them ship a Kit-compatible SDK that you can layer on top of `createSolanaRpc(...)` to merge their additional methods into the typed RPC object. ## Next steps * [RPC subscriptions](/docs/guides/rpc-subscriptions) β€” receive live updates from a WebSocket endpoint. * [Fetching accounts](/docs/guides/fetching-accounts) β€” go from raw account bytes to typed data. * [Sending transactions](/docs/guides/sending-transactions) β€” submit transactions through your client. # Sending multiple transactions (/docs/guides/sending-multiple-transactions) When an operation cannot fit in a single transaction β€” too many instructions, too much data, or work that should run in parallel β€” you need to split it across several transactions. Kit clients support this through the same `client.sendTransactions(...)` and `client.planTransactions(...)` methods you used in [Sending transactions](/docs/guides/sending-transactions), but plural. ## Prerequisites This guide assumes a transaction-ready client, like the one set up in [Sending transactions](/docs/guides/sending-transactions). The same bundle plugins from `@solana/kit-plugin-rpc` and `@solana/kit-plugin-litesvm` install everything `client.sendTransactions(...)` needs out of the box. ## Instruction plans An instruction plan describes an operation made of several instructions together with constraints on how they can run β€” some steps must happen sequentially, others may run in parallel, and some must stay atomic. Kit represents this as a tree, so simple operations stay simple while more complex flows can nest sequential and parallel branches inside each other. The plan is then handed to a [transaction planner](/docs/advanced-guides/instruction-plans) that decides how to pack it into transaction messages, and then to a [transaction plan executor](/docs/advanced-guides/instruction-plans) that sends those transactions. Kit's planners can divide work, batch it into transactions, and even pack variable-sized data into the available space. For most cases you only need to know about three building blocks: `singleInstructionPlan`, `sequentialInstructionPlan`, and `parallelInstructionPlan`. The [Instruction plans](/docs/advanced-guides/instruction-plans) advanced guide goes much deeper. ## Run work sequentially Use `sequentialInstructionPlan(...)` when each step depends on the previous one β€” for example, creating an account before initializing it. ```ts twoslash import { Instruction, sequentialInstructionPlan } from '@solana/kit'; const createAccount = {} as Instruction; const initializeAccount = {} as Instruction; // ---cut-before--- const instructionPlan = sequentialInstructionPlan([createAccount, initializeAccount]); ``` Sequential plans accept either raw instructions or other instruction plans, so you can compose larger flows from smaller ones. A `nonDivisibleSequentialInstructionPlan(...)` variant also exists for steps that must run atomically inside a single transaction (or transaction bundle when not possible). ## Run work in parallel Use `parallelInstructionPlan(...)` when independent steps can run in any order. The planner is then free to pack them into separate transactions and send them concurrently. ```ts twoslash import { Instruction, parallelInstructionPlan } from '@solana/kit'; const transferToBob = {} as Instruction; const transferToCarla = {} as Instruction; // ---cut-before--- const instructionPlan = parallelInstructionPlan([transferToBob, transferToCarla]); ``` The two helpers compose freely: a sequential plan can contain parallel children and vice versa. This is how you describe operations like "set up these two accounts in parallel, then run the operation that depends on both of them". ## Plan multiple transactions When you only want to inspect or persist the planned transactions, `client.planTransactions(plan)` runs the planner without executing anything and returns the resulting `TransactionPlan` tree. ```ts twoslash import { lamports, parallelInstructionPlan } from '@solana/kit'; import { getTransferSolInstruction } from '@solana-program/system'; // ---cut-start--- import { address } from '@solana/kit'; import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(10_000_000_000n))); const bob = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const carla = address('Ay1zdJ3VDbhrAtkRiqBUJgKLHYbgFZN5BXk7svtMowif'); // ---cut-end--- const instructionPlan = parallelInstructionPlan([ getTransferSolInstruction({ source: client.payer, destination: bob, amount: lamports(500_000n), }), getTransferSolInstruction({ source: client.payer, destination: carla, amount: lamports(500_000n), }), ]); const transactionPlan = await client.planTransactions(instructionPlan); ``` The returned `TransactionPlan` keeps the same sequential and parallel structure as the original instruction plan, but its leaves are the concrete transaction messages the planner chose to pack the work into. This is useful for dry runs, debugging, or feeding a custom executor. ## Send multiple transactions To plan and send in one call, use `client.sendTransactions(plan)`. The result is a `TransactionPlanResult` tree that mirrors the original plan, with one leaf per transaction. ```ts twoslash import { lamports, parallelInstructionPlan } from '@solana/kit'; import { getTransferSolInstruction } from '@solana-program/system'; // ---cut-start--- import { address } from '@solana/kit'; import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(10_000_000_000n))); const bob = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const carla = address('Ay1zdJ3VDbhrAtkRiqBUJgKLHYbgFZN5BXk7svtMowif'); // ---cut-end--- const instructionPlan = parallelInstructionPlan([ getTransferSolInstruction({ source: client.payer, destination: bob, amount: lamports(500_000n), }), getTransferSolInstruction({ source: client.payer, destination: carla, amount: lamports(500_000n), }), ]); const result = await client.sendTransactions(instructionPlan); ``` `client.sendTransactions(...)` is the multi-transaction counterpart of `client.sendTransaction(...)`. The single-transaction version asserts that the plan resolves to exactly one transaction and unwraps its result β€” a convenience for the common case. The plural version preserves the full tree, which you can walk to see what happened. ## Understand transaction plan results Every leaf in the result tree is a `SingleTransactionPlanResult` with one of three statuses: * `successful` β€” the transaction was sent and confirmed; `context.signature` is always present. * `failed` β€” the transaction was attempted but failed during preflight, simulation, or execution. `error` carries the underlying error. * `canceled` β€” the transaction was never attempted, typically because a prior transaction in a sequential branch failed first. ```ts twoslash import { TransactionPlanResult } from '@solana/kit'; const result = {} as TransactionPlanResult; // ---cut-before--- if (result.kind === 'single') { if (result.status === 'successful') { console.log('Signature:', result.context.signature); } else if (result.status === 'failed') { console.error('Failed:', result.error); } else { console.warn('Canceled before being sent'); } } ``` Branch nodes use `kind: 'parallel'` or `kind: 'sequential'`, with their child results in `plans`. You usually do not need to walk the tree by hand β€” the helpers in the next sections cover the common cases. ## Summarize results `summarizeTransactionPlanResult(...)` flattens the tree and bucketizes the results so you can quickly check whether everything succeeded. ```ts twoslash import { summarizeTransactionPlanResult, TransactionPlanResult } from '@solana/kit'; const result = {} as TransactionPlanResult; // ---cut-before--- const summary = summarizeTransactionPlanResult(result); if (summary.successful) { console.log(`βœ… ${summary.successfulTransactions.length} transactions confirmed`); } else { console.warn( `${summary.successfulTransactions.length} ok, ` + `${summary.failedTransactions.length} failed, ` + `${summary.canceledTransactions.length} canceled`, ); } ``` This is usually the first thing to reach for after `client.sendTransactions(...)` β€” it gives you a quick health check without writing any tree-walking code. ## Continue after failures By default, `client.sendTransactions(...)` throws as soon as any transaction in the plan fails. That behaviour is convenient for small operations, but counterproductive when you are running a large batch and want to inspect partial results. The `passthroughFailedTransactionPlanExecution(...)` helper turns that thrown error back into a `TransactionPlanResult`. ```ts twoslash import { InstructionPlan, passthroughFailedTransactionPlanExecution } from '@solana/kit'; const instructionPlan = {} as InstructionPlan; // ---cut-start--- import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(10_000_000_000n))); // ---cut-end--- const result = await passthroughFailedTransactionPlanExecution( client.sendTransactions(instructionPlan), ); ``` After this call, `result` is the same tree you would have received on full success β€” but with `failed` and `canceled` leaves where the issues occurred. You can then summarize it, walk it, or react however you need. ## Handle partial success When you want to react to each transaction individually, `flattenTransactionPlanResult(...)` collapses the tree into an array of leaf results in the order they appear. ```ts twoslash import { flattenTransactionPlanResult, TransactionPlanResult } from '@solana/kit'; const result = {} as TransactionPlanResult; // ---cut-before--- for (const single of flattenTransactionPlanResult(result)) { if (single.status === 'successful') { console.log('βœ…', single.context.signature); } else if (single.status === 'failed') { console.error('❌', single.error.message); } else { console.warn('⏭️', 'canceled'); } } ``` Combined with `passthroughFailedTransactionPlanExecution(...)`, this is enough to drive a UI that shows per-transaction status, retry buttons, or detailed error messages for a long-running multi-transaction operation. ## Next steps * [Sending transactions](/docs/guides/sending-transactions) β€” single-transaction basics. * [Advanced guides β€” Instruction plans](/docs/advanced-guides/instruction-plans) β€” the full instruction plan API. * [Advanced guides β€” Errors](/docs/advanced-guides/errors) β€” recover from `SolanaError` failures. # Sending transactions (/docs/guides/sending-transactions) A Kit client can take a list of instructions and turn it into a fully signed, sent, and confirmed transaction in a single call. This guide covers the basics of sending one transaction at a time. When an operation needs to span multiple transactions, see [Sending multiple transactions](/docs/guides/sending-multiple-transactions). ## Create a transaction-ready client Sending transactions requires a client that exposes a `sendTransaction` method. At the lowest level, this means installing the [`planAndSendTransactions`](/docs/plugins/available-plugins) plugin from `@solana/kit-plugin-instruction-plan` on top of a custom `transactionPlanner` and `transactionPlanExecutor`. In practice, you almost always pick a higher-level bundle that does this for you. ```ts twoslash import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaLocalRpc()); ``` The bundle plugins from `@solana/kit-plugin-rpc` (`solanaRpc`, `solanaMainnetRpc`, `solanaDevnetRpc`, `solanaLocalRpc`) and the `litesvm` plugin from `@solana/kit-plugin-litesvm` all install a working planner and executor out of the box. Community plugins that target other backends should follow the same pattern, so the rest of this guide works the same way regardless of where transactions are actually sent. The signer plugin must be installed before the bundle, because the bundle's transaction planner needs a `payer` on the client to plan transactions. See [Setting up signers](/docs/guides/setting-up-signers) for the full set of signer options. ## Send instructions Once your client is ready, `client.sendTransaction([...])` accepts an array of instructions and turns them into a single transaction. The client takes care of fetching a recent blockhash, estimating compute units when applicable, setting the fee payer, signing with all attached signers, sending the transaction, and waiting for confirmation. ```ts twoslash import { address, lamports } from '@solana/kit'; import { getTransferSolInstruction } from '@solana-program/system'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))); // ---cut-end--- const recipient = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const result = await client.sendTransaction([ getTransferSolInstruction({ source: client.payer, destination: recipient, amount: lamports(500_000n), }), getTransferSolInstruction({ source: client.payer, destination: recipient, amount: lamports(500_000n), }), ]); ``` A single `client.sendTransaction([...])` call always produces exactly one transaction onchain, which means every instruction succeeds together or fails together. If you have so many instructions that they cannot fit in one transaction, use [`client.sendTransactions(...)`](/docs/guides/sending-multiple-transactions) instead. ## Plan before sending Sometimes you do not want to send the transaction immediately. You may want to inspect the planned message before signing, log it for debugging, or take over the rest of the lifecycle yourself. The `client.planTransaction([...])` method returns the planned transaction message and stops there, leaving signing and sending to you. ```ts twoslash import { address, lamports } from '@solana/kit'; import { getTransferSolInstruction } from '@solana-program/system'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))); // ---cut-end--- const recipient = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const transactionMessage = await client.planTransaction([ getTransferSolInstruction({ source: client.payer, destination: recipient, amount: lamports(500_000n), }), ]); ``` This gives you full control over what happens next: you can sign the message with [`signTransactionMessageWithSigners`](/docs/advanced-guides/signers), encode it for transmission to another service, or pass it to a custom executor. Note that the executor used by `client.sendTransaction([...])` may further mutate the planned message before sending β€” for example by attaching a fresh blockhash or refreshing the compute unit limit β€” so the message you inspect here is not guaranteed to be byte-identical to what would land onchain. The [Kit without a client](/docs/advanced-guides/kit-without-a-client) guide goes deeper into building and sending transactions step by step. ## Handle transaction errors When a transaction fails, `client.sendTransaction(...)` throws a [`SolanaError`](/docs/advanced-guides/errors) with the `SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION` code. The error message identifies whether the failure happened in preflight or onchain, and the `cause` carries the underlying error you can branch on. ```ts twoslash import { address, isSolanaError, lamports, SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION, } from '@solana/kit'; import { getTransferSolInstruction } from '@solana-program/system'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))); const recipient = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); // ---cut-end--- try { await client.sendTransaction([ getTransferSolInstruction({ source: client.payer, destination: recipient, amount: lamports(500_000n), }), ]); } catch (error) { if (isSolanaError(error, SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION)) { console.error(error.message); console.error('Logs:', error.context.logs); } else { throw error; } } ``` The same `error.context` object also exposes the underlying `transactionPlanResult`, which is particularly useful when you want to inspect the failed transaction message or its signature. Program-specific errors (such as System program or SPL Token program errors) live deeper inside `error.cause`. The [Errors](/docs/advanced-guides/errors) guide covers how to identify and handle them. ## Inspect transaction signatures A successful `client.sendTransaction(...)` resolves with a result object whose `context` carries the transaction `signature` and the original transaction message. You can use the signature to log a link to a block explorer or store it for later reference. ```ts twoslash import { address, lamports } from '@solana/kit'; import { getTransferSolInstruction } from '@solana-program/system'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))); const recipient = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); // ---cut-end--- const result = await client.sendTransaction([ getTransferSolInstruction({ source: client.payer, destination: recipient, amount: lamports(500_000n), }), ]); console.log(`βœ… ${result.context.signature}`); ``` Transaction signatures are deterministic, so the signature is known as soon as the fee payer signs the transaction β€” you do not need to wait for confirmation to learn what it will be. If you build and sign your own transactions, the [`getSignatureFromTransaction`](/docs/advanced-guides/transactions) helper exposes the same value. ## Next steps * [Sending multiple transactions](/docs/guides/sending-multiple-transactions) β€” plan and execute work that does not fit in a single transaction. * [Using program plugins](/docs/guides/using-program-plugins) β€” discover the `.sendTransaction()` shortcut on typed program helpers. * [Advanced guides β€” Transactions](/docs/advanced-guides/transactions) β€” learn the full transaction lifecycle. * [Advanced guides β€” Errors](/docs/advanced-guides/errors) β€” handle failures with `SolanaError`. # Setting up signers (/docs/guides/setting-up-signers) Most Kit applications need at least one signer. Signers represent the accounts that authorize transactions, pay fees, and own onchain assets such as tokens or program authorities. This guide covers the different ways you can attach signers to a Kit client and the situations each one is best suited for. ## Installation You will need Kit and the signer plugin package. ```bash npm install @solana/kit @solana/kit-plugin-signer ``` ```bash pnpm add @solana/kit @solana/kit-plugin-signer ``` ```bash yarn add @solana/kit @solana/kit-plugin-signer ``` ```bash bun add @solana/kit @solana/kit-plugin-signer ``` Some examples below also use `@solana/kit-plugin-rpc` or `@solana/kit-plugin-litesvm` to fund signers in local environments. ## What is a signer? A signer is an object that carries an `Address` and knows how to produce a signature for that address. Where the underlying private key actually lives β€” in memory, in a keypair file, in a browser wallet, on a hardware device, or behind a remote signing service β€” is an implementation detail. As long as the signer implements one of Kit's signer interfaces, it can be plugged into the same APIs. This means you can swap a generated keypair for a wallet-backed signer without changing the rest of your code. The [Advanced guides β€” Signers](/docs/advanced-guides/signers) page goes into the different signer interfaces and when each one applies. ## Payer and identity Kit clients hold two distinct signer roles: * **`payer`** β€” the signer that pays transaction fees and storage costs (the rent reserved when creating new accounts). * **`identity`** β€” the signer that represents the wallet your application acts on behalf of, typically the authority over accounts, tokens, or other onchain assets. In most apps these roles are filled by the same signer, but they can be separated when you want a sponsored fee payer, a custodial backend, or any setup where authority and fee payment do not belong to the same key. ## Install signers on your client The most common way to install a signer is to use the `signer(...)` plugin, which sets the same signer as both the `payer` and the `identity` of the client. ```ts twoslash import { createClient, generateKeyPairSigner } from '@solana/kit'; import { signer } from '@solana/kit-plugin-signer'; const mySigner = await generateKeyPairSigner(); const client = createClient().use(signer(mySigner)); ``` The `signer(...)` plugin accepts any object that implements the `TransactionSigner` interface, so a signer obtained from somewhere else in your code β€” a library, a hook, a custom factory β€” can be passed in directly without any wrapping. If your application needs a sponsored fee payer or otherwise wants to set the two roles independently, you may use the `payer(...)` and `identity(...)` plugins instead. They have the exact same shape as `signer(...)` but install only one role each. ```ts twoslash import { createClient, generateKeyPairSigner } from '@solana/kit'; import { identity, payer } from '@solana/kit-plugin-signer'; const feePayer = await generateKeyPairSigner(); const owner = await generateKeyPairSigner(); const client = createClient().use(payer(feePayer)).use(identity(owner)); ``` ## Load a signer from a file Most Solana CLI keypairs are stored as a JSON byte array on disk. The `signerFromFile(...)` plugin reads such a file and installs the resulting signer on both the `payer` and `identity` roles. ```ts twoslash import { createClient } from '@solana/kit'; import { signerFromFile } from '@solana/kit-plugin-signer'; const client = await createClient().use(signerFromFile('~/.config/solana/id.json')); ``` This is convenient for command-line tools, scripts, and backend services that already use a Solana CLI keypair. As with the in-memory plugins above, `payerFromFile(path)` and `identityFromFile(path)` are available if you only want to install a single role. The file-based signer plugins read from the local filesystem and therefore only work in Node.js environments. They throw an error in browsers and React Native. Make sure your keypair files are excluded from version control and from any production build artifact. ## Use a browser wallet signer A dedicated wallet signer plugin is on its way and will be documented here once it lands. It will use the [Wallet Standard](https://github.com/wallet-standard/wallet-standard) under the hood and expose a framework-agnostic reactive layer, so it can be used from any UI framework β€” not just React. Until then, the [`@solana/react`](/api) hooks can produce a `TransactionSigner` from a connected wallet account, and you can install that signer on a Kit client with the `signer(...)`, `payer(...)`, or `identity(...)` plugins shown above. ## Generate signers for tests When writing tests, generating a fresh signer per run keeps each scenario isolated and avoids leaking state between tests. The `generatedSigner()` plugin creates a brand new keypair signer and installs it on both roles. ```ts twoslash import { createClient } from '@solana/kit'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()); ``` `generatedPayer()` and `generatedIdentity()` follow the same pattern when you only want to generate one of the two roles. Generated signers are great for tests but should not be used as long-lived production identities, since the keypair only exists for the lifetime of the client. ## Fund signers in local environments Generated signers start with no SOL, so they can not pay fees or rent until they have been funded. The typical local pattern is to install a generated signer first, then install a local environment that ships an `airdrop` capability β€” either `solanaLocalRpc()` or `litesvm()` β€” and finally airdrop SOL to the signer with the `airdropSigner(...)` plugin. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))); ``` The order matters: the signer must exist before the RPC bundle is added (so the bundle can wire the signer into transaction planning), and the airdrop function must be available before `airdropSigner(...)` runs (which `solanaLocalRpc()` and `litesvm()` both provide). `airdropPayer(...)` and `airdropIdentity(...)` are available if you split roles between two different signers. Airdrops only work on test clusters such as devnet, testnet, and local validators. Mainnet does not have a faucet, and `solanaMainnetRpc(...)` will refuse to type-check an `airdrop` call. ## Next steps * [Sending transactions](/docs/guides/sending-transactions) β€” use your client to send and confirm transactions. * [Testing and local development](/docs/guides/testing-and-local-development) β€” set up local validators or LiteSVM for testing. * [Advanced guides β€” Signers](/docs/advanced-guides/signers) β€” learn the signer interfaces in depth. # Testing & local development (/docs/guides/testing-and-local-development) Local development and testing benefit hugely from Kit's plugin system: the same application code can run against devnet, a local validator, or an in-process [LiteSVM](https://github.com/litesvm/litesvm) instance, depending on which bundle plugin you install. This guide walks through the three options and the small patterns that make tests easy to write and maintain. ## Choose a local environment Each environment shines in a different situation. The table below summarizes when to reach for each. | Environment | Best for | Tradeoffs | | --------------- | ---------------------------------------------------- | --------------------------------------------------------- | | Devnet | shared/manual testing | faucet limits, network latency, shared state across tests | | Local validator | integration testing, full RPC API | requires a separate process, shared state across tests | | LiteSVM | fast unit tests, manipulating account state per test | Node.js only, RPC subset, in-memory only state | You do not have to commit to one environment for the whole project. It is common to use LiteSVM for fast unit tests, a local validator for integration tests, and devnet for manual exploration. ## Use devnet for shared testing Devnet is the easiest way to share a Solana environment with your team. The `solanaDevnetRpc()` plugin defaults to the public devnet endpoint and bundles an `airdrop` capability for funding accounts. ```ts twoslash import { address, createClient, lamports } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { signerFromFile } from '@solana/kit-plugin-signer'; const client = await createClient() .use(signerFromFile('~/.config/solana/id.json')) .use(solanaDevnetRpc()); await client.airdrop(client.payer.address, lamports(1_000_000_000n)); ``` Devnet is great for one-off scripts and manual exploration, but the public faucet has tight rate limits. For automated tests, prefer one of the local options. ## Use a local validator A local validator runs the same software as mainnet but on your own machine. You can install the `solana-test-validator` binary by following the [Anza installation guide](https://docs.anza.xyz/cli/install) and start it with a single command. ```shell solana-test-validator ``` Once the validator is running, the `solanaLocalRpc()` plugin connects to its default endpoints (`http://127.0.0.1:8899` and `ws://127.0.0.1:8900`) and ships the same `airdrop` capability as devnet β€” without any rate limits. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))); ``` Use this setup for integration tests that need the full Solana RPC API or to load deployed programs the way a real validator would. Make sure the validator is running before your tests start; otherwise, the first RPC call will fail with a connection error. ## Use LiteSVM for fast tests LiteSVM runs the Solana virtual machine in-process, with no validator and no network. It is significantly faster than a local validator and is ideal for unit tests. The `litesvm()` plugin from `@solana/kit-plugin-litesvm` installs a LiteSVM-backed client that exposes the same `client.rpc`, `client.airdrop`, `client.sendTransaction`, and `client.sendTransactions` APIs as the RPC bundles. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { litesvm } from '@solana/kit-plugin-litesvm'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(litesvm()) .use(airdropSigner(lamports(1_000_000_000n))); ``` Each LiteSVM-backed client owns its own in-memory SVM instance, so every test can have a completely isolated state. This is particularly useful for unit tests where one test should never affect the state observed by another. LiteSVM runs natively in Node.js. It will throw if you try to use it in a browser or in React Native. The exposed RPC also covers a subset of the full API β€” enough for most tests, but worth double-checking against the [`@solana/kit-plugin-litesvm` README](https://github.com/anza-xyz/kit-plugins/tree/main/packages/kit-plugin-litesvm#readme) for the methods you rely on. ## Create a funded test client For most tests you want a fresh, funded signer for every run. The pattern is the same regardless of the chosen environment: install a generated signer, install the environment, and airdrop SOL. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { litesvm } from '@solana/kit-plugin-litesvm'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient() .use(generatedSigner()) .use(litesvm()) .use(airdropSigner(lamports(10_000_000_000n))); ``` Swapping `litesvm()` for `solanaLocalRpc()` is a one-line change and the rest of your test code stays the same. This is one of the main benefits of the plugin model: the surface your tests interact with is a `client`, not a particular environment. ## Reuse setup across tests Wrap the client creation in a small factory so every test starts from a clean state. Adding any program plugins or extra setup to the factory keeps tests focused on what they are actually testing. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { litesvm } from '@solana/kit-plugin-litesvm'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; import { tokenProgram } from '@solana-program/token'; async function createTestClient() { return await createClient() .use(generatedSigner()) .use(litesvm()) .use(airdropSigner(lamports(10_000_000_000n))) .use(systemProgram()) .use(tokenProgram()); } ``` Because Kit clients are immutable, you do not need to worry about leaking state between tests as long as you do not share a single client instance across them. ## Seed accounts and programs LiteSVM exposes the underlying SVM through `client.svm`, which lets you preload accounts and programs before your test code runs. This is the quickest way to set up a specific scenario without chaining a series of transactions. ```ts twoslash import { address, EncodedAccount, lamports } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { litesvm } from '@solana/kit-plugin-litesvm'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(litesvm()); // ---cut-end--- const myAccount: EncodedAccount = { address: address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'), data: new Uint8Array([1, 2, 3]), executable: false, lamports: lamports(1_000_000_000n), programAddress: address('11111111111111111111111111111111'), space: 3n, }; client.svm.setAccount(myAccount); client.svm.addProgramFromFile( address('MyProgram111111111111111111111111111111111'), './my_program.so', ); ``` A local validator supports similar workflows through its CLI flags (`--account`, `--bpf-program`, etc.), which you can pass when starting `solana-test-validator`. See [`@solana/kit-plugin-litesvm`](/docs/plugins/available-plugins) and the [Anza CLI documentation](https://docs.anza.xyz/cli/) for the exact APIs. ## Troubleshooting A few issues come up often when wiring up local environments: * **Faucet rate limits on devnet** β€” switch to `solanaLocalRpc()` or `litesvm()` for repeated runs, or top up your devnet signer manually from the [Solana Faucet](https://faucet.solana.com). * **Validator not running** β€” `solana-test-validator` must be running before tests start; check the process and the default port (`8899`). * **WebSocket endpoint mismatch** β€” when overriding `rpcUrl`, also set `rpcSubscriptionsUrl` if your provider uses a different URL for WebSocket traffic. * **`litesvm()` errors in browser tests** β€” LiteSVM is Node.js only; run those tests in a Node.js environment or pick a different bundle. ## Next steps * [Sending transactions](/docs/guides/sending-transactions) β€” exercise your client end-to-end. * [Using program plugins](/docs/guides/using-program-plugins) β€” add typed program access to your tests. * [Available plugins](/docs/plugins/available-plugins) β€” explore the LiteSVM and RPC plugin packages. # Using program plugins (/docs/guides/using-program-plugins) Program plugins are how Kit clients gain typed access to a specific Solana program. They install a typed namespace under the client β€” `client.system`, `client.token`, and so on β€” and expose the program's accounts and instructions through it. This guide walks through adding program plugins to a client and using them, alongside the standalone helpers that the same packages also expose. ## Installation Most popular Solana programs ship a Codama-generated package that doubles as a Kit program plugin. Install one for each program you want to interact with. ```bash npm install @solana-program/system @solana-program/token ``` ```bash pnpm add @solana-program/system @solana-program/token ``` ```bash yarn add @solana-program/system @solana-program/token ``` ```bash bun add @solana-program/system @solana-program/token ``` The [Available plugins](/docs/plugins/available-plugins) page lists the program plugins available today. Once installed, apply each plugin with `.use(...)` after your signer and bundle plugins, and the client gains a new typed namespace named after the program. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(10_000_000_000n))) .use(systemProgram()) .use(tokenProgram()); ``` `client.system` and `client.token` now expose `accounts` and `instructions` namespaces typed against the System and Token programs. Multiple program plugins compose freely β€” installing more of them simply adds more namespaces to the client. ## What is a program plugin? A program plugin is a function from a Codama-generated package that adds a typed namespace for one program's accounts and instructions to a Kit client. The same package also exports standalone helpers β€” `getXInstruction`, `fetchX`, `decodeX`, and so on, where `X` is the instruction or account name β€” for cases where you do not want a client. ```ts twoslash import { systemProgram } from '@solana-program/system'; import { tokenProgram } from '@solana-program/token'; ``` You can think of a program plugin as a typed adapter on top of these standalone helpers. The plugin handles the wiring β€” passing the client's RPC and payer where needed β€” so your code can focus on what the program does. This is great for developer experience and program discoverability, but the tradeoff is tree-shakability: pulling an entire program namespace into your client tends to produce a larger bundle than importing only the standalone helpers you actually use. ## Fetch typed accounts Each `accounts` namespace exposes one entry per account type defined by the program, with `fetch`, `fetchMaybe`, `fetchAll`, and `fetchAllMaybe` methods that already know the codec to use. ```ts twoslash import { address } from '@solana/kit'; // ---cut-start--- import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(10_000_000_000n))) .use(tokenProgram()); // ---cut-end--- const mint = await client.token.accounts.mint.fetch( address('So11111111111111111111111111111111111111112'), ); mint.data.decimals; // typed as `number` ``` Because the account namespace is generated from the program's IDL, every field on `mint.data` is fully typed β€” autocompletion and refactors flow through naturally. See [Fetching accounts](/docs/guides/fetching-accounts) for raw account fetching that doesn't depend on a program plugin. ## Create typed instructions The matching `instructions` namespace exposes one builder per instruction the program defines. The builders accept a typed input and return an instruction ready to be sent. ```ts twoslash import { address, lamports } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(10_000_000_000n))) .use(systemProgram()); const recipient = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); // ---cut-end--- const transferSol = client.system.instructions.transferSol({ source: client.payer, destination: recipient, amount: lamports(500_000n), }); ``` ## Use the `.sendTransaction()` shortcut Each typed instruction returned by a program plugin also exposes a `.sendTransaction()` method that wraps `client.sendTransaction([instruction])`. This is the most concise way to send a one-off transaction. ```ts twoslash import { address, lamports } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(10_000_000_000n))) .use(systemProgram()); const recipient = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); // ---cut-end--- const result = await client.system.instructions .transferSol({ source: client.payer, destination: recipient, amount: lamports(500_000n), }) .sendTransaction(); ``` The same returned object also exposes `.sendTransactions()`, `.planTransaction()`, and `.planTransactions()` shortcuts that wrap the matching client methods. The shortcut shines for single-instruction operations where the rest of the transaction would just be ceremony. When you want to combine several instructions into one transaction or compose larger operations, [`client.sendTransaction([...])`](/docs/guides/sending-transactions) is the more flexible primitive. ## Use instruction plans from program plugins Some operations naturally span more than one instruction β€” creating and initializing a token mint is a classic example. Program plugins expose these as instruction plans rather than raw instructions, which means they can also be combined into larger plans. ```ts twoslash import { generateKeyPairSigner } from '@solana/kit'; // ---cut-start--- import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(10_000_000_000n))) .use(tokenProgram()); // ---cut-end--- const newMint = await generateKeyPairSigner(); const createMintPlan = client.token.instructions.createMint({ newMint, decimals: 9, mintAuthority: client.identity.address, }); ``` The returned plan can be sent on its own with `.sendTransaction()` or `.sendTransactions()`, fed into [`client.sendTransaction([...])`](/docs/guides/sending-transactions) alongside other work, or combined with [`sequentialInstructionPlan(...)`](/docs/guides/sending-multiple-transactions) and [`parallelInstructionPlan(...)`](/docs/guides/sending-multiple-transactions) helpers when building larger operations. ## Use program libraries without a client Every program package also exports standalone helpers that work on a plain `Rpc` object or with raw `Instruction`s. This is useful for libraries that should not assume a Kit client, or when you want maximum tree-shaking. ```ts twoslash import { address, createSolanaRpc, generateKeyPairSigner, lamports } from '@solana/kit'; import { fetchMint } from '@solana-program/token'; import { getTransferSolInstruction } from '@solana-program/system'; const rpc = createSolanaRpc('https://api.devnet.solana.com'); const mint = await fetchMint(rpc, address('So11111111111111111111111111111111111111112')); const source = await generateKeyPairSigner(); const transferSol = getTransferSolInstruction({ source, destination: address('Ay1zdJ3VDbhrAtkRiqBUJgKLHYbgFZN5BXk7svtMowif'), amount: lamports(500_000n), }); ``` Because the standalone helpers and the plugin-based namespaces are generated from the same IDL, the input shapes match exactly. You can move from one style to the other without rewriting the data your application passes around. ## Generate plugins for your own programs Any program with a Codama IDL can be turned into a Kit-compatible package, with both standalone helpers and a program plugin, using the [Codama JS renderer](https://github.com/codama-idl/renderers-js). The renderer reads the IDL, emits TypeScript bindings, and wires them up through the same `@solana/program-client-core` primitives the `@solana-program/*` packages use. If your program is built with Anchor, you can convert its Anchor IDL to a Codama IDL first, which means program plugin generation works for Anchor programs as well. See [Generating program plugins](/docs/plugins/generating-program-plugins) for a step-by-step walkthrough. ## Next steps * [Available plugins](/docs/plugins/available-plugins) β€” browse the program plugins available today. * [Generating program plugins](/docs/plugins/generating-program-plugins) β€” generate a plugin for your own program. * [Fetching accounts](/docs/guides/fetching-accounts) β€” combine typed accounts with raw RPC reads. * [Sending transactions](/docs/guides/sending-transactions) β€” use typed instructions with `client.sendTransaction([...])`. # Available plugins (/docs/plugins/available-plugins) This page lists the Kit plugins published today. Anyone can author and publish a plugin; if you have one you'd like added here, open a PR against [`anza-xyz/kit`](https://github.com/anza-xyz/kit) to be listed alongside the others. The tables below group plugins by category. Within each category, generic plugins from Anza are listed first because they target the broadest range of use cases, followed by community plugins in alphabetical order. When a single package contains plugins with materially different purposes, those plugins are split across multiple rows so each description stays targeted. ## Signer plugins Signer plugins install a `TransactionSigner` on the client as the `payer`, the `identity`, or both. See [Setting up signers](/docs/guides/setting-up-signers) for an overview of when each variant fits. | Maintainer | Package | Plugins | Description | | ----------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------- | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-signer`](https://www.npmjs.com/package/@solana/kit-plugin-signer) | `signer`, `payer`, `identity` | Install an existing `TransactionSigner` on the client. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-signer`](https://www.npmjs.com/package/@solana/kit-plugin-signer) | `signerFromFile`, `payerFromFile`, `identityFromFile` | Load a Solana CLI keypair from a JSON file (Node.js only). | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-signer`](https://www.npmjs.com/package/@solana/kit-plugin-signer) | `generatedSigner`, `generatedPayer`, `generatedIdentity` | Generate a fresh in-memory keypair, useful for tests. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-signer`](https://www.npmjs.com/package/@solana/kit-plugin-signer) | `generatedSignerWithSol`, `generatedPayerWithSol`, `generatedIdentityWithSol` | Generate a signer and airdrop SOL to it in one step. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-signer`](https://www.npmjs.com/package/@solana/kit-plugin-signer) | `airdropSigner`, `airdropPayer`, `airdropIdentity` | Airdrop SOL to a signer that is already installed on the client. | ## RPC plugins RPC plugins install Solana RPC connectivity on the client. LiteSVM is included here because it implements a subset of the same RPC API in-process, with no network involved. | Maintainer | Package | Plugins | Description | | ---------------------------------- | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-rpc`](https://www.npmjs.com/package/@solana/kit-plugin-rpc) | `solanaRpc`, `solanaMainnetRpc`, `solanaDevnetRpc`, `solanaLocalRpc` | Bundle plugins that wire up RPC, subscriptions, planning, and sending in one step. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-rpc`](https://www.npmjs.com/package/@solana/kit-plugin-rpc) | `solanaRpcConnection` | Install `client.rpc` and `client.rpcSubscriptions` from a cluster URL. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-rpc`](https://www.npmjs.com/package/@solana/kit-plugin-rpc) | `rpcAirdrop` | Add `client.airdrop` for devnet, testnet, and local validators. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-rpc`](https://www.npmjs.com/package/@solana/kit-plugin-rpc) | `rpcGetMinimumBalance` | Add `client.getMinimumBalance` using the matching RPC method. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-litesvm`](https://www.npmjs.com/package/@solana/kit-plugin-litesvm) | `litesvm` | Bundle plugin that runs an in-process Solana VM with full transaction sending support. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-litesvm`](https://www.npmjs.com/package/@solana/kit-plugin-litesvm) | `litesvmConnection` | Install `client.svm` and a subset of `client.rpc` backed by an in-process VM. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-litesvm`](https://www.npmjs.com/package/@solana/kit-plugin-litesvm) | `litesvmAirdrop` | Add `client.airdrop` against the in-process VM. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-litesvm`](https://www.npmjs.com/package/@solana/kit-plugin-litesvm) | `litesvmGetMinimumBalance` | Add `client.getMinimumBalance` against the in-process VM. | | [@amilz](https://github.com/amilz) | [`local-validator`](https://github.com/amilz/kit-helpers/tree/main/plugins/local-validator) (unpublished) | `localValidatorPlugin` | Manage the lifecycle of a local `solana-test-validator` (start, stop, restart). | ## Instruction plan plugins Instruction plan plugins install transaction planning and sending capabilities on the client. The RPC and LiteSVM packages are listed here too because they ship default planner and executor implementations on top of their respective backends β€” including the bundle plugins, which install everything needed to call `client.planTransaction(s)` and `client.sendTransaction(s)` in one step. | Maintainer | Package | Plugins | Description | | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-instruction-plan`](https://www.npmjs.com/package/@solana/kit-plugin-instruction-plan) | `transactionPlanner` | Install a custom transaction planner on the client. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-instruction-plan`](https://www.npmjs.com/package/@solana/kit-plugin-instruction-plan) | `transactionPlanExecutor` | Install a custom transaction plan executor on the client. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-instruction-plan`](https://www.npmjs.com/package/@solana/kit-plugin-instruction-plan) | `planAndSendTransactions` | Add `client.planTransaction(s)` and `client.sendTransaction(s)` on top of an existing planner and executor. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-rpc`](https://www.npmjs.com/package/@solana/kit-plugin-rpc) | `solanaRpc`, `solanaMainnetRpc`, `solanaDevnetRpc`, `solanaLocalRpc` | Bundle plugins that wire up RPC, subscriptions, planning, and sending in one step. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-rpc`](https://www.npmjs.com/package/@solana/kit-plugin-rpc) | `rpcTransactionPlanner`, `rpcTransactionPlanExecutor` | Default transaction planner and executor backed by RPC. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-litesvm`](https://www.npmjs.com/package/@solana/kit-plugin-litesvm) | `litesvm` | Bundle plugin that runs an in-process Solana VM with full transaction sending support. | | [Anza](https://www.anza.xyz/) | [`@solana/kit-plugin-litesvm`](https://www.npmjs.com/package/@solana/kit-plugin-litesvm) | `litesvmTransactionPlanner`, `litesvmTransactionPlanExecutor` | Default transaction planner and executor backed by LiteSVM. | | [@amilz](https://github.com/amilz) | [`transaction-builder`](https://github.com/amilz/kit-helpers/tree/main/plugins/transaction-builder) (unpublished) | `transactionBuilderPlugin` | Helpers for constructing, signing, and sending transactions. | ## Program plugins Program plugins are generated from program IDLs and install a typed `client.` namespace with `accounts` and `instructions` helpers. See [Using program plugins](/docs/guides/using-program-plugins) for usage and [Generating program plugins](/docs/plugins/generating-program-plugins) for authoring new ones. | Maintainer | Package | Plugins | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------ | --------------------------------- | ----------------------------------------------------------------------------- | | [Anza](https://www.anza.xyz/) | [`@solana-program/address-lookup-table`](https://www.npmjs.com/package/@solana-program/address-lookup-table) | *Plugin coming soon* | Address Lookup Table program. | | [Anza](https://www.anza.xyz/) | [`@solana-program/compute-budget`](https://www.npmjs.com/package/@solana-program/compute-budget) | *Plugin coming soon* | Compute Budget program: priority fees and compute unit limits. | | [Anza](https://www.anza.xyz/) | [`@solana-program/memo`](https://www.npmjs.com/package/@solana-program/memo) | *Plugin coming soon* | Memo program. | | [Anza](https://www.anza.xyz/) | [`@solana-program/stake`](https://www.npmjs.com/package/@solana-program/stake) | *Plugin coming soon* | Stake program. | | [Anza](https://www.anza.xyz/) | [`@solana-program/system`](https://www.npmjs.com/package/@solana-program/system) | `systemProgram` | Native System program: account creation, transfers, nonce accounts, and more. | | [Anza](https://www.anza.xyz/) | [`@solana-program/token`](https://www.npmjs.com/package/@solana-program/token) | `tokenProgram` | SPL Token program: mints, token accounts, and ATAs. | | [Anza](https://www.anza.xyz/) | [`@solana-program/token-2022`](https://www.npmjs.com/package/@solana-program/token-2022) | *Plugin coming soon* | SPL Token Extension program (Token-2022). | | [@amilz](https://github.com/amilz) | [`airdrop-token`](https://github.com/amilz/kit-helpers/tree/main/plugins/airdrop-token) (unpublished) | `airdropToken`, `testTokenPlugin` | Helpers for creating mints, ATAs, and minting tokens for tests. | ## Other plugins Plugins that don't fit into the categories above land here. Nothing has been listed yet β€” open a PR against [`anza-xyz/kit`](https://github.com/anza-xyz/kit) to add yours. ## Next steps * [Creating custom plugins](/docs/plugins/creating-custom-plugins) β€” write your own plugin and publish it. * [Generating program plugins](/docs/plugins/generating-program-plugins) β€” generate a typed plugin for a Solana program. * [Using program plugins](/docs/guides/using-program-plugins) β€” consume program plugins from a Kit client. # Creating custom plugins (/docs/plugins/creating-custom-plugins) Plugins are small, focused functions that extend a Kit client with new capabilities. This page walks through writing a plugin from scratch, declaring its prerequisites, handling asynchronous setup, registering cleanup logic, and composing several plugins into a higher-level bundle. ## The `ClientPlugin` shape A plugin is a function that takes a client and returns a new client object. The recommended way to add properties is the `extendClient(client, additions)` helper from `@solana/kit`, which preserves property descriptors (getters, symbol-keyed properties) that a plain object spread would flatten. ```ts twoslash import { createClient, extendClient } from '@solana/kit'; function apple() { return (client: T) => extendClient(client, { fruit: 'apple' as const }); } const client = createClient().use(apple()); client.fruit; // 'apple' ``` Wrapping the plugin in a small factory function (`apple()` rather than `apple`) is the convention across Kit plugins. It gives you somewhere to accept configuration without changing the shape of the function returned to `.use(...)`. ## Add prerequisites with TypeScript generics Plugins can require capabilities from the input client by constraining the input type. If a consumer applies your plugin in the wrong order, TypeScript reports a compile-time error rather than letting it fail at runtime. ```ts twoslash // @errors: 2345 import { createClient, extendClient } from '@solana/kit'; function appleTart() { return (client: T) => extendClient(client, { dessert: 'appleTart' as const }); } createClient().use(appleTart()); // ❌ Missing `fruit: 'apple'`. ``` The same mechanism is what makes the official plugins compose so cleanly: `airdropPayer()` requires `ClientWithPayer & ClientWithAirdrop`, `solanaRpc(...)` requires `ClientWithPayer`, and so on. Adopting the same pattern in your own plugins keeps users honest about the order of operations. ## Use the standard interfaces Whenever possible, declare your prerequisites and additions using the standard interfaces from `@solana/plugin-interfaces` (re-exported from `@solana/kit`). This lets your plugin compose with any other plugin that targets the same shape, regardless of its package. The most common interfaces are: * `ClientWithPayer` and `ClientWithIdentity` for signer roles. * `ClientWithRpc` and `ClientWithRpcSubscriptions` for transports. * `ClientWithAirdrop` and `ClientWithGetMinimumBalance` for funding helpers. * `ClientWithTransactionPlanning`, `ClientWithTransactionSending` and `ClientWithTransactionSigning` for the transaction lifecycle. If your plugin's capability does not match any existing interface, define your own type and export it. If you think the capability is generally useful and there is a gap in the standard interfaces, consider opening a PR against [`anza-xyz/kit`](https://github.com/anza-xyz/kit) so other plugins can adopt it too. Treating capabilities as named interfaces makes them addressable from other code without naming the specific plugin that installed them. ## Asynchronous plugins Plugins can return a `Promise` instead of a `Client`. The `.use(...)` chain awaits async plugins automatically, so you only need a single `await` at the end of the chain. ```ts twoslash import { createClient, createKeyPairSignerFromBytes, extendClient, KeyPairSigner, } from '@solana/kit'; import { readFile } from 'node:fs/promises'; function signerFromBytesFile(path: string) { return async (client: T) => { const bytes = JSON.parse(await readFile(path, 'utf-8')) as number[]; const signer: KeyPairSigner = await createKeyPairSignerFromBytes(new Uint8Array(bytes)); return extendClient(client, { payer: signer, identity: signer }); }; } const client = await createClient().use(signerFromBytesFile('./keypair.json')); ``` Async and sync plugins can be mixed freely in the same chain. Once any async plugin is involved, the `.use(...)` chain returns an `AsyncClient` that you await once at the end. ## Release resources on disposal Plugins that hold disposable resources β€” WebSocket connections, intervals, file handles β€” can register a cleanup function with `withCleanup(...)`. The returned client implements `Disposable`, so a `using` declaration runs the cleanup when the client goes out of scope. ```ts twoslash import { extendClient, withCleanup } from '@solana/kit'; function liveFeed(url: string) { return (client: T) => { const socket = new WebSocket(url); return withCleanup(extendClient(client, { socket }), () => socket.close()); }; } ``` `withCleanup` chains existing dispose logic, so you can call it more than once across plugins without overriding earlier cleanup. Reach for it whenever your plugin owns a resource the user would otherwise have to remember to release manually. ## Compose smaller plugins into a bundle A bundle plugin is just a regular plugin that applies several smaller plugins one after another. The `pipe(...)` helper from `@solana/kit` makes the composition concise and the resulting type predictable. ```ts twoslash // @noErrors import { ClientWithPayer, pipe } from '@solana/kit'; import { rpcAirdrop, rpcGetMinimumBalance, solanaRpcConnection, SolanaRpcConnectionConfig, } from '@solana/kit-plugin-rpc'; function myDevnetBundle(config: SolanaRpcConnectionConfig) { return (client: T) => pipe(client, solanaRpcConnection(config), rpcGetMinimumBalance(), rpcAirdrop()); } ``` The bundle accepts an existing client rather than calling `createClient()` itself. That keeps your bundle composable: callers stay in control of their own client and can apply additional plugins before or after yours. It is also what lets the official `solanaRpc`, `solanaDevnetRpc`, `solanaLocalRpc`, and `litesvm` bundles drop into any client the same way a single plugin would. ## Publish your plugin A few small conventions go a long way once a plugin lands on npm: * Name the factory function after the capability it installs (e.g. `signer`, `rpcAirdrop`, `tokenProgram`) rather than the package, and make sure it reads well at the call site β€” `use(tokenProgram())` should sound like the sentence you would write to describe what it does. * Document the standard interfaces your plugin requires and provides; this is what other plugin authors will read first. * Keep the public surface minimal β€” one factory function per concept β€” and prefer composition over bigger plugins that try to do everything. Once your plugin is published, open a PR against [`anza-xyz/kit`](https://github.com/anza-xyz/kit) to be listed on the [Available plugins](/docs/plugins/available-plugins) page so other developers can find it. ## Next steps * [Plugins](/docs/plugins) β€” revisit the client model and standard interfaces. * [Available plugins](/docs/plugins/available-plugins) β€” see how published plugins describe themselves. * [Generating program plugins](/docs/plugins/generating-program-plugins) β€” let Codama write a program plugin for you. # Generating program plugins (/docs/plugins/generating-program-plugins) Program plugins are generated from program IDLs by [Codama](https://github.com/codama-idl/codama). Codama's CLI is the quickest path to a working plugin: two commands set up a configuration file in your repo and emit a Kit-compatible package containing both standalone helpers and a typed program plugin. This page focuses on how the generated output fits into the Kit ecosystem. Codama itself has comprehensive docs that go much deeper into IDLs, visitors, and renderer configuration. ## What Codama generates For every program, the JavaScript renderer emits two things side by side: standalone helpers for use without a client, and a program plugin that installs a typed namespace on a Kit client. ```ts // Standalone helpers, one per instruction and account defined in the IDL. import { decodeMyAccount, fetchMyAccount, getMyInstruction } from '@your-scope/your-program'; // Program plugin β€” installs `client.yourProgram.accounts` and `client.yourProgram.instructions`. import { yourProgram } from '@your-scope/your-program'; ``` Both forms are generated automatically from your IDL. The standalone helpers tree-shake well and keeps JS bundles small, while the program plugin is the most ergonomic way to use the program from a Kit client. ## Set up Codama with `codama init` Install Codama as a dev dependency and run `codama init`. The CLI prompts you for the path to your IDL and writes a `codama.json` configuration file at the root of your project. Make sure to select the JS client option to generate a Kit-compatible program library. ```sh pnpm install codama codama init ``` The CLI auto-detects Anchor IDLs and configures the conversion step for you, so this same flow works for both native programs (with a Codama IDL) and Anchor programs (with an Anchor IDL). ## Generate the plugin with `codama run js` Once the configuration file exists, generating the JavaScript client is a single command. Codama installs the renderer the first time it runs and writes the generated files to the path declared in the configuration. ```sh codama run js ``` The output includes the standalone helpers, the program plugin, and the supporting types. Importing it from a Kit client looks the same as any other program plugin: ```ts twoslash // @noErrors import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; import { yourProgram } from '@your-scope/your-program'; const client = await createClient() .use(generatedSigner()) .use(solanaDevnetRpc()) .use(yourProgram()); ``` ## Configure the renderer The `codama.json` file generated by `codama init` controls where the output lands and which visitors run before the renderer. You can edit it to rename accounts, add custom transformations, or change the output directory. See the [Codama JS renderer docs](https://github.com/codama-idl/renderers-js) for the full list of configuration options. If you need more than one client (for example, both JavaScript and Rust), additional renderers can be added to the same configuration file and run with `codama run --all`. ## Publish your generated plugin Once your plugin is generating cleanly, publishing it follows the same pattern as the official `@solana-program/*` packages. A few conventions worth keeping in mind: * Use a `@/` package layout, with a single entry point that re-exports both the standalone helpers and the `programName()` plugin. * Once published, open a PR against [`anza-xyz/kit`](https://github.com/anza-xyz/kit) to list your plugin on the [Available plugins](/docs/plugins/available-plugins) page so other developers can find it. ## Next steps * [Using program plugins](/docs/guides/using-program-plugins) β€” consume program plugins from a Kit client. * [Available plugins](/docs/plugins/available-plugins) β€” browse program plugins published today. * [Creating custom plugins](/docs/plugins/creating-custom-plugins) β€” write a plugin that is not generated from an IDL. # Plugins (/docs/plugins) Plugins are how Kit clients gain capabilities. Everything from RPC connectivity, wallet signers, transaction sending, and even typed access to Solana programs is delivered as a plugin you opt into. This page explains the underlying client model and the conventions plugins follow. ## What is a Kit client? A Kit client is a frozen, typed JavaScript object created with `createClient()` from `@solana/kit` and extended by chaining `.use(plugin())` calls. Each call applies a plugin, and the returned client is a brand new immutable object β€” the previous one is left untouched. ```ts twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = await createClient().use(generatedSigner()).use(solanaDevnetRpc()); ``` Because the client is immutable, you cannot accidentally mutate it from somewhere else in your application: `client` always reflects the exact set of plugins you applied at creation time. ## What is a plugin? A plugin is a function that takes a client object and returns either a new client object or a promise resolving to one. The shape is captured by the `ClientPlugin` type. ```ts twoslash import { ClientPlugin, extendClient } from '@solana/kit'; const apple = (): ClientPlugin => (client) => extendClient(client, { fruit: 'apple' as const }); ``` Most plugins follow the same convention: they are exported as small factory functions (so you can pass configuration to them) that return the actual `ClientPlugin` function. Asynchronous plugins are supported too; the `.use(...)` chain awaits them automatically, so you only need a single `await` at the end. ## Plugin requirements and ordering Plugins can require capabilities from the input client by constraining the input type. This means installing them in the wrong order produces a TypeScript error rather than a runtime surprise. ```ts twoslash // @errors: 2345 import { ClientWithPayer, createClient, extendClient } from '@solana/kit'; function airdropPayer() { return (client: T) => extendClient(client, { airdropped: true }); } // Requires a `payer` to be installed first; this fails at compile time. const client = createClient().use(airdropPayer()); ``` Adding `payer(...)` (or any other plugin that satisfies `ClientWithPayer`) before `airdropPayer()` makes the chain type-check. The TypeScript compiler walks the whole chain and verifies that each plugin's input requirements are met by the time it is applied. ## Standard plugin interfaces Kit ships a small set of standard interfaces in `@solana/plugin-interfaces` (re-exported from `@solana/kit`) so plugins from different packages can interoperate. A plugin that installs `client.rpc` declares it provides `ClientWithRpc<...>`; a plugin that needs a payer constrains its input with `ClientWithPayer`. The most common interfaces are: * `ClientWithPayer` β€” installs `client.payer`. * `ClientWithIdentity` β€” installs `client.identity`. * `ClientWithRpc` β€” installs `client.rpc`. * `ClientWithRpcSubscriptions` β€” installs `client.rpcSubscriptions`. * `ClientWithAirdrop` β€” installs `client.airdrop`. * `ClientWithGetMinimumBalance` β€” installs `client.getMinimumBalance`. * `ClientWithTransactionPlanning` β€” installs `client.planTransaction(s)`. * `ClientWithTransactionSending` β€” installs `client.sendTransaction(s)`. * `ClientWithTransactionSigning` β€” installs `client.signTransaction(s)`. Sticking to these interfaces lets plugins from any source compose freely with each other β€” and lets your application code take a `ClientWithRpc` rather than caring which specific plugin produced the RPC capability. ## Next steps * [Available plugins](/docs/plugins/available-plugins) β€” browse the plugins published today. * [Creating custom plugins](/docs/plugins/creating-custom-plugins) β€” write your own plugin. * [Generating program plugins](/docs/plugins/generating-program-plugins) β€” generate a typed plugin for a Solana program. # Core hooks (/docs/guides/react/core-hooks) Every hook on this page must be rendered under a [`ClientProvider`](/docs/guides/react). They fall into four groups: accessing the client, reading once, reading live data, and triggering actions. ## Accessing the client ### `useClient` Reads the Kit client published by the nearest `ClientProvider`. Throws `SOLANA_ERROR__REACT__MISSING_PROVIDER` if no provider is mounted above it. Pass your client's type through the generic so every capability you installed is typed at the call site. The simplest way is to reuse the type of the [client you already built](/docs/guides/react) - export it once alongside the client - so the hook's type always matches your real plugin composition: ```tsx twoslash // client.ts β€” where you build the client import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; export const client = createClient().use(generatedSigner()).use(solanaDevnetRpc()); export type AppClient = Awaited; // any component import { useClient } from '@solana/react'; function FetchEpochButton() { const client = useClient(); // rpc, signers, … all typed return ; } ``` `AppClient` uses `Awaited` so it resolves the promise when a plugin is async, for a fully-synchronous client `Awaited<…>` is a no-op and `typeof client` alone would do. `useClient` is a pure type-cast with no runtime check. ### `useClientCapability` A runtime escape hatch for the uncommon case where the client isn't precisely typed β€” a loosely-typed `Client` read from context, say β€” and you want a clear failure at mount instead of a downstream `undefined`. It reads the client, asserts a capability is installed, and narrows the return type via the generic; if the capability is absent it throws `SOLANA_ERROR__REACT__MISSING_CAPABILITY` with the `hookName` and `providerHint` you supply. When you type your client with `useClient()` the compiler already guarantees the capability is present, so you rarely need this. ```tsx twoslash import { ClientWithRpc, GetEpochInfoApi } from '@solana/kit'; import { useClientCapability } from '@solana/react'; // The provider holds a loosely-typed `Client` (built elsewhere, or by a // third party), so `useClient` can't prove `rpc` is installed. Assert it here // and get a clear mount-time error β€” with your hint β€” if it isn't. function EpochBadge() { const client = useClientCapability>({ capability: 'rpc', hookName: 'EpochBadge', providerHint: 'Install a `solanaRpc()` plugin on the client.', }); return ; } ``` Pass an array for `capability` when you need more than one (e.g. `['rpc', 'rpcSubscriptions']`); the same `providerHint` is reported for whichever is missing. ## Reading once ### `useRequest` Fires a one-shot request on mount and re-fires whenever the source changes identity or you call `refresh()`. The result tracks the call's lifecycle and keeps stale `data`/`error` populated while a refresh is in flight (stale-while-revalidate). Status is `fetching`, `success`, `error`, or `disabled` (when the source is `null`). Pass either a Kit request source (most commonly a `PendingRpcRequest`) or an `async (signal) => Promise` function to wrap any one-shot async call. Memoize the source (`useMemo`) or function (`useCallback`) on its inputs. ```tsx twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = createClient().use(generatedSigner()).use(solanaDevnetRpc()); type AppClient = Awaited; // ---cut-before--- import { useMemo } from 'react'; import { useClient, useRequest } from '@solana/react'; function LatestBlockhash() { const client = useClient(); const source = useMemo(() => client.rpc.getLatestBlockhash(), [client]); const { data, error, status, refresh } = useRequest(source, { getAbortSignal: () => AbortSignal.timeout(5_000), }); if (error) return ; return

{data ? `Blockhash: ${data.value.blockhash}` : 'Loading…'}

; } ``` The `getAbortSignal` factory runs on every attempt (initial fire and every `refresh()`), so `() => AbortSignal.timeout(5_000)` gives each attempt its own five-second clock. ## Reading live data ### `useSubscription` Subscribes to a stream source and surfaces the latest notification - no initial fetch. The subscription opens on mount, re-opens when the source changes identity, and tears down on unmount. Use `reconnect()` to re-open manually. Status is `loading`, `loaded`, `error`, or `disabled`. ```tsx twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = createClient().use(generatedSigner()).use(solanaDevnetRpc()); type AppClient = Awaited; // ---cut-before--- import { useMemo } from 'react'; import { Address } from '@solana/kit'; import { useClient, useSubscription } from '@solana/react'; function LiveAccount({ address }: { address: Address }) { const client = useClient(); const source = useMemo( () => client.rpcSubscriptions.accountNotifications(address), [client, address], ); const { data, error, reconnect } = useSubscription(source); if (error) return ; return (

{data ? `${data.value.lamports} lamports at slot ${data.context.slot}` : 'Connecting…'}

); } ``` ### `useTrackedData` Renders a value that loads quickly and then stays live: a one-shot fetch seeds the value, and a subscription keeps it updated. The underlying store slot-dedupes between the two sources, so out-of-order arrivals never regress the surfaced value. `data` is a `SolanaRpcResponse` envelope (`{ context: { slot }, value }`), so you can read `data.value` and `data.context.slot` directly. Status is `loading`, `loaded`, `error`, or `disabled`. Pass a memoized spec with an `initialValueSource` + `initialValueMapper` (the initial fetch) and a `streamSource` + `streamValueMapper` (the subscription). ```tsx twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = createClient().use(generatedSigner()).use(solanaDevnetRpc()); type AppClient = Awaited; // ---cut-before--- import { useMemo } from 'react'; import { Address } from '@solana/kit'; import { useClient, useTrackedData } from '@solana/react'; function AccountBalance({ address }: { address: Address }) { const client = useClient(); const spec = useMemo( () => ({ initialValueSource: client.rpc.getBalance(address), initialValueMapper: (lamports: bigint) => lamports, streamSource: client.rpcSubscriptions.accountNotifications(address), streamValueMapper: ({ lamports }: { lamports: bigint }) => lamports, }), [client, address], ); const { data, error, refresh } = useTrackedData(spec); if (error) return ; return

{data ? `${data.value} lamports at slot ${data.context.slot}` : 'Loading…'}

; } ``` Reach for `useSubscription` when there is no meaningful "initial value" to fetch, reach for `useTrackedData` when you want a value before the first notification arrives. ## Triggering actions ### `useAction` Wraps an arbitrary async function and tracks each invocation through React state. Each `dispatch(...)` runs the function with a fresh `AbortSignal`, dispatching again while a call is in flight aborts the first. Status is `idle`, `running`, `success`, or `error`. Use `dispatch` from event handlers (fire-and-forget, never throws) and `dispatchAsync` when you need the resolved value or to propagate errors. ```tsx twoslash import { useAction } from '@solana/react'; function PostMessageButton({ url, body }: { url: string; body: string }) { const { dispatch, isRunning, error } = useAction(async (signal, content: string) => { const res = await fetch(url, { body: content, method: 'POST', signal }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return (await res.json()) as { id: string }; }); return ( ); } ``` `reset()` returns the action to `idle` and aborts any in-flight call. The `isIdle` / `isRunning` / `isSuccess` / `isError` booleans are derived from `status` - use whichever reads better at the call site. # Overview (/docs/guides/react) `@solana/react` is a set of React hooks built on top of Kit. ```bash npm install @solana/kit @solana/react ``` ```bash pnpm add @solana/kit @solana/react ``` ```bash yarn add @solana/kit @solana/react ``` ```bash bun add @solana/kit @solana/react ``` ## Set up the provider Every hook reads a Kit client from the nearest `ClientProvider`. You compose the client in plain Kit with `createClient().use(...)` and hand the finished client to the provider - the provider does no composition or lifecycle management, it just distributes the value you pass in. ```ts twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; // Build once, at module scope, so the reference is stable across renders. export const client = createClient().use(generatedSigner()).use(solanaDevnetRpc()); // Export the client's type too, so components can read a fully-typed client. // `Awaited<…>` resolves the promise when a plugin is async; it's a no-op otherwise. export type AppClient = Awaited; ``` Exporting `AppClient` lets any component ask for the fully-typed client with [`useClient()`](/docs/guides/react/core-hooks#useclient) - every capability you installed above is typed, with no per-call narrowing or casting. Wrap your app in the provider and pass the client in: ```tsx twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; const client = createClient().use(generatedSigner()).use(solanaDevnetRpc()); function Dashboard() { return null; } // ---cut-before--- import { ClientProvider } from '@solana/react'; export function App() { return ( ); } ``` The client reference must be **stable** across renders. Build it at module scope (as above), or memoize it with `useMemo` when its configuration is reactive. ### Rebuilding the client at runtime When a configuration value changes at runtime - a cluster toggle, an RPC URL switch - rebuild the client in `useMemo` keyed on that value and pass the new reference. The subtree re-subscribes against the new client identity. ```tsx twoslash function ClusterToggle(props: { value: 'devnet' | 'mainnet'; onChange: (value: 'devnet' | 'mainnet') => void; }) { return null; } function Dashboard() { return null; } // ---cut-before--- import { useMemo, useState } from 'react'; import { createClient } from '@solana/kit'; import { solanaDevnetRpc, solanaMainnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; import { ClientProvider } from '@solana/react'; export function App() { const [cluster, setCluster] = useState<'devnet' | 'mainnet'>('mainnet'); const client = useMemo( () => createClient() .use(generatedSigner()) .use( cluster === 'mainnet' ? solanaMainnetRpc({ rpcUrl: 'https://api.mainnet-beta.solana.com' }) : solanaDevnetRpc(), ), [cluster], ); return ( ); } ``` ### Async plugins (Suspense) If any plugin's `.use()` is async, `createClient().use(...)` returns a `Promise`. Pass the promise straight to `ClientProvider` and it suspends the subtree via the nearest `` boundary until the client resolves. The promise identity must be stable - pass a `useMemo`'d or module-scope value, never an inline `new Promise(...)`. ```tsx twoslash import { createClient } from '@solana/kit'; import { solanaDevnetRpc } from '@solana/kit-plugin-rpc'; import { generatedSigner } from '@solana/kit-plugin-signer'; async function createClientWithAsyncPlugins() { return createClient().use(generatedSigner()).use(solanaDevnetRpc()); } function Dashboard() { return null; } function Splash() { return null; } // ---cut-before--- import { Suspense, useMemo } from 'react'; import { ClientProvider } from '@solana/react'; function Root() { const clientPromise = useMemo(() => createClientWithAsyncPlugins(), []); return ( ); } export function App() { return ( }> ); } ``` ## Choosing a hook Once a provider is mounted, pick a hook by what you are trying to do: | You want to… | Hook | What you get back | | ----------------------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | Access your typed client imperatively | [`useClient`](/docs/guides/react/core-hooks#useclient) | Your `AppClient` from context (type-cast, no runtime check). | | Runtime-guard a capability on an untyped client | [`useClientCapability`](/docs/guides/react/core-hooks#useclientcapability) | The narrowed client; throws at mount if the capability is missing. | | Read a value once | [`useRequest`](/docs/guides/react/core-hooks#userequest) | `{ data, error, status, refresh }`. Request fires on mount, `refresh()` re-fires. | | Subscribe to a stream of notifications | [`useSubscription`](/docs/guides/react/core-hooks#usesubscription) | `{ data, error, status, reconnect }`. Latest notification, no initial fetch. | | Read a value that updates live | [`useTrackedData`](/docs/guides/react/core-hooks#usetrackeddata) | `{ data, error, status, refresh }`. Initial fetch seeds, subscription keeps it live. | | Trigger an async action on user input | [`useAction`](/docs/guides/react/core-hooks#useaction) | `{ dispatch, status, data, error, reset }`. Fires on demand. | The [SWR](/docs/guides/react/swr) and [TanStack Query](/docs/guides/react/query) adapters route the read hooks through those libraries' caches. These add features such as deduplication and devtools. ## Server rendering Every hook is safe to render on the server. The fetch or subscription is committed in an effect, which never runs during SSR, so no request opens and no socket connects until the component hydrates on the client. On the server - and on the first client render, before hydration - each hook reports its pre-fetch status: `fetching` for `useRequest`, `loading` for `useSubscription` and `useTrackedData`, and `idle` for `useAction` (which only ever fires on demand). Server and client markup therefore match, and the live work begins after hydration. # TanStack Query adapter (/docs/guides/react/query) The TanStack Query adapter routes the core read hooks through TanStack Query's cache: components reading the same key dedupe into one in-flight request, all TanStack Query features are available, and everything shows up in TanStack Query's devtools. Use it when your app already uses TanStack Query, or when you want its revalidation and cache-invalidation model. ```bash npm install @solana/react @tanstack/react-query ``` ```bash pnpm add @solana/react @tanstack/react-query ``` ```bash yarn add @solana/react @tanstack/react-query ``` ```bash bun add @solana/react @tanstack/react-query ``` Import from the `@solana/react/query` subpath. It declares `@tanstack/react-query` as a peer dependency, pulled in only when this subpath is imported. As with any TanStack Query usage, the tree must be wrapped in a `QueryClientProvider`. There's a Query variant for each core read hook. All three take a cache `key` up front and return TanStack's `UseQueryResult`: | Core hook | Query variant | | ------------------------------------------------------------------ | ---------------------- | | [`useRequest`](/docs/guides/react/core-hooks#userequest) | `useRequestQuery` | | [`useSubscription`](/docs/guides/react/core-hooks#usesubscription) | `useSubscriptionQuery` | | [`useTrackedData`](/docs/guides/react/core-hooks#usetrackeddata) | `useTrackedDataQuery` | ## `useRequestQuery` The TanStack Query-backed counterpart to `useRequest`. It takes a query `key`, the same source shape as `useRequest`, and any `useQuery` options. It returns TanStack's own `useQuery` result, so `data`, `error`, `isLoading`, and `refetch` behave as they do everywhere else. ```tsx twoslash import { ClientWithRpc, GetLatestBlockhashApi } from '@solana/kit'; import { useClient } from '@solana/react'; import { useRequestQuery } from '@solana/react/query'; function LatestBlockhash() { const client = useClient>(); const { data, error, isLoading, refetch } = useRequestQuery( ['latestBlockhash'], client.rpc.getLatestBlockhash(), { getAbortSignal: () => AbortSignal.timeout(5_000) }, ); if (error) return ; if (isLoading) return

Loading…

; return

Blockhash: {data!.value.blockhash}

; } ``` Unlike core `useRequest`, the source does **not** need to be memoized. The cache is keyed by `key`. TanStack Query hands the `queryFn` its own cancellation `AbortSignal`, and the hook threads that signal into the source. When you also pass a `getAbortSignal` factory, the two signals are combined with `AbortSignal.any`, so aborting either cancels the attempt. In addition to TanStack's `enabled: false`, you can pass `null` for `source` to disable the query. Call `refetch()` to refresh. ## `useSubscriptionQuery` The counterpart to `useSubscription`, for a long-lived stream with no one-shot fetch. It takes a `key` and the same source shape as `useSubscription`, routes the stream through TanStack Query's cache (via `experimental_streamedQuery`), and returns a `UseQueryResult`. `data` is the raw notification exactly as the source emits it. ```tsx twoslash import { ClientWithRpcSubscriptions, SlotNotificationsApi } from '@solana/kit'; import { useClient } from '@solana/react'; import { useSubscriptionQuery } from '@solana/react/query'; function SlotHeight() { const client = useClient>(); const { data, error } = useSubscriptionQuery( ['slot'], client.rpcSubscriptions.slotNotifications(), ); if (error) return

Disconnected.

; if (!data) return

Connecting…

; return

Slot {String(data.slot)}

; } ``` Because the stream never settles, the query stays in `fetchStatus: 'fetching'` for the subscription's whole life: `isFetching` is permanently `true`, while `isLoading` flips to `false` after the first notification. `refetch()` reconnects but the returned promise never resolves for a never-ending stream, so don't `await` it. The prior value stays visible across a reconnect. By default `retry`, `staleTime`, and `refetchOnWindowFocus` are tuned for a long-lived socket (`false`, `Infinity`, `false` respectively). All are overridable through the options. Again the source does not need to be memoized, and passing `null` disables the subscription. ## `useTrackedDataQuery` The counterpart to `useTrackedData`: a one-shot fetch seeds the value and a subscription keeps it live, with the unified stream routed through TanStack Query's cache. It takes a `key` and the same `TrackedDataSpec` as `useTrackedData`. `data` is the `SolanaRpcResponse` envelope, so read `data.value` and `data.context.slot` directly. ```tsx twoslash import { Address, ClientWithRpc, ClientWithRpcSubscriptions, GetBalanceApi, AccountNotificationsApi, } from '@solana/kit'; import { useClient } from '@solana/react'; import { useTrackedDataQuery } from '@solana/react/query'; function AccountBalance({ address }: { address: Address }) { const client = useClient< ClientWithRpc & ClientWithRpcSubscriptions >(); const { data, error } = useTrackedDataQuery(['balance', address], { initialValueSource: client.rpc.getBalance(address), initialValueMapper: (lamports: bigint) => lamports, streamSource: client.rpcSubscriptions.accountNotifications(address), streamValueMapper: ({ lamports }: { lamports: bigint }) => lamports, }); if (error) return

Failed to load.

; return

{data ? `${data.value} lamports at slot ${data.context.slot}` : 'Loading…'}

; } ``` Like `useSubscriptionQuery`, the query never settles (`isFetching` stays `true`, don't `await refetch()`), and the same long-lived-socket defaults apply. The spec does not need to be memoized. Slot dedupe applies across a reconnect. We do not have a `useAction` counterpart. Use `useAction` or TanStack Query's `useMutation` directly, and call `queryClient.invalidateQueries()` if you need to invalidate cached reads. # SWR adapter (/docs/guides/react/swr) The SWR adapter routes the core read hooks through SWR's cache: components reading the same key dedupe into one in-flight request, all SWR features are available, and everything shows up in SWR's devtools. Use it when your app already uses SWR, or when you want its revalidation and cache-invalidation model. ```bash npm install @solana/react swr ``` ```bash pnpm add @solana/react swr ``` ```bash yarn add @solana/react swr ``` ```bash bun add @solana/react swr ``` Import from the `@solana/react/swr` subpath. It declares `swr` as a peer dependency, pulled in only when this subpath is imported. There's an SWR variant for each core read hook, each taking a cache `key` up front. Their return shapes differ: `useRequestSWR` gives you SWR's full response object, while the two stream-backed variants are built on `useSWRSubscription` and return only `{ data, error }`. | Core hook | SWR variant | Returns | | ------------------------------------------------------------------ | -------------------- | ------------------------- | | [`useRequest`](/docs/guides/react/core-hooks#userequest) | `useRequestSWR` | `SWRResponse` | | [`useSubscription`](/docs/guides/react/core-hooks#usesubscription) | `useSubscriptionSWR` | `SWRSubscriptionResponse` | | [`useTrackedData`](/docs/guides/react/core-hooks#usetrackeddata) | `useTrackedDataSWR` | `SWRSubscriptionResponse` | ## `useRequestSWR` The SWR-backed counterpart to `useRequest`. It takes an SWR `key`, the same source shape as `useRequest`, and any SWR configuration. It returns SWR's `SWRResponse`, so `data`, `error`, `isLoading`, and `mutate` behave exactly as they do everywhere else. ```tsx twoslash import { ClientWithRpc, GetLatestBlockhashApi } from '@solana/kit'; import { useClient } from '@solana/react'; import { useRequestSWR } from '@solana/react/swr'; function LatestBlockhash() { const client = useClient>(); const { data, error, isLoading, mutate } = useRequestSWR( ['latestBlockhash'], client.rpc.getLatestBlockhash(), { getAbortSignal: () => AbortSignal.timeout(5_000) }, ); if (error) return ; if (isLoading) return

Loading…

; return

Blockhash: {data!.value.blockhash}

; } ``` Unlike core `useRequest`, the source does **not** need to be memoized. The cache is keyed by `key`. Pass `null` for the `key` or the `source` to disable the request. Call `mutate()` to refresh. ## `useSubscriptionSWR` The counterpart to `useSubscription`, for a long-lived stream with no one-shot fetch. It takes a `key` and the same source shape as `useSubscription`, and routes the stream through SWR's subscription cache (`useSWRSubscription`). It returns SWR's `SWRSubscriptionResponse`. `data` is the raw notification exactly as the source emits it. ```tsx twoslash import { ClientWithRpcSubscriptions, SlotNotificationsApi } from '@solana/kit'; import { useClient } from '@solana/react'; import { useSubscriptionSWR } from '@solana/react/swr'; function SlotHeight() { const client = useClient>(); const { data, error } = useSubscriptionSWR( ['slot'], client.rpcSubscriptions.slotNotifications(), ); if (error) return

Disconnected.

; if (!data) return

Connecting…

; return

Slot {String(data.slot)}

; } ``` There's no `reconnect` and no `getAbortSignal`: to stop or restart the subscription, toggle its `key` to or from `null`. The source does not need to be memoized. When `key` flips to `null` the `data` is cleared, unlike core `useSubscription` where `reconnect()` keeps the last `data` visible. Pass SWR's `keepPreviousData` if you want the last value to persist across the toggle. ## `useTrackedDataSWR` The counterpart to `useTrackedData`: a one-shot fetch seeds the value and a subscription keeps it live, with the unified stream routed through SWR's subscription cache. It takes a `key` and the same `TrackedDataSpec` as `useTrackedData`. Like `useSubscriptionSWR` it returns an `SWRSubscriptionResponse`, but `data` is the `SolanaRpcResponse` envelope, so read `data.value` and `data.context.slot` directly. ```tsx twoslash import { Address, ClientWithRpc, ClientWithRpcSubscriptions, GetBalanceApi, AccountNotificationsApi, } from '@solana/kit'; import { useClient } from '@solana/react'; import { useTrackedDataSWR } from '@solana/react/swr'; function AccountBalance({ address }: { address: Address }) { const client = useClient< ClientWithRpc & ClientWithRpcSubscriptions >(); const { data, error } = useTrackedDataSWR(['balance', address], { initialValueSource: client.rpc.getBalance(address), initialValueMapper: (lamports: bigint) => lamports, streamSource: client.rpcSubscriptions.accountNotifications(address), streamValueMapper: ({ lamports }: { lamports: bigint }) => lamports, }); if (error) return

Failed to load.

; return

{data ? `${data.value} lamports at slot ${data.context.slot}` : 'Loading…'}

; } ``` Like `useSubscriptionSWR`, it returns only `{ data, error }`, toggle the `key` to or from `null` to stop or restart. The spec does not need to be memoized. Slot dedupe spans the cache, not just one store, so a reconnect's fresh fetch can't regress the cached envelope to an older slot. Like `useSubscriptionSWR`, when `key` flips to `null` the `data` is cleared. Pass SWR's `keepPreviousData` if you want the last value to persist across the toggle. We do not have a `useAction` counterpart. Use `useAction` or SWR's `mutate` directly. # Airdropping tokens (/recipes/airdropping-tokens) This recipe airdrops a freshly minted SPL token to many recipient wallets at once. It demonstrates how to compose an [instruction plan](/docs/guides/sending-multiple-transactions) that creates the mint sequentially first and then mints to every recipient in parallel β€” letting Kit pack the work into as few transactions as possible and send the parallel batches concurrently. ## Set up a client Install Kit and the plugins you need. ```bash npm install @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/token ``` ```bash pnpm add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/token ``` ```bash yarn add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/token ``` ```bash bun add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/token ``` Compose a client with a generated signer, a local RPC connection, an airdrop to fund the signer, and the Token program plugin. Make sure a local validator is running (`solana-test-validator`) before this code executes. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(100_000_000_000n))) .use(tokenProgram()); ``` The signer is funded with 100 SOL because creating ATAs costs a small amount of rent for each recipient. ## Generate the recipients For the demo, generate 100 random destination addresses up front. In a real airdrop, this list would come from a database, a CSV, or some other source. ```ts twoslash import { generateKeyPairSigner } from '@solana/kit'; const recipients = await Promise.all( Array.from({ length: 100 }, async () => (await generateKeyPairSigner()).address), ); ``` ## Build the airdrop plan Compose the work as a `sequentialInstructionPlan` whose first child creates the mint and whose second child is a `parallelInstructionPlan` containing one mint-to-ATA plan per recipient. ```ts twoslash import { Address, generateKeyPairSigner, parallelInstructionPlan, sequentialInstructionPlan, } from '@solana/kit'; const recipients = null as unknown as Address[]; // ---cut-start--- import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(100_000_000_000n))) .use(tokenProgram()); // ---cut-end--- const mint = await generateKeyPairSigner(); const instructionPlan = sequentialInstructionPlan([ client.token.instructions.createMint({ newMint: mint, decimals: 6, mintAuthority: client.identity.address, }), parallelInstructionPlan( await Promise.all( recipients.map((owner) => client.token.instructions.mintToATA({ mint: mint.address, owner, mintAuthority: client.identity, amount: 1_000n * 10n ** 6n, // 1,000 tokens decimals: 6, }), ), ), ), ]); ``` The mint must exist before any recipient can receive tokens, which is why the outer plan is sequential. Each `mintToATA` is independent of the others, so wrapping them in a `parallelInstructionPlan` lets Kit run them concurrently. The Token plugin's `mintToATA` is asynchronous because it derives each recipient's ATA address up front, so wrap the whole list in a single `Promise.all`. ## Send and inspect the results `client.sendTransactions(plan)` plans, signs, sends, and confirms every transaction in the tree. Wrap the call in [`passthroughFailedTransactionPlanExecution`](/docs/advanced-guides/errors#walking-transaction-plan-results) so a failure on one transaction does not throw β€” you keep the full result tree and can decide what to do per recipient. ```ts twoslash import { flattenTransactionPlanResult, InstructionPlan, passthroughFailedTransactionPlanExecution, } from '@solana/kit'; const instructionPlan = null as unknown as InstructionPlan; // ---cut-start--- import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(100_000_000_000n))) .use(tokenProgram()); // ---cut-end--- const result = await passthroughFailedTransactionPlanExecution( client.sendTransactions(instructionPlan), ); for (const [index, single] of flattenTransactionPlanResult(result).entries()) { if (single.status === 'successful') { console.log(`#${index} βœ… ${single.context.signature}`); } else if (single.status === 'failed') { console.error(`#${index} ❌ ${single.error.message}`); } else { console.warn(`#${index} ⏭️ canceled`); } } ``` `flattenTransactionPlanResult` collapses the tree into one entry per transaction in the order they were planned, so iterating the array is enough to log each outcome individually. For a single bottom-line view across the whole airdrop, [`summarizeTransactionPlanResult`](/docs/advanced-guides/errors#walking-transaction-plan-results) returns success/failure/cancellation counts and a top-level `successful` boolean. ## Next steps * [Sending multiple transactions](/docs/guides/sending-multiple-transactions) β€” the full guide on multi-transaction operations and instruction plan composition. * [Advanced guides β€” Errors](/docs/advanced-guides/errors) β€” deep dive on `TransactionPlanResult`, walking failed trees, and program-specific errors. * [Creating a token](/recipes/creating-a-token) β€” the simpler single-recipient version of this flow. # Creating a token (/recipes/creating-a-token) This recipe walks through the full lifecycle of an SPL token: creating a mint, minting tokens to your own associated token account (ATA), and transferring some to another wallet. It runs against a local validator so you can experiment without spending mainnet SOL. ## Set up a client Install Kit and the plugins you need. ```bash npm install @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/token ``` ```bash pnpm add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/token ``` ```bash yarn add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/token ``` ```bash bun add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/token ``` Compose a client with a generated signer, a local RPC connection, an airdrop to fund the signer, and the Token program plugin. Make sure a local validator is running (`solana-test-validator`) before this code executes. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))) .use(tokenProgram()); ``` ## Create the mint Generate a fresh signer for the mint account and ask the Token program plugin to build a `createMint` instruction plan. The plan creates the mint account, funds it for rent exemption, and initializes it as a Token mint β€” all in one atomic operation. ```ts twoslash import { generateKeyPairSigner } from '@solana/kit'; // ---cut-start--- import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))) .use(tokenProgram()); // ---cut-end--- const mint = await generateKeyPairSigner(); await client.token.instructions .createMint({ newMint: mint, decimals: 9, mintAuthority: client.identity.address, }) .sendTransaction(); console.log(`πŸŽ‰ Mint created: ${mint.address}`); ``` The mint authority is the signer allowed to mint new tokens later. Setting it to `client.identity.address` makes the current client's identity the authority, which is what you want for a recipe like this one. ## Mint tokens to your ATA Tokens live in associated token accounts (ATAs) β€” one ATA per `(owner, mint)` pair. The plugin's `mintToATA` helper derives the ATA address, creates it if it does not exist yet, and mints tokens to it in a single instruction plan. ```ts twoslash import { Address } from '@solana/kit'; const mintAddress = null as unknown as Address; // ---cut-start--- import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))) .use(tokenProgram()); // ---cut-end--- await client.token.instructions .mintToATA({ mint: mintAddress, owner: client.identity.address, mintAuthority: client.identity, amount: 1_000n * 10n ** 9n, // 1,000 tokens with 9 decimals decimals: 9, }) .sendTransaction(); ``` `mintToATA` is asynchronous because it derives the ATA address before building the plan, but the `.sendTransaction()` shortcut is exposed on the returned promise itself β€” a single `await` on the call is enough. Pass the same `decimals` you used when creating the mint; the plugin uses it as a safety check to make sure you are minting against the mint you think you are. ## Transfer tokens to a recipient Sending tokens to another wallet follows the same pattern as minting: the plugin derives both the source and destination ATAs, creates the destination if it doesn't exist, and issues the transfer. ```ts twoslash import { address, Address } from '@solana/kit'; const mintAddress = null as unknown as Address; // ---cut-start--- import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { tokenProgram } from '@solana-program/token'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))) .use(tokenProgram()); // ---cut-end--- const recipient = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); await client.token.instructions .transferToATA({ mint: mintAddress, authority: client.identity, recipient, amount: 100n * 10n ** 9n, // 100 tokens decimals: 9, }) .sendTransaction(); ``` The `authority` is the owner of the source tokens, which here is the same identity that minted them. The plugin pulls tokens out of `authority`'s ATA for the given mint, creates the recipient's ATA if needed, and deposits the tokens. ## Next steps * [Using program plugins](/docs/guides/using-program-plugins) β€” explore everything `client.token` and other program namespaces expose. * [Fetching accounts](/docs/guides/fetching-accounts) β€” read the mint and token account balances back from the chain. * [Airdropping tokens](/recipes/airdropping-tokens) β€” extend this recipe to many recipients in parallel. # Recipes (/recipes) Recipes are short, copy-pasteable walkthroughs for specific tasks. Each one starts with a working setup, then walks through the steps you need to ship a feature β€” sending SOL, creating a token, airdropping tokens to many wallets, and so on. If you are new to Kit, start with the [Getting started](/docs/getting-started) tutorial first. If you are looking for deeper, reference-style coverage, the [Guides](/docs/guides) section is the next step. Recipes sit between the two: focused, end-to-end snippets you can drop into a project today. # Transferring SOL (/recipes/transferring-sol) This recipe walks through sending SOL from your client's payer to another address. It uses a local validator so you can run it end-to-end without touching real funds, and shows how to surface a useful error when a transfer fails. ## Set up a client Install Kit and the plugins you need. ```bash npm install @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/system ``` ```bash pnpm add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/system ``` ```bash yarn add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/system ``` ```bash bun add @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/system ``` Compose a client with a generated signer, a local RPC connection, an airdrop to fund the signer, and the System program plugin. Make sure a local validator is running (`solana-test-validator`) before this code executes. ```ts twoslash import { createClient, lamports } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))) .use(systemProgram()); ``` ## Send the transfer Use `client.system.instructions.transferSol` to build the transfer instruction, then call `.sendTransaction()` to plan, sign, send, and confirm it in one step. ```ts twoslash import { address, lamports } from '@solana/kit'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))) .use(systemProgram()); // ---cut-end--- const recipient = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); const result = await client.system.instructions .transferSol({ source: client.payer, destination: recipient, amount: lamports(10_000_000n), // 0.01 SOL }) .sendTransaction(); console.log(`βœ… ${result.context.signature}`); ``` The shortcut is equivalent to passing the instruction to `client.sendTransaction([...])`. Reach for the array form when you want to combine several instructions into a single atomic transaction. ## Handle errors When a transfer fails, `client.sendTransaction(...)` throws a [`SolanaError`](/docs/advanced-guides/errors) with the `SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION` code. Wrapping the call lets you surface a useful message and inspect the underlying program error. ```ts twoslash import { address, isSolanaError, lamports, SingleTransactionPlanResult, SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION, } from '@solana/kit'; import { getSystemErrorMessage, isSystemError } from '@solana-program/system'; // ---cut-start--- import { createClient } from '@solana/kit'; import { solanaLocalRpc } from '@solana/kit-plugin-rpc'; import { airdropSigner, generatedSigner } from '@solana/kit-plugin-signer'; import { systemProgram } from '@solana-program/system'; const client = await createClient() .use(generatedSigner()) .use(solanaLocalRpc()) .use(airdropSigner(lamports(1_000_000_000n))) .use(systemProgram()); const recipient = address('GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ'); // ---cut-end--- try { await client.system.instructions .transferSol({ source: client.payer, destination: recipient, amount: lamports(10_000_000n), }) .sendTransaction(); } catch (e) { if (!isSolanaError(e, SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION)) throw e; const result = e.context.transactionPlanResult as SingleTransactionPlanResult; const transactionMessage = result.context.message ?? result.plannedMessage; const cause = e.cause as Error; if (isSystemError(cause, transactionMessage)) { console.error(`System program error: ${getSystemErrorMessage(cause.context.code)}`); } else { console.error('Transfer failed:', e.message); } } ``` `error.cause` carries the underlying error, and `error.context.transactionPlanResult` carries the planned transaction message. Pairing them with `isSystemError` and `getSystemErrorMessage` from `@solana-program/system` turns an opaque program error code into a human-readable message β€” invaluable when something like an underfunded source account causes the transfer to fail. ## Next steps * [Sending transactions](/docs/guides/sending-transactions) β€” the full guide on single transactions, including planning and configuration. * [Advanced guides β€” Errors](/docs/advanced-guides/errors) β€” deep dive on `SolanaError` codes and program-specific error parsing. # API Reference (/api) Welcome to the Solana Kit API Reference! It covers a total of **46 packages** most of which are available via the main `@solana/kit` package. ## Need Help? * Check out our [Getting Started guide](/docs/getting-started/). * Learn about key concepts in our [Advanced Guides](/docs/advanced-guides/). ## All Packages ### `@solana/kit`

Packages (32)

[@solana/accounts](#solanaaccounts) \ [@solana/addresses](#solanaaddresses) \ [@solana/codecs-core](#solanacodecs-core) \ [@solana/codecs-data-structures](#solanacodecs-data-structures) \ [@solana/codecs-numbers](#solanacodecs-numbers) \ [@solana/codecs-strings](#solanacodecs-strings) \ [@solana/errors](#solanaerrors) \ [@solana/fixed-points](#solanafixed-points) \ [@solana/functional](#solanafunctional) \ [@solana/instruction-plans](#solanainstruction-plans) \ [@solana/instructions](#solanainstructions) \ [@solana/keys](#solanakeys) \ [@solana/offchain-messages](#solanaoffchain-messages) \ [@solana/options](#solanaoptions) \ [@solana/plugin-core](#solanaplugin-core) \ [@solana/plugin-interfaces](#solanaplugin-interfaces) \ [@solana/programs](#solanaprograms) \ [@solana/promises](#solanapromises) \ [@solana/rpc](#solanarpc) \ [@solana/rpc-api](#solanarpc-api) \ [@solana/rpc-parsed-types](#solanarpc-parsed-types) \ [@solana/rpc-spec](#solanarpc-spec) \ [@solana/rpc-spec-types](#solanarpc-spec-types) \ [@solana/rpc-subscriptions](#solanarpc-subscriptions) \ [@solana/rpc-subscriptions-api](#solanarpc-subscriptions-api) \ [@solana/rpc-subscriptions-spec](#solanarpc-subscriptions-spec) \ [@solana/rpc-types](#solanarpc-types) \ [@solana/signers](#solanasigners) \ [@solana/subscribable](#solanasubscribable) \ [@solana/transaction-introspection](#solanatransaction-introspection) \ [@solana/transaction-messages](#solanatransaction-messages) \ [@solana/transactions](#solanatransactions)

Types (2)

[CreateReactiveStoreWithInitialValueAndSlotTrackingConfig](/api/type-aliases/CreateReactiveStoreWithInitialValueAndSlotTrackingConfig) \ [ResourceLimitsEstimate](/api/type-aliases/ResourceLimitsEstimate)

Functions (14)

[airdropFactory](/api/functions/airdropFactory) \ [createAsyncGeneratorWithInitialValueAndSlotTracking](/api/functions/createAsyncGeneratorWithInitialValueAndSlotTracking) \ [createClientWithFetchAccountsFromRpc](/api/functions/createClientWithFetchAccountsFromRpc) \ [createClientWithGetMinimumBalanceFromRpc](/api/functions/createClientWithGetMinimumBalanceFromRpc) \ [createClientWithInterfacesFromRpc](/api/functions/createClientWithInterfacesFromRpc) \ [createReactiveStoreWithInitialValueAndSlotTracking](/api/functions/createReactiveStoreWithInitialValueAndSlotTracking) \ [decompileTransactionMessageFetchingLookupTables](/api/functions/decompileTransactionMessageFetchingLookupTables) \ [estimateAndSetResourceLimitsFactory](/api/functions/estimateAndSetResourceLimitsFactory) \ [estimateResourceLimitsFactory](/api/functions/estimateResourceLimitsFactory) \ [fetchAddressesForLookupTables](/api/functions/fetchAddressesForLookupTables) \ [fillTransactionMessageProvisoryResourceLimits](/api/functions/fillTransactionMessageProvisoryResourceLimits) \ [sendAndConfirmDurableNonceTransactionFactory](/api/functions/sendAndConfirmDurableNonceTransactionFactory) \ [sendAndConfirmTransactionFactory](/api/functions/sendAndConfirmTransactionFactory) \ [sendTransactionWithoutConfirmingFactory](/api/functions/sendTransactionWithoutConfirmingFactory)
### `@solana/accounts`

Types (7)

[Account](/api/interfaces/Account) \ [BaseAccount](/api/interfaces/BaseAccount) \ [EncodedAccount](/api/interfaces/EncodedAccount) \ [FetchAccountConfig](/api/interfaces/FetchAccountConfig) \ [FetchAccountsConfig](/api/interfaces/FetchAccountsConfig) \ [MaybeAccount](/api/type-aliases/MaybeAccount) \ [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount)

Functions (12)

[assertAccountDecoded](/api/functions/assertAccountDecoded) \ [assertAccountExists](/api/functions/assertAccountExists) \ [assertAccountsDecoded](/api/functions/assertAccountsDecoded) \ [assertAccountsExist](/api/functions/assertAccountsExist) \ [decodeAccount](/api/functions/decodeAccount) \ [fetchEncodedAccount](/api/functions/fetchEncodedAccount) \ [fetchEncodedAccounts](/api/functions/fetchEncodedAccounts) \ [fetchJsonParsedAccount](/api/functions/fetchJsonParsedAccount) \ [fetchJsonParsedAccounts](/api/functions/fetchJsonParsedAccounts) \ [parseBase58RpcAccount](/api/functions/parseBase58RpcAccount) \ [parseBase64RpcAccount](/api/functions/parseBase64RpcAccount) \ [parseJsonRpcAccount](/api/functions/parseJsonRpcAccount)

Variables (1)

[BASE\_ACCOUNT\_SIZE](/api/variables/BASE_ACCOUNT_SIZE)
### `@solana/addresses`

Types (4)

[Address](/api/type-aliases/Address) \ [OffCurveAddress](/api/type-aliases/OffCurveAddress) \ [ProgramDerivedAddress](/api/type-aliases/ProgramDerivedAddress) \ [ProgramDerivedAddressBump](/api/type-aliases/ProgramDerivedAddressBump)

Functions (16)

[address](/api/functions/address) \ [assertIsAddress](/api/functions/assertIsAddress) \ [assertIsOffCurveAddress](/api/functions/assertIsOffCurveAddress) \ [assertIsProgramDerivedAddress](/api/functions/assertIsProgramDerivedAddress) \ [createAddressWithSeed](/api/functions/createAddressWithSeed) \ [getAddressCodec](/api/functions/getAddressCodec) \ [getAddressComparator](/api/functions/getAddressComparator) \ [getAddressDecoder](/api/functions/getAddressDecoder) \ [getAddressEncoder](/api/functions/getAddressEncoder) \ [getAddressFromPublicKey](/api/functions/getAddressFromPublicKey) \ [getProgramDerivedAddress](/api/functions/getProgramDerivedAddress) \ [getPublicKeyFromAddress](/api/functions/getPublicKeyFromAddress) \ [isAddress](/api/functions/isAddress) \ [isOffCurveAddress](/api/functions/isOffCurveAddress) \ [isProgramDerivedAddress](/api/functions/isProgramDerivedAddress) \ [offCurveAddress](/api/functions/offCurveAddress)
### `@solana/assertions`

Functions (6)

[assertDigestCapabilityIsAvailable](/api/functions/assertDigestCapabilityIsAvailable) \ [assertKeyExporterIsAvailable](/api/functions/assertKeyExporterIsAvailable) \ [assertKeyGenerationIsAvailable](/api/functions/assertKeyGenerationIsAvailable) \ [assertPRNGIsAvailable](/api/functions/assertPRNGIsAvailable) \ [assertSigningCapabilityIsAvailable](/api/functions/assertSigningCapabilityIsAvailable) \ [assertVerificationCapabilityIsAvailable](/api/functions/assertVerificationCapabilityIsAvailable)
### `@solana/codecs`

Packages (6)

[@solana/codecs-core](#solanacodecs-core) \ [@solana/codecs-data-structures](#solanacodecs-data-structures) \ [@solana/codecs-numbers](#solanacodecs-numbers) \ [@solana/codecs-strings](#solanacodecs-strings) \ [@solana/fixed-points](#solanafixed-points) \ [@solana/options](#solanaoptions)
### `@solana/codecs-core`

Types (11)

[Codec](/api/type-aliases/Codec) \ [Decoder](/api/type-aliases/Decoder) \ [Encoder](/api/type-aliases/Encoder) \ [FixedSizeCodec](/api/interfaces/FixedSizeCodec) \ [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) \ [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder) \ [Offset](/api/type-aliases/Offset) \ [ReadonlyUint8Array](/api/interfaces/ReadonlyUint8Array) \ [VariableSizeCodec](/api/interfaces/VariableSizeCodec) \ [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) \ [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder)

Functions (46)

[addCodecSentinel](/api/functions/addCodecSentinel) \ [addCodecSizePrefix](/api/functions/addCodecSizePrefix) \ [addDecoderSentinel](/api/functions/addDecoderSentinel) \ [addDecoderSizePrefix](/api/functions/addDecoderSizePrefix) \ [addEncoderSentinel](/api/functions/addEncoderSentinel) \ [addEncoderSizePrefix](/api/functions/addEncoderSizePrefix) \ [assertByteArrayHasEnoughBytesForCodec](/api/functions/assertByteArrayHasEnoughBytesForCodec) \ [assertByteArrayIsNotEmptyForCodec](/api/functions/assertByteArrayIsNotEmptyForCodec) \ [assertByteArrayOffsetIsNotOutOfRange](/api/functions/assertByteArrayOffsetIsNotOutOfRange) \ [assertIsFixedSize](/api/functions/assertIsFixedSize) \ [assertIsVariableSize](/api/functions/assertIsVariableSize) \ [bytesEqual](/api/functions/bytesEqual) \ [combineCodec](/api/functions/combineCodec) \ [containsBytes](/api/functions/containsBytes) \ [createCodec](/api/functions/createCodec) \ [createDecoder](/api/functions/createDecoder) \ [createDecoderThatConsumesEntireByteArray](/api/functions/createDecoderThatConsumesEntireByteArray) \ [createEncoder](/api/functions/createEncoder) \ [fixBytes](/api/functions/fixBytes) \ [fixCodecSize](/api/functions/fixCodecSize) \ [fixDecoderSize](/api/functions/fixDecoderSize) \ [fixEncoderSize](/api/functions/fixEncoderSize) \ [getEncodedSize](/api/functions/getEncodedSize) \ [isFixedSize](/api/functions/isFixedSize) \ [isVariableSize](/api/functions/isVariableSize) \ [mergeBytes](/api/functions/mergeBytes) \ [offsetCodec](/api/functions/offsetCodec) \ [offsetDecoder](/api/functions/offsetDecoder) \ [offsetEncoder](/api/functions/offsetEncoder) \ [padBytes](/api/functions/padBytes) \ [padLeftCodec](/api/functions/padLeftCodec) \ [padLeftDecoder](/api/functions/padLeftDecoder) \ [padLeftEncoder](/api/functions/padLeftEncoder) \ [padRightCodec](/api/functions/padRightCodec) \ [padRightDecoder](/api/functions/padRightDecoder) \ [padRightEncoder](/api/functions/padRightEncoder) \ [resizeCodec](/api/functions/resizeCodec) \ [resizeDecoder](/api/functions/resizeDecoder) \ [resizeEncoder](/api/functions/resizeEncoder) \ [reverseCodec](/api/functions/reverseCodec) \ [reverseDecoder](/api/functions/reverseDecoder) \ [reverseEncoder](/api/functions/reverseEncoder) \ [toArrayBuffer](/api/functions/toArrayBuffer) \ [transformCodec](/api/functions/transformCodec) \ [transformDecoder](/api/functions/transformDecoder) \ [transformEncoder](/api/functions/transformEncoder)
### `@solana/codecs-data-structures`

Types (16)

[ArrayCodecConfig](/api/type-aliases/ArrayCodecConfig) \ [ArrayLikeCodecSize](/api/type-aliases/ArrayLikeCodecSize) \ [BitArrayCodecConfig](/api/type-aliases/BitArrayCodecConfig) \ [BooleanCodecConfig](/api/type-aliases/BooleanCodecConfig) \ [DependentStructDecoderBuilder](/api/type-aliases/DependentStructDecoderBuilder) \ [DependentStructDecoderFieldFactory](/api/type-aliases/DependentStructDecoderFieldFactory) \ [DiscriminatedUnion](/api/type-aliases/DiscriminatedUnion) \ [DiscriminatedUnionCodecConfig](/api/type-aliases/DiscriminatedUnionCodecConfig) \ [EnumCodecConfig](/api/type-aliases/EnumCodecConfig) \ [GetDiscriminatedUnionVariant](/api/type-aliases/GetDiscriminatedUnionVariant) \ [GetDiscriminatedUnionVariantContent](/api/type-aliases/GetDiscriminatedUnionVariantContent) \ [LiteralUnionCodecConfig](/api/type-aliases/LiteralUnionCodecConfig) \ [MapCodecConfig](/api/type-aliases/MapCodecConfig) \ [NullableCodecConfig](/api/type-aliases/NullableCodecConfig) \ [SetCodecConfig](/api/type-aliases/SetCodecConfig) \ [TupleCodecConfig](/api/type-aliases/TupleCodecConfig)

Functions (59)

[assertValidNumberOfItemsForCodec](/api/functions/assertValidNumberOfItemsForCodec) \ [createDependentStructDecoder](/api/functions/createDependentStructDecoder) \ [getArrayCodec](/api/functions/getArrayCodec) \ [getArrayDecoder](/api/functions/getArrayDecoder) \ [getArrayEncoder](/api/functions/getArrayEncoder) \ [getBitArrayCodec](/api/functions/getBitArrayCodec) \ [getBitArrayDecoder](/api/functions/getBitArrayDecoder) \ [getBitArrayEncoder](/api/functions/getBitArrayEncoder) \ [getBooleanCodec](/api/functions/getBooleanCodec) \ [getBooleanDecoder](/api/functions/getBooleanDecoder) \ [getBooleanEncoder](/api/functions/getBooleanEncoder) \ [getBytesCodec](/api/functions/getBytesCodec) \ [getBytesDecoder](/api/functions/getBytesDecoder) \ [getBytesEncoder](/api/functions/getBytesEncoder) \ [getConstantCodec](/api/functions/getConstantCodec) \ [getConstantDecoder](/api/functions/getConstantDecoder) \ [getConstantEncoder](/api/functions/getConstantEncoder) \ [getDiscriminatedUnionCodec](/api/functions/getDiscriminatedUnionCodec) \ [getDiscriminatedUnionDecoder](/api/functions/getDiscriminatedUnionDecoder) \ [getDiscriminatedUnionEncoder](/api/functions/getDiscriminatedUnionEncoder) \ [getEnumCodec](/api/functions/getEnumCodec) \ [getEnumDecoder](/api/functions/getEnumDecoder) \ [getEnumEncoder](/api/functions/getEnumEncoder) \ [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec) \ [getHiddenPrefixDecoder](/api/functions/getHiddenPrefixDecoder) \ [getHiddenPrefixEncoder](/api/functions/getHiddenPrefixEncoder) \ [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec) \ [getHiddenSuffixDecoder](/api/functions/getHiddenSuffixDecoder) \ [getHiddenSuffixEncoder](/api/functions/getHiddenSuffixEncoder) \ [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec) \ [getLiteralUnionDecoder](/api/functions/getLiteralUnionDecoder) \ [getLiteralUnionEncoder](/api/functions/getLiteralUnionEncoder) \ [getMapCodec](/api/functions/getMapCodec) \ [getMapDecoder](/api/functions/getMapDecoder) \ [getMapEncoder](/api/functions/getMapEncoder) \ [getNullableCodec](/api/functions/getNullableCodec) \ [getNullableDecoder](/api/functions/getNullableDecoder) \ [getNullableEncoder](/api/functions/getNullableEncoder) \ [getPatternMatchCodec](/api/functions/getPatternMatchCodec) \ [getPatternMatchDecoder](/api/functions/getPatternMatchDecoder) \ [getPatternMatchEncoder](/api/functions/getPatternMatchEncoder) \ [getPredicateCodec](/api/functions/getPredicateCodec) \ [getPredicateDecoder](/api/functions/getPredicateDecoder) \ [getPredicateEncoder](/api/functions/getPredicateEncoder) \ [getSetCodec](/api/functions/getSetCodec) \ [getSetDecoder](/api/functions/getSetDecoder) \ [getSetEncoder](/api/functions/getSetEncoder) \ [getStructCodec](/api/functions/getStructCodec) \ [getStructDecoder](/api/functions/getStructDecoder) \ [getStructEncoder](/api/functions/getStructEncoder) \ [getTupleCodec](/api/functions/getTupleCodec) \ [getTupleDecoder](/api/functions/getTupleDecoder) \ [getTupleEncoder](/api/functions/getTupleEncoder) \ [getUnionCodec](/api/functions/getUnionCodec) \ [getUnionDecoder](/api/functions/getUnionDecoder) \ [getUnionEncoder](/api/functions/getUnionEncoder) \ [getUnitCodec](/api/functions/getUnitCodec) \ [getUnitDecoder](/api/functions/getUnitDecoder) \ [getUnitEncoder](/api/functions/getUnitEncoder)
### `@solana/codecs-numbers`

Enums (1)

[Endian](/api/enumerations/Endian)

Types (7)

[FixedSizeNumberCodec](/api/type-aliases/FixedSizeNumberCodec) \ [FixedSizeNumberDecoder](/api/type-aliases/FixedSizeNumberDecoder) \ [FixedSizeNumberEncoder](/api/type-aliases/FixedSizeNumberEncoder) \ [NumberCodec](/api/type-aliases/NumberCodec) \ [NumberCodecConfig](/api/type-aliases/NumberCodecConfig) \ [NumberDecoder](/api/type-aliases/NumberDecoder) \ [NumberEncoder](/api/type-aliases/NumberEncoder)

Functions (40)

[assertNumberIsBetweenForCodec](/api/functions/assertNumberIsBetweenForCodec) \ [getF32Codec](/api/functions/getF32Codec) \ [getF32Decoder](/api/functions/getF32Decoder) \ [getF32Encoder](/api/functions/getF32Encoder) \ [getF64Codec](/api/functions/getF64Codec) \ [getF64Decoder](/api/functions/getF64Decoder) \ [getF64Encoder](/api/functions/getF64Encoder) \ [getI128Codec](/api/functions/getI128Codec) \ [getI128Decoder](/api/functions/getI128Decoder) \ [getI128Encoder](/api/functions/getI128Encoder) \ [getI16Codec](/api/functions/getI16Codec) \ [getI16Decoder](/api/functions/getI16Decoder) \ [getI16Encoder](/api/functions/getI16Encoder) \ [getI32Codec](/api/functions/getI32Codec) \ [getI32Decoder](/api/functions/getI32Decoder) \ [getI32Encoder](/api/functions/getI32Encoder) \ [getI64Codec](/api/functions/getI64Codec) \ [getI64Decoder](/api/functions/getI64Decoder) \ [getI64Encoder](/api/functions/getI64Encoder) \ [getI8Codec](/api/functions/getI8Codec) \ [getI8Decoder](/api/functions/getI8Decoder) \ [getI8Encoder](/api/functions/getI8Encoder) \ [getShortU16Codec](/api/functions/getShortU16Codec) \ [getShortU16Decoder](/api/functions/getShortU16Decoder) \ [getShortU16Encoder](/api/functions/getShortU16Encoder) \ [getU128Codec](/api/functions/getU128Codec) \ [getU128Decoder](/api/functions/getU128Decoder) \ [getU128Encoder](/api/functions/getU128Encoder) \ [getU16Codec](/api/functions/getU16Codec) \ [getU16Decoder](/api/functions/getU16Decoder) \ [getU16Encoder](/api/functions/getU16Encoder) \ [getU32Codec](/api/functions/getU32Codec) \ [getU32Decoder](/api/functions/getU32Decoder) \ [getU32Encoder](/api/functions/getU32Encoder) \ [getU64Codec](/api/functions/getU64Codec) \ [getU64Decoder](/api/functions/getU64Decoder) \ [getU64Encoder](/api/functions/getU64Encoder) \ [getU8Codec](/api/functions/getU8Codec) \ [getU8Decoder](/api/functions/getU8Decoder) \ [getU8Encoder](/api/functions/getU8Encoder)
### `@solana/codecs-strings`

Functions (24)

[assertValidBaseString](/api/functions/assertValidBaseString) \ [getBase10Codec](/api/functions/getBase10Codec) \ [getBase10Decoder](/api/functions/getBase10Decoder) \ [getBase10Encoder](/api/functions/getBase10Encoder) \ [getBase16Codec](/api/functions/getBase16Codec) \ [getBase16Decoder](/api/functions/getBase16Decoder) \ [getBase16Encoder](/api/functions/getBase16Encoder) \ [getBase58Codec](/api/functions/getBase58Codec) \ [getBase58Decoder](/api/functions/getBase58Decoder) \ [getBase58Encoder](/api/functions/getBase58Encoder) \ [getBase64Codec](/api/functions/getBase64Codec) \ [getBase64Decoder](/api/functions/getBase64Decoder) \ [getBase64Encoder](/api/functions/getBase64Encoder) \ [getBaseXCodec](/api/functions/getBaseXCodec) \ [getBaseXDecoder](/api/functions/getBaseXDecoder) \ [getBaseXEncoder](/api/functions/getBaseXEncoder) \ [getBaseXResliceCodec](/api/functions/getBaseXResliceCodec) \ [getBaseXResliceDecoder](/api/functions/getBaseXResliceDecoder) \ [getBaseXResliceEncoder](/api/functions/getBaseXResliceEncoder) \ [getUtf8Codec](/api/functions/getUtf8Codec) \ [getUtf8Decoder](/api/functions/getUtf8Decoder) \ [getUtf8Encoder](/api/functions/getUtf8Encoder) \ [padNullCharacters](/api/functions/padNullCharacters) \ [removeNullCharacters](/api/functions/removeNullCharacters)
### `@solana/compat`

Functions (4)

[fromLegacyKeypair](/api/functions/fromLegacyKeypair) \ [fromLegacyPublicKey](/api/functions/fromLegacyPublicKey) \ [fromLegacyTransactionInstruction](/api/functions/fromLegacyTransactionInstruction) \ [fromVersionedTransaction](/api/functions/fromVersionedTransaction)
### `@solana/errors`

Classes (1)

[SolanaError](/api/classes/SolanaError)

Types (4)

[SolanaErrorCode](/api/type-aliases/SolanaErrorCode) \ [SolanaErrorCodeWithCause](/api/type-aliases/SolanaErrorCodeWithCause) \ [SolanaErrorCodeWithDeprecatedCause](/api/type-aliases/SolanaErrorCodeWithDeprecatedCause) \ [SolanaErrorWithDeprecatedCause](/api/interfaces/SolanaErrorWithDeprecatedCause)

Functions (6)

[getSolanaErrorFromInstructionError](/api/functions/getSolanaErrorFromInstructionError) \ [getSolanaErrorFromJsonRpcError](/api/functions/getSolanaErrorFromJsonRpcError) \ [getSolanaErrorFromTransactionError](/api/functions/getSolanaErrorFromTransactionError) \ [isSolanaError](/api/functions/isSolanaError) \ [safeCaptureStackTrace](/api/functions/safeCaptureStackTrace) \ [unwrapSimulationError](/api/functions/unwrapSimulationError)

Variables (328)

[SOLANA\_ERROR\_\_ACCOUNTS\_\_ACCOUNT\_NOT\_FOUND](/api/variables/SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND) \ [SOLANA\_ERROR\_\_ACCOUNTS\_\_EXPECTED\_ALL\_ACCOUNTS\_TO\_BE\_DECODED](/api/variables/SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED) \ [SOLANA\_ERROR\_\_ACCOUNTS\_\_EXPECTED\_DECODED\_ACCOUNT](/api/variables/SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT) \ [SOLANA\_ERROR\_\_ACCOUNTS\_\_FAILED\_TO\_DECODE\_ACCOUNT](/api/variables/SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT) \ [SOLANA\_ERROR\_\_ACCOUNTS\_\_ONE\_OR\_MORE\_ACCOUNTS\_NOT\_FOUND](/api/variables/SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_FAILED\_TO\_FIND\_VIABLE\_PDA\_BUMP\_SEED](/api/variables/SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_INVALID\_BASE58\_ENCODED\_ADDRESS](/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_INVALID\_BYTE\_LENGTH](/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_INVALID\_ED25519\_PUBLIC\_KEY](/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_INVALID\_OFF\_CURVE\_ADDRESS](/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_INVALID\_SEEDS\_POINT\_ON\_CURVE](/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_MALFORMED\_PDA](/api/variables/SOLANA_ERROR__ADDRESSES__MALFORMED_PDA) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_MAX\_NUMBER\_OF\_PDA\_SEEDS\_EXCEEDED](/api/variables/SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_MAX\_PDA\_SEED\_LENGTH\_EXCEEDED](/api/variables/SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_PDA\_BUMP\_SEED\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_PDA\_ENDS\_WITH\_PDA\_MARKER](/api/variables/SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER) \ [SOLANA\_ERROR\_\_ADDRESSES\_\_STRING\_LENGTH\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_BLOCK\_HEIGHT\_EXCEEDED](/api/variables/SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED) \ [SOLANA\_ERROR\_\_BLOCKHASH\_STRING\_LENGTH\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_CODECS\_\_CANNOT\_DECODE\_EMPTY\_BYTE\_ARRAY](/api/variables/SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY) \ [SOLANA\_ERROR\_\_CODECS\_\_CANNOT\_USE\_LEXICAL\_VALUES\_AS\_ENUM\_DISCRIMINATORS](/api/variables/SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS) \ [SOLANA\_ERROR\_\_CODECS\_\_ENCODED\_BYTES\_MUST\_NOT\_INCLUDE\_SENTINEL](/api/variables/SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL) \ [SOLANA\_ERROR\_\_CODECS\_\_ENCODER\_DECODER\_FIXED\_SIZE\_MISMATCH](/api/variables/SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH) \ [SOLANA\_ERROR\_\_CODECS\_\_ENCODER\_DECODER\_MAX\_SIZE\_MISMATCH](/api/variables/SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH) \ [SOLANA\_ERROR\_\_CODECS\_\_ENCODER\_DECODER\_SIZE\_COMPATIBILITY\_MISMATCH](/api/variables/SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH) \ [SOLANA\_ERROR\_\_CODECS\_\_ENUM\_DISCRIMINATOR\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_CODECS\_\_EXPECTED\_DECODER\_TO\_CONSUME\_ENTIRE\_BYTE\_ARRAY](/api/variables/SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY) \ [SOLANA\_ERROR\_\_CODECS\_\_EXPECTED\_FIXED\_LENGTH](/api/variables/SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH) \ [SOLANA\_ERROR\_\_CODECS\_\_EXPECTED\_POSITIVE\_BYTE\_LENGTH](/api/variables/SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH) \ [SOLANA\_ERROR\_\_CODECS\_\_EXPECTED\_VARIABLE\_LENGTH](/api/variables/SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH) \ [SOLANA\_ERROR\_\_CODECS\_\_EXPECTED\_ZERO\_VALUE\_TO\_MATCH\_ITEM\_FIXED\_SIZE](/api/variables/SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE) \ [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_BYTE\_LENGTH](/api/variables/SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH) \ [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_CONSTANT](/api/variables/SOLANA_ERROR__CODECS__INVALID_CONSTANT) \ [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_DISCRIMINATED\_UNION\_VARIANT](/api/variables/SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT) \ [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_ENUM\_VARIANT](/api/variables/SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT) \ [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_LITERAL\_UNION\_VARIANT](/api/variables/SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT) \ [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_NUMBER\_OF\_ITEMS](/api/variables/SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS) \ [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_PATTERN\_MATCH\_BYTES](/api/variables/SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES) \ [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_PATTERN\_MATCH\_VALUE](/api/variables/SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE) \ [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_STRING\_FOR\_BASE](/api/variables/SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE) \ [SOLANA\_ERROR\_\_CODECS\_\_LITERAL\_UNION\_DISCRIMINATOR\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_CODECS\_\_NUMBER\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_CODECS\_\_OFFSET\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_CODECS\_\_SENTINEL\_MISSING\_IN\_DECODED\_BYTES](/api/variables/SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES) \ [SOLANA\_ERROR\_\_CODECS\_\_UNION\_VARIANT\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_CRYPTO\_\_RANDOM\_VALUES\_FUNCTION\_UNIMPLEMENTED](/api/variables/SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED) \ [SOLANA\_ERROR\_\_FAILED\_TO\_SEND\_TRANSACTION](/api/variables/SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION) \ [SOLANA\_ERROR\_\_FAILED\_TO\_SEND\_TRANSACTIONS](/api/variables/SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS) \ [SOLANA\_ERROR\_\_FAILED\_TO\_SIGN\_TRANSACTION](/api/variables/SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION) \ [SOLANA\_ERROR\_\_FAILED\_TO\_SIGN\_TRANSACTIONS](/api/variables/SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_ARITHMETIC\_OVERFLOW](/api/variables/SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_DIVISION\_BY\_ZERO](/api/variables/SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_FRACTIONAL\_BITS\_EXCEED\_TOTAL\_BITS](/api/variables/SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_INVALID\_DECIMALS](/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_INVALID\_FRACTIONAL\_BITS](/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_INVALID\_STRING](/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_STRING) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_INVALID\_TOTAL\_BITS](/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_INVALID\_ZERO\_DENOMINATOR\_RATIO](/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_MALFORMED\_RAW\_VALUE](/api/variables/SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_SHAPE\_MISMATCH](/api/variables/SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_STRICT\_MODE\_PRECISION\_LOSS](/api/variables/SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_TOTAL\_BITS\_NOT\_BYTE\_ALIGNED](/api/variables/SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED) \ [SOLANA\_ERROR\_\_FIXED\_POINTS\_\_VALUE\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_FS\_\_UNSUPPORTED\_ENVIRONMENT](/api/variables/SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT) \ [SOLANA\_ERROR\_\_INSTRUCTION\_\_EXPECTED\_TO\_HAVE\_ACCOUNTS](/api/variables/SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS) \ [SOLANA\_ERROR\_\_INSTRUCTION\_\_EXPECTED\_TO\_HAVE\_DATA](/api/variables/SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA) \ [SOLANA\_ERROR\_\_INSTRUCTION\_\_PROGRAM\_ID\_MISMATCH](/api/variables/SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_ACCOUNT\_ALREADY\_INITIALIZED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_ACCOUNT\_BORROW\_FAILED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_ACCOUNT\_BORROW\_OUTSTANDING](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_ACCOUNT\_DATA\_SIZE\_CHANGED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_ACCOUNT\_DATA\_TOO\_SMALL](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_ACCOUNT\_NOT\_EXECUTABLE](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_ACCOUNT\_NOT\_RENT\_EXEMPT](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_ARITHMETIC\_OVERFLOW](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_BORSH\_IO\_ERROR](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_BUILTIN\_PROGRAMS\_MUST\_CONSUME\_COMPUTE\_UNITS](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_CALL\_DEPTH](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_COMPUTATIONAL\_BUDGET\_EXCEEDED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_CUSTOM](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_DUPLICATE\_ACCOUNT\_INDEX](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_DUPLICATE\_ACCOUNT\_OUT\_OF\_SYNC](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_EXECUTABLE\_ACCOUNT\_NOT\_RENT\_EXEMPT](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_EXECUTABLE\_DATA\_MODIFIED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_EXECUTABLE\_LAMPORT\_CHANGE](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_EXECUTABLE\_MODIFIED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_EXTERNAL\_ACCOUNT\_DATA\_MODIFIED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_EXTERNAL\_ACCOUNT\_LAMPORT\_SPEND](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_GENERIC\_ERROR](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_ILLEGAL\_OWNER](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_IMMUTABLE](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INCORRECT\_AUTHORITY](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INCORRECT\_PROGRAM\_ID](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INSUFFICIENT\_FUNDS](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INVALID\_ACCOUNT\_DATA](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INVALID\_ACCOUNT\_OWNER](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INVALID\_ARGUMENT](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INVALID\_ERROR](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INVALID\_INSTRUCTION\_DATA](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INVALID\_REALLOC](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_INVALID\_SEEDS](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_MAX\_ACCOUNTS\_DATA\_ALLOCATIONS\_EXCEEDED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_MAX\_ACCOUNTS\_EXCEEDED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_MAX\_INSTRUCTION\_TRACE\_LENGTH\_EXCEEDED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_MAX\_SEED\_LENGTH\_EXCEEDED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_MISSING\_ACCOUNT](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_MISSING\_REQUIRED\_SIGNATURE](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_MODIFIED\_PROGRAM\_ID](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_NOT\_ENOUGH\_ACCOUNT\_KEYS](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_PRIVILEGE\_ESCALATION](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_PROGRAM\_ENVIRONMENT\_SETUP\_FAILURE](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_PROGRAM\_FAILED\_TO\_COMPILE](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_PROGRAM\_FAILED\_TO\_COMPLETE](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_READONLY\_DATA\_MODIFIED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_READONLY\_LAMPORT\_CHANGE](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_REENTRANCY\_NOT\_ALLOWED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_RENT\_EPOCH\_MODIFIED](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_UNBALANCED\_INSTRUCTION](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_UNINITIALIZED\_ACCOUNT](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_UNKNOWN](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_UNSUPPORTED\_PROGRAM\_ID](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID) \ [SOLANA\_ERROR\_\_INSTRUCTION\_ERROR\_\_UNSUPPORTED\_SYSVAR](/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_EMPTY\_INSTRUCTION\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_EXPECTED\_SUCCESSFUL\_TRANSACTION\_PLAN\_RESULT](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_FAILED\_SINGLE\_TRANSACTION\_PLAN\_RESULT\_NOT\_FOUND](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_FAILED\_TO\_EXECUTE\_TRANSACTION\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_INVALID\_MAX\_INSTRUCTIONS\_PER\_TRANSACTION](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_MAX\_INSTRUCTIONS\_PER\_TRANSACTION\_EXCEEDED](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_MESSAGE\_CANNOT\_ACCOMMODATE\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_MESSAGE\_PACKER\_ALREADY\_COMPLETE](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_NON\_DIVISIBLE\_TRANSACTION\_PLANS\_NOT\_SUPPORTED](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_UNEXPECTED\_INSTRUCTION\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_UNEXPECTED\_TRANSACTION\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN) \ [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_UNEXPECTED\_TRANSACTION\_PLAN\_RESULT](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT) \ [SOLANA\_ERROR\_\_INVALID\_BLOCKHASH\_BYTE\_LENGTH](/api/variables/SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH) \ [SOLANA\_ERROR\_\_INVALID\_NONCE](/api/variables/SOLANA_ERROR__INVALID_NONCE) \ [SOLANA\_ERROR\_\_INVARIANT\_VIOLATION\_\_CACHED\_ABORTABLE\_ITERABLE\_CACHE\_ENTRY\_MISSING](/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING) \ [SOLANA\_ERROR\_\_INVARIANT\_VIOLATION\_\_DATA\_PUBLISHER\_CHANNEL\_UNIMPLEMENTED](/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED) \ [SOLANA\_ERROR\_\_INVARIANT\_VIOLATION\_\_INVALID\_INSTRUCTION\_PLAN\_KIND](/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND) \ [SOLANA\_ERROR\_\_INVARIANT\_VIOLATION\_\_INVALID\_TRANSACTION\_PLAN\_KIND](/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND) \ [SOLANA\_ERROR\_\_INVARIANT\_VIOLATION\_\_SUBSCRIPTION\_ITERATOR\_MUST\_NOT\_POLL\_BEFORE\_RESOLVING\_EXISTING\_MESSAGE\_PROMISE](/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE) \ [SOLANA\_ERROR\_\_INVARIANT\_VIOLATION\_\_SUBSCRIPTION\_ITERATOR\_STATE\_MISSING](/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING) \ [SOLANA\_ERROR\_\_INVARIANT\_VIOLATION\_\_SWITCH\_MUST\_BE\_EXHAUSTIVE](/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_INTERNAL\_ERROR](/api/variables/SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_INVALID\_PARAMS](/api/variables/SOLANA_ERROR__JSON_RPC__INVALID_PARAMS) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_INVALID\_REQUEST](/api/variables/SOLANA_ERROR__JSON_RPC__INVALID_REQUEST) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_METHOD\_NOT\_FOUND](/api/variables/SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_PARSE\_ERROR](/api/variables/SOLANA_ERROR__JSON_RPC__PARSE_ERROR) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SCAN\_ERROR](/api/variables/SOLANA_ERROR__JSON_RPC__SCAN_ERROR) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_BLOCK\_CLEANED\_UP](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_BLOCK\_NOT\_AVAILABLE](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_BLOCK\_STATUS\_NOT\_AVAILABLE\_YET](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_EPOCH\_REWARDS\_PERIOD\_ACTIVE](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_FILTER\_TRANSACTION\_NOT\_FOUND](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_KEY\_EXCLUDED\_FROM\_SECONDARY\_INDEX](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_LONG\_TERM\_STORAGE\_SLOT\_SKIPPED](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_LONG\_TERM\_STORAGE\_UNREACHABLE](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_MIN\_CONTEXT\_SLOT\_NOT\_REACHED](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_NO\_SLOT\_HISTORY](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_NO\_SNAPSHOT](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_NODE\_UNHEALTHY](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_SEND\_TRANSACTION\_PREFLIGHT\_FAILURE](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_SLOT\_NOT\_EPOCH\_BOUNDARY](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_SLOT\_SKIPPED](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_TRANSACTION\_HISTORY\_NOT\_AVAILABLE](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_TRANSACTION\_PRECOMPILE\_VERIFICATION\_FAILURE](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_TRANSACTION\_SIGNATURE\_LEN\_MISMATCH](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_TRANSACTION\_SIGNATURE\_VERIFICATION\_FAILURE](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE) \ [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_UNSUPPORTED\_TRANSACTION\_VERSION](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION) \ [SOLANA\_ERROR\_\_KEYS\_\_INVALID\_BASE58\_IN\_GRIND\_REGEX](/api/variables/SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX) \ [SOLANA\_ERROR\_\_KEYS\_\_INVALID\_KEY\_PAIR\_BYTE\_LENGTH](/api/variables/SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH) \ [SOLANA\_ERROR\_\_KEYS\_\_INVALID\_PRIVATE\_KEY\_BYTE\_LENGTH](/api/variables/SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH) \ [SOLANA\_ERROR\_\_KEYS\_\_INVALID\_SIGNATURE\_BYTE\_LENGTH](/api/variables/SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH) \ [SOLANA\_ERROR\_\_KEYS\_\_PUBLIC\_KEY\_MUST\_MATCH\_PRIVATE\_KEY](/api/variables/SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY) \ [SOLANA\_ERROR\_\_KEYS\_\_SIGNATURE\_STRING\_LENGTH\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_KEYS\_\_WRITE\_KEY\_PAIR\_UNSUPPORTED\_ENVIRONMENT](/api/variables/SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT) \ [SOLANA\_ERROR\_\_LAMPORTS\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_MALFORMED\_BIGINT\_STRING](/api/variables/SOLANA_ERROR__MALFORMED_BIGINT_STRING) \ [SOLANA\_ERROR\_\_MALFORMED\_JSON\_RPC\_ERROR](/api/variables/SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR) \ [SOLANA\_ERROR\_\_MALFORMED\_NUMBER\_STRING](/api/variables/SOLANA_ERROR__MALFORMED_NUMBER_STRING) \ [SOLANA\_ERROR\_\_NONCE\_ACCOUNT\_NOT\_FOUND](/api/variables/SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_ADDRESSES\_CANNOT\_SIGN\_OFFCHAIN\_MESSAGE](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_APPLICATION\_DOMAIN\_STRING\_LENGTH\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_CONTENT\_DOES\_NOT\_MATCH\_EXPECTED](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_ENVELOPE\_SIGNERS\_MISMATCH](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_INVALID\_APPLICATION\_DOMAIN\_BYTE\_LENGTH](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_MAXIMUM\_LENGTH\_EXCEEDED](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_MESSAGE\_FORMAT\_MISMATCH](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_MESSAGE\_LENGTH\_MISMATCH](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_MESSAGE\_MUST\_BE\_NON\_EMPTY](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_NUM\_ENVELOPE\_SIGNATURES\_CANNOT\_BE\_ZERO](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_NUM\_REQUIRED\_SIGNERS\_CANNOT\_BE\_ZERO](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_NUM\_SIGNATURES\_MISMATCH](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_REQUIRED\_SIGNATORIES\_DO\_NOT\_MATCH\_EXPECTED](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_RESTRICTED\_ASCII\_BODY\_CHARACTER\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_SIGNATORIES\_MUST\_BE\_SORTED](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_SIGNATORIES\_MUST\_BE\_UNIQUE](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_SIGNATURE\_VERIFICATION\_FAILURE](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_SIGNATURES\_MISSING](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_UNEXPECTED\_VERSION](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION) \ [SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_VERSION\_NUMBER\_NOT\_SUPPORTED](/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED) \ [SOLANA\_ERROR\_\_PROGRAM\_CLIENTS\_\_FAILED\_TO\_IDENTIFY\_ACCOUNT](/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT) \ [SOLANA\_ERROR\_\_PROGRAM\_CLIENTS\_\_FAILED\_TO\_IDENTIFY\_INSTRUCTION](/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION) \ [SOLANA\_ERROR\_\_PROGRAM\_CLIENTS\_\_INSUFFICIENT\_ACCOUNT\_METAS](/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS) \ [SOLANA\_ERROR\_\_PROGRAM\_CLIENTS\_\_RESOLVED\_INSTRUCTION\_INPUT\_MUST\_BE\_NON\_NULL](/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL) \ [SOLANA\_ERROR\_\_PROGRAM\_CLIENTS\_\_UNEXPECTED\_RESOLVED\_INSTRUCTION\_INPUT\_TYPE](/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE) \ [SOLANA\_ERROR\_\_PROGRAM\_CLIENTS\_\_UNRECOGNIZED\_ACCOUNT\_TYPE](/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE) \ [SOLANA\_ERROR\_\_PROGRAM\_CLIENTS\_\_UNRECOGNIZED\_INSTRUCTION\_TYPE](/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE) \ [SOLANA\_ERROR\_\_REACT\_\_MISSING\_CAPABILITY](/api/variables/SOLANA_ERROR__REACT__MISSING_CAPABILITY) \ [SOLANA\_ERROR\_\_REACT\_\_MISSING\_PROVIDER](/api/variables/SOLANA_ERROR__REACT__MISSING_PROVIDER) \ [SOLANA\_ERROR\_\_REACT\_\_SUBSCRIPTION\_CLOSED\_WITHOUT\_ERROR](/api/variables/SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR) \ [SOLANA\_ERROR\_\_RPC\_\_API\_PLAN\_MISSING\_FOR\_RPC\_METHOD](/api/variables/SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD) \ [SOLANA\_ERROR\_\_RPC\_\_INTEGER\_OVERFLOW](/api/variables/SOLANA_ERROR__RPC__INTEGER_OVERFLOW) \ [SOLANA\_ERROR\_\_RPC\_\_TRANSPORT\_HTTP\_ERROR](/api/variables/SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) \ [SOLANA\_ERROR\_\_RPC\_\_TRANSPORT\_HTTP\_HEADER\_FORBIDDEN](/api/variables/SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN) \ [SOLANA\_ERROR\_\_RPC\_SUBSCRIPTIONS\_\_CANNOT\_CREATE\_SUBSCRIPTION\_PLAN](/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN) \ [SOLANA\_ERROR\_\_RPC\_SUBSCRIPTIONS\_\_CHANNEL\_CLOSED\_BEFORE\_MESSAGE\_BUFFERED](/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED) \ [SOLANA\_ERROR\_\_RPC\_SUBSCRIPTIONS\_\_CHANNEL\_CONNECTION\_CLOSED](/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED) \ [SOLANA\_ERROR\_\_RPC\_SUBSCRIPTIONS\_\_CHANNEL\_FAILED\_TO\_CONNECT](/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT) \ [SOLANA\_ERROR\_\_RPC\_SUBSCRIPTIONS\_\_EXPECTED\_SERVER\_SUBSCRIPTION\_ID](/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID) \ [SOLANA\_ERROR\_\_SIGNER\_\_ADDRESS\_CANNOT\_HAVE\_MULTIPLE\_SIGNERS](/api/variables/SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS) \ [SOLANA\_ERROR\_\_SIGNER\_\_EXPECTED\_KEY\_PAIR\_SIGNER](/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER) \ [SOLANA\_ERROR\_\_SIGNER\_\_EXPECTED\_MESSAGE\_MODIFYING\_SIGNER](/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER) \ [SOLANA\_ERROR\_\_SIGNER\_\_EXPECTED\_MESSAGE\_PARTIAL\_SIGNER](/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER) \ [SOLANA\_ERROR\_\_SIGNER\_\_EXPECTED\_MESSAGE\_SIGNER](/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER) \ [SOLANA\_ERROR\_\_SIGNER\_\_EXPECTED\_TRANSACTION\_MODIFYING\_SIGNER](/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER) \ [SOLANA\_ERROR\_\_SIGNER\_\_EXPECTED\_TRANSACTION\_PARTIAL\_SIGNER](/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER) \ [SOLANA\_ERROR\_\_SIGNER\_\_EXPECTED\_TRANSACTION\_SENDING\_SIGNER](/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER) \ [SOLANA\_ERROR\_\_SIGNER\_\_EXPECTED\_TRANSACTION\_SIGNER](/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER) \ [SOLANA\_ERROR\_\_SIGNER\_\_TRANSACTION\_CANNOT\_HAVE\_MULTIPLE\_SENDING\_SIGNERS](/api/variables/SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS) \ [SOLANA\_ERROR\_\_SIGNER\_\_TRANSACTION\_SENDING\_SIGNER\_MISSING](/api/variables/SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING) \ [SOLANA\_ERROR\_\_SIGNER\_\_WALLET\_ACCOUNT\_CANNOT\_SIGN\_TRANSACTION](/api/variables/SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION) \ [SOLANA\_ERROR\_\_SIGNER\_\_WALLET\_MULTISIGN\_UNIMPLEMENTED](/api/variables/SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED) \ [SOLANA\_ERROR\_\_SUBSCRIBABLE\_\_RETRY\_NOT\_SUPPORTED](/api/variables/SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED) \ [SOLANA\_ERROR\_\_SUBSCRIBABLE\_\_STREAM\_CLOSED\_WITHOUT\_ERROR](/api/variables/SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR) \ [SOLANA\_ERROR\_\_SUBTLE\_CRYPTO\_\_CANNOT\_EXPORT\_NON\_EXTRACTABLE\_KEY](/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY) \ [SOLANA\_ERROR\_\_SUBTLE\_CRYPTO\_\_DIGEST\_UNIMPLEMENTED](/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED) \ [SOLANA\_ERROR\_\_SUBTLE\_CRYPTO\_\_DISALLOWED\_IN\_INSECURE\_CONTEXT](/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT) \ [SOLANA\_ERROR\_\_SUBTLE\_CRYPTO\_\_ED25519\_ALGORITHM\_UNIMPLEMENTED](/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED) \ [SOLANA\_ERROR\_\_SUBTLE\_CRYPTO\_\_EXPORT\_FUNCTION\_UNIMPLEMENTED](/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED) \ [SOLANA\_ERROR\_\_SUBTLE\_CRYPTO\_\_GENERATE\_FUNCTION\_UNIMPLEMENTED](/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED) \ [SOLANA\_ERROR\_\_SUBTLE\_CRYPTO\_\_SIGN\_FUNCTION\_UNIMPLEMENTED](/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED) \ [SOLANA\_ERROR\_\_SUBTLE\_CRYPTO\_\_VERIFY\_FUNCTION\_UNIMPLEMENTED](/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED) \ [SOLANA\_ERROR\_\_TIMESTAMP\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_ADDRESS\_MISSING](/api/variables/SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_ADDRESSES\_CANNOT\_SIGN\_TRANSACTION](/api/variables/SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_CANNOT\_DECODE\_EMPTY\_TRANSACTION\_BYTES](/api/variables/SOLANA_ERROR__TRANSACTION__CANNOT_DECODE_EMPTY_TRANSACTION_BYTES) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_CANNOT\_ENCODE\_WITH\_EMPTY\_MESSAGE\_BYTES](/api/variables/SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_CANNOT\_ENCODE\_WITH\_EMPTY\_SIGNATURES](/api/variables/SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_COMPUTE\_UNIT\_LIMIT\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__TRANSACTION__COMPUTE_UNIT_LIMIT_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_EXCEEDS\_SIZE\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_EXPECTED\_BLOCKHASH\_LIFETIME](/api/variables/SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_EXPECTED\_NONCE\_LIFETIME](/api/variables/SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_TO\_DECOMPILE\_ADDRESS\_LOOKUP\_TABLE\_CONTENTS\_MISSING](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_TO\_DECOMPILE\_ADDRESS\_LOOKUP\_TABLE\_INDEX\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_TO\_DECOMPILE\_FEE\_PAYER\_MISSING](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_TO\_DECOMPILE\_INSTRUCTION\_ACCOUNT\_INDEX\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_TO\_DECOMPILE\_INSTRUCTION\_PROGRAM\_ADDRESS\_NOT\_FOUND](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_TO\_ESTIMATE\_COMPUTE\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_TO\_ESTIMATE\_LOADED\_ACCOUNTS\_DATA\_SIZE\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_LOADED_ACCOUNTS_DATA_SIZE_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_WHEN\_SIMULATING\_TO\_ESTIMATE\_COMPUTE\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_WHEN\_SIMULATING\_TO\_ESTIMATE\_RESOURCE\_LIMITS](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FEE\_PAYER\_MISSING](/api/variables/SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_FEE\_PAYER\_SIGNATURE\_MISSING](/api/variables/SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_INSTRUCTION\_HEADERS\_PAYLOADS\_MISMATCH](/api/variables/SOLANA_ERROR__TRANSACTION__INSTRUCTION_HEADERS_PAYLOADS_MISMATCH) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_INVALID\_CONFIG\_MASK\_PRIORITY\_FEE\_BITS](/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_INVALID\_CONFIG\_VALUE\_KIND](/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_INVALID\_HEAP\_SIZE](/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_HEAP_SIZE) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_INVALID\_NONCE\_ACCOUNT\_INDEX](/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_INVALID\_NONCE\_TRANSACTION\_FIRST\_INSTRUCTION\_MUST\_BE\_ADVANCE\_NONCE](/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_INVALID\_NONCE\_TRANSACTION\_INSTRUCTIONS\_MISSING](/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_INVOKED\_PROGRAMS\_CANNOT\_PAY\_FEES](/api/variables/SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_INVOKED\_PROGRAMS\_MUST\_NOT\_BE\_WRITABLE](/api/variables/SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_MALFORMED\_MESSAGE\_BYTES](/api/variables/SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_MESSAGE\_SIGNATURES\_MISMATCH](/api/variables/SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_NONCE\_ACCOUNT\_CANNOT\_BE\_IN\_LOOKUP\_TABLE](/api/variables/SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_SIGNATURE\_COUNT\_TOO\_HIGH\_FOR\_TRANSACTION\_BYTES](/api/variables/SOLANA_ERROR__TRANSACTION__SIGNATURE_COUNT_TOO_HIGH_FOR_TRANSACTION_BYTES) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_SIGNATURES\_MISSING](/api/variables/SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_TOO\_MANY\_ACCOUNT\_ADDRESSES](/api/variables/SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNT_ADDRESSES) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_TOO\_MANY\_ACCOUNTS\_IN\_INSTRUCTION](/api/variables/SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNTS_IN_INSTRUCTION) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_TOO\_MANY\_INSTRUCTIONS](/api/variables/SOLANA_ERROR__TRANSACTION__TOO_MANY_INSTRUCTIONS) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_TOO\_MANY\_SIGNER\_ADDRESSES](/api/variables/SOLANA_ERROR__TRANSACTION__TOO_MANY_SIGNER_ADDRESSES) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_VERSION\_NUMBER\_NOT\_SUPPORTED](/api/variables/SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_VERSION\_NUMBER\_OUT\_OF\_RANGE](/api/variables/SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE) \ [SOLANA\_ERROR\_\_TRANSACTION\_\_VERSION\_ZERO\_MUST\_BE\_ENCODED\_WITH\_SIGNATURES\_FIRST](/api/variables/SOLANA_ERROR__TRANSACTION__VERSION_ZERO_MUST_BE_ENCODED_WITH_SIGNATURES_FIRST) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_ACCOUNT\_BORROW\_OUTSTANDING](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_ACCOUNT\_IN\_USE](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_ACCOUNT\_LOADED\_TWICE](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_ACCOUNT\_NOT\_FOUND](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_ADDRESS\_LOOKUP\_TABLE\_NOT\_FOUND](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_ALREADY\_PROCESSED](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_BLOCKHASH\_NOT\_FOUND](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_CALL\_CHAIN\_TOO\_DEEP](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_CLUSTER\_MAINTENANCE](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_DUPLICATE\_INSTRUCTION](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INSUFFICIENT\_FUNDS\_FOR\_FEE](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INSUFFICIENT\_FUNDS\_FOR\_RENT](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INVALID\_ACCOUNT\_FOR\_FEE](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INVALID\_ACCOUNT\_INDEX](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INVALID\_ADDRESS\_LOOKUP\_TABLE\_DATA](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INVALID\_ADDRESS\_LOOKUP\_TABLE\_INDEX](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INVALID\_ADDRESS\_LOOKUP\_TABLE\_OWNER](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INVALID\_LOADED\_ACCOUNTS\_DATA\_SIZE\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INVALID\_PROGRAM\_FOR\_EXECUTION](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INVALID\_RENT\_PAYING\_ACCOUNT](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_INVALID\_WRITABLE\_ACCOUNT](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_MAX\_LOADED\_ACCOUNTS\_DATA\_SIZE\_EXCEEDED](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_MISSING\_SIGNATURE\_FOR\_FEE](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_PROGRAM\_ACCOUNT\_NOT\_FOUND](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_PROGRAM\_EXECUTION\_TEMPORARILY\_RESTRICTED](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_RESANITIZATION\_NEEDED](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_SANITIZE\_FAILURE](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_SIGNATURE\_FAILURE](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_TOO\_MANY\_ACCOUNT\_LOCKS](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_UNBALANCED\_TRANSACTION](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_UNKNOWN](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_UNSUPPORTED\_VERSION](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_WOULD\_EXCEED\_ACCOUNT\_DATA\_BLOCK\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_WOULD\_EXCEED\_ACCOUNT\_DATA\_TOTAL\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_WOULD\_EXCEED\_MAX\_ACCOUNT\_COST\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_WOULD\_EXCEED\_MAX\_BLOCK\_COST\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_ERROR\_\_WOULD\_EXCEED\_MAX\_VOTE\_COST\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT) \ [SOLANA\_ERROR\_\_TRANSACTION\_INTROSPECTION\_\_CANNOT\_DECODE\_JSON\_PARSED\_TRANSACTION](/api/variables/SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION) \ [SOLANA\_ERROR\_\_TRANSACTION\_INTROSPECTION\_\_UNRECOGNIZED\_GET\_TRANSACTION\_RESPONSE](/api/variables/SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE) \ [SOLANA\_ERROR\_\_WALLET\_\_ACCOUNT\_NOT\_AVAILABLE](/api/variables/SOLANA_ERROR__WALLET__ACCOUNT_NOT_AVAILABLE) \ [SOLANA\_ERROR\_\_WALLET\_\_NO\_SIGNER\_CONNECTED](/api/variables/SOLANA_ERROR__WALLET__NO_SIGNER_CONNECTED) \ [SOLANA\_ERROR\_\_WALLET\_\_NOT\_CONNECTED](/api/variables/SOLANA_ERROR__WALLET__NOT_CONNECTED) \ [SOLANA\_ERROR\_\_WALLET\_\_SIGNER\_NOT\_AVAILABLE](/api/variables/SOLANA_ERROR__WALLET__SIGNER_NOT_AVAILABLE) ### `@solana/fixed-points`

Types (6)

[BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) \ [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) \ [FixedPointCodecConfig](/api/type-aliases/FixedPointCodecConfig) \ [FixedPointToStringOptions](/api/type-aliases/FixedPointToStringOptions) \ [RoundingMode](/api/type-aliases/RoundingMode) \ [Signedness](/api/type-aliases/Signedness)

Functions (53)

[absoluteBinaryFixedPoint](/api/functions/absoluteBinaryFixedPoint) \ [absoluteDecimalFixedPoint](/api/functions/absoluteDecimalFixedPoint) \ [addBinaryFixedPoint](/api/functions/addBinaryFixedPoint) \ [addDecimalFixedPoint](/api/functions/addDecimalFixedPoint) \ [assertIsBinaryFixedPoint](/api/functions/assertIsBinaryFixedPoint) \ [assertIsDecimalFixedPoint](/api/functions/assertIsDecimalFixedPoint) \ [binaryFixedPoint](/api/functions/binaryFixedPoint) \ [binaryFixedPointToBase10](/api/functions/binaryFixedPointToBase10) \ [binaryFixedPointToNumber](/api/functions/binaryFixedPointToNumber) \ [binaryFixedPointToString](/api/functions/binaryFixedPointToString) \ [cmpBinaryFixedPoint](/api/functions/cmpBinaryFixedPoint) \ [cmpDecimalFixedPoint](/api/functions/cmpDecimalFixedPoint) \ [decimalFixedPoint](/api/functions/decimalFixedPoint) \ [decimalFixedPointToNumber](/api/functions/decimalFixedPointToNumber) \ [decimalFixedPointToString](/api/functions/decimalFixedPointToString) \ [divideBinaryFixedPoint](/api/functions/divideBinaryFixedPoint) \ [divideDecimalFixedPoint](/api/functions/divideDecimalFixedPoint) \ [eqBinaryFixedPoint](/api/functions/eqBinaryFixedPoint) \ [eqDecimalFixedPoint](/api/functions/eqDecimalFixedPoint) \ [formatBinaryFixedPoint](/api/functions/formatBinaryFixedPoint) \ [formatDecimalFixedPoint](/api/functions/formatDecimalFixedPoint) \ [getBinaryFixedPointCodec](/api/functions/getBinaryFixedPointCodec) \ [getBinaryFixedPointDecoder](/api/functions/getBinaryFixedPointDecoder) \ [getBinaryFixedPointEncoder](/api/functions/getBinaryFixedPointEncoder) \ [getDecimalFixedPointCodec](/api/functions/getDecimalFixedPointCodec) \ [getDecimalFixedPointDecoder](/api/functions/getDecimalFixedPointDecoder) \ [getDecimalFixedPointEncoder](/api/functions/getDecimalFixedPointEncoder) \ [gtBinaryFixedPoint](/api/functions/gtBinaryFixedPoint) \ [gtDecimalFixedPoint](/api/functions/gtDecimalFixedPoint) \ [gteBinaryFixedPoint](/api/functions/gteBinaryFixedPoint) \ [gteDecimalFixedPoint](/api/functions/gteDecimalFixedPoint) \ [isBinaryFixedPoint](/api/functions/isBinaryFixedPoint) \ [isDecimalFixedPoint](/api/functions/isDecimalFixedPoint) \ [ltBinaryFixedPoint](/api/functions/ltBinaryFixedPoint) \ [ltDecimalFixedPoint](/api/functions/ltDecimalFixedPoint) \ [lteBinaryFixedPoint](/api/functions/lteBinaryFixedPoint) \ [lteDecimalFixedPoint](/api/functions/lteDecimalFixedPoint) \ [multiplyBinaryFixedPoint](/api/functions/multiplyBinaryFixedPoint) \ [multiplyDecimalFixedPoint](/api/functions/multiplyDecimalFixedPoint) \ [negateBinaryFixedPoint](/api/functions/negateBinaryFixedPoint) \ [negateDecimalFixedPoint](/api/functions/negateDecimalFixedPoint) \ [ratioBinaryFixedPoint](/api/functions/ratioBinaryFixedPoint) \ [ratioDecimalFixedPoint](/api/functions/ratioDecimalFixedPoint) \ [rawBinaryFixedPoint](/api/functions/rawBinaryFixedPoint) \ [rawDecimalFixedPoint](/api/functions/rawDecimalFixedPoint) \ [rescaleBinaryFixedPoint](/api/functions/rescaleBinaryFixedPoint) \ [rescaleDecimalFixedPoint](/api/functions/rescaleDecimalFixedPoint) \ [subtractBinaryFixedPoint](/api/functions/subtractBinaryFixedPoint) \ [subtractDecimalFixedPoint](/api/functions/subtractDecimalFixedPoint) \ [toSignedBinaryFixedPoint](/api/functions/toSignedBinaryFixedPoint) \ [toSignedDecimalFixedPoint](/api/functions/toSignedDecimalFixedPoint) \ [toUnsignedBinaryFixedPoint](/api/functions/toUnsignedBinaryFixedPoint) \ [toUnsignedDecimalFixedPoint](/api/functions/toUnsignedDecimalFixedPoint)
### `@solana/functional`

Functions (1)

[pipe](/api/functions/pipe)
### `@solana/instruction-plans`

Types (27)

[CanceledSingleTransactionPlanResult](/api/type-aliases/CanceledSingleTransactionPlanResult) \ [FailedSingleTransactionPlanResult](/api/type-aliases/FailedSingleTransactionPlanResult) \ [InstructionPlan](/api/type-aliases/InstructionPlan) \ [InstructionPlanInput](/api/type-aliases/InstructionPlanInput) \ [MessagePacker](/api/type-aliases/MessagePacker) \ [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) \ [ParallelInstructionPlan](/api/type-aliases/ParallelInstructionPlan) \ [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan) \ [ParallelTransactionPlanResult](/api/type-aliases/ParallelTransactionPlanResult) \ [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) \ [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) \ [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) \ [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan) \ [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan) \ [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) \ [SuccessfulSingleTransactionPlanResult](/api/type-aliases/SuccessfulSingleTransactionPlanResult) \ [SuccessfulTransactionPlanResult](/api/type-aliases/SuccessfulTransactionPlanResult) \ [TransactionPlan](/api/type-aliases/TransactionPlan) \ [TransactionPlanExecutor](/api/type-aliases/TransactionPlanExecutor) \ [TransactionPlanExecutorConfig](/api/type-aliases/TransactionPlanExecutorConfig) \ [TransactionPlanInput](/api/type-aliases/TransactionPlanInput) \ [TransactionPlanner](/api/type-aliases/TransactionPlanner) \ [TransactionPlannerConfig](/api/type-aliases/TransactionPlannerConfig) \ [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) \ [TransactionPlanResultContext](/api/type-aliases/TransactionPlanResultContext) \ [TransactionPlanResultContextWithSignature](/api/type-aliases/TransactionPlanResultContextWithSignature) \ [TransactionPlanResultSummary](/api/type-aliases/TransactionPlanResultSummary)

Functions (81)

[appendTransactionMessageInstructionPlan](/api/functions/appendTransactionMessageInstructionPlan) \ [assertIsCanceledSingleTransactionPlanResult](/api/functions/assertIsCanceledSingleTransactionPlanResult) \ [assertIsFailedSingleTransactionPlanResult](/api/functions/assertIsFailedSingleTransactionPlanResult) \ [assertIsMessagePackerInstructionPlan](/api/functions/assertIsMessagePackerInstructionPlan) \ [assertIsNonDivisibleSequentialInstructionPlan](/api/functions/assertIsNonDivisibleSequentialInstructionPlan) \ [assertIsNonDivisibleSequentialTransactionPlan](/api/functions/assertIsNonDivisibleSequentialTransactionPlan) \ [assertIsNonDivisibleSequentialTransactionPlanResult](/api/functions/assertIsNonDivisibleSequentialTransactionPlanResult) \ [assertIsParallelInstructionPlan](/api/functions/assertIsParallelInstructionPlan) \ [assertIsParallelTransactionPlan](/api/functions/assertIsParallelTransactionPlan) \ [assertIsParallelTransactionPlanResult](/api/functions/assertIsParallelTransactionPlanResult) \ [assertIsSequentialInstructionPlan](/api/functions/assertIsSequentialInstructionPlan) \ [assertIsSequentialTransactionPlan](/api/functions/assertIsSequentialTransactionPlan) \ [assertIsSequentialTransactionPlanResult](/api/functions/assertIsSequentialTransactionPlanResult) \ [assertIsSingleInstructionPlan](/api/functions/assertIsSingleInstructionPlan) \ [assertIsSingleTransactionPlan](/api/functions/assertIsSingleTransactionPlan) \ [assertIsSingleTransactionPlanResult](/api/functions/assertIsSingleTransactionPlanResult) \ [assertIsSuccessfulSingleTransactionPlanResult](/api/functions/assertIsSuccessfulSingleTransactionPlanResult) \ [assertIsSuccessfulTransactionPlanResult](/api/functions/assertIsSuccessfulTransactionPlanResult) \ [canceledSingleTransactionPlanResult](/api/functions/canceledSingleTransactionPlanResult) \ [createFailedToExecuteTransactionPlanError](/api/functions/createFailedToExecuteTransactionPlanError) \ [createFailedToSendTransactionError](/api/functions/createFailedToSendTransactionError) \ [createFailedToSendTransactionsError](/api/functions/createFailedToSendTransactionsError) \ [createFailedToSignTransactionError](/api/functions/createFailedToSignTransactionError) \ [createFailedToSignTransactionsError](/api/functions/createFailedToSignTransactionsError) \ [createTransactionPlanExecutor](/api/functions/createTransactionPlanExecutor) \ [createTransactionPlanExecutorWithConcurrentLeaves](/api/functions/createTransactionPlanExecutorWithConcurrentLeaves) \ [createTransactionPlanner](/api/functions/createTransactionPlanner) \ [everyInstructionPlan](/api/functions/everyInstructionPlan) \ [everyTransactionPlan](/api/functions/everyTransactionPlan) \ [everyTransactionPlanResult](/api/functions/everyTransactionPlanResult) \ [failedSingleTransactionPlanResult](/api/functions/failedSingleTransactionPlanResult) \ [findInstructionPlan](/api/functions/findInstructionPlan) \ [findTransactionPlan](/api/functions/findTransactionPlan) \ [findTransactionPlanResult](/api/functions/findTransactionPlanResult) \ [flattenInstructionPlan](/api/functions/flattenInstructionPlan) \ [flattenTransactionPlan](/api/functions/flattenTransactionPlan) \ [flattenTransactionPlanResult](/api/functions/flattenTransactionPlanResult) \ [getFirstFailedSingleTransactionPlanResult](/api/functions/getFirstFailedSingleTransactionPlanResult) \ [getLinearMessagePackerInstructionPlan](/api/functions/getLinearMessagePackerInstructionPlan) \ [getMessagePackerInstructionPlanFromInstructions](/api/functions/getMessagePackerInstructionPlanFromInstructions) \ [getReallocMessagePackerInstructionPlan](/api/functions/getReallocMessagePackerInstructionPlan) \ [isCanceledSingleTransactionPlanResult](/api/functions/isCanceledSingleTransactionPlanResult) \ [isFailedSingleTransactionPlanResult](/api/functions/isFailedSingleTransactionPlanResult) \ [isInstructionPlan](/api/functions/isInstructionPlan) \ [isMessagePackerInstructionPlan](/api/functions/isMessagePackerInstructionPlan) \ [isNonDivisibleSequentialInstructionPlan](/api/functions/isNonDivisibleSequentialInstructionPlan) \ [isNonDivisibleSequentialTransactionPlan](/api/functions/isNonDivisibleSequentialTransactionPlan) \ [isNonDivisibleSequentialTransactionPlanResult](/api/functions/isNonDivisibleSequentialTransactionPlanResult) \ [isParallelInstructionPlan](/api/functions/isParallelInstructionPlan) \ [isParallelTransactionPlan](/api/functions/isParallelTransactionPlan) \ [isParallelTransactionPlanResult](/api/functions/isParallelTransactionPlanResult) \ [isSequentialInstructionPlan](/api/functions/isSequentialInstructionPlan) \ [isSequentialTransactionPlan](/api/functions/isSequentialTransactionPlan) \ [isSequentialTransactionPlanResult](/api/functions/isSequentialTransactionPlanResult) \ [isSingleInstructionPlan](/api/functions/isSingleInstructionPlan) \ [isSingleTransactionPlan](/api/functions/isSingleTransactionPlan) \ [isSingleTransactionPlanResult](/api/functions/isSingleTransactionPlanResult) \ [isSuccessfulSingleTransactionPlanResult](/api/functions/isSuccessfulSingleTransactionPlanResult) \ [isSuccessfulTransactionPlanResult](/api/functions/isSuccessfulTransactionPlanResult) \ [isTransactionPlan](/api/functions/isTransactionPlan) \ [isTransactionPlanResult](/api/functions/isTransactionPlanResult) \ [nonDivisibleSequentialInstructionPlan](/api/functions/nonDivisibleSequentialInstructionPlan) \ [nonDivisibleSequentialTransactionPlan](/api/functions/nonDivisibleSequentialTransactionPlan) \ [nonDivisibleSequentialTransactionPlanResult](/api/functions/nonDivisibleSequentialTransactionPlanResult) \ [parallelInstructionPlan](/api/functions/parallelInstructionPlan) \ [parallelTransactionPlan](/api/functions/parallelTransactionPlan) \ [parallelTransactionPlanResult](/api/functions/parallelTransactionPlanResult) \ [parseInstructionOrTransactionPlanInput](/api/functions/parseInstructionOrTransactionPlanInput) \ [parseInstructionPlanInput](/api/functions/parseInstructionPlanInput) \ [parseTransactionPlanInput](/api/functions/parseTransactionPlanInput) \ [passthroughFailedTransactionPlanExecution](/api/functions/passthroughFailedTransactionPlanExecution) \ [sequentialInstructionPlan](/api/functions/sequentialInstructionPlan) \ [sequentialTransactionPlan](/api/functions/sequentialTransactionPlan) \ [sequentialTransactionPlanResult](/api/functions/sequentialTransactionPlanResult) \ [singleInstructionPlan](/api/functions/singleInstructionPlan) \ [singleTransactionPlan](/api/functions/singleTransactionPlan) \ [successfulSingleTransactionPlanResult](/api/functions/successfulSingleTransactionPlanResult) \ [summarizeTransactionPlanResult](/api/functions/summarizeTransactionPlanResult) \ [transformInstructionPlan](/api/functions/transformInstructionPlan) \ [transformTransactionPlan](/api/functions/transformTransactionPlan) \ [transformTransactionPlanResult](/api/functions/transformTransactionPlanResult)
### `@solana/instructions`

Enums (1)

[AccountRole](/api/enumerations/AccountRole)

Types (11)

[AccountLookupMeta](/api/interfaces/AccountLookupMeta) \ [AccountMeta](/api/interfaces/AccountMeta) \ [Instruction](/api/interfaces/Instruction) \ [InstructionWithAccounts](/api/interfaces/InstructionWithAccounts) \ [InstructionWithData](/api/interfaces/InstructionWithData) \ [ReadonlyAccount](/api/type-aliases/ReadonlyAccount) \ [ReadonlyAccountLookup](/api/type-aliases/ReadonlyAccountLookup) \ [ReadonlySignerAccount](/api/type-aliases/ReadonlySignerAccount) \ [WritableAccount](/api/type-aliases/WritableAccount) \ [WritableAccountLookup](/api/type-aliases/WritableAccountLookup) \ [WritableSignerAccount](/api/type-aliases/WritableSignerAccount)

Functions (13)

[assertIsInstructionForProgram](/api/functions/assertIsInstructionForProgram) \ [assertIsInstructionWithAccounts](/api/functions/assertIsInstructionWithAccounts) \ [assertIsInstructionWithData](/api/functions/assertIsInstructionWithData) \ [downgradeRoleToNonSigner](/api/functions/downgradeRoleToNonSigner) \ [downgradeRoleToReadonly](/api/functions/downgradeRoleToReadonly) \ [isInstructionForProgram](/api/functions/isInstructionForProgram) \ [isInstructionWithAccounts](/api/functions/isInstructionWithAccounts) \ [isInstructionWithData](/api/functions/isInstructionWithData) \ [isSignerRole](/api/functions/isSignerRole) \ [isWritableRole](/api/functions/isWritableRole) \ [mergeRoles](/api/functions/mergeRoles) \ [upgradeRoleToSigner](/api/functions/upgradeRoleToSigner) \ [upgradeRoleToWritable](/api/functions/upgradeRoleToWritable)
### `@solana/keys`

Types (5)

[GrindKeyPairMatches](/api/type-aliases/GrindKeyPairMatches) \ [GrindKeyPairsConfig](/api/type-aliases/GrindKeyPairsConfig) \ [Signature](/api/type-aliases/Signature) \ [SignatureBytes](/api/type-aliases/SignatureBytes) \ [WriteKeyPairConfig](/api/type-aliases/WriteKeyPairConfig)

Functions (16)

[assertIsSignature](/api/functions/assertIsSignature) \ [assertIsSignatureBytes](/api/functions/assertIsSignatureBytes) \ [createKeyPairFromBytes](/api/functions/createKeyPairFromBytes) \ [createKeyPairFromPrivateKeyBytes](/api/functions/createKeyPairFromPrivateKeyBytes) \ [createPrivateKeyFromBytes](/api/functions/createPrivateKeyFromBytes) \ [generateKeyPair](/api/functions/generateKeyPair) \ [getPublicKeyFromPrivateKey](/api/functions/getPublicKeyFromPrivateKey) \ [grindKeyPair](/api/functions/grindKeyPair) \ [grindKeyPairs](/api/functions/grindKeyPairs) \ [isSignature](/api/functions/isSignature) \ [isSignatureBytes](/api/functions/isSignatureBytes) \ [signature](/api/functions/signature) \ [signatureBytes](/api/functions/signatureBytes) \ [signBytes](/api/functions/signBytes) \ [verifySignature](/api/functions/verifySignature) \ [writeKeyPair](/api/functions/writeKeyPair)
### `@solana/nominal-types`

Types (5)

[AffinePoint](/api/type-aliases/AffinePoint) \ [Brand](/api/type-aliases/Brand) \ [CompressedData](/api/type-aliases/CompressedData) \ [EncodedString](/api/type-aliases/EncodedString) \ [NominalType](/api/type-aliases/NominalType)
### `@solana/offchain-messages`

Enums (1)

[OffchainMessageContentFormat](/api/enumerations/OffchainMessageContentFormat)

Types (20)

[BaseOffchainMessageV0](/api/type-aliases/BaseOffchainMessageV0) \ [BaseOffchainMessageV1](/api/type-aliases/BaseOffchainMessageV1) \ [FullySignedOffchainMessageEnvelope](/api/type-aliases/FullySignedOffchainMessageEnvelope) \ [OffchainMessage](/api/type-aliases/OffchainMessage) \ [OffchainMessageApplicationDomain](/api/type-aliases/OffchainMessageApplicationDomain) \ [OffchainMessageBytes](/api/type-aliases/OffchainMessageBytes) \ [OffchainMessageContent](/api/type-aliases/OffchainMessageContent) \ [OffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) \ [OffchainMessageContentUtf8Of1232BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of1232BytesMax) \ [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) \ [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope) \ [OffchainMessageSignatory](/api/type-aliases/OffchainMessageSignatory) \ [OffchainMessageV0](/api/type-aliases/OffchainMessageV0) \ [OffchainMessageV1](/api/type-aliases/OffchainMessageV1) \ [OffchainMessageVersion](/api/type-aliases/OffchainMessageVersion) \ [OffchainMessageWithContent](/api/type-aliases/OffchainMessageWithContent) \ [OffchainMessageWithRequiredSignatories](/api/interfaces/OffchainMessageWithRequiredSignatories) \ [OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent](/api/interfaces/OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent) \ [OffchainMessageWithUtf8Of1232BytesMaxContent](/api/interfaces/OffchainMessageWithUtf8Of1232BytesMaxContent) \ [OffchainMessageWithUtf8Of65535BytesMaxContent](/api/interfaces/OffchainMessageWithUtf8Of65535BytesMaxContent)

Functions (39)

[assertIsFullySignedOffchainMessageEnvelope](/api/functions/assertIsFullySignedOffchainMessageEnvelope) \ [assertIsOffchainMessageApplicationDomain](/api/functions/assertIsOffchainMessageApplicationDomain) \ [assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/functions/assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax) \ [assertIsOffchainMessageContentUtf8Of1232BytesMax](/api/functions/assertIsOffchainMessageContentUtf8Of1232BytesMax) \ [assertIsOffchainMessageContentUtf8Of65535BytesMax](/api/functions/assertIsOffchainMessageContentUtf8Of65535BytesMax) \ [assertIsOffchainMessageRestrictedAsciiOf1232BytesMax](/api/functions/assertIsOffchainMessageRestrictedAsciiOf1232BytesMax) \ [assertIsOffchainMessageUtf8Of1232BytesMax](/api/functions/assertIsOffchainMessageUtf8Of1232BytesMax) \ [assertIsOffchainMessageUtf8Of65535BytesMax](/api/functions/assertIsOffchainMessageUtf8Of65535BytesMax) \ [assertOffchainMessageV1Equal](/api/functions/assertOffchainMessageV1Equal) \ [compileOffchainMessageEnvelope](/api/functions/compileOffchainMessageEnvelope) \ [compileOffchainMessageV0Envelope](/api/functions/compileOffchainMessageV0Envelope) \ [compileOffchainMessageV1Envelope](/api/functions/compileOffchainMessageV1Envelope) \ [getOffchainMessageApplicationDomainCodec](/api/functions/getOffchainMessageApplicationDomainCodec) \ [getOffchainMessageApplicationDomainDecoder](/api/functions/getOffchainMessageApplicationDomainDecoder) \ [getOffchainMessageApplicationDomainEncoder](/api/functions/getOffchainMessageApplicationDomainEncoder) \ [getOffchainMessageCodec](/api/functions/getOffchainMessageCodec) \ [getOffchainMessageDecoder](/api/functions/getOffchainMessageDecoder) \ [getOffchainMessageEncoder](/api/functions/getOffchainMessageEncoder) \ [getOffchainMessageEnvelopeCodec](/api/functions/getOffchainMessageEnvelopeCodec) \ [getOffchainMessageEnvelopeDecoder](/api/functions/getOffchainMessageEnvelopeDecoder) \ [getOffchainMessageEnvelopeEncoder](/api/functions/getOffchainMessageEnvelopeEncoder) \ [getOffchainMessageV0Codec](/api/functions/getOffchainMessageV0Codec) \ [getOffchainMessageV0Decoder](/api/functions/getOffchainMessageV0Decoder) \ [getOffchainMessageV0Encoder](/api/functions/getOffchainMessageV0Encoder) \ [getOffchainMessageV1Codec](/api/functions/getOffchainMessageV1Codec) \ [getOffchainMessageV1Decoder](/api/functions/getOffchainMessageV1Decoder) \ [getOffchainMessageV1Encoder](/api/functions/getOffchainMessageV1Encoder) \ [isFullySignedOffchainMessageEnvelope](/api/functions/isFullySignedOffchainMessageEnvelope) \ [isOffchainMessageApplicationDomain](/api/functions/isOffchainMessageApplicationDomain) \ [isOffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/functions/isOffchainMessageContentRestrictedAsciiOf1232BytesMax) \ [isOffchainMessageContentUtf8Of1232BytesMax](/api/functions/isOffchainMessageContentUtf8Of1232BytesMax) \ [isOffchainMessageContentUtf8Of65535BytesMax](/api/functions/isOffchainMessageContentUtf8Of65535BytesMax) \ [offchainMessageApplicationDomain](/api/functions/offchainMessageApplicationDomain) \ [offchainMessageContentRestrictedAsciiOf1232BytesMax](/api/functions/offchainMessageContentRestrictedAsciiOf1232BytesMax) \ [offchainMessageContentUtf8Of1232BytesMax](/api/functions/offchainMessageContentUtf8Of1232BytesMax) \ [offchainMessageContentUtf8Of65535BytesMax](/api/functions/offchainMessageContentUtf8Of65535BytesMax) \ [partiallySignOffchainMessageEnvelope](/api/functions/partiallySignOffchainMessageEnvelope) \ [signOffchainMessageEnvelope](/api/functions/signOffchainMessageEnvelope) \ [verifyOffchainMessageEnvelope](/api/functions/verifyOffchainMessageEnvelope)
### `@solana/options`

Types (6)

[None](/api/type-aliases/None) \ [Option](/api/type-aliases/Option) \ [OptionCodecConfig](/api/type-aliases/OptionCodecConfig) \ [OptionOrNullable](/api/type-aliases/OptionOrNullable) \ [Some](/api/type-aliases/Some) \ [UnwrappedOption](/api/type-aliases/UnwrappedOption)

Functions (11)

[getOptionCodec](/api/functions/getOptionCodec) \ [getOptionDecoder](/api/functions/getOptionDecoder) \ [getOptionEncoder](/api/functions/getOptionEncoder) \ [isNone](/api/functions/isNone) \ [isOption](/api/functions/isOption) \ [isSome](/api/functions/isSome) \ [none](/api/functions/none) \ [some](/api/functions/some) \ [unwrapOption](/api/functions/unwrapOption) \ [unwrapOptionRecursively](/api/functions/unwrapOptionRecursively) \ [wrapNullable](/api/functions/wrapNullable)
### `@solana/plugin-core`

Types (4)

[AsyncClient](/api/type-aliases/AsyncClient) \ [Client](/api/type-aliases/Client) \ [ClientPlugin](/api/type-aliases/ClientPlugin) \ [ExtendedClient](/api/type-aliases/ExtendedClient)

Functions (3)

[createClient](/api/functions/createClient) \ [extendClient](/api/functions/extendClient) \ [withCleanup](/api/functions/withCleanup)
### `@solana/plugin-interfaces`

Types (14)

[ClientWithAirdrop](/api/type-aliases/ClientWithAirdrop) \ [ClientWithFetchAccounts](/api/type-aliases/ClientWithFetchAccounts) \ [ClientWithGetMinimumBalance](/api/type-aliases/ClientWithGetMinimumBalance) \ [ClientWithIdentity](/api/type-aliases/ClientWithIdentity) \ [ClientWithPayer](/api/type-aliases/ClientWithPayer) \ [ClientWithRpc](/api/type-aliases/ClientWithRpc) \ [ClientWithRpcSubscriptions](/api/type-aliases/ClientWithRpcSubscriptions) \ [ClientWithSubscribeToIdentity](/api/type-aliases/ClientWithSubscribeToIdentity) \ [ClientWithSubscribeToPayer](/api/type-aliases/ClientWithSubscribeToPayer) \ [ClientWithTransactionPlanning](/api/type-aliases/ClientWithTransactionPlanning) \ [ClientWithTransactionSending](/api/type-aliases/ClientWithTransactionSending) \ [ClientWithTransactionSigning](/api/type-aliases/ClientWithTransactionSigning) \ [GetMinimumBalanceConfig](/api/type-aliases/GetMinimumBalanceConfig) \ [SubscribeToFn](/api/type-aliases/SubscribeToFn)
### `@solana/program-client-core`

Types (4)

[InstructionWithByteDelta](/api/type-aliases/InstructionWithByteDelta) \ [ResolvedInstructionAccount](/api/type-aliases/ResolvedInstructionAccount) \ [SelfFetchFunctions](/api/type-aliases/SelfFetchFunctions) \ [SelfPlanAndSendFunctions](/api/type-aliases/SelfPlanAndSendFunctions)

Functions (7)

[addSelfFetchFunctions](/api/functions/addSelfFetchFunctions) \ [addSelfPlanAndSendFunctions](/api/functions/addSelfPlanAndSendFunctions) \ [getAccountMetaFactory](/api/functions/getAccountMetaFactory) \ [getAddressFromResolvedInstructionAccount](/api/functions/getAddressFromResolvedInstructionAccount) \ [getNonNullResolvedInstructionInput](/api/functions/getNonNullResolvedInstructionInput) \ [getResolvedInstructionAccountAsProgramDerivedAddress](/api/functions/getResolvedInstructionAccountAsProgramDerivedAddress) \ [getResolvedInstructionAccountAsTransactionSigner](/api/functions/getResolvedInstructionAccountAsTransactionSigner)
### `@solana/programs`

Functions (1)

[isProgramError](/api/functions/isProgramError)
### `@solana/promises`

Functions (3)

[getAbortablePromise](/api/functions/getAbortablePromise) \ [isAbortError](/api/functions/isAbortError) \ [safeRace](/api/functions/safeRace)
### `@solana/react`

Types (13)

[ActionResult](/api/type-aliases/ActionResult) \ [ClientProviderProps](/api/type-aliases/ClientProviderProps) \ [RequestResult](/api/type-aliases/RequestResult) \ [SelectedWalletAccountContextProviderProps](/api/type-aliases/SelectedWalletAccountContextProviderProps) \ [SelectedWalletAccountContextValue](/api/type-aliases/SelectedWalletAccountContextValue) \ [SelectedWalletAccountState](/api/type-aliases/SelectedWalletAccountState) \ [SubscriptionResult](/api/type-aliases/SubscriptionResult) \ [TrackedDataResult](/api/type-aliases/TrackedDataResult) \ [TrackedDataSpec](/api/type-aliases/TrackedDataSpec) \ [UseClientCapabilityConfig](/api/type-aliases/UseClientCapabilityConfig) \ [UseRequestOptions](/api/type-aliases/UseRequestOptions) \ [UseSubscriptionOptions](/api/type-aliases/UseSubscriptionOptions) \ [UseTrackedDataOptions](/api/type-aliases/UseTrackedDataOptions)

Functions (25)

[ClientProvider](/api/functions/ClientProvider) \ [SelectedWalletAccountContextProvider](/api/functions/SelectedWalletAccountContextProvider) \ [useAction](/api/functions/useAction) \ [useAirdrop](/api/functions/useAirdrop) \ [useClient](/api/functions/useClient) \ [useClientCapability](/api/functions/useClientCapability) \ [useIdentity](/api/functions/useIdentity) \ [usePayer](/api/functions/usePayer) \ [usePlanTransaction](/api/functions/usePlanTransaction) \ [usePlanTransactions](/api/functions/usePlanTransactions) \ [useRequest](/api/functions/useRequest) \ [useSelectedWalletAccount](/api/functions/useSelectedWalletAccount) \ [useSendTransaction](/api/functions/useSendTransaction) \ [useSendTransactions](/api/functions/useSendTransactions) \ [useSignAndSendTransaction](/api/functions/useSignAndSendTransaction) \ [useSignAndSendTransactions](/api/functions/useSignAndSendTransactions) \ [useSignIn](/api/functions/useSignIn) \ [useSignMessage](/api/functions/useSignMessage) \ [useSignTransaction](/api/functions/useSignTransaction) \ [useSignTransactions](/api/functions/useSignTransactions) \ [useSubscription](/api/functions/useSubscription) \ [useTrackedData](/api/functions/useTrackedData) \ [useWalletAccountMessageSigner](/api/functions/useWalletAccountMessageSigner) \ [useWalletAccountTransactionSendingSigner](/api/functions/useWalletAccountTransactionSendingSigner) \ [useWalletAccountTransactionSigner](/api/functions/useWalletAccountTransactionSigner)

Variables (2)

[ClientContext](/api/variables/ClientContext) \ [SelectedWalletAccountContext](/api/variables/SelectedWalletAccountContext)
### `@solana/rpc`

Packages (2)

[@solana/rpc-api](#solanarpc-api) \ [@solana/rpc-spec](#solanarpc-spec)

Types (10)

[RpcDevnet](/api/type-aliases/RpcDevnet) \ [RpcFromTransport](/api/type-aliases/RpcFromTransport) \ [RpcMainnet](/api/type-aliases/RpcMainnet) \ [RpcTestnet](/api/type-aliases/RpcTestnet) \ [RpcTransportDevnet](/api/type-aliases/RpcTransportDevnet) \ [RpcTransportFromClusterUrl](/api/type-aliases/RpcTransportFromClusterUrl) \ [RpcTransportMainnet](/api/type-aliases/RpcTransportMainnet) \ [RpcTransportTestnet](/api/type-aliases/RpcTransportTestnet) \ [SolanaRpcApiFromClusterUrl](/api/type-aliases/SolanaRpcApiFromClusterUrl) \ [SolanaRpcApiFromTransport](/api/type-aliases/SolanaRpcApiFromTransport)

Functions (3)

[createDefaultRpcTransport](/api/functions/createDefaultRpcTransport) \ [createSolanaRpc](/api/functions/createSolanaRpc) \ [createSolanaRpcFromTransport](/api/functions/createSolanaRpcFromTransport)

Variables (1)

[DEFAULT\_RPC\_CONFIG](/api/variables/DEFAULT_RPC_CONFIG)
### `@solana/rpc-api`

Types (62)

[GetAccountInfoApi](/api/type-aliases/GetAccountInfoApi) \ [GetAgGenesisCertApi](/api/type-aliases/GetAgGenesisCertApi) \ [GetBalanceApi](/api/type-aliases/GetBalanceApi) \ [GetBlockApi](/api/type-aliases/GetBlockApi) \ [GetBlockCommitmentApi](/api/type-aliases/GetBlockCommitmentApi) \ [GetBlockHeightApi](/api/type-aliases/GetBlockHeightApi) \ [GetBlockProductionApi](/api/type-aliases/GetBlockProductionApi) \ [GetBlocksApi](/api/type-aliases/GetBlocksApi) \ [GetBlocksWithLimitApi](/api/type-aliases/GetBlocksWithLimitApi) \ [GetBlockTimeApi](/api/type-aliases/GetBlockTimeApi) \ [GetClusterNodesApi](/api/type-aliases/GetClusterNodesApi) \ [GetEpochInfoApi](/api/type-aliases/GetEpochInfoApi) \ [GetEpochScheduleApi](/api/type-aliases/GetEpochScheduleApi) \ [GetFeeForMessageApi](/api/type-aliases/GetFeeForMessageApi) \ [GetFirstAvailableBlockApi](/api/type-aliases/GetFirstAvailableBlockApi) \ [GetGenesisHashApi](/api/type-aliases/GetGenesisHashApi) \ [GetHealthApi](/api/type-aliases/GetHealthApi) \ [GetHighestSnapshotSlotApi](/api/type-aliases/GetHighestSnapshotSlotApi) \ [GetIdentityApi](/api/type-aliases/GetIdentityApi) \ [GetInflationGovernorApi](/api/type-aliases/GetInflationGovernorApi) \ [GetInflationRateApi](/api/type-aliases/GetInflationRateApi) \ [GetInflationRewardApi](/api/type-aliases/GetInflationRewardApi) \ [GetLargestAccountsApi](/api/type-aliases/GetLargestAccountsApi) \ [GetLatestBlockhashApi](/api/type-aliases/GetLatestBlockhashApi) \ [GetLeaderScheduleApi](/api/type-aliases/GetLeaderScheduleApi) \ [GetMaxRetransmitSlotApi](/api/type-aliases/GetMaxRetransmitSlotApi) \ [GetMaxShredInsertSlotApi](/api/type-aliases/GetMaxShredInsertSlotApi) \ [GetMinimumBalanceForRentExemptionApi](/api/type-aliases/GetMinimumBalanceForRentExemptionApi) \ [GetMultipleAccountsApi](/api/type-aliases/GetMultipleAccountsApi) \ [GetProgramAccountsApi](/api/type-aliases/GetProgramAccountsApi) \ [GetRecentPerformanceSamplesApi](/api/type-aliases/GetRecentPerformanceSamplesApi) \ [GetRecentPrioritizationFeesApi](/api/type-aliases/GetRecentPrioritizationFeesApi) \ [GetSignaturesForAddressApi](/api/type-aliases/GetSignaturesForAddressApi) \ [GetSignatureStatusesApi](/api/type-aliases/GetSignatureStatusesApi) \ [GetSlotApi](/api/type-aliases/GetSlotApi) \ [GetSlotLeaderApi](/api/type-aliases/GetSlotLeaderApi) \ [GetSlotLeadersApi](/api/type-aliases/GetSlotLeadersApi) \ [GetStakeMinimumDelegationApi](/api/type-aliases/GetStakeMinimumDelegationApi) \ [GetSupplyApi](/api/type-aliases/GetSupplyApi) \ [GetTokenAccountBalanceApi](/api/type-aliases/GetTokenAccountBalanceApi) \ [GetTokenAccountsByDelegateApi](/api/type-aliases/GetTokenAccountsByDelegateApi) \ [GetTokenAccountsByOwnerApi](/api/type-aliases/GetTokenAccountsByOwnerApi) \ [GetTokenLargestAccountsApi](/api/type-aliases/GetTokenLargestAccountsApi) \ [GetTokenSupplyApi](/api/type-aliases/GetTokenSupplyApi) \ [GetTransactionApi](/api/type-aliases/GetTransactionApi) \ [GetTransactionApiResponseBase58](/api/type-aliases/GetTransactionApiResponseBase58) \ [GetTransactionApiResponseBase64](/api/type-aliases/GetTransactionApiResponseBase64) \ [GetTransactionApiResponseJson](/api/type-aliases/GetTransactionApiResponseJson) \ [GetTransactionApiResponseJsonParsed](/api/type-aliases/GetTransactionApiResponseJsonParsed) \ [GetTransactionCountApi](/api/type-aliases/GetTransactionCountApi) \ [GetTransactionsForAddressApi](/api/type-aliases/GetTransactionsForAddressApi) \ [GetVersionApi](/api/type-aliases/GetVersionApi) \ [GetVoteAccountsApi](/api/type-aliases/GetVoteAccountsApi) \ [IsBlockhashValidApi](/api/type-aliases/IsBlockhashValidApi) \ [MinimumLedgerSlotApi](/api/type-aliases/MinimumLedgerSlotApi) \ [RequestAirdropApi](/api/type-aliases/RequestAirdropApi) \ [SendTransactionApi](/api/type-aliases/SendTransactionApi) \ [SimulateTransactionApi](/api/type-aliases/SimulateTransactionApi) \ [SolanaRpcApi](/api/type-aliases/SolanaRpcApi) \ [SolanaRpcApiDevnet](/api/type-aliases/SolanaRpcApiDevnet) \ [SolanaRpcApiMainnet](/api/type-aliases/SolanaRpcApiMainnet) \ [SolanaRpcApiTestnet](/api/type-aliases/SolanaRpcApiTestnet)

Functions (1)

[createSolanaRpcApi](/api/functions/createSolanaRpcApi)
### `@solana/rpc-parsed-types`

Types (11)

[JsonParsedAddressLookupTableAccount](/api/type-aliases/JsonParsedAddressLookupTableAccount) \ [JsonParsedBpfUpgradeableLoaderProgramAccount](/api/type-aliases/JsonParsedBpfUpgradeableLoaderProgramAccount) \ [JsonParsedConfigProgramAccount](/api/type-aliases/JsonParsedConfigProgramAccount) \ [JsonParsedNonceAccount](/api/type-aliases/JsonParsedNonceAccount) \ [JsonParsedStakeProgramAccount](/api/type-aliases/JsonParsedStakeProgramAccount) \ [JsonParsedSysvarAccount](/api/type-aliases/JsonParsedSysvarAccount) \ [JsonParsedTokenAccount](/api/type-aliases/JsonParsedTokenAccount) \ [JsonParsedTokenProgramAccount](/api/type-aliases/JsonParsedTokenProgramAccount) \ [JsonParsedVoteAccount](/api/type-aliases/JsonParsedVoteAccount) \ [RpcParsedInfo](/api/type-aliases/RpcParsedInfo) \ [RpcParsedType](/api/type-aliases/RpcParsedType)
### `@solana/rpc-spec`

Types (8)

[PendingRpcRequest](/api/type-aliases/PendingRpcRequest) \ [Rpc](/api/type-aliases/Rpc) \ [RpcApi](/api/type-aliases/RpcApi) \ [RpcApiConfig](/api/type-aliases/RpcApiConfig) \ [RpcConfig](/api/type-aliases/RpcConfig) \ [RpcPlan](/api/type-aliases/RpcPlan) \ [RpcSendOptions](/api/type-aliases/RpcSendOptions) \ [RpcTransport](/api/type-aliases/RpcTransport)

Functions (3)

[createJsonRpcApi](/api/functions/createJsonRpcApi) \ [createRpc](/api/functions/createRpc) \ [isJsonRpcPayload](/api/functions/isJsonRpcPayload)
### `@solana/rpc-spec-types`

Types (10)

[Callable](/api/type-aliases/Callable) \ [Flatten](/api/type-aliases/Flatten) \ [OverloadImplementations](/api/type-aliases/OverloadImplementations) \ [Overloads](/api/type-aliases/Overloads) \ [RpcRequest](/api/type-aliases/RpcRequest) \ [RpcRequestTransformer](/api/type-aliases/RpcRequestTransformer) \ [RpcResponse](/api/type-aliases/RpcResponse) \ [RpcResponseData](/api/type-aliases/RpcResponseData) \ [RpcResponseTransformer](/api/type-aliases/RpcResponseTransformer) \ [UnionToIntersection](/api/type-aliases/UnionToIntersection)

Functions (3)

[createRpcMessage](/api/functions/createRpcMessage) \ [parseJsonWithBigInts](/api/functions/parseJsonWithBigInts) \ [stringifyJsonWithBigInts](/api/functions/stringifyJsonWithBigInts)
### `@solana/rpc-subscriptions`

Packages (2)

[@solana/rpc-subscriptions-api](#solanarpc-subscriptions-api) \ [@solana/rpc-subscriptions-spec](#solanarpc-subscriptions-spec)

Types (21)

[DefaultRpcSubscriptionsChannelConfig](/api/type-aliases/DefaultRpcSubscriptionsChannelConfig) \ [DefaultRpcSubscriptionsTransportConfig](/api/type-aliases/DefaultRpcSubscriptionsTransportConfig) \ [RpcSubscriptionsChannelCreatorDevnet](/api/type-aliases/RpcSubscriptionsChannelCreatorDevnet) \ [RpcSubscriptionsChannelCreatorFromClusterUrl](/api/type-aliases/RpcSubscriptionsChannelCreatorFromClusterUrl) \ [RpcSubscriptionsChannelCreatorMainnet](/api/type-aliases/RpcSubscriptionsChannelCreatorMainnet) \ [RpcSubscriptionsChannelCreatorTestnet](/api/type-aliases/RpcSubscriptionsChannelCreatorTestnet) \ [RpcSubscriptionsChannelCreatorWithCluster](/api/type-aliases/RpcSubscriptionsChannelCreatorWithCluster) \ [RpcSubscriptionsChannelDevnet](/api/type-aliases/RpcSubscriptionsChannelDevnet) \ [RpcSubscriptionsChannelFromClusterUrl](/api/type-aliases/RpcSubscriptionsChannelFromClusterUrl) \ [RpcSubscriptionsChannelMainnet](/api/type-aliases/RpcSubscriptionsChannelMainnet) \ [RpcSubscriptionsChannelTestnet](/api/type-aliases/RpcSubscriptionsChannelTestnet) \ [RpcSubscriptionsChannelWithCluster](/api/type-aliases/RpcSubscriptionsChannelWithCluster) \ [RpcSubscriptionsDevnet](/api/type-aliases/RpcSubscriptionsDevnet) \ [RpcSubscriptionsFromTransport](/api/type-aliases/RpcSubscriptionsFromTransport) \ [RpcSubscriptionsMainnet](/api/type-aliases/RpcSubscriptionsMainnet) \ [RpcSubscriptionsTestnet](/api/type-aliases/RpcSubscriptionsTestnet) \ [RpcSubscriptionsTransportDevnet](/api/type-aliases/RpcSubscriptionsTransportDevnet) \ [RpcSubscriptionsTransportFromClusterUrl](/api/type-aliases/RpcSubscriptionsTransportFromClusterUrl) \ [RpcSubscriptionsTransportMainnet](/api/type-aliases/RpcSubscriptionsTransportMainnet) \ [RpcSubscriptionsTransportTestnet](/api/type-aliases/RpcSubscriptionsTransportTestnet) \ [RpcSubscriptionsTransportWithCluster](/api/type-aliases/RpcSubscriptionsTransportWithCluster)

Functions (12)

[createDefaultRpcSubscriptionsChannelCreator](/api/functions/createDefaultRpcSubscriptionsChannelCreator) \ [createDefaultRpcSubscriptionsTransport](/api/functions/createDefaultRpcSubscriptionsTransport) \ [createDefaultSolanaRpcSubscriptionsChannelCreator](/api/functions/createDefaultSolanaRpcSubscriptionsChannelCreator) \ [createRpcSubscriptionsTransportFromChannelCreator](/api/functions/createRpcSubscriptionsTransportFromChannelCreator) \ [createSolanaRpcSubscriptions](/api/functions/createSolanaRpcSubscriptions) \ [createSolanaRpcSubscriptions\_UNSTABLE](/api/functions/createSolanaRpcSubscriptions_UNSTABLE) \ [createSolanaRpcSubscriptionsFromTransport](/api/functions/createSolanaRpcSubscriptionsFromTransport) \ [getChannelPoolingChannelCreator](/api/functions/getChannelPoolingChannelCreator) \ [getRpcSubscriptionsChannelWithAutoping](/api/functions/getRpcSubscriptionsChannelWithAutoping) \ [getRpcSubscriptionsChannelWithBigIntJSONSerialization](/api/functions/getRpcSubscriptionsChannelWithBigIntJSONSerialization) \ [getRpcSubscriptionsChannelWithJSONSerialization](/api/functions/getRpcSubscriptionsChannelWithJSONSerialization) \ [getRpcSubscriptionsTransportWithSubscriptionCoalescing](/api/functions/getRpcSubscriptionsTransportWithSubscriptionCoalescing)

Variables (1)

[DEFAULT\_RPC\_SUBSCRIPTIONS\_CONFIG](/api/variables/DEFAULT_RPC_SUBSCRIPTIONS_CONFIG)
### `@solana/rpc-subscriptions-api`

Types (11)

[AccountNotificationsApi](/api/type-aliases/AccountNotificationsApi) \ [BlockNotificationsApi](/api/type-aliases/BlockNotificationsApi) \ [LogsNotificationsApi](/api/type-aliases/LogsNotificationsApi) \ [ProgramNotificationsApi](/api/type-aliases/ProgramNotificationsApi) \ [RootNotificationsApi](/api/type-aliases/RootNotificationsApi) \ [SignatureNotificationsApi](/api/type-aliases/SignatureNotificationsApi) \ [SlotNotificationsApi](/api/type-aliases/SlotNotificationsApi) \ [SlotsUpdatesNotificationsApi](/api/type-aliases/SlotsUpdatesNotificationsApi) \ [SolanaRpcSubscriptionsApi](/api/type-aliases/SolanaRpcSubscriptionsApi) \ [SolanaRpcSubscriptionsApiUnstable](/api/type-aliases/SolanaRpcSubscriptionsApiUnstable) \ [VoteNotificationsApi](/api/type-aliases/VoteNotificationsApi)

Functions (2)

[createSolanaRpcSubscriptionsApi](/api/functions/createSolanaRpcSubscriptionsApi) \ [createSolanaRpcSubscriptionsApi\_UNSTABLE](/api/functions/createSolanaRpcSubscriptionsApi_UNSTABLE)
### `@solana/rpc-subscriptions-channel-websocket`

Types (1)

[Config](/api/type-aliases/Config)

Functions (1)

[createWebSocketChannel](/api/functions/createWebSocketChannel)
### `@solana/rpc-subscriptions-spec`

Types (13)

[PendingRpcSubscriptionsRequest](/api/type-aliases/PendingRpcSubscriptionsRequest) \ [RpcSubscribeOptions](/api/type-aliases/RpcSubscribeOptions) \ [RpcSubscriptionChannelEvents](/api/type-aliases/RpcSubscriptionChannelEvents) \ [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) \ [RpcSubscriptionsApi](/api/type-aliases/RpcSubscriptionsApi) \ [RpcSubscriptionsApiConfig](/api/type-aliases/RpcSubscriptionsApiConfig) \ [RpcSubscriptionsApiMethods](/api/interfaces/RpcSubscriptionsApiMethods) \ [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel) \ [RpcSubscriptionsChannelCreator](/api/type-aliases/RpcSubscriptionsChannelCreator) \ [RpcSubscriptionsConfig](/api/type-aliases/RpcSubscriptionsConfig) \ [RpcSubscriptionsPlan](/api/type-aliases/RpcSubscriptionsPlan) \ [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport) \ [RpcSubscriptionsTransportDataEvents](/api/type-aliases/RpcSubscriptionsTransportDataEvents)

Functions (5)

[createRpcSubscriptionsApi](/api/functions/createRpcSubscriptionsApi) \ [createSubscriptionRpc](/api/functions/createSubscriptionRpc) \ [executeRpcPubSubSubscriptionPlan](/api/functions/executeRpcPubSubSubscriptionPlan) \ [transformChannelInboundMessages](/api/functions/transformChannelInboundMessages) \ [transformChannelOutboundMessages](/api/functions/transformChannelOutboundMessages)
### `@solana/rpc-transformers`

Types (7)

[AllowedNumericKeypaths](/api/type-aliases/AllowedNumericKeypaths) \ [IntegerOverflowHandler](/api/type-aliases/IntegerOverflowHandler) \ [KeyPath](/api/type-aliases/KeyPath) \ [KeyPathWildcard](/api/type-aliases/KeyPathWildcard) \ [RequestTransformerConfig](/api/type-aliases/RequestTransformerConfig) \ [ResponseTransformerConfig](/api/type-aliases/ResponseTransformerConfig) \ [TraversalState](/api/type-aliases/TraversalState)

Functions (10)

[getBigIntUpcastResponseTransformer](/api/functions/getBigIntUpcastResponseTransformer) \ [getDefaultCommitmentRequestTransformer](/api/functions/getDefaultCommitmentRequestTransformer) \ [getDefaultRequestTransformerForSolanaRpc](/api/functions/getDefaultRequestTransformerForSolanaRpc) \ [getDefaultResponseTransformerForSolanaRpc](/api/functions/getDefaultResponseTransformerForSolanaRpc) \ [getDefaultResponseTransformerForSolanaRpcSubscriptions](/api/functions/getDefaultResponseTransformerForSolanaRpcSubscriptions) \ [getIntegerOverflowRequestTransformer](/api/functions/getIntegerOverflowRequestTransformer) \ [getResultResponseTransformer](/api/functions/getResultResponseTransformer) \ [getThrowSolanaErrorResponseTransformer](/api/functions/getThrowSolanaErrorResponseTransformer) \ [getTreeWalkerRequestTransformer](/api/functions/getTreeWalkerRequestTransformer) \ [getTreeWalkerResponseTransformer](/api/functions/getTreeWalkerResponseTransformer)

Variables (6)

[innerInstructionsConfigs](/api/variables/innerInstructionsConfigs) \ [jsonParsedAccountsConfigs](/api/variables/jsonParsedAccountsConfigs) \ [jsonParsedTokenAccountsConfigs](/api/variables/jsonParsedTokenAccountsConfigs) \ [KEYPATH\_WILDCARD](/api/variables/KEYPATH_WILDCARD) \ [messageConfig](/api/variables/messageConfig) \ [tokenBalancesConfigs](/api/variables/tokenBalancesConfigs)
### `@solana/rpc-transport-http`

Functions (2)

[createHttpTransport](/api/functions/createHttpTransport) \ [createHttpTransportForSolanaRpc](/api/functions/createHttpTransportForSolanaRpc)
### `@solana/rpc-types`

Types (47)

[AccountInfoBase](/api/type-aliases/AccountInfoBase) \ [AccountInfoWithBase58Bytes](/api/type-aliases/AccountInfoWithBase58Bytes) \ [AccountInfoWithBase58EncodedData](/api/type-aliases/AccountInfoWithBase58EncodedData) \ [AccountInfoWithBase64EncodedData](/api/type-aliases/AccountInfoWithBase64EncodedData) \ [AccountInfoWithBase64EncodedZStdCompressedData](/api/type-aliases/AccountInfoWithBase64EncodedZStdCompressedData) \ [AccountInfoWithJsonData](/api/type-aliases/AccountInfoWithJsonData) \ [AccountInfoWithPubkey](/api/type-aliases/AccountInfoWithPubkey) \ [Base58EncodedBytes](/api/type-aliases/Base58EncodedBytes) \ [Base58EncodedDataResponse](/api/type-aliases/Base58EncodedDataResponse) \ [Base64EncodedBytes](/api/type-aliases/Base64EncodedBytes) \ [Base64EncodedDataResponse](/api/type-aliases/Base64EncodedDataResponse) \ [Base64EncodedZStdCompressedBytes](/api/type-aliases/Base64EncodedZStdCompressedBytes) \ [Base64EncodedZStdCompressedDataResponse](/api/type-aliases/Base64EncodedZStdCompressedDataResponse) \ [Blockhash](/api/type-aliases/Blockhash) \ [ClusterUrl](/api/type-aliases/ClusterUrl) \ [Commitment](/api/type-aliases/Commitment) \ [DataSlice](/api/type-aliases/DataSlice) \ [DevnetUrl](/api/type-aliases/DevnetUrl) \ [Epoch](/api/type-aliases/Epoch) \ [F64UnsafeSeeDocumentation](/api/type-aliases/F64UnsafeSeeDocumentation) \ [GetProgramAccountsDatasizeFilter](/api/type-aliases/GetProgramAccountsDatasizeFilter) \ [GetProgramAccountsMemcmpFilter](/api/type-aliases/GetProgramAccountsMemcmpFilter) \ [Lamports](/api/type-aliases/Lamports) \ [MainnetUrl](/api/type-aliases/MainnetUrl) \ [MicroLamports](/api/type-aliases/MicroLamports) \ [Reward](/api/type-aliases/Reward) \ [SignedLamports](/api/type-aliases/SignedLamports) \ [Slot](/api/type-aliases/Slot) \ [Sol](/api/type-aliases/Sol) \ [SolanaRpcResponse](/api/type-aliases/SolanaRpcResponse) \ [StringifiedBigInt](/api/type-aliases/StringifiedBigInt) \ [StringifiedNumber](/api/type-aliases/StringifiedNumber) \ [TestnetUrl](/api/type-aliases/TestnetUrl) \ [TokenAmount](/api/type-aliases/TokenAmount) \ [TokenBalance](/api/type-aliases/TokenBalance) \ [TransactionConfig](/api/type-aliases/TransactionConfig) \ [TransactionError](/api/type-aliases/TransactionError) \ [TransactionForAccounts](/api/type-aliases/TransactionForAccounts) \ [TransactionForFullBase58](/api/type-aliases/TransactionForFullBase58) \ [TransactionForFullBase64](/api/type-aliases/TransactionForFullBase64) \ [TransactionForFullJson](/api/type-aliases/TransactionForFullJson) \ [TransactionForFullJsonParsed](/api/type-aliases/TransactionForFullJsonParsed) \ [TransactionForFullMetaInnerInstructionsParsed](/api/type-aliases/TransactionForFullMetaInnerInstructionsParsed) \ [TransactionForFullMetaInnerInstructionsUnparsed](/api/type-aliases/TransactionForFullMetaInnerInstructionsUnparsed) \ [TransactionStatus](/api/type-aliases/TransactionStatus) \ [UnixTimestamp](/api/type-aliases/UnixTimestamp) \ [UnwrapRpcResponse](/api/type-aliases/UnwrapRpcResponse)

Functions (36)

[assertIsBlockhash](/api/functions/assertIsBlockhash) \ [assertIsLamports](/api/functions/assertIsLamports) \ [assertIsStringifiedBigInt](/api/functions/assertIsStringifiedBigInt) \ [assertIsStringifiedNumber](/api/functions/assertIsStringifiedNumber) \ [assertIsUnixTimestamp](/api/functions/assertIsUnixTimestamp) \ [blockhash](/api/functions/blockhash) \ [commitmentComparator](/api/functions/commitmentComparator) \ [devnet](/api/functions/devnet) \ [getBlockhashCodec](/api/functions/getBlockhashCodec) \ [getBlockhashComparator](/api/functions/getBlockhashComparator) \ [getBlockhashDecoder](/api/functions/getBlockhashDecoder) \ [getBlockhashEncoder](/api/functions/getBlockhashEncoder) \ [getDefaultLamportsCodec](/api/functions/getDefaultLamportsCodec) \ [getDefaultLamportsDecoder](/api/functions/getDefaultLamportsDecoder) \ [getDefaultLamportsEncoder](/api/functions/getDefaultLamportsEncoder) \ [getLamportsCodec](/api/functions/getLamportsCodec) \ [getLamportsDecoder](/api/functions/getLamportsDecoder) \ [getLamportsEncoder](/api/functions/getLamportsEncoder) \ [getSolCodec](/api/functions/getSolCodec) \ [getSolDecoder](/api/functions/getSolDecoder) \ [getSolEncoder](/api/functions/getSolEncoder) \ [isBlockhash](/api/functions/isBlockhash) \ [isLamports](/api/functions/isLamports) \ [isSolanaRpcResponse](/api/functions/isSolanaRpcResponse) \ [isStringifiedBigInt](/api/functions/isStringifiedBigInt) \ [isStringifiedNumber](/api/functions/isStringifiedNumber) \ [isUnixTimestamp](/api/functions/isUnixTimestamp) \ [lamports](/api/functions/lamports) \ [lamportsToSol](/api/functions/lamportsToSol) \ [mainnet](/api/functions/mainnet) \ [sol](/api/functions/sol) \ [solToLamports](/api/functions/solToLamports) \ [stringifiedBigInt](/api/functions/stringifiedBigInt) \ [stringifiedNumber](/api/functions/stringifiedNumber) \ [testnet](/api/functions/testnet) \ [unixTimestamp](/api/functions/unixTimestamp)
### `@solana/signers`

Packages (1)

[@solana/keys](#solanakeys)

Types (24)

[AccountSignerMeta](/api/interfaces/AccountSignerMeta) \ [BaseSignerConfig](/api/type-aliases/BaseSignerConfig) \ [BaseTransactionSignerConfig](/api/interfaces/BaseTransactionSignerConfig) \ [InstructionWithSigners](/api/interfaces/InstructionWithSigners) \ [KeyPairSigner](/api/type-aliases/KeyPairSigner) \ [MessageModifyingSigner](/api/type-aliases/MessageModifyingSigner) \ [MessageModifyingSignerConfig](/api/type-aliases/MessageModifyingSignerConfig) \ [MessagePartialSigner](/api/type-aliases/MessagePartialSigner) \ [MessagePartialSignerConfig](/api/type-aliases/MessagePartialSignerConfig) \ [MessageSigner](/api/type-aliases/MessageSigner) \ [NoopSigner](/api/type-aliases/NoopSigner) \ [OffchainMessageSignatorySigner](/api/type-aliases/OffchainMessageSignatorySigner) \ [SignableMessage](/api/type-aliases/SignableMessage) \ [SignatureDictionary](/api/type-aliases/SignatureDictionary) \ [TransactionMessageWithFeePayerSigner](/api/interfaces/TransactionMessageWithFeePayerSigner) \ [TransactionMessageWithSigners](/api/type-aliases/TransactionMessageWithSigners) \ [TransactionMessageWithSingleSendingSigner](/api/type-aliases/TransactionMessageWithSingleSendingSigner) \ [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) \ [TransactionModifyingSignerConfig](/api/type-aliases/TransactionModifyingSignerConfig) \ [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner) \ [TransactionPartialSignerConfig](/api/type-aliases/TransactionPartialSignerConfig) \ [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) \ [TransactionSendingSignerConfig](/api/type-aliases/TransactionSendingSignerConfig) \ [TransactionSigner](/api/type-aliases/TransactionSigner)

Functions (42)

[addSignersToInstruction](/api/functions/addSignersToInstruction) \ [addSignersToTransactionMessage](/api/functions/addSignersToTransactionMessage) \ [assertContainsResolvableTransactionSendingSigner](/api/functions/assertContainsResolvableTransactionSendingSigner) \ [assertIsKeyPairSigner](/api/functions/assertIsKeyPairSigner) \ [assertIsMessageModifyingSigner](/api/functions/assertIsMessageModifyingSigner) \ [assertIsMessagePartialSigner](/api/functions/assertIsMessagePartialSigner) \ [assertIsMessageSigner](/api/functions/assertIsMessageSigner) \ [assertIsTransactionMessageWithSingleSendingSigner](/api/functions/assertIsTransactionMessageWithSingleSendingSigner) \ [assertIsTransactionModifyingSigner](/api/functions/assertIsTransactionModifyingSigner) \ [assertIsTransactionPartialSigner](/api/functions/assertIsTransactionPartialSigner) \ [assertIsTransactionSendingSigner](/api/functions/assertIsTransactionSendingSigner) \ [assertIsTransactionSigner](/api/functions/assertIsTransactionSigner) \ [createKeyPairSignerFromBytes](/api/functions/createKeyPairSignerFromBytes) \ [createKeyPairSignerFromPrivateKeyBytes](/api/functions/createKeyPairSignerFromPrivateKeyBytes) \ [createNoopSigner](/api/functions/createNoopSigner) \ [createSignableMessage](/api/functions/createSignableMessage) \ [createSignerFromKeyPair](/api/functions/createSignerFromKeyPair) \ [generateKeyPairSigner](/api/functions/generateKeyPairSigner) \ [getSignersFromInstruction](/api/functions/getSignersFromInstruction) \ [getSignersFromOffchainMessage](/api/functions/getSignersFromOffchainMessage) \ [getSignersFromTransactionMessage](/api/functions/getSignersFromTransactionMessage) \ [grindKeyPairSigner](/api/functions/grindKeyPairSigner) \ [grindKeyPairSigners](/api/functions/grindKeyPairSigners) \ [isKeyPairSigner](/api/functions/isKeyPairSigner) \ [isMessageModifyingSigner](/api/functions/isMessageModifyingSigner) \ [isMessagePartialSigner](/api/functions/isMessagePartialSigner) \ [isMessageSigner](/api/functions/isMessageSigner) \ [isTransactionMessageWithSingleSendingSigner](/api/functions/isTransactionMessageWithSingleSendingSigner) \ [isTransactionModifyingSigner](/api/functions/isTransactionModifyingSigner) \ [isTransactionPartialSigner](/api/functions/isTransactionPartialSigner) \ [isTransactionSendingSigner](/api/functions/isTransactionSendingSigner) \ [isTransactionSigner](/api/functions/isTransactionSigner) \ [partiallySignOffchainMessageWithSigners](/api/functions/partiallySignOffchainMessageWithSigners) \ [partiallySignTransactionMessageWithSigners](/api/functions/partiallySignTransactionMessageWithSigners) \ [partiallySignTransactionWithSigners](/api/functions/partiallySignTransactionWithSigners) \ [setTransactionMessageFeePayerSigner](/api/functions/setTransactionMessageFeePayerSigner) \ [signAndSendTransactionMessageWithSigners](/api/functions/signAndSendTransactionMessageWithSigners) \ [signAndSendTransactionWithSigners](/api/functions/signAndSendTransactionWithSigners) \ [signOffchainMessageWithSigners](/api/functions/signOffchainMessageWithSigners) \ [signTransactionMessageWithSigners](/api/functions/signTransactionMessageWithSigners) \ [signTransactionWithSigners](/api/functions/signTransactionWithSigners) \ [writeKeyPairSigner](/api/functions/writeKeyPairSigner)
### `@solana/subscribable`

Types (10)

[DataPublisher](/api/interfaces/DataPublisher) \ [ReactiveActionSource](/api/type-aliases/ReactiveActionSource) \ [ReactiveActionState](/api/type-aliases/ReactiveActionState) \ [ReactiveActionStatus](/api/type-aliases/ReactiveActionStatus) \ [ReactiveActionStore](/api/type-aliases/ReactiveActionStore) \ [ReactiveState](/api/type-aliases/ReactiveState) \ [ReactiveStreamSource](/api/type-aliases/ReactiveStreamSource) \ [ReactiveStreamStore](/api/type-aliases/ReactiveStreamStore) \ [TypedEventEmitter](/api/interfaces/TypedEventEmitter) \ [TypedEventTarget](/api/interfaces/TypedEventTarget)

Functions (6)

[bridgeStoreToAsyncIterable](/api/functions/bridgeStoreToAsyncIterable) \ [createAsyncIterableFromDataPublisher](/api/functions/createAsyncIterableFromDataPublisher) \ [createReactiveActionStore](/api/functions/createReactiveActionStore) \ [createReactiveStoreFromDataPublisherFactory](/api/functions/createReactiveStoreFromDataPublisherFactory) \ [demultiplexDataPublisher](/api/functions/demultiplexDataPublisher) \ [getDataPublisherFromEventEmitter](/api/functions/getDataPublisherFromEventEmitter)
### `@solana/sysvars`

Types (9)

[SysvarClock](/api/type-aliases/SysvarClock) \ [SysvarEpochRewards](/api/type-aliases/SysvarEpochRewards) \ [SysvarEpochSchedule](/api/type-aliases/SysvarEpochSchedule) \ [SysvarLastRestartSlot](/api/type-aliases/SysvarLastRestartSlot) \ [SysvarRecentBlockhashes](/api/type-aliases/SysvarRecentBlockhashes) \ [SysvarRent](/api/type-aliases/SysvarRent) \ [SysvarSlotHashes](/api/type-aliases/SysvarSlotHashes) \ [SysvarSlotHistory](/api/type-aliases/SysvarSlotHistory) \ [SysvarStakeHistory](/api/type-aliases/SysvarStakeHistory)

Functions (38)

[fetchEncodedSysvarAccount](/api/functions/fetchEncodedSysvarAccount) \ [fetchJsonParsedSysvarAccount](/api/functions/fetchJsonParsedSysvarAccount) \ [fetchSysvarClock](/api/functions/fetchSysvarClock) \ [fetchSysvarEpochRewards](/api/functions/fetchSysvarEpochRewards) \ [fetchSysvarEpochSchedule](/api/functions/fetchSysvarEpochSchedule) \ [fetchSysvarLastRestartSlot](/api/functions/fetchSysvarLastRestartSlot) \ [fetchSysvarRecentBlockhashes](/api/functions/fetchSysvarRecentBlockhashes) \ [fetchSysvarRent](/api/functions/fetchSysvarRent) \ [fetchSysvarSlotHashes](/api/functions/fetchSysvarSlotHashes) \ [fetchSysvarSlotHistory](/api/functions/fetchSysvarSlotHistory) \ [fetchSysvarStakeHistory](/api/functions/fetchSysvarStakeHistory) \ [getSysvarClockCodec](/api/functions/getSysvarClockCodec) \ [getSysvarClockDecoder](/api/functions/getSysvarClockDecoder) \ [getSysvarClockEncoder](/api/functions/getSysvarClockEncoder) \ [getSysvarEpochRewardsCodec](/api/functions/getSysvarEpochRewardsCodec) \ [getSysvarEpochRewardsDecoder](/api/functions/getSysvarEpochRewardsDecoder) \ [getSysvarEpochRewardsEncoder](/api/functions/getSysvarEpochRewardsEncoder) \ [getSysvarEpochScheduleCodec](/api/functions/getSysvarEpochScheduleCodec) \ [getSysvarEpochScheduleDecoder](/api/functions/getSysvarEpochScheduleDecoder) \ [getSysvarEpochScheduleEncoder](/api/functions/getSysvarEpochScheduleEncoder) \ [getSysvarLastRestartSlotCodec](/api/functions/getSysvarLastRestartSlotCodec) \ [getSysvarLastRestartSlotDecoder](/api/functions/getSysvarLastRestartSlotDecoder) \ [getSysvarLastRestartSlotEncoder](/api/functions/getSysvarLastRestartSlotEncoder) \ [getSysvarRecentBlockhashesCodec](/api/functions/getSysvarRecentBlockhashesCodec) \ [getSysvarRecentBlockhashesDecoder](/api/functions/getSysvarRecentBlockhashesDecoder) \ [getSysvarRecentBlockhashesEncoder](/api/functions/getSysvarRecentBlockhashesEncoder) \ [getSysvarRentCodec](/api/functions/getSysvarRentCodec) \ [getSysvarRentDecoder](/api/functions/getSysvarRentDecoder) \ [getSysvarRentEncoder](/api/functions/getSysvarRentEncoder) \ [getSysvarSlotHashesCodec](/api/functions/getSysvarSlotHashesCodec) \ [getSysvarSlotHashesDecoder](/api/functions/getSysvarSlotHashesDecoder) \ [getSysvarSlotHashesEncoder](/api/functions/getSysvarSlotHashesEncoder) \ [getSysvarSlotHistoryCodec](/api/functions/getSysvarSlotHistoryCodec) \ [getSysvarSlotHistoryDecoder](/api/functions/getSysvarSlotHistoryDecoder) \ [getSysvarSlotHistoryEncoder](/api/functions/getSysvarSlotHistoryEncoder) \ [getSysvarStakeHistoryCodec](/api/functions/getSysvarStakeHistoryCodec) \ [getSysvarStakeHistoryDecoder](/api/functions/getSysvarStakeHistoryDecoder) \ [getSysvarStakeHistoryEncoder](/api/functions/getSysvarStakeHistoryEncoder)

Variables (10)

[SYSVAR\_CLOCK\_ADDRESS](/api/variables/SYSVAR_CLOCK_ADDRESS) \ [SYSVAR\_EPOCH\_REWARDS\_ADDRESS](/api/variables/SYSVAR_EPOCH_REWARDS_ADDRESS) \ [SYSVAR\_EPOCH\_SCHEDULE\_ADDRESS](/api/variables/SYSVAR_EPOCH_SCHEDULE_ADDRESS) \ [SYSVAR\_INSTRUCTIONS\_ADDRESS](/api/variables/SYSVAR_INSTRUCTIONS_ADDRESS) \ [SYSVAR\_LAST\_RESTART\_SLOT\_ADDRESS](/api/variables/SYSVAR_LAST_RESTART_SLOT_ADDRESS) \ [SYSVAR\_RECENT\_BLOCKHASHES\_ADDRESS](/api/variables/SYSVAR_RECENT_BLOCKHASHES_ADDRESS) \ [SYSVAR\_RENT\_ADDRESS](/api/variables/SYSVAR_RENT_ADDRESS) \ [SYSVAR\_SLOT\_HASHES\_ADDRESS](/api/variables/SYSVAR_SLOT_HASHES_ADDRESS) \ [SYSVAR\_SLOT\_HISTORY\_ADDRESS](/api/variables/SYSVAR_SLOT_HISTORY_ADDRESS) \ [SYSVAR\_STAKE\_HISTORY\_ADDRESS](/api/variables/SYSVAR_STAKE_HISTORY_ADDRESS)
### `@solana/transaction-confirmation`

Types (1)

[TransactionWithLastValidBlockHeight](/api/type-aliases/TransactionWithLastValidBlockHeight)

Functions (7)

[createBlockHeightExceedencePromiseFactory](/api/functions/createBlockHeightExceedencePromiseFactory) \ [createNonceInvalidationPromiseFactory](/api/functions/createNonceInvalidationPromiseFactory) \ [createRecentSignatureConfirmationPromiseFactory](/api/functions/createRecentSignatureConfirmationPromiseFactory) \ [getTimeoutPromise](/api/functions/getTimeoutPromise) \ [waitForDurableNonceTransactionConfirmation](/api/functions/waitForDurableNonceTransactionConfirmation) \ [waitForRecentTransactionConfirmation](/api/functions/waitForRecentTransactionConfirmation) \ [waitForRecentTransactionConfirmationUntilTimeout](/api/functions/waitForRecentTransactionConfirmationUntilTimeout)
### `@solana/transaction-introspection`

Types (6)

[DecodedRpcTransaction](/api/type-aliases/DecodedRpcTransaction) \ [InstructionTrace](/api/type-aliases/InstructionTrace) \ [LoadedAddresses](/api/type-aliases/LoadedAddresses) \ [MetaWithInnerInstructions](/api/type-aliases/MetaWithInnerInstructions) \ [ResolvedInstruction](/api/type-aliases/ResolvedInstruction) \ [TracedInstruction](/api/type-aliases/TracedInstruction)

Functions (5)

[decodeTransactionFromRpcResponse](/api/functions/decodeTransactionFromRpcResponse) \ [getAccountMetasFromCompiledTransactionMessage](/api/functions/getAccountMetasFromCompiledTransactionMessage) \ [getInnerInstructionsFromMeta](/api/functions/getInnerInstructionsFromMeta) \ [getInstructionsFromCompiledTransactionMessage](/api/functions/getInstructionsFromCompiledTransactionMessage) \ [walkInstructions](/api/functions/walkInstructions)
### `@solana/transaction-messages`

Types (21)

[AddressesByLookupTableAddress](/api/type-aliases/AddressesByLookupTableAddress) \ [BlockhashLifetimeConstraint](/api/type-aliases/BlockhashLifetimeConstraint) \ [CompiledTransactionMessage](/api/type-aliases/CompiledTransactionMessage) \ [CompiledTransactionMessageWithLifetime](/api/type-aliases/CompiledTransactionMessageWithLifetime) \ [DecompileTransactionMessageConfig](/api/type-aliases/DecompileTransactionMessageConfig) \ [ExcludeTransactionMessageDurableNonceLifetime](/api/type-aliases/ExcludeTransactionMessageDurableNonceLifetime) \ [ExcludeTransactionMessageLifetime](/api/type-aliases/ExcludeTransactionMessageLifetime) \ [ExcludeTransactionMessageWithinSizeLimit](/api/type-aliases/ExcludeTransactionMessageWithinSizeLimit) \ [LegacyCompiledTransactionMessage](/api/type-aliases/LegacyCompiledTransactionMessage) \ [Nonce](/api/type-aliases/Nonce) \ [NonceLifetimeConstraint](/api/type-aliases/NonceLifetimeConstraint) \ [TransactionMessage](/api/type-aliases/TransactionMessage) \ [TransactionMessageWithBlockhashLifetime](/api/interfaces/TransactionMessageWithBlockhashLifetime) \ [TransactionMessageWithDurableNonceLifetime](/api/interfaces/TransactionMessageWithDurableNonceLifetime) \ [TransactionMessageWithFeePayer](/api/interfaces/TransactionMessageWithFeePayer) \ [TransactionMessageWithinSizeLimit](/api/type-aliases/TransactionMessageWithinSizeLimit) \ [TransactionMessageWithLifetime](/api/type-aliases/TransactionMessageWithLifetime) \ [TransactionVersion](/api/type-aliases/TransactionVersion) \ [V0CompiledTransactionMessage](/api/type-aliases/V0CompiledTransactionMessage) \ [V1CompiledTransactionMessage](/api/type-aliases/V1CompiledTransactionMessage) \ [V1TransactionConfig](/api/type-aliases/V1TransactionConfig)

Functions (39)

[appendTransactionMessageInstruction](/api/functions/appendTransactionMessageInstruction) \ [appendTransactionMessageInstructions](/api/functions/appendTransactionMessageInstructions) \ [areV1ConfigsEqual](/api/functions/areV1ConfigsEqual) \ [assertIsTransactionMessageWithBlockhashLifetime](/api/functions/assertIsTransactionMessageWithBlockhashLifetime) \ [assertIsTransactionMessageWithDurableNonceLifetime](/api/functions/assertIsTransactionMessageWithDurableNonceLifetime) \ [compileTransactionMessage](/api/functions/compileTransactionMessage) \ [compressTransactionMessageUsingAddressLookupTables](/api/functions/compressTransactionMessageUsingAddressLookupTables) \ [createTransactionMessage](/api/functions/createTransactionMessage) \ [decompileTransactionMessage](/api/functions/decompileTransactionMessage) \ [getCompiledTransactionMessageCodec](/api/functions/getCompiledTransactionMessageCodec) \ [getCompiledTransactionMessageDecoder](/api/functions/getCompiledTransactionMessageDecoder) \ [getCompiledTransactionMessageEncoder](/api/functions/getCompiledTransactionMessageEncoder) \ [getTransactionMessageComputeUnitLimit](/api/functions/getTransactionMessageComputeUnitLimit) \ [getTransactionMessageComputeUnitPrice](/api/functions/getTransactionMessageComputeUnitPrice) \ [getTransactionMessageHeapSize](/api/functions/getTransactionMessageHeapSize) \ [getTransactionMessageLoadedAccountsDataSizeLimit](/api/functions/getTransactionMessageLoadedAccountsDataSizeLimit) \ [getTransactionMessagePriorityFeeLamports](/api/functions/getTransactionMessagePriorityFeeLamports) \ [getTransactionVersionCodec](/api/functions/getTransactionVersionCodec) \ [getTransactionVersionDecoder](/api/functions/getTransactionVersionDecoder) \ [getTransactionVersionEncoder](/api/functions/getTransactionVersionEncoder) \ [isAdvanceNonceAccountInstruction](/api/functions/isAdvanceNonceAccountInstruction) \ [isTransactionMessageWithBlockhashLifetime](/api/functions/isTransactionMessageWithBlockhashLifetime) \ [isTransactionMessageWithDurableNonceLifetime](/api/functions/isTransactionMessageWithDurableNonceLifetime) \ [isV1ConfigEmpty](/api/functions/isV1ConfigEmpty) \ [prependTransactionMessageInstruction](/api/functions/prependTransactionMessageInstruction) \ [prependTransactionMessageInstructions](/api/functions/prependTransactionMessageInstructions) \ [setTransactionMessageComputeUnitLimit](/api/functions/setTransactionMessageComputeUnitLimit) \ [setTransactionMessageComputeUnitPrice](/api/functions/setTransactionMessageComputeUnitPrice) \ [setTransactionMessageConfig](/api/functions/setTransactionMessageConfig) \ [setTransactionMessageFeePayer](/api/functions/setTransactionMessageFeePayer) \ [setTransactionMessageHeapSize](/api/functions/setTransactionMessageHeapSize) \ [setTransactionMessageLifetimeUsingBlockhash](/api/functions/setTransactionMessageLifetimeUsingBlockhash) \ [setTransactionMessageLifetimeUsingDurableNonce](/api/functions/setTransactionMessageLifetimeUsingDurableNonce) \ [setTransactionMessageLoadedAccountsDataSizeLimit](/api/functions/setTransactionMessageLoadedAccountsDataSizeLimit) \ [setTransactionMessagePriorityFeeLamports](/api/functions/setTransactionMessagePriorityFeeLamports) \ [transactionConfigMaskHasComputeUnitLimit](/api/functions/transactionConfigMaskHasComputeUnitLimit) \ [transactionConfigMaskHasHeapSize](/api/functions/transactionConfigMaskHasHeapSize) \ [transactionConfigMaskHasLoadedAccountsDataSizeLimit](/api/functions/transactionConfigMaskHasLoadedAccountsDataSizeLimit) \ [transactionConfigMaskHasPriorityFee](/api/functions/transactionConfigMaskHasPriorityFee)

Variables (5)

[MAX\_SUPPORTED\_TRANSACTION\_VERSION](/api/variables/MAX_SUPPORTED_TRANSACTION_VERSION) \ [TRANSACTION\_CONFIG\_COMPUTE\_UNIT\_LIMIT\_BIT\_MASK](/api/variables/TRANSACTION_CONFIG_COMPUTE_UNIT_LIMIT_BIT_MASK) \ [TRANSACTION\_CONFIG\_HEAP\_SIZE\_BIT\_MASK](/api/variables/TRANSACTION_CONFIG_HEAP_SIZE_BIT_MASK) \ [TRANSACTION\_CONFIG\_LOADED\_ACCOUNTS\_DATA\_SIZE\_LIMIT\_BIT\_MASK](/api/variables/TRANSACTION_CONFIG_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_BIT_MASK) \ [TRANSACTION\_CONFIG\_PRIORITY\_FEE\_LAMPORTS\_BIT\_MASK](/api/variables/TRANSACTION_CONFIG_PRIORITY_FEE_LAMPORTS_BIT_MASK)
### `@solana/transactions`

Types (16)

[Base64EncodedWireTransaction](/api/type-aliases/Base64EncodedWireTransaction) \ [FullySignedTransaction](/api/type-aliases/FullySignedTransaction) \ [SendableTransaction](/api/type-aliases/SendableTransaction) \ [SetTransactionLifetimeFromTransactionMessage](/api/type-aliases/SetTransactionLifetimeFromTransactionMessage) \ [SetTransactionWithinSizeLimitFromTransactionMessage](/api/type-aliases/SetTransactionWithinSizeLimitFromTransactionMessage) \ [SignaturesMap](/api/type-aliases/SignaturesMap) \ [Transaction](/api/type-aliases/Transaction) \ [TransactionBlockhashLifetime](/api/type-aliases/TransactionBlockhashLifetime) \ [TransactionDurableNonceLifetime](/api/type-aliases/TransactionDurableNonceLifetime) \ [TransactionFromTransactionMessage](/api/type-aliases/TransactionFromTransactionMessage) \ [TransactionMessageBytes](/api/type-aliases/TransactionMessageBytes) \ [TransactionMessageBytesBase64](/api/type-aliases/TransactionMessageBytesBase64) \ [TransactionWithBlockhashLifetime](/api/type-aliases/TransactionWithBlockhashLifetime) \ [TransactionWithDurableNonceLifetime](/api/type-aliases/TransactionWithDurableNonceLifetime) \ [TransactionWithinSizeLimit](/api/type-aliases/TransactionWithinSizeLimit) \ [TransactionWithLifetime](/api/type-aliases/TransactionWithLifetime)

Functions (25)

[assertIsFullySignedTransaction](/api/functions/assertIsFullySignedTransaction) \ [assertIsSendableTransaction](/api/functions/assertIsSendableTransaction) \ [assertIsTransactionMessageWithinSizeLimit](/api/functions/assertIsTransactionMessageWithinSizeLimit) \ [assertIsTransactionWithBlockhashLifetime](/api/functions/assertIsTransactionWithBlockhashLifetime) \ [assertIsTransactionWithDurableNonceLifetime](/api/functions/assertIsTransactionWithDurableNonceLifetime) \ [assertIsTransactionWithinSizeLimit](/api/functions/assertIsTransactionWithinSizeLimit) \ [compileTransaction](/api/functions/compileTransaction) \ [getBase64EncodedWireTransaction](/api/functions/getBase64EncodedWireTransaction) \ [getSignatureFromTransaction](/api/functions/getSignatureFromTransaction) \ [getTransactionCodec](/api/functions/getTransactionCodec) \ [getTransactionDecoder](/api/functions/getTransactionDecoder) \ [getTransactionEncoder](/api/functions/getTransactionEncoder) \ [getTransactionLifetimeConstraintFromCompiledTransactionMessage](/api/functions/getTransactionLifetimeConstraintFromCompiledTransactionMessage) \ [getTransactionMessageSize](/api/functions/getTransactionMessageSize) \ [getTransactionMessageSizeLimit](/api/functions/getTransactionMessageSizeLimit) \ [getTransactionSize](/api/functions/getTransactionSize) \ [getTransactionSizeLimit](/api/functions/getTransactionSizeLimit) \ [isFullySignedTransaction](/api/functions/isFullySignedTransaction) \ [isSendableTransaction](/api/functions/isSendableTransaction) \ [isTransactionMessageWithinSizeLimit](/api/functions/isTransactionMessageWithinSizeLimit) \ [isTransactionWithBlockhashLifetime](/api/functions/isTransactionWithBlockhashLifetime) \ [isTransactionWithDurableNonceLifetime](/api/functions/isTransactionWithDurableNonceLifetime) \ [isTransactionWithinSizeLimit](/api/functions/isTransactionWithinSizeLimit) \ [partiallySignTransaction](/api/functions/partiallySignTransaction) \ [signTransaction](/api/functions/signTransaction) ### `@solana/wallet-account-signer`

Functions (4)

[createMessageSignerFromWalletAccount](/api/functions/createMessageSignerFromWalletAccount) \ [createSignerFromWalletAccount](/api/functions/createSignerFromWalletAccount) \ [createTransactionSendingSignerFromWalletAccount](/api/functions/createTransactionSendingSignerFromWalletAccount) \ [createTransactionSignerFromWalletAccount](/api/functions/createTransactionSignerFromWalletAccount)
### `@solana/webcrypto-ed25519-polyfill`

Functions (1)

[install](/api/functions/install)
This documentation is automatically generated from the source code using TypeDoc. # SolanaError (/api/classes/SolanaError) Encapsulates an error's stacktrace, a Solana-specific numeric code that indicates what went wrong, and optional context if the type of error indicated by the code supports it. ## Extends * [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) ## Type Parameters | Type Parameter | Default type | | ----------------------------------------------------------------------------- | ------------------------------------------------------ | | `TErrorCode` *extends* [`SolanaErrorCode`](/api/type-aliases/SolanaErrorCode) | [`SolanaErrorCode`](/api/type-aliases/SolanaErrorCode) | ## Constructors ### Constructor ```ts new SolanaError(...__namedParameters): SolanaError; ``` #### Parameters | Parameter | Type | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ...`__namedParameters` | `ReadonlyContextValue`\<`DefaultUnspecifiedErrorContextToUndefined`\<`BasicInstructionErrorContext`\< \| `4615000` \| `4615001` \| `4615002` \| `4615003` \| `4615004` \| `4615005` \| `4615006` \| `4615007` \| `4615008` \| `4615009` \| `4615010` \| `4615011` \| `4615012` \| `4615013` \| `4615014` \| `4615015` \| `4615016` \| `4615017` \| `4615018` \| `4615019` \| `4615020` \| `4615021` \| `4615022` \| `4615023` \| `4615024` \| `4615025` \| `4615026` \| `4615027` \| `4615028` \| `4615029` \| `4615030` \| `4615031` \| `4615032` \| `4615033` \| `4615034` \| `4615035` \| `4615036` \| `4615037` \| `4615038` \| `4615039` \| `4615040` \| `4615041` \| `4615042` \| `4615043` \| `4615044` \| `4615045` \| `4615046` \| `4615047` \| `4615048` \| `4615049` \| `4615050` \| `4615051` \| `4615052` \| `4615053` \| `4615054`> & `object`>>\[`TErrorCode`] *extends* `undefined` ? \[`TErrorCode`, `ErrorOptions`] : \[`TErrorCode`, `ReadonlyContextValue`\<`DefaultUnspecifiedErrorContextToUndefined`\<`BasicInstructionErrorContext`\< \| `4615000` \| `4615001` \| `4615002` \| `4615003` \| `4615004` \| `4615005` \| `4615006` \| `4615007` \| `4615008` \| `4615009` \| `4615010` \| `4615011` \| `4615012` \| `4615013` \| `4615014` \| `4615015` \| `4615016` \| `4615017` \| `4615018` \| `4615019` \| `4615020` \| `4615021` \| `4615022` \| `4615023` \| `4615024` \| `4615025` \| `4615026` \| `4615027` \| `4615028` \| `4615029` \| `4615030` \| `4615031` \| `4615032` \| `4615033` \| `4615034` \| `4615035` \| `4615036` \| `4615037` \| `4615038` \| `4615039` \| `4615040` \| `4615041` \| `4615042` \| `4615043` \| `4615044` \| `4615045` \| `4615046` \| `4615047` \| `4615048` \| `4615049` \| `4615050` \| `4615051` \| `4615052` \| `4615053` \| `4615054`> & `object`>>\[`TErrorCode`] & `ErrorOptions` \| `undefined`] | #### Returns `SolanaError`\<`TErrorCode`> #### Overrides ```ts Error.constructor ``` ## Properties | Property | Modifier | Type | Description | Overrides | Inherited from | | ----------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ----------------------- | | `cause?` | `readonly` | `TErrorCode` *extends* [`SolanaErrorCodeWithCause`](/api/type-aliases/SolanaErrorCodeWithCause) ? `SolanaError`\<[`SolanaErrorCode`](/api/type-aliases/SolanaErrorCode)> : `unknown` | Indicates the root cause of this SolanaError, if any. For example, a transaction error might have an instruction error as its root cause. In this case, you will be able to access the instruction error on the transaction error as `cause`. | `Error.cause` | - | | `context` | `readonly` | `SolanaErrorCodedContext`\[`TErrorCode`] | Contains context that can assist in understanding or recovering from a SolanaError. | - | - | | `message` | `public` | `string` | - | - | `Error.message` | | `name` | `public` | `string` | - | - | `Error.name` | | `stack?` | `public` | `string` | - | - | `Error.stack` | | `stackTraceLimit` | `static` | `number` | The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured *after* the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. | - | `Error.stackTraceLimit` | ## Methods ### captureStackTrace() ```ts static captureStackTrace(targetObject, constructorOpt?): void; ``` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` #### Parameters | Parameter | Type | | ----------------- | ------------------------------------------------------------------------------------------------- | | `targetObject` | `object` | | `constructorOpt?` | [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) | #### Returns `void` #### Inherited from ```ts Error.captureStackTrace ``` *** ### prepareStackTrace() ```ts static prepareStackTrace(err, stackTraces): any; ``` #### Parameters | Parameter | Type | | ------------- | ------------------------------------------------------------------------------------------- | | `err` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | | `stackTraces` | `CallSite`\[] | #### Returns `any` #### See [https://v8.dev/docs/stack-trace-api#customizing-stack-traces](https://v8.dev/docs/stack-trace-api#customizing-stack-traces) #### Inherited from ```ts Error.prepareStackTrace ``` # AccountRole (/api/enumerations/AccountRole) Describes the purpose for which an account participates in a transaction. Every account that participates in a transaction can be read from, but only ones that you mark as writable may be written to, and only ones that you indicate must sign the transaction will gain the privileges associated with signers at runtime. | | `isSigner` | `isWritable` | | ----------------------------- | ---------- | ------------ | | `AccountRole.READONLY` | ❌ | ❌ | | `AccountRole.WRITABLE` | ❌ | βœ… | | `AccountRole.READONLY_SIGNER` | βœ… | ❌ | | `AccountRole.WRITABLE_SIGNER` | βœ… | βœ… | ## Enumeration Members | Enumeration Member | Value | | --------------------------------------------------------------- | ----- | | `READONLY` | `0` | | `READONLY_SIGNER` | `2` | | `WRITABLE` | `1` | | `WRITABLE_SIGNER` | `3` | # Endian (/api/enumerations/Endian) Defines the byte order used for number serialization. * `Little`: The least significant byte is stored first. * `Big`: The most significant byte is stored first. ## Enumeration Members | Enumeration Member | Value | | --------------------------------------------- | ----- | | `Big` | `1` | | `Little` | `0` | # OffchainMessageContentFormat (/api/enumerations/OffchainMessageContentFormat) A restriction on what characters the message text can contain and how long it can be. The aim of this restriction is to make a message more likely to be signable by a hardware wallet that imposes limits on message size. In the case of wanting a message to be clear-signable, restricting the character set to ASCII may ensure that certain models of hardware wallet without extended character sets can display it onscreen. ## Remarks This only applies to v0 messages. ## Enumeration Members | Enumeration Member | Value | | ----------------------------------------------------------------------------------------------- | ----- | | `RESTRICTED_ASCII_1232_BYTES_MAX` | `0` | | `UTF8_1232_BYTES_MAX` | `1` | | `UTF8_65535_BYTES_MAX` | `2` | # Account (/api/interfaces/Account) Contains all the information relevant to a Solana account. It includes the account's address and data, as well as the properties of [BaseAccount](/api/interfaces/BaseAccount). ## Example ```ts // Encoded const myEncodedAccount: Account = { address: address('1234..5678'), data: new Uint8Array([1, 2, 3]), executable: false, lamports: lamports(1_000_000_000n), programAddress: address('1111..1111'), space: 42n, }; // Decoded type MyAccountData = { name: string; age: number }; const myDecodedAccount: Account = { address: address('1234..5678'), data: { name: 'Alice', age: 30 }, executable: false, lamports: lamports(1_000_000_000n), programAddress: address('1111..1111'), space: 42n, }; ``` ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TData` *extends* \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) \| `object` | - | The nature of this account's data. It can be represented as either a `Uint8Array` – meaning the account is encoded – or a custom data type – meaning the account is decoded. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ## Properties | Property | Modifier | Type | | --------------------------------------------------- | ---------- | --------------------------------------------------- | | `address` | `readonly` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `data` | `readonly` | `TData` | | `executable` | `readonly` | `boolean` | | `lamports` | `readonly` | [`Lamports`](/api/type-aliases/Lamports) | | `programAddress` | `readonly` | [`Address`](/api/type-aliases/Address) | | `space` | `readonly` | `bigint` | # AccountLookupMeta (/api/interfaces/AccountLookupMeta) Represents a lookup of the account's address in an address lookup table. It specifies which lookup table account in which to perform the lookup, the index of the desired account address in that table, and metadata about its mutability. Notably, account addresses obtained via lookups may not act as signers. Typically, you will use one of its subtypes. | | `role` | `isSigner` | `isWritable` | | ------------------------------------------------------ | ---------------------- | ---------- | ------------ | | `ReadonlyLookupAccount` | `AccountRole.READONLY` | No | No | | `WritableLookupAccount` | `AccountRole.WRITABLE` | No | Yes | ## Example **A type for the Rent sysvar account that you looked up in a lookup table** ```ts type RentSysvar = ReadonlyLookupAccount< 'SysvarRent111111111111111111111111111111111', 'MyLookupTable111111111111111111111111111111' >; ``` ## Type Parameters | Type Parameter | Default type | | ---------------------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | | `TLookupTableAddress` *extends* `string` | `string` | ## Properties | Property | Modifier | Type | | ----------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `readonly` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `addressIndex` | `readonly` | `number` | | `lookupTableAddress` | `readonly` | [`Address`](/api/type-aliases/Address)\<`TLookupTableAddress`> | | `role` | `readonly` | \| [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) \| [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) | # AccountMeta (/api/interfaces/AccountMeta) Represents an account's address and metadata about its mutability and whether it must be a signer of the transaction. Typically, you will use one of its subtypes. | | `role` | `isSigner` | `isWritable` | | --------------------------------- | ----------------------------- | ---------- | ------------ | | `ReadonlyAccount` | `AccountRole.READONLY` | No | No | | `WritableAccount` | `AccountRole.WRITABLE` | No | Yes | | `ReadonlySignerAccount` | `AccountRole.READONLY_SIGNER` | Yes | No | | `WritableSignerAccount` | `AccountRole.WRITABLE_SIGNER` | Yes | Yes | ## Example **A type for the Rent sysvar account** ```ts type RentSysvar = ReadonlyAccount<'SysvarRent111111111111111111111111111111111'>; ``` ## Extended by * [`AccountSignerMeta`](/api/interfaces/AccountSignerMeta) ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## Properties | Property | Modifier | Type | | ------------------------------------- | ---------- | --------------------------------------------------- | | `address` | `readonly` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `role` | `readonly` | [`AccountRole`](/api/enumerations/AccountRole) | # AccountSignerMeta (/api/interfaces/AccountSignerMeta) An extension of the AccountMeta type that allows us to store [TransactionSigners](/api/type-aliases/TransactionSigner) inside it. Note that, because this type represents a signer, it must use one the following two roles: * AccountRole.READONLY\_SIGNER * AccountRole.WRITABLE\_SIGNER ## Example ```ts import { AccountRole } from '@solana/instructions'; import { generateKeyPairSigner, AccountSignerMeta } from '@solana/signers'; const signer = await generateKeyPairSigner(); const account: AccountSignerMeta = { address: signer.address, role: AccountRole.READONLY_SIGNER, signer, }; ``` ## Extends * `AccountMeta`\<`TAddress`> ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | | `TSigner` *extends* [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TAddress`> | [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TAddress`> | Optionally provide a narrower type for the [TransactionSigner](/api/type-aliases/TransactionSigner) to use within the account meta. | ## Properties | Property | Modifier | Type | Overrides | Inherited from | | ------------------------------------- | ---------- | -------------------------------------- | ------------------ | --------------------- | | `address` | `readonly` | `Address`\<`TAddress`> | - | `AccountMeta.address` | | `role` | `readonly` | `WRITABLE_SIGNER` \| `READONLY_SIGNER` | `AccountMeta.role` | - | | `signer` | `readonly` | `TSigner` | - | - | # BaseAccount (/api/interfaces/BaseAccount) Defines the attributes common to all Solana accounts. Namely, it contains everything stored on-chain except the account data itself. ## Example ```ts const BaseAccount: BaseAccount = { executable: false, lamports: lamports(1_000_000_000n), programAddress: address('1111..1111'), space: 42n, }; ``` ## Properties | Property | Modifier | Type | | --------------------------------------------------- | ---------- | ---------------------------------------- | | `executable` | `readonly` | `boolean` | | `lamports` | `readonly` | [`Lamports`](/api/type-aliases/Lamports) | | `programAddress` | `readonly` | [`Address`](/api/type-aliases/Address) | | `space` | `readonly` | `bigint` | # BaseTransactionSignerConfig (/api/interfaces/BaseTransactionSignerConfig) The base configuration object for transaction signers only. ## Extends * [`BaseSignerConfig`](/api/type-aliases/BaseSignerConfig) ## Properties | Property | Modifier | Type | Description | Inherited from | | ---------------------------------------------------- | ---------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | | `abortSignal?` | `readonly` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | An optional `AbortSignal` that can be used to cancel the signing process. **Example** `import { generateKeyPairSigner } from '@solana/signers'; const abortController = new AbortController(); const signer = await generateKeyPairSigner(); signer.signMessages([message], { abortSignal: abortController.signal }); abortController.abort();` | `BaseSignerConfig.abortSignal` | | `minContextSlot?` | `public` | `bigint` | Signers that simulate transactions (eg. wallets) might be interested in knowing which slot was current when the transaction was prepared. They can use this information to ensure that they don't run the simulation at too early a slot. | - | # DataPublisher (/api/interfaces/DataPublisher) Represents an object with an `on` function that you can call to subscribe to certain data over a named channel. ## Example ```ts let dataPublisher: DataPublisher<{ error: SolanaError }>; dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name. dataPublisher.on('error', e => { console.error(e); }); // OK. ``` ## Type Parameters | Type Parameter | Default type | | ------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | | `TDataByChannelName` *extends* [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `unknown`> | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `unknown`> | ## Methods ### on() ```ts on( channelName, subscriber, options?): UnsubscribeFn; ``` Call this to subscribe to data over a named channel. #### Type Parameters | Type Parameter | | --------------------------------------------------------- | | `TChannelName` *extends* `string` \| `number` \| `symbol` | #### Parameters | Parameter | Type | Description | | ----------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | `channelName` | `TChannelName` | The name of the channel on which to subscribe for messages | | `subscriber` | (`data`) => `void` | The function to call when a message becomes available | | `options?` | \{ `signal`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); } | - | | `options.signal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | An abort signal you can fire to unsubscribe | #### Returns `UnsubscribeFn` A function that you can call to unsubscribe # EncodedAccount (/api/interfaces/EncodedAccount) Represents an encoded account and is equivalent to an [Account](/api/interfaces/Account) with `Uint8Array` account data. ## Example ```ts { address: address('1234..5678'), data: new Uint8Array([1, 2, 3]), executable: false, lamports: lamports(1_000_000_000n), programAddress: address('1111..1111'), space: 42n, } satisfies EncodedAccount<'1234..5678'>; ``` ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ## Properties | Property | Modifier | Type | | --------------------------------------------------- | ---------- | ---------------------------------------------------------- | | `address` | `readonly` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `data` | `readonly` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | | `executable` | `readonly` | `boolean` | | `lamports` | `readonly` | [`Lamports`](/api/type-aliases/Lamports) | | `programAddress` | `readonly` | [`Address`](/api/type-aliases/Address) | | `space` | `readonly` | `bigint` | # FetchAccountConfig (/api/interfaces/FetchAccountConfig) Optional configuration for fetching a singular account. ## Properties | Property | Type | Default value | Description | | ---------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | `abortSignal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | `undefined` | - | | `commitment?` | [`Commitment`](/api/type-aliases/Commitment) | Whichever default is applied by the underlying RpcApi in use. For example, when using an API created by a `createSolanaRpc*()` helper, the default commitment is `"confirmed"` unless configured otherwise. Unmitigated by an API layer on the client, the default commitment applied by the server is `"finalized"`. | Fetch the details of the account as of the highest slot that has reached this level of commitment. | | `minContextSlot?` | `bigint` | `undefined` | Prevents accessing stale data by enforcing that the RPC node has processed transactions up to this slot | # FetchAccountsConfig (/api/interfaces/FetchAccountsConfig) Optional configuration for fetching multiple accounts. ## Properties | Property | Type | Default value | Description | | ---------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | `abortSignal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | `undefined` | - | | `commitment?` | [`Commitment`](/api/type-aliases/Commitment) | Whichever default is applied by the underlying RpcApi in use. For example, when using an API created by a `createSolanaRpc*()` helper, the default commitment is `"confirmed"` unless configured otherwise. Unmitigated by an API layer on the client, the default commitment applied by the server is `"finalized"`. | Fetch the details of the accounts as of the highest slot that has reached this level of commitment. | | `minContextSlot?` | `bigint` | `undefined` | Prevents accessing stale data by enforcing that the RPC node has processed transactions up to this slot | # FixedSizeCodec (/api/interfaces/FixedSizeCodec) An object that can encode and decode a value to and from a fixed-size byte array. See [Codec](/api/type-aliases/Codec) to learn more about creating and composing codecs. ## Example ```ts const codec: FixedSizeCodec; const bytes = codec.encode(42); const value = codec.decode(bytes); // 42n const size = codec.fixedSize; // 8 ``` ## See * [Codec](/api/type-aliases/Codec) * [VariableSizeCodec](/api/interfaces/VariableSizeCodec) ## Type Parameters | Type Parameter | Default type | Description | | -------------------------- | ------------ | --------------------------------------------- | | `TFrom` | - | The type of the value to encode. | | `TTo` *extends* `TFrom` | `TFrom` | The type of the decoded value. | | `TSize` *extends* `number` | `number` | The fixed size of the encoded value in bytes. | ## Properties | Property | Modifier | Type | Description | | ----------------------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `decode` | `readonly` | (`bytes`, `offset?`) => `TTo` | Decodes the provided byte array at the given offset (or zero) and returns the value directly. | | `encode` | `readonly` | (`value`) => [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> | Encode the provided value and return the encoded bytes directly. | | `fixedSize` | `readonly` | `TSize` | The fixed size of the encoded value in bytes. | | `read` | `readonly` | (`bytes`, `offset`) => \[`TTo`, `number`] | Reads the encoded value from the provided byte array at the given offset. Returns the decoded value and the offset of the next byte after the encoded value. | | `write` | `readonly` | (`value`, `bytes`, `offset`) => `number` | Writes the encoded value into the provided byte array at the given offset. Returns the offset of the next byte after the encoded value. | # FixedSizeDecoder (/api/interfaces/FixedSizeDecoder) An object that can decode a fixed-size byte array into a value of type [TTo](#tto). See [Decoder](/api/type-aliases/Decoder) to learn more about creating and composing decoders. ## Example ```ts const decoder: FixedSizeDecoder; const value = decoder.decode(bytes); const size = decoder.fixedSize; // 4 ``` ## See * [Decoder](/api/type-aliases/Decoder) * [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) ## Type Parameters | Type Parameter | Default type | Description | | -------------------------- | ------------ | --------------------------------------------- | | `TTo` | - | The type of the decoded value. | | `TSize` *extends* `number` | `number` | The fixed size of the encoded value in bytes. | ## Properties | Property | Modifier | Type | Description | | ----------------------------------------- | ---------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `decode` | `readonly` | (`bytes`, `offset?`) => `TTo` | Decodes the provided byte array at the given offset (or zero) and returns the value directly. | | `fixedSize` | `readonly` | `TSize` | The fixed size of the encoded value in bytes. | | `read` | `readonly` | (`bytes`, `offset`) => \[`TTo`, `number`] | Reads the encoded value from the provided byte array at the given offset. Returns the decoded value and the offset of the next byte after the encoded value. | # FixedSizeEncoder (/api/interfaces/FixedSizeEncoder) An object that can encode a value of type [TFrom](#tfrom) into a fixed-size [ReadonlyUint8Array](/api/interfaces/ReadonlyUint8Array). See [Encoder](/api/type-aliases/Encoder) to learn more about creating and composing encoders. ## Example ```ts const encoder: FixedSizeEncoder; const bytes = encoder.encode(42); const size = encoder.fixedSize; // 4 ``` ## See * [Encoder](/api/type-aliases/Encoder) * [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder) ## Type Parameters | Type Parameter | Default type | Description | | -------------------------- | ------------ | --------------------------------------------- | | `TFrom` | - | The type of the value to encode. | | `TSize` *extends* `number` | `number` | The fixed size of the encoded value in bytes. | ## Properties | Property | Modifier | Type | Description | | ----------------------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `encode` | `readonly` | (`value`) => [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> | Encode the provided value and return the encoded bytes directly. | | `fixedSize` | `readonly` | `TSize` | The fixed size of the encoded value in bytes. | | `write` | `readonly` | (`value`, `bytes`, `offset`) => `number` | Writes the encoded value into the provided byte array at the given offset. Returns the offset of the next byte after the encoded value. | # Instruction (/api/interfaces/Instruction) An instruction destined for a given program. ## Example ```ts type StakeProgramInstruction = Instruction<'StakeConfig11111111111111111111111111111111'>; ``` ## Extended by * [`InstructionWithAccounts`](/api/interfaces/InstructionWithAccounts) * [`InstructionWithData`](/api/interfaces/InstructionWithData) ## Type Parameters | Type Parameter | Default type | | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | | `TProgramAddress` *extends* `string` | `string` | | `TAccounts` *extends* readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta) \| [`AccountMeta`](/api/interfaces/AccountMeta))\[] | readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta) \| [`AccountMeta`](/api/interfaces/AccountMeta))\[] | ## Properties | Property | Modifier | Type | | --------------------------------------------------- | ---------- | ------------------------------------------------------------------------------ | | `accounts?` | `readonly` | `TAccounts` | | `data?` | `readonly` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | | `programAddress` | `readonly` | [`Address`](/api/type-aliases/Address)\<`TProgramAddress`> | # InstructionWithAccounts (/api/interfaces/InstructionWithAccounts) An instruction that loads certain accounts. ## Example ```ts type InstructionWithTwoAccounts = InstructionWithAccounts< [ WritableAccount, // First account RentSysvar, // Second account ] >; ``` ## Extends * [`Instruction`](/api/interfaces/Instruction) ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `TAccounts` *extends* readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta) \| [`AccountMeta`](/api/interfaces/AccountMeta))\[] | ## Properties | Property | Modifier | Type | Overrides | Inherited from | | --------------------------------------------------- | ---------- | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `accounts` | `readonly` | `TAccounts` | [`Instruction`](/api/interfaces/Instruction).[`accounts`](/api/interfaces/Instruction#property-accounts) | - | | `data?` | `readonly` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | - | [`Instruction`](/api/interfaces/Instruction).[`data`](/api/interfaces/Instruction#property-data) | | `programAddress` | `readonly` | [`Address`](/api/type-aliases/Address)\<`string`> | - | [`Instruction`](/api/interfaces/Instruction).[`programAddress`](/api/interfaces/Instruction#property-programaddress) | # InstructionWithData (/api/interfaces/InstructionWithData) An instruction whose data conforms to a certain type. This is most useful when you have a branded `Uint8Array` that represents a particular instruction's data. ## Example **A type for the \`AdvanceNonce\` instruction of the System program** ```ts type AdvanceNonceAccountInstruction< TNonceAccountAddress extends string = string, TNonceAuthorityAddress extends string = string, > = Instruction<'11111111111111111111111111111111'> & InstructionWithAccounts< [ WritableAccount, ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>, ReadonlySignerAccount, ] > & InstructionWithData; ``` ## Extends * [`Instruction`](/api/interfaces/Instruction) ## Type Parameters | Type Parameter | | ---------------------------------------------------------------------------- | | `TData` *extends* [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ## Properties | Property | Modifier | Type | Overrides | Inherited from | | --------------------------------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | | `accounts?` | `readonly` | readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[] | - | [`Instruction`](/api/interfaces/Instruction).[`accounts`](/api/interfaces/Instruction#property-accounts) | | `data` | `readonly` | `TData` | [`Instruction`](/api/interfaces/Instruction).[`data`](/api/interfaces/Instruction#property-data) | - | | `programAddress` | `readonly` | [`Address`](/api/type-aliases/Address)\<`string`> | - | [`Instruction`](/api/interfaces/Instruction).[`programAddress`](/api/interfaces/Instruction#property-programaddress) | # InstructionWithSigners (/api/interfaces/InstructionWithSigners) Composable type that allows [AccountSignerMetas](/api/interfaces/AccountSignerMeta) to be used inside the instruction's `accounts` array ## Example ```ts import { AccountRole, Instruction } from '@solana/instructions'; import { generateKeyPairSigner, InstructionWithSigners } from '@solana/signers'; const [authority, buffer] = await Promise.all([ generateKeyPairSigner(), generateKeyPairSigner(), ]); const instruction: Instruction & InstructionWithSigners = { programAddress: address('1234..5678'), accounts: [ // The authority is a signer account. { address: authority.address, role: AccountRole.READONLY_SIGNER, signer: authority, }, // The buffer is a writable account. { address: buffer.address, role: AccountRole.WRITABLE }, ], }; ``` ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------------------------------------------ | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `TSigner` *extends* [`TransactionSigner`](/api/type-aliases/TransactionSigner) | [`TransactionSigner`](/api/type-aliases/TransactionSigner) | Optionally provide a narrower type for [TransactionSigners](/api/type-aliases/TransactionSigner). | | `TAccounts` *extends* readonly `AccountMetaWithSigner`\<`TSigner`>\[] | readonly `AccountMetaWithSigner`\<`TSigner`>\[] | Optionally provide a narrower type for the account metas. | ## Properties | Property | Modifier | Type | | ---------------------------------------- | ---------- | ----------- | | `accounts?` | `readonly` | `TAccounts` | # OffchainMessageEnvelope (/api/interfaces/OffchainMessageEnvelope) ## Properties | Property | Modifier | Type | Description | | ------------------------------------------- | ---------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `content` | `readonly` | [`OffchainMessageBytes`](/api/type-aliases/OffchainMessageBytes) | The bytes of the combined offchain message preamble and content | | `signatures` | `readonly` | `OffchainMessageSignaturesMap` | A map between the addresses of an offchain message's signers, and the 64-byte Ed25519 signature of the combined message preamble and message content by the private key associated with each. | # OffchainMessageWithRequiredSignatories (/api/interfaces/OffchainMessageWithRequiredSignatories) An offchain message having a list of accounts that must sign it in order for it to be valid. ## Type Parameters | Type Parameter | Default type | | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | `TSignatory` *extends* [`OffchainMessageSignatory`](/api/type-aliases/OffchainMessageSignatory) | [`OffchainMessageSignatory`](/api/type-aliases/OffchainMessageSignatory) | ## Properties | Property | Type | | ------------------------------------------------------------- | ------------------------ | | `requiredSignatories` | readonly `TSignatory`\[] | # OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent (/api/interfaces/OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent) An offchain message whose content conforms to [OffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) ## Properties | Property | Modifier | Type | | ------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------ | | `content` | `readonly` | [`OffchainMessageContentRestrictedAsciiOf1232BytesMax`](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) | # OffchainMessageWithUtf8Of1232BytesMaxContent (/api/interfaces/OffchainMessageWithUtf8Of1232BytesMaxContent) An offchain message whose content conforms to [offchainMessageContentUtf8Of1232BytesMax](/api/functions/offchainMessageContentUtf8Of1232BytesMax) ## Properties | Property | Modifier | Type | | ------------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------- | | `content` | `readonly` | [`OffchainMessageContentUtf8Of1232BytesMax`](/api/type-aliases/OffchainMessageContentUtf8Of1232BytesMax) | # OffchainMessageWithUtf8Of65535BytesMaxContent (/api/interfaces/OffchainMessageWithUtf8Of65535BytesMaxContent) An offchain message whose content conforms to [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) ## Properties | Property | Modifier | Type | | ------------------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------- | | `content` | `readonly` | [`OffchainMessageContentUtf8Of65535BytesMax`](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) | # ReadonlyUint8Array (/api/interfaces/ReadonlyUint8Array) A read-only variant of `Uint8Array`. This type prevents modifications to the array by omitting mutable methods such as `copyWithin`, `fill`, `reverse`, `set`, and `sort`, while still allowing indexed access to elements. ## Example ```ts const bytes: ReadonlyUint8Array = new Uint8Array([1, 2, 3]); console.log(bytes[0]); // 1 bytes[0] = 42; // Type error: Cannot assign to '0' because it is a read-only property. ``` ## Extends * [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`TArrayBuffer`>, `TypedArrayMutableProperties`> ## Type Parameters | Type Parameter | Default type | | ------------------------------------------ | ----------------- | | `TArrayBuffer` *extends* `ArrayBufferLike` | `ArrayBufferLike` | ## Indexable ```ts [n: number]: number ``` ## Properties | Property | Modifier | Type | Description | Inherited from | | --------------------------------------------------------- | ---------- | -------------- | ------------------------------------------------- | ------------------------ | | `[toStringTag]` | `readonly` | `"Uint8Array"` | - | `Omit.[toStringTag]` | | `buffer` | `readonly` | `TArrayBuffer` | The ArrayBuffer instance referenced by the array. | `Omit.buffer` | | `byteLength` | `readonly` | `number` | The length in bytes of the array. | `Omit.byteLength` | | `byteOffset` | `readonly` | `number` | The offset in bytes of the array. | `Omit.byteOffset` | | `BYTES_PER_ELEMENT` | `readonly` | `number` | The size in bytes of each element in the array. | `Omit.BYTES_PER_ELEMENT` | | `length` | `readonly` | `number` | The length of the array. | `Omit.length` | ## Methods ### \[iterator]\() ```ts iterator: ArrayIterator; ``` #### Returns `ArrayIterator`\<`number`> #### Inherited from ```ts Omit.[iterator] ``` *** ### at() ```ts at(index): number | undefined; ``` Returns the item located at the specified index. #### Parameters | Parameter | Type | Description | | --------- | -------- | --------------------------------------------------------------------------------------------------- | | `index` | `number` | The zero-based index of the desired code unit. A negative index will count back from the last item. | #### Returns `number` | `undefined` #### Inherited from ```ts Omit.at ``` *** ### entries() ```ts entries(): ArrayIterator<[number, number]>; ``` Returns an array of key, value pairs for every entry in the array #### Returns `ArrayIterator`\<\[`number`, `number`]> #### Inherited from ```ts Omit.entries ``` *** ### every() ```ts every(predicate, thisArg?): boolean; ``` Determines whether all the members of an array satisfy the specified test. #### Parameters | Parameter | Type | Description | | ----------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `predicate` | (`value`, `index`, `array`) => `unknown` | A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array. | | `thisArg?` | `any` | An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. | #### Returns `boolean` #### Inherited from ```ts Omit.every ``` *** ### filter() ```ts filter(predicate, thisArg?): Uint8Array; ``` Returns the elements of an array that meet the condition specified in a callback function. #### Parameters | Parameter | Type | Description | | ----------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | | `predicate` | (`value`, `index`, `array`) => `any` | A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array. | | `thisArg?` | `any` | An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. | #### Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> #### Inherited from ```ts Omit.filter ``` *** ### find() ```ts find(predicate, thisArg?): number | undefined; ``` Returns the value of the first element in the array where predicate is true, and undefined otherwise. #### Parameters | Parameter | Type | Description | | ----------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `predicate` | (`value`, `index`, `obj`) => `boolean` | find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined. | | `thisArg?` | `any` | If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead. | #### Returns `number` | `undefined` #### Inherited from ```ts Omit.find ``` *** ### findIndex() ```ts findIndex(predicate, thisArg?): number; ``` Returns the index of the first element in the array where predicate is true, and -1 otherwise. #### Parameters | Parameter | Type | Description | | ----------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `predicate` | (`value`, `index`, `obj`) => `boolean` | find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1. | | `thisArg?` | `any` | If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead. | #### Returns `number` #### Inherited from ```ts Omit.findIndex ``` *** ### findLast() #### Call Signature ```ts findLast(predicate, thisArg?): S | undefined; ``` Returns the value of the last element in the array where predicate is true, and undefined otherwise. ##### Type Parameters | Type Parameter | | ---------------------- | | `S` *extends* `number` | ##### Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `predicate` | (`value`, `index`, `array`) => `value is S` | findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined. | | `thisArg?` | `any` | If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead. | ##### Returns `S` | `undefined` ##### Inherited from ```ts Omit.findLast ``` #### Call Signature ```ts findLast(predicate, thisArg?): number | undefined; ``` ##### Parameters | Parameter | Type | | ----------- | ---------------------------------------- | | `predicate` | (`value`, `index`, `array`) => `unknown` | | `thisArg?` | `any` | ##### Returns `number` | `undefined` ##### Inherited from ```ts Omit.findLast ``` *** ### findLastIndex() ```ts findLastIndex(predicate, thisArg?): number; ``` Returns the index of the last element in the array where predicate is true, and -1 otherwise. #### Parameters | Parameter | Type | Description | | ----------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `predicate` | (`value`, `index`, `array`) => `unknown` | findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. | | `thisArg?` | `any` | If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead. | #### Returns `number` #### Inherited from ```ts Omit.findLastIndex ``` *** ### forEach() ```ts forEach(callbackfn, thisArg?): void; ``` Performs the specified action for each element in an array. #### Parameters | Parameter | Type | Description | | ------------ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `callbackfn` | (`value`, `index`, `array`) => `void` | A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. | | `thisArg?` | `any` | An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. | #### Returns `void` #### Inherited from ```ts Omit.forEach ``` *** ### includes() ```ts includes(searchElement, fromIndex?): boolean; ``` Determines whether an array includes a certain element, returning true or false as appropriate. #### Parameters | Parameter | Type | Description | | --------------- | -------- | ------------------------------------------------------------------------- | | `searchElement` | `number` | The element to search for. | | `fromIndex?` | `number` | The position in this array at which to begin searching for searchElement. | #### Returns `boolean` #### Inherited from ```ts Omit.includes ``` *** ### indexOf() ```ts indexOf(searchElement, fromIndex?): number; ``` Returns the index of the first occurrence of a value in an array. #### Parameters | Parameter | Type | Description | | --------------- | -------- | ---------------------------------------------------------------------------------------------------- | | `searchElement` | `number` | The value to locate in the array. | | `fromIndex?` | `number` | The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. | #### Returns `number` #### Inherited from ```ts Omit.indexOf ``` *** ### join() ```ts join(separator?): string; ``` Adds all the elements of an array separated by the specified separator string. #### Parameters | Parameter | Type | Description | | ------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `separator?` | `string` | A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. | #### Returns `string` #### Inherited from ```ts Omit.join ``` *** ### keys() ```ts keys(): ArrayIterator; ``` Returns an list of keys in the array #### Returns `ArrayIterator`\<`number`> #### Inherited from ```ts Omit.keys ``` *** ### lastIndexOf() ```ts lastIndexOf(searchElement, fromIndex?): number; ``` Returns the index of the last occurrence of a value in an array. #### Parameters | Parameter | Type | Description | | --------------- | -------- | ---------------------------------------------------------------------------------------------------- | | `searchElement` | `number` | The value to locate in the array. | | `fromIndex?` | `number` | The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. | #### Returns `number` #### Inherited from ```ts Omit.lastIndexOf ``` *** ### map() ```ts map(callbackfn, thisArg?): Uint8Array; ``` Calls a defined callback function on each element of an array, and returns an array that contains the results. #### Parameters | Parameter | Type | Description | | ------------ | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `callbackfn` | (`value`, `index`, `array`) => `number` | A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. | | `thisArg?` | `any` | An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. | #### Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> #### Inherited from ```ts Omit.map ``` *** ### reduce() #### Call Signature ```ts reduce(callbackfn): number; ``` Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. ##### Parameters | Parameter | Type | Description | | ------------ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `callbackfn` | (`previousValue`, `currentValue`, `currentIndex`, `array`) => `number` | A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. | ##### Returns `number` ##### Inherited from ```ts Omit.reduce ``` #### Call Signature ```ts reduce(callbackfn, initialValue): number; ``` ##### Parameters | Parameter | Type | | -------------- | ---------------------------------------------------------------------- | | `callbackfn` | (`previousValue`, `currentValue`, `currentIndex`, `array`) => `number` | | `initialValue` | `number` | ##### Returns `number` ##### Inherited from ```ts Omit.reduce ``` #### Call Signature ```ts reduce(callbackfn, initialValue): U; ``` Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. ##### Type Parameters | Type Parameter | | -------------- | | `U` | ##### Parameters | Parameter | Type | Description | | -------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `callbackfn` | (`previousValue`, `currentValue`, `currentIndex`, `array`) => `U` | A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. | | `initialValue` | `U` | If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. | ##### Returns `U` ##### Inherited from ```ts Omit.reduce ``` *** ### reduceRight() #### Call Signature ```ts reduceRight(callbackfn): number; ``` Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. ##### Parameters | Parameter | Type | Description | | ------------ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `callbackfn` | (`previousValue`, `currentValue`, `currentIndex`, `array`) => `number` | A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. | ##### Returns `number` ##### Inherited from ```ts Omit.reduceRight ``` #### Call Signature ```ts reduceRight(callbackfn, initialValue): number; ``` ##### Parameters | Parameter | Type | | -------------- | ---------------------------------------------------------------------- | | `callbackfn` | (`previousValue`, `currentValue`, `currentIndex`, `array`) => `number` | | `initialValue` | `number` | ##### Returns `number` ##### Inherited from ```ts Omit.reduceRight ``` #### Call Signature ```ts reduceRight(callbackfn, initialValue): U; ``` Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. ##### Type Parameters | Type Parameter | | -------------- | | `U` | ##### Parameters | Parameter | Type | Description | | -------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `callbackfn` | (`previousValue`, `currentValue`, `currentIndex`, `array`) => `U` | A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. | | `initialValue` | `U` | If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. | ##### Returns `U` ##### Inherited from ```ts Omit.reduceRight ``` *** ### slice() ```ts slice(start?, end?): Uint8Array; ``` Returns a section of an array. #### Parameters | Parameter | Type | Description | | --------- | -------- | --------------------------------------------------------------------------------------------------- | | `start?` | `number` | The beginning of the specified portion of the array. | | `end?` | `number` | The end of the specified portion of the array. This is exclusive of the element at the index 'end'. | #### Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> #### Inherited from ```ts Omit.slice ``` *** ### some() ```ts some(predicate, thisArg?): boolean; ``` Determines whether the specified callback function returns true for any element of an array. #### Parameters | Parameter | Type | Description | | ----------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `predicate` | (`value`, `index`, `array`) => `unknown` | A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array. | | `thisArg?` | `any` | An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. | #### Returns `boolean` #### Inherited from ```ts Omit.some ``` *** ### subarray() ```ts subarray(begin?, end?): Uint8Array; ``` Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements at begin, inclusive, up to end, exclusive. #### Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------------------------- | | `begin?` | `number` | The index of the beginning of the array. | | `end?` | `number` | The index of the end of the array. | #### Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`TArrayBuffer`> #### Inherited from ```ts Omit.subarray ``` *** ### toLocaleString() #### Call Signature ```ts toLocaleString(): string; ``` Converts a number to a string by using the current locale. ##### Returns `string` ##### Inherited from ```ts Omit.toLocaleString ``` #### Call Signature ```ts toLocaleString(locales, options?): string; ``` ##### Parameters | Parameter | Type | | ---------- | ----------------------- | | `locales` | `string` \| `string`\[] | | `options?` | `NumberFormatOptions` | ##### Returns `string` ##### Inherited from ```ts Omit.toLocaleString ``` *** ### toReversed() ```ts toReversed(): Uint8Array; ``` Copies the array and returns the copy with the elements in reverse order. #### Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> #### Inherited from ```ts Omit.toReversed ``` *** ### toSorted() ```ts toSorted(compareFn?): Uint8Array; ``` Copies and sorts the array. #### Parameters | Parameter | Type | Description | | ------------ | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `compareFn?` | (`a`, `b`) => `number` | Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending order. `const myNums = Uint8Array.from([11, 2, 22, 1]); myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]` | #### Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> #### Inherited from ```ts Omit.toSorted ``` *** ### toString() ```ts toString(): string; ``` Returns a string representation of an array. #### Returns `string` #### Inherited from ```ts Omit.toString ``` *** ### valueOf() ```ts valueOf(): this; ``` Returns the primitive value of the specified object. #### Returns `this` #### Inherited from ```ts Omit.valueOf ``` *** ### values() ```ts values(): ArrayIterator; ``` Returns an list of values in the array #### Returns `ArrayIterator`\<`number`> #### Inherited from ```ts Omit.values ``` *** ### with() ```ts with(index, value): Uint8Array; ``` Copies the array and inserts the given number at the provided index. #### Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------------------------------------------------------------------------------------------- | | `index` | `number` | The index of the value to overwrite. If the index is negative, then it replaces from the end of the array. | | `value` | `number` | The value to insert into the copied array. | #### Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> A copy of the original array with the inserted value. #### Inherited from ```ts Omit.with ``` # RpcSubscriptionsApiMethods (/api/interfaces/RpcSubscriptionsApiMethods) ## Indexable ```ts [methodName: string]: RpcSubscriptionsApiMethod ``` # RpcSubscriptionsChannel (/api/interfaces/RpcSubscriptionsChannel) A DataPublisher on which you can subscribe to events of type [RpcSubscriptionChannelEvents\](/api/type-aliases/RpcSubscriptionChannelEvents). Additionally, you can use this object to send messages of type `TOutboundMessage` back to the remote end by calling its [\`send(message)\`](#send) method. ## Extends * `DataPublisher`\<[`RpcSubscriptionChannelEvents`](/api/type-aliases/RpcSubscriptionChannelEvents)\<`TInboundMessage`>> ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | ## Methods ### on() ```ts on( channelName, subscriber, options?): UnsubscribeFn; ``` Call this to subscribe to data over a named channel. #### Type Parameters | Type Parameter | | ----------------------------------------------------------------------------------------------------------------------------------- | | `TChannelName` *extends* keyof [`RpcSubscriptionChannelEvents`](/api/type-aliases/RpcSubscriptionChannelEvents)\<`TInboundMessage`> | #### Parameters | Parameter | Type | Description | | ----------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | `channelName` | `TChannelName` | The name of the channel on which to subscribe for messages | | `subscriber` | (`data`) => `void` | The function to call when a message becomes available | | `options?` | \{ `signal`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); } | - | | `options.signal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | An abort signal you can fire to unsubscribe | #### Returns `UnsubscribeFn` A function that you can call to unsubscribe #### Inherited from ```ts DataPublisher.on ``` *** ### send() ```ts send(message): Promise; ``` #### Parameters | Parameter | Type | | --------- | ------------------ | | `message` | `TOutboundMessage` | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`> # RpcSubscriptionsTransport (/api/interfaces/RpcSubscriptionsTransport) A function that can act as a transport for a [RpcSubscriptions](/api/type-aliases/RpcSubscriptions). It need only return a promise for a DataPublisher given the supplied config. ```ts RpcSubscriptionsTransport(config): Promise>>; ``` A function that can act as a transport for a [RpcSubscriptions](/api/type-aliases/RpcSubscriptions). It need only return a promise for a DataPublisher given the supplied config. ## Type Parameters | Type Parameter | | --------------- | | `TNotification` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------- | | `config` | `RpcSubscriptionsTransportConfig`\<`TNotification`> | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`DataPublisher`\<[`RpcSubscriptionsTransportDataEvents`](/api/type-aliases/RpcSubscriptionsTransportDataEvents)\<`TNotification`>>> # SolanaErrorWithDeprecatedCause (/api/interfaces/SolanaErrorWithDeprecatedCause) A variant of [SolanaError](/api/classes/SolanaError) where the `cause` property is deprecated. This type is returned by [isSolanaError](/api/functions/isSolanaError) when checking for error codes in [SolanaErrorCodeWithDeprecatedCause](/api/type-aliases/SolanaErrorCodeWithDeprecatedCause). Accessing `cause` on these errors will show a deprecation warning in IDEs that support JSDoc `@deprecated` tags. ## Extends * [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`SolanaError`](/api/classes/SolanaError)\<`TErrorCode`>, `"cause"`> ## Type Parameters | Type Parameter | Default type | | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `TErrorCode` *extends* [`SolanaErrorCodeWithDeprecatedCause`](/api/type-aliases/SolanaErrorCodeWithDeprecatedCause) | [`SolanaErrorCodeWithDeprecatedCause`](/api/type-aliases/SolanaErrorCodeWithDeprecatedCause) | ## Properties | Property | Modifier | Type | Description | Inherited from | | -------------------------------------- | ---------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | ~~`cause?`~~ | `readonly` | `unknown` | **Deprecated** The `cause` property is deprecated for this error code. Use the error's `context` property instead to access relevant error information. | - | | `context` | `readonly` | `SolanaErrorCodedContext`\[`TErrorCode`] | Contains context that can assist in understanding or recovering from a [SolanaError](/api/classes/SolanaError). | `Omit.context` | | `message` | `public` | `string` | - | [`SolanaError`](/api/classes/SolanaError).[`message`](/api/classes/SolanaError#property-message) | | `name` | `public` | `string` | - | [`SolanaError`](/api/classes/SolanaError).[`name`](/api/classes/SolanaError#property-name) | | `stack?` | `public` | `string` | - | [`SolanaError`](/api/classes/SolanaError).[`stack`](/api/classes/SolanaError#property-stack) | # TransactionMessageWithBlockhashLifetime (/api/interfaces/TransactionMessageWithBlockhashLifetime) Represents a transaction message whose lifetime is defined by the age of the blockhash it includes. Such a transaction can only be landed on the network if the current block height of the network is less than or equal to the value of `TransactionMessageWithBlockhashLifetime['lifetimeConstraint']['lastValidBlockHeight']`. ## Properties | Property | Modifier | Type | | ----------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------ | | `lifetimeConstraint` | `readonly` | [`BlockhashLifetimeConstraint`](/api/type-aliases/BlockhashLifetimeConstraint) | # TransactionMessageWithDurableNonceLifetime (/api/interfaces/TransactionMessageWithDurableNonceLifetime) Represents a transaction message whose lifetime is defined by the value of a nonce it includes. Such a transaction can only be landed on the network if the nonce is known to the network and has not already been used to land a different transaction. ## Type Parameters | Type Parameter | Default type | | ------------------------------------------- | ------------ | | `TNonceAccountAddress` *extends* `string` | `string` | | `TNonceAuthorityAddress` *extends* `string` | `string` | | `TNonceValue` *extends* `string` | `string` | ## Properties | Property | Modifier | Type | | ----------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `instructions` | `readonly` | readonly \[`AdvanceNonceAccountInstruction`\<`TNonceAccountAddress`, `TNonceAuthorityAddress`>, `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]>] | | `lifetimeConstraint` | `readonly` | [`NonceLifetimeConstraint`](/api/type-aliases/NonceLifetimeConstraint)\<`TNonceValue`> | # TransactionMessageWithFeePayer (/api/interfaces/TransactionMessageWithFeePayer) Represents a transaction message for which a fee payer has been declared. A transaction must conform to this type to be compiled and landed on the network. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## Properties | Property | Modifier | Type | | --------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `feePayer` | `readonly` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`TAddress`>; }> | # TransactionMessageWithFeePayerSigner (/api/interfaces/TransactionMessageWithFeePayerSigner) Alternative to TransactionMessageWithFeePayer that uses a [TransactionSigner](/api/type-aliases/TransactionSigner) for the fee payer. ## Example ```ts import { TransactionMessage } from '@solana/transaction-messages'; import { generateKeyPairSigner, TransactionMessageWithFeePayerSigner } from '@solana/signers'; const transactionMessage: TransactionMessage & TransactionMessageWithFeePayerSigner = { feePayer: await generateKeyPairSigner(), instructions: [], version: 0, }; ``` ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define a fee payer having a particular address. | | `TSigner` *extends* [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TAddress`> | [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TAddress`> | Optionally provide a narrower type for the [TransactionSigner](/api/type-aliases/TransactionSigner). | ## Properties | Property | Modifier | Type | | --------------------------------------- | ---------- | --------- | | `feePayer` | `readonly` | `TSigner` | # TypedEventEmitter (/api/interfaces/TypedEventEmitter) This type allows you to type `addEventListener` and `removeEventListener` so that the call signature of the listener matches the event type given. ## Example ```ts const emitter: TypedEventEmitter<{ message: MessageEvent }> = new WebSocket('wss://api.devnet.solana.com'); emitter.addEventListener('data', handleData); // ERROR. `data` is not a known event type. emitter.addEventListener('message', message => { console.log(message.origin); // OK. `message` is a `MessageEvent` so it has an `origin` property. }); ``` ## Type Parameters | Type Parameter | | -------------------------------- | | `TEventMap` *extends* `EventMap` | ## Methods ### addEventListener() ```ts addEventListener( type, listener, options?): void; ``` #### Type Parameters | Type Parameter | | ------------------------------------------------------- | | `TEventType` *extends* `string` \| `number` \| `symbol` | #### Parameters | Parameter | Type | | ---------- | --------------------------------------- | | `type` | `TEventType` | | `listener` | `Listener`\<`TEventMap`\[`TEventType`]> | | `options?` | `boolean` \| `AddEventListenerOptions` | #### Returns `void` *** ### removeEventListener() ```ts removeEventListener( type, listener, options?): void; ``` #### Type Parameters | Type Parameter | | ------------------------------------------------------- | | `TEventType` *extends* `string` \| `number` \| `symbol` | #### Parameters | Parameter | Type | | ---------- | --------------------------------------- | | `type` | `TEventType` | | `listener` | `Listener`\<`TEventMap`\[`TEventType`]> | | `options?` | `boolean` \| `EventListenerOptions` | #### Returns `void` # TypedEventTarget (/api/interfaces/TypedEventTarget) This type is a superset of `TypedEventEmitter` that allows you to constrain calls to `dispatchEvent`. ## Example ```ts const target: TypedEventTarget<{ candyVended: CustomEvent<{ flavour: string }> }> = new EventTarget(); target.dispatchEvent(new CustomEvent('candyVended', { detail: { flavour: 'raspberry' } })); // OK. target.dispatchEvent(new CustomEvent('candyVended', { detail: { flavor: 'raspberry' } })); // ERROR. Misspelling in detail. ``` ## Type Parameters | Type Parameter | | -------------------------------- | | `TEventMap` *extends* `EventMap` | ## Methods ### addEventListener() ```ts addEventListener( type, listener, options?): void; ``` #### Type Parameters | Type Parameter | | ------------------------------------------------------- | | `TEventType` *extends* `string` \| `number` \| `symbol` | #### Parameters | Parameter | Type | | ---------- | --------------------------------------- | | `type` | `TEventType` | | `listener` | `Listener`\<`TEventMap`\[`TEventType`]> | | `options?` | `boolean` \| `AddEventListenerOptions` | #### Returns `void` *** ### dispatchEvent() ```ts dispatchEvent(ev): void; ``` #### Type Parameters | Type Parameter | | ------------------------------------------------------- | | `TEventType` *extends* `string` \| `number` \| `symbol` | #### Parameters | Parameter | Type | | --------- | -------------------------- | | `ev` | `TEventMap`\[`TEventType`] | #### Returns `void` *** ### removeEventListener() ```ts removeEventListener( type, listener, options?): void; ``` #### Type Parameters | Type Parameter | | ------------------------------------------------------- | | `TEventType` *extends* `string` \| `number` \| `symbol` | #### Parameters | Parameter | Type | | ---------- | --------------------------------------- | | `type` | `TEventType` | | `listener` | `Listener`\<`TEventMap`\[`TEventType`]> | | `options?` | `boolean` \| `EventListenerOptions` | #### Returns `void` # VariableSizeCodec (/api/interfaces/VariableSizeCodec) An object that can encode and decode a value to and from a variable-size byte array. See [Codec](/api/type-aliases/Codec) to learn more about creating and composing codecs. ## Example ```ts const codec: VariableSizeCodec; const bytes = codec.encode(42); const value = codec.decode(bytes); // 42n const size = codec.getSizeFromValue(42); ``` ## See * [Codec](/api/type-aliases/Codec) * [FixedSizeCodec](/api/interfaces/FixedSizeCodec) ## Type Parameters | Type Parameter | Default type | Description | | ----------------------- | ------------ | -------------------------------- | | `TFrom` | - | The type of the value to encode. | | `TTo` *extends* `TFrom` | `TFrom` | The type of the decoded value. | ## Properties | Property | Modifier | Type | Description | | ------------------------------------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `decode` | `readonly` | (`bytes`, `offset?`) => `TTo` | Decodes the provided byte array at the given offset (or zero) and returns the value directly. | | `encode` | `readonly` | (`value`) => [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> | Encode the provided value and return the encoded bytes directly. | | `getSizeFromValue` | `readonly` | (`value`) => `number` | Returns the size of the encoded value in bytes for a given input. | | `maxSize?` | `readonly` | `number` | The maximum possible size of an encoded value in bytes, if applicable. | | `read` | `readonly` | (`bytes`, `offset`) => \[`TTo`, `number`] | Reads the encoded value from the provided byte array at the given offset. Returns the decoded value and the offset of the next byte after the encoded value. | | `write` | `readonly` | (`value`, `bytes`, `offset`) => `number` | Writes the encoded value into the provided byte array at the given offset. Returns the offset of the next byte after the encoded value. | # VariableSizeDecoder (/api/interfaces/VariableSizeDecoder) An object that can decode a variable-size byte array into a value of type [TTo](#tto). See [Decoder](/api/type-aliases/Decoder) to learn more about creating and composing decoders. ## Example ```ts const decoder: VariableSizeDecoder; const value = decoder.decode(bytes); ``` ## See * [Decoder](/api/type-aliases/Decoder) * VariableSizeDecoder ## Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ## Properties | Property | Modifier | Type | Description | | -------------------------------------- | ---------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `decode` | `readonly` | (`bytes`, `offset?`) => `TTo` | Decodes the provided byte array at the given offset (or zero) and returns the value directly. | | `maxSize?` | `readonly` | `number` | The maximum possible size of an encoded value in bytes, if applicable. | | `read` | `readonly` | (`bytes`, `offset`) => \[`TTo`, `number`] | Reads the encoded value from the provided byte array at the given offset. Returns the decoded value and the offset of the next byte after the encoded value. | # VariableSizeEncoder (/api/interfaces/VariableSizeEncoder) An object that can encode a value of type [TFrom](#tfrom) into a variable-size [ReadonlyUint8Array](/api/interfaces/ReadonlyUint8Array). See [Encoder](/api/type-aliases/Encoder) to learn more about creating and composing encoders. ## Example ```ts const encoder: VariableSizeEncoder; const bytes = encoder.encode('hello'); const size = encoder.getSizeFromValue('hello'); ``` ## See * [Encoder](/api/type-aliases/Encoder) * [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder) ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ## Properties | Property | Modifier | Type | Description | | ------------------------------------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `encode` | `readonly` | (`value`) => [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<[`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)> | Encode the provided value and return the encoded bytes directly. | | `getSizeFromValue` | `readonly` | (`value`) => `number` | Returns the size of the encoded value in bytes for a given input. | | `maxSize?` | `readonly` | `number` | The maximum possible size of an encoded value in bytes, if applicable. | | `write` | `readonly` | (`value`, `bytes`, `offset`) => `number` | Writes the encoded value into the provided byte array at the given offset. Returns the offset of the next byte after the encoded value. | # AccountInfoBase (/api/type-aliases/AccountInfoBase) ```ts type AccountInfoBase = Readonly<{ executable: boolean; lamports: Lamports; owner: Address; space: bigint; }>; ``` # AccountInfoWithBase58Bytes (/api/type-aliases/AccountInfoWithBase58Bytes) ```ts type AccountInfoWithBase58Bytes = Readonly<{ data: Base58EncodedBytes; }>; ``` ## Deprecated # AccountInfoWithBase58EncodedData (/api/type-aliases/AccountInfoWithBase58EncodedData) ```ts type AccountInfoWithBase58EncodedData = Readonly<{ data: Base58EncodedDataResponse; }>; ``` ## Deprecated # AccountInfoWithBase64EncodedData (/api/type-aliases/AccountInfoWithBase64EncodedData) ```ts type AccountInfoWithBase64EncodedData = Readonly<{ data: Base64EncodedDataResponse; }>; ``` # AccountInfoWithBase64EncodedZStdCompressedData (/api/type-aliases/AccountInfoWithBase64EncodedZStdCompressedData) ```ts type AccountInfoWithBase64EncodedZStdCompressedData = Readonly<{ data: Base64EncodedZStdCompressedDataResponse; }>; ``` # AccountInfoWithJsonData (/api/type-aliases/AccountInfoWithJsonData) ```ts type AccountInfoWithJsonData = Readonly<{ data: | Base64EncodedDataResponse | Readonly<{ parsed: { info?: object; type: string; }; program: string; space: bigint; }>; }>; ``` # AccountInfoWithPubkey (/api/type-aliases/AccountInfoWithPubkey) ```ts type AccountInfoWithPubkey = Readonly<{ account: TAccount; pubkey: Address; }>; ``` ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------- | | `TAccount` *extends* [`AccountInfoBase`](/api/type-aliases/AccountInfoBase) | # AccountNotificationsApi (/api/type-aliases/AccountNotificationsApi) ```ts type AccountNotificationsApi = object; ``` ## Methods ### accountNotifications() #### Call Signature ```ts accountNotifications(address, config): SolanaRpcResponse; ``` Subscribe for notifications when there is a change in the Lamports or data of the account at the specified address. The notification format is the same as seen in the GetAccountInfoApi.getAccountInfo RPC HTTP method. If the account has data, it will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`> ##### See [https://solana.com/docs/rpc/websocket/accountsubscribe](https://solana.com/docs/rpc/websocket/accountsubscribe) #### Call Signature ```ts accountNotifications(address, config): SolanaRpcResponse; ``` Subscribe for notifications when there is a change in the Lamports or data of the account at the specified address. The notification format is the same as seen in the GetAccountInfoApi.getAccountInfo RPC HTTP method. If the account has data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64+zstd"`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`> ##### See [https://solana.com/docs/rpc/websocket/accountsubscribe](https://solana.com/docs/rpc/websocket/accountsubscribe) #### Call Signature ```ts accountNotifications(address, config): SolanaRpcResponse; ``` Subscribe for notifications when there is a change in the Lamports or data of the account at the specified address. The notification format is the same as seen in the GetAccountInfoApi.getAccountInfo RPC HTTP method. If the account has data, the server will attempt to process it using a parser specific to the account's owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoBase` & `AccountInfoWithJsonData`> ##### See [https://solana.com/docs/rpc/websocket/accountsubscribe](https://solana.com/docs/rpc/websocket/accountsubscribe) #### Call Signature ```ts accountNotifications(address, config): SolanaRpcResponse; ``` Subscribe for notifications when there is a change in the Lamports or data of the account at the specified address. The notification format is the same as seen in the GetAccountInfoApi.getAccountInfo RPC HTTP method. If the account has data, it will be returned in the response as a tuple whose first element is a base58-encoded string. If the account contains more than 129 bytes of data, the `data` field will materialize as the string `"error: data too large for bs58 encoding"`. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoBase` & `AccountInfoWithBase58EncodedData`> ##### See [https://solana.com/docs/rpc/websocket/accountsubscribe](https://solana.com/docs/rpc/websocket/accountsubscribe) #### Call Signature ```ts accountNotifications(address, config?): SolanaRpcResponse; ``` Subscribe for notifications when there is a change in the Lamports or data of the account at the specified address. The notification format is the same as seen in the GetAccountInfoApi.getAccountInfo RPC HTTP method. If the account has data, it will be returned in the response as a base58-encoded string. If the account contains more than 129 bytes of data, the `data` field will materialize as the string `"error: data too large for bs58 encoding"`. ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | | `address` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoBase` & `AccountInfoWithBase58Bytes`> ##### See [https://solana.com/docs/rpc/websocket/accountsubscribe](https://solana.com/docs/rpc/websocket/accountsubscribe) # ActionResult (/api/type-aliases/ActionResult) ```ts type ActionResult = object; ``` Reactive state and controls for an async action managed by [useAction](/api/functions/useAction) (and plugin-specific hooks built on top of it). Lifecycle: starts at `idle`. Each `dispatch(...)` flips to `running`, then to `success` or `error` depending on the outcome. `data` from a prior `success` and `error` from a prior failure both persist through subsequent `running` states for stale-while-revalidate UX. `success` clears `error`; only `reset()` clears `data`. Calling `dispatch(...)` while a previous call is in flight aborts the first via its `AbortSignal` and replaces it. Fire-and-forget `dispatch` callers never observe this; awaiters of a superseded `dispatchAsync` call see a rejection with an `AbortError`, filterable via `isAbortError` from `@solana/promises`. ## Type Parameters | Type Parameter | Description | | --------------------------------------- | ------------------------------------------------------------------------------------------------ | | `TArgs` *extends* readonly `unknown`\[] | The argument tuple `dispatch` accepts; forwarded to the wrapped function after the abort signal. | | `TResult` | The value the wrapped function resolves to on success. | ## Properties ### data ```ts data: TResult | undefined; ``` The result on success, or `undefined` if no successful call has happened yet. *** ### dispatch ```ts dispatch: (...args) => void; ``` Trigger the action and forget it. Returns `undefined` synchronously and never throws β€” failures surface on `status` / `error`, and superseded or `reset()`-aborted calls produce no state change. This is the variant to wire into UI event handlers (`onClick={() => dispatch()}`): there is no promise to handle, so it can't produce an unhandled rejection. Calling `dispatch` again while a prior call is in flight aborts the first. Stable reference. #### Parameters | Parameter | Type | | --------- | ------- | | ...`args` | `TArgs` | #### Returns `void` #### See [ActionResult.dispatchAsync](#dispatchasync) when you need the resolved value or propagated errors. *** ### dispatchAsync ```ts dispatchAsync: (...args) => Promise; ``` Trigger the action and await the outcome. Resolves with the wrapped function's result, or rejects with the thrown error. Calling `dispatch`/`dispatchAsync` again while a prior call is in flight aborts the first and rejects its promise with an `AbortError`. Stable reference. Mirrors `ReactiveActionStore.dispatchAsync`. Use this from imperative callers that read the resolved value (e.g. to navigate on success); filter supersede rejections with `isAbortError` from `@solana/promises`. Prefer [ActionResult.dispatch](#dispatch) from event handlers that don't await β€” its returned promise, left unhandled, surfaces every supersede/abort as an `unhandledrejection`. #### Parameters | Parameter | Type | | --------- | ------- | | ...`args` | `TArgs` | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TResult`> *** ### error ```ts error: unknown; ``` The error from the most recent failed call, or `undefined`. Persists through a subsequent `running` state so UIs can keep showing the prior failure while a retry is in flight; a subsequent `success` clears it. *** ### isError ```ts isError: boolean; ``` `true` when `status === 'error'`. *** ### isIdle ```ts isIdle: boolean; ``` `true` when `status === 'idle'`. *** ### isRunning ```ts isRunning: boolean; ``` `true` when `status === 'running'` β€” a dispatch is in flight. *** ### isSuccess ```ts isSuccess: boolean; ``` `true` when `status === 'success'`. *** ### reset ```ts reset: () => void; ``` Reset state back to `idle`, aborting any in-flight call. Stable reference. #### Returns `void` *** ### status ```ts status: "error" | "idle" | "running" | "success"; ``` The current lifecycle status as a discriminated string. The `isIdle` / `isRunning` / `isSuccess` / `isError` booleans below are derived from this β€” pick whichever reads better at the call site. # Address (/api/type-aliases/Address) ```ts type Address = Brand, "Address">; ``` Represents a string that validates as a Solana address. Functions that require well-formed addresses should specify their inputs in terms of this type. Whenever you need to validate an arbitrary string as a base58-encoded address, use the [address](/api/functions/address), [assertIsAddress](/api/functions/assertIsAddress), or [isAddress](/api/functions/isAddress) functions in this package. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | # AddressesByLookupTableAddress (/api/type-aliases/AddressesByLookupTableAddress) ```ts type AddressesByLookupTableAddress = object; ``` Represents a mapping of lookup table addresses to the addresses of the accounts that are stored in them. ## Index Signature ```ts [lookupTableAddress: Address]: Address[] ``` # AffinePoint (/api/type-aliases/AffinePoint) ```ts type AffinePoint = NominalType<"affinePoint", TValidity> & T; ``` Use this to produce a new type that satisfies the original type, but adds extra type information that marks the type as being an affine point over a field that either lies on a given curve (is valid) or does not (is invalid). ## Type Parameters | Type Parameter | Description | | ------------------------------------------- | ------------------------------------- | | `T` | The underlying type | | `TValidity` *extends* `AffinePointValidity` | Whether the point is valid or invalid | ## Example ```ts const address = 'dv1ZAGvdsz5hHLwWXsVnM94hWf1pjbKVau1QVkaMJ92'; const onCurveAddress = address as AffinePoint; onCurveAddress satisfies AffinePoint<'dv1ZAGvdsz5hHLwWXsVnM94hWf1pjbKVau1QVkaMJ92', 'valid'>; // OK onCurveAddress satisfies AffinePoint; // OK onCurveAddress satisfies AffinePoint; // ERROR address satisfies AffinePoint; // ERROR address satisfies AffinePoint; // ERROR ``` # AllowedNumericKeypaths (/api/type-aliases/AllowedNumericKeypaths) ```ts type AllowedNumericKeypaths = Partial>; ``` ## Type Parameters | Type Parameter | | -------------- | | `TApi` | # ArrayCodecConfig (/api/type-aliases/ArrayCodecConfig) ```ts type ArrayCodecConfig = object; ``` Defines the configuration options for array codecs. ## Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `TPrefix` *extends* \| [`NumberCodec`](/api/type-aliases/NumberCodec) \| [`NumberDecoder`](/api/type-aliases/NumberDecoder) \| [`NumberEncoder`](/api/type-aliases/NumberEncoder) | A number codec, decoder, or encoder used for size prefixing. | ## Properties ### description? ```ts optional description?: string; ``` An optional description for the codec, that will be used in error messages. *** ### size? ```ts optional size?: ArrayLikeCodecSize; ``` Specifies how the size of the array is determined. * A [NumberCodec](/api/type-aliases/NumberCodec), [NumberDecoder](/api/type-aliases/NumberDecoder), or [NumberEncoder](/api/type-aliases/NumberEncoder) stores a size prefix before encoding the array. * A `number` enforces a fixed number of elements. * `"remainder"` uses all remaining bytes to infer the array length (only for fixed-size items). #### Default Value A `u32` size prefix. # ArrayLikeCodecSize (/api/type-aliases/ArrayLikeCodecSize) ```ts type ArrayLikeCodecSize = TPrefix | number | "remainder"; ``` Defines the possible size strategies for array-like codecs (`array`, `map`, and `set`). The size of the collection can be determined using one of the following approaches: * A [NumberCodec](/api/type-aliases/NumberCodec), [NumberDecoder](/api/type-aliases/NumberDecoder), or [NumberEncoder](/api/type-aliases/NumberEncoder) to store a size prefix. * A fixed `number` of items, enforcing an exact length. * The string `"remainder"`, which infers the number of items by consuming the rest of the available bytes. ## Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `TPrefix` *extends* \| [`NumberCodec`](/api/type-aliases/NumberCodec) \| [`NumberDecoder`](/api/type-aliases/NumberDecoder) \| [`NumberEncoder`](/api/type-aliases/NumberEncoder) | A number codec, decoder, or encoder used for size prefixing. | # AsyncClient (/api/type-aliases/AsyncClient) ```ts type AsyncClient = Promise> & object; ``` An asynchronous wrapper that represents a promise of a client. The `AsyncClient` type is returned when an async plugin is applied to a client. It behaves like a `Promise>` but with an additional `use` method that allows chaining more plugins before the promise resolves. This enables fluent chaining of both synchronous and asynchronous plugins without having to await intermediate promises. ## Type Declaration | Name | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | | `use()` | \<`TOutput`>(`plugin`) => `AsyncClient`\<`TOutput` *extends* [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\ ? `U` *extends* `object` ? `U` : `never` : `TOutput`> | Applies a plugin to the client once it resolves. | ## Type Parameters | Type Parameter | Description | | -------------------------- | ---------------------------------------------------------------------- | | `TSelf` *extends* `object` | The shape of the client object that this async client will resolve to. | # Base58EncodedBytes (/api/type-aliases/Base58EncodedBytes) ```ts type Base58EncodedBytes = EncodedString; ``` # Base58EncodedDataResponse (/api/type-aliases/Base58EncodedDataResponse) ```ts type Base58EncodedDataResponse = [Base58EncodedBytes, "base58"]; ``` # Base64EncodedBytes (/api/type-aliases/Base64EncodedBytes) ```ts type Base64EncodedBytes = EncodedString; ``` # Base64EncodedDataResponse (/api/type-aliases/Base64EncodedDataResponse) ```ts type Base64EncodedDataResponse = [Base64EncodedBytes, "base64"]; ``` # Base64EncodedWireTransaction (/api/type-aliases/Base64EncodedWireTransaction) ```ts type Base64EncodedWireTransaction = Brand, "Base64EncodedWireTransaction">; ``` Represents the wire format of a transaction as a base64-encoded string. # Base64EncodedZStdCompressedBytes (/api/type-aliases/Base64EncodedZStdCompressedBytes) ```ts type Base64EncodedZStdCompressedBytes = EncodedString, "base64">; ``` # Base64EncodedZStdCompressedDataResponse (/api/type-aliases/Base64EncodedZStdCompressedDataResponse) ```ts type Base64EncodedZStdCompressedDataResponse = [Base64EncodedZStdCompressedBytes, "base64+zstd"]; ``` # BaseOffchainMessageV0 (/api/type-aliases/BaseOffchainMessageV0) ```ts type BaseOffchainMessageV0 = Omit; ``` # BaseOffchainMessageV1 (/api/type-aliases/BaseOffchainMessageV1) ```ts type BaseOffchainMessageV1 = Omit; ``` # BaseSignerConfig (/api/type-aliases/BaseSignerConfig) ```ts type BaseSignerConfig = Readonly<{ abortSignal?: AbortSignal; }>; ``` The base configuration object for all signers β€” including transaction and message signers. # BinaryFixedPoint (/api/type-aliases/BinaryFixedPoint) ```ts type BinaryFixedPoint = object; ``` A fixed-point number whose scale is a power of 2. The stored `raw` bigint represents the mathematical value `raw / 2 ** fractionalBits`. Binary fixed-point is the fastest fractional representation to compute with β€” rescaling is a bit shift β€” so it is the preferred choice for audio samples, graphics, probabilities, and any other quantity where performance matters and the scale does not need to align with decimal digits. ## Example A 16-bit signed Q1.15 audio sample: ```ts type AudioSample = BinaryFixedPoint<'signed', 16, 15>; ``` ## See * [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) * [Signedness](/api/type-aliases/Signedness) ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------- | ----------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | Whether the value can be negative. | | `TTotalBits` *extends* `number` | The total number of bits used to store the raw value. | | `TFractionalBits` *extends* `number` | The number of bits to the right of the binary point. | ## Properties ### fractionalBits ```ts readonly fractionalBits: TFractionalBits; ``` *** ### kind ```ts readonly kind: "binaryFixedPoint"; ``` *** ### raw ```ts readonly raw: bigint; ``` *** ### signedness ```ts readonly signedness: TSignedness; ``` *** ### totalBits ```ts readonly totalBits: TTotalBits; ``` # BitArrayCodecConfig (/api/type-aliases/BitArrayCodecConfig) ```ts type BitArrayCodecConfig = object; ``` Defines the configuration options for bit array codecs. A bit array codec encodes an array of booleans into bits, packing them into bytes. This configuration allows adjusting the bit ordering. ## See * [getBitArrayEncoder](/api/functions/getBitArrayEncoder) * [getBitArrayDecoder](/api/functions/getBitArrayDecoder) * [getBitArrayCodec](/api/functions/getBitArrayCodec) ## Properties ### backward? ```ts optional backward?: boolean; ``` Determines whether the bits should be read in reverse order. * `false` (default): The first boolean is stored in the most significant bit (MSB-first). * `true`: The first boolean is stored in the least significant bit (LSB-first). #### Default Value `false` # BlockNotificationsApi (/api/type-aliases/BlockNotificationsApi) ```ts type BlockNotificationsApi = object; ``` ## Methods ### blockNotifications() #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards`: `false`; `transactionDetails`: `"none"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: `BlockNotificationsNotificationBlock` | `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards?`: `true`; `transactionDetails`: `"none"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only signatures of transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards`: `false`; `transactionDetails`: `"signatures"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithSignatures` \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only signatures of transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards?`: `true`; `transactionDetails`: `"signatures"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithSignatures` \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards`: `false`; `transactionDetails`: `"accounts"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForAccounts`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `BlockNotificationsEncoding`; `showRewards`: `false`; `transactionDetails`: `"accounts"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForAccounts`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards?`: `true`; `transactionDetails`: `"accounts"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForAccounts`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `BlockNotificationsEncoding`; `showRewards?`: `true`; `transactionDetails`: `"accounts"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForAccounts`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards`: `false`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullBase58`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `showRewards`: `false`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullBase58`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards?`: `true`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullBase58`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `showRewards?`: `true`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullBase58`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards`: `false`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullBase64`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `showRewards`: `false`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullBase64`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards?`: `true`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullBase64`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `showRewards?`: `true`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullBase64`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards`: `false`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullJsonParsed`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `showRewards`: `false`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullJsonParsed`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards?`: `true`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullJsonParsed`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `showRewards?`: `true`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullJsonParsed`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards`: `false`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullJson`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `showRewards`: `false`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullJson`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `maxSupportedTransactionVersion`: `BlockNotificationsMaxSupportedTransactionVersion`; `showRewards?`: `true`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullJson`\<`BlockNotificationsMaxSupportedTransactionVersion`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) #### Call Signature ```ts blockNotifications(filter, config?): SolanaRpcResponse> | null; }>>; ``` Subscribe to receive notifications anytime a new block reaches the specified level of commitment. The notification format is the same as seen in the GetBlockApi.getBlock RPC HTTP method. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `BlockNotificationsFilter` | Notifications will only be produced for blocks that match this filter. Only transactions that match this filter will be included in the block. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `BlockNotificationsEncoding`; `maxSupportedTransactionVersion?`: `BlockNotificationsMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `BlockNotificationTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `showRewards?`: `true`; `transactionDetails?`: `"full"`; }> | - | ##### Returns `SolanaRpcResponse`\<`BlockNotificationsNotificationBase` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: | `BlockNotificationsNotificationBlock` & `BlockNotificationsNotificationBlockWithRewards` & `BlockNotificationsNotificationBlockWithTransactions`\<`TransactionForFullJson`\<`void`>> \| `null`; }>> ##### See [https://solana.com/docs/rpc/websocket/blocksubscribe](https://solana.com/docs/rpc/websocket/blocksubscribe) # Blockhash (/api/type-aliases/Blockhash) ```ts type Blockhash = Brand, "Blockhash">; ``` # BlockhashLifetimeConstraint (/api/type-aliases/BlockhashLifetimeConstraint) ```ts type BlockhashLifetimeConstraint = Readonly<{ blockhash: Blockhash; lastValidBlockHeight: bigint; }>; ``` A constraint which, when applied to a transaction message, makes that transaction message eligible to land on the network. The transaction message will continue to be eligible to land until the network considers the `blockhash` to be expired. This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash is considered valid, or when the network switches to a fork where that blockhash is not present. # BooleanCodecConfig (/api/type-aliases/BooleanCodecConfig) ```ts type BooleanCodecConfig = object; ``` Defines the configuration options for boolean codecs. A boolean codec encodes `true` as `1` and `false` as `0`. The `size` option allows customizing the number codec used for storage. ## See * [getBooleanEncoder](/api/functions/getBooleanEncoder) * [getBooleanDecoder](/api/functions/getBooleanDecoder) * [getBooleanCodec](/api/functions/getBooleanCodec) ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `TSize` *extends* \| [`NumberCodec`](/api/type-aliases/NumberCodec) \| [`NumberDecoder`](/api/type-aliases/NumberDecoder) \| [`NumberEncoder`](/api/type-aliases/NumberEncoder) | A number codec, encoder, or decoder used for boolean representation. | ## Properties ### size? ```ts optional size?: TSize; ``` The number codec used to store boolean values. * By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`). * A custom number codec can be provided to change the storage size. #### Default Value `u8` # Brand (/api/type-aliases/Brand) ```ts type Brand = NominalType<"brand", TBrandName> & T; ``` Use this to produce a new type that satisfies the original type, but not the other way around. That is to say, the branded type is acceptable wherever the original type is specified, but wherever the branded type is specified, the original type will be insufficient. You can use this to create specialized instances of strings, numbers, objects, and more which you would like to assert are special in some way (eg. numbers that are non-negative, strings which represent the names of foods, objects that have passed validation). ## Type Parameters | Type Parameter | Description | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `T` | The base type to brand | | `TBrandName` *extends* `string` | A string that identifies a particular brand. Branded types with identical names will satisfy each other so long as their base types satisfy each other. Branded types with different names will never satisfy each other. | ## Example ```ts const unverifiedName = 'Alice'; const verifiedName = unverifiedName as Brand<'Alice', 'VerifiedName'>; 'Alice' satisfies Brand; // ERROR 'Alice' satisfies Brand<'Alice', 'VerifiedName'>; // ERROR unverifiedName satisfies Brand; // ERROR verifiedName satisfies Brand<'Bob', 'VerifiedName'>; // ERROR verifiedName satisfies Brand<'Alice', 'VerifiedName'>; // OK verifiedName satisfies Brand; // OK ``` # Callable (/api/type-aliases/Callable) ```ts type Callable = (...args) => any; ``` ## Parameters | Parameter | Type | | --------- | -------- | | ...`args` | `any`\[] | ## Returns `any` # CanceledSingleTransactionPlanResult (/api/type-aliases/CanceledSingleTransactionPlanResult) ```ts type CanceledSingleTransactionPlanResult = object; ``` A [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) with a 'canceled' status. This type represents a single transaction whose execution was canceled before it could complete. It includes the original planned message and a context object in which every field is optional β€” including [TransactionMessage](/api/type-aliases/TransactionMessage), [Signature](/api/type-aliases/Signature), and [Transaction](/api/type-aliases/Transaction) fields that may or may not be populated depending on how far execution progressed before cancellation. You may use the [canceledSingleTransactionPlanResult](/api/functions/canceledSingleTransactionPlanResult) helper to create objects of this type. ## Example Creating a canceled result from a transaction message. ```ts const result = canceledSingleTransactionPlanResult(transactionMessage); result satisfies CanceledSingleTransactionPlanResult; ``` ## See * [canceledSingleTransactionPlanResult](/api/functions/canceledSingleTransactionPlanResult) * [isCanceledSingleTransactionPlanResult](/api/functions/isCanceledSingleTransactionPlanResult) * [assertIsCanceledSingleTransactionPlanResult](/api/functions/assertIsCanceledSingleTransactionPlanResult) ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with the result. | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | The type of the transaction message. | ## Properties ### context ```ts context: Readonly>; ``` *** ### kind ```ts kind: "single"; ``` *** ### plannedMessage ```ts plannedMessage: TTransactionMessage; ``` *** ### planType ```ts planType: "transactionPlanResult"; ``` *** ### status ```ts status: "canceled"; ``` # Client (/api/type-aliases/Client) ```ts type Client = TSelf & object; ``` A client that can be extended with plugins. The `Client` type represents a client object that can be built up through the application of one or more plugins. It provides a `use` method to apply plugins, either synchronously (returning a new `Client`) or asynchronously (returning an [AsyncClient](/api/type-aliases/AsyncClient)). ## Type Declaration | Name | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `use()` | \<`TOutput`>(`plugin`) => `TOutput` *extends* [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\ ? [`AsyncClient`](/api/type-aliases/AsyncClient)\<`U` *extends* `object` ? `U` : `never`> : `Client`\<`TOutput`> | Applies a plugin to extend or transform the client. | ## Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------------------------------- | | `TSelf` *extends* `object` | The current shape of the client object including all applied plugins. | # ClientPlugin (/api/type-aliases/ClientPlugin) ```ts type ClientPlugin = (input) => TOutput; ``` Defines a plugin that transforms or extends a client with additional functionality. For instance, plugins may add RPC capabilities, wallet integration, transaction building, or other features necessary for interacting with the Solana blockchain. Plugins are functions that take a client object as input and return a new client object or a promise that resolves to a new client object. This allows for both synchronous and asynchronous transformations and extensions of the client. Plugins are usually applied using the `use` method on a [Client](/api/type-aliases/Client) or [AsyncClient](/api/type-aliases/AsyncClient) instance, which [createClient](/api/functions/createClient) provides as a starting point. ## Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | `TInput` *extends* `object` | The input client object type that this plugin accepts. | | `TOutput` *extends* \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`object`> \| `object` | The output type. Either a new client object or a promise resolving to one. | ## Parameters | Parameter | Type | | --------- | -------- | | `input` | `TInput` | ## Returns `TOutput` ## Examples **Basic RPC plugin** Given an RPC endpoint, this plugin adds an `rpc` property to the client. ```ts import { createClient, createSolanaRpc } from '@solana/kit'; // Define a simple RPC plugin. function rpcPlugin(endpoint: string) { return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) }); } // Use the plugin. const client = createClient().use(rpcPlugin('https://api.mainnet-beta.solana.com')); await client.rpc.getLatestBlockhash().send(); ``` **Async plugin that generates a payer wallet** The following plugin shows how to create an asynchronous plugin that generates a new keypair signer. ```ts import { createClient, generateKeypairSigner } from '@solana/kit'; // Define a plugin that generates a new keypair signer. function generatedPayerPlugin() { return async (client: T) => ({...client, payer: await generateKeypairSigner() }); } // Use the plugin. const client = await createClient().use(generatedPayerPlugin()); console.log(client.payer.address); ``` **Plugins with input requirements** A plugin can specify required properties on the input client. The example below requires the client to already have a `payer` signer attached to the client in order to perform an airdrop. ```ts import { createClient, TransactionSigner, Lamports, lamports } from '@solana/kit'; // Define a plugin that airdrops lamports to the payer set on the client. function airdropPayerPlugin(lamports: Lamports) { return async (client: T) => { await myAirdropFunction(client.payer, lamports); return client; }; } // Use the plugins. const client = await createClient() .use(generatedPayerPlugin()) // This is required before using the airdrop plugin. .use(airdropPayerPlugin(lamports(1_000_000_000n))); ``` **Chaining plugins** Multiple plugins β€” asynchronous or not β€” can be chained together to build up complex clients. The example below demonstrates how to gradually build a client with multiple plugins. Notice how, despite having multiple asynchronous plugins, we only need to `await` the final result. This is because the `use` method on `AsyncClient` returns another `AsyncClient`, allowing for seamless chaining. ```ts import { createClient, createSolanaRpc, createSolanaRpcSubscriptions, generateKeypairSigner } from '@solana/kit'; // Define multiple plugins. function rpcPlugin(endpoint: string) { return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) }); } function rpcSubscriptionsPlugin(endpoint: string) { return (client: T) => ({...client, rpc: createSolanaRpcSubscriptions(endpoint) }); } function generatedPayerPlugin() { return async (client: T) => ({...client, payer: await generateKeypairSigner() }); } function generatedAuthorityPlugin() { return async (client: T) => ({...client, authority: await generateKeypairSigner() }); } // Chain plugins together. const client = await createClient() .use(rpcPlugin('https://api.mainnet-beta.solana.com')) .use(rpcSubscriptionsPlugin('wss://api.mainnet-beta.solana.com')) .use(generatedPayerPlugin()) .use(generatedAuthorityPlugin()); ``` # ClientProviderProps (/api/type-aliases/ClientProviderProps) ```ts type ClientProviderProps = Readonly<{ children?: React.ReactNode; client: | Client | Promise>; }>; ``` Props accepted by [ClientProvider](/api/functions/ClientProvider). # ClientWithAirdrop (/api/type-aliases/ClientWithAirdrop) ```ts type ClientWithAirdrop = object; ``` Represents a client that can request airdrops of SOL to a specified address. The airdrop capability is typically available on test networks (devnet, testnet) and local validators. It allows funding accounts with SOL for testing purposes. ## Example ```ts async function fundAccount(client: ClientWithAirdrop, address: Address) { const signature = await client.airdrop(address, lamports(1_000_000_000n)); console.log(`Airdrop confirmed: ${signature ?? '[no signature]'}`); } ``` ## Properties ### airdrop ```ts airdrop: (address, amount, abortSignal?) => Promise; ``` Requests an airdrop of SOL to the specified address. The returned promise resolves when the airdrop succeeds and rejects on failure. Some implementations (e.g., LiteSVM) update account balances directly without sending a transaction, in which case no signature is returned. #### Parameters | Parameter | Type | Description | | -------------- | ----------------------------------------------------------------------- | ------------------------------------------------ | | `address` | `Address` | The address to receive the airdrop. | | `amount` | `Lamports` | The amount of lamports to airdrop. | | `abortSignal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | An optional signal to abort the airdrop request. | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`Signature` | `undefined`> A promise resolving to the transaction signature if the airdrop was performed via a transaction, or `undefined` if no transaction was used. # ClientWithFetchAccounts (/api/type-aliases/ClientWithFetchAccounts) ```ts type ClientWithFetchAccounts = object; ``` Represents a client that can fetch the content of accounts from their addresses. Different implementations may fetch accounts differently β€” for example, by calling the `getAccountInfo` and/or `getMultipleAccounts` RPC methods, by reading from a local validator, or by using a locally cached value. Note that this interface only fetches encoded accounts. Callers that need decoded accounts should decode the returned MaybeEncodedAccount | MaybeEncodedAccounts themselves using the codec of their choice. If you have a raw `Rpc` object instead of a client, you can construct a client implementing this interface using the createClientWithFetchAccountsFromRpc helper from `@solana/kit`. ## Example ```ts async function fetchProgramAddresses(client: ClientWithFetchAccounts, addresses: Address[]) { const accounts = await client.fetchAccounts(addresses); return accounts.filter(account => account.exists).map(account => account.programAddress); } ``` ## Properties ### fetchAccounts ```ts fetchAccounts: (addresses, config?) => Promise; ``` Fetches the encoded content of the accounts at the provided addresses. The returned array matches the provided addresses in both length and order. Each item is a MaybeEncodedAccount so that missing accounts can be represented whilst keeping track of their address. #### Parameters | Parameter | Type | Description | | ----------- | --------------------- | --------------------------------------- | | `addresses` | `Address`\[] | The addresses of the accounts to fetch. | | `config?` | `FetchAccountsConfig` | Optional configuration for the fetch. | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`MaybeEncodedAccount`\[]> A promise resolving to an array of MaybeEncodedAccount | MaybeEncodedAccounts in the same order as the provided addresses. # ClientWithGetMinimumBalance (/api/type-aliases/ClientWithGetMinimumBalance) ```ts type ClientWithGetMinimumBalance = object; ``` Represents a client that can compute the minimum balance required for an account to be exempt from deletion. Different implementations may compute this value differently β€” for example, by calling the `getMinimumBalanceForRentExemption` RPC method, or by using a locally cached value. ## Example ```ts async function logAccountCost(client: ClientWithGetMinimumBalance, dataSize: number) { const minimumBalance = await client.getMinimumBalance(dataSize); console.log(`Minimum balance for ${dataSize} bytes: ${minimumBalance} lamports`); } ``` ## Properties ### getMinimumBalance ```ts getMinimumBalance: (space, config?) => Promise; ``` Computes the minimum lamports required for an account with the given data size. By default, the 128-byte account header is added on top of the provided `space`. Pass `{ withoutHeader: true }` to skip adding the header bytes. #### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------- | ------------------------------------------- | | `space` | `number` | The number of bytes of account data. | | `config?` | [`GetMinimumBalanceConfig`](/api/type-aliases/GetMinimumBalanceConfig) | Optional configuration for the computation. | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`Lamports`> A promise resolving to the minimum Lamports required. #### See @solana/accounts#BASE\_ACCOUNT\_SIZE | BASE\_ACCOUNT\_SIZE for the account header size constant. # ClientWithIdentity (/api/type-aliases/ClientWithIdentity) ```ts type ClientWithIdentity = object; ``` Represents a client that provides a default identity signer. The identity is a TransactionSigner representing the wallet that owns things in the application β€” for instance, the authority over accounts, tokens, or other on-chain assets owned by the current user. Unlike [ClientWithPayer](/api/type-aliases/ClientWithPayer), which describes the signer responsible for paying transaction fees and storage costs, the identity describes the signer whose assets the application is acting upon. In many apps, the payer and identity refer to the same signer, but they can differ β€” for example, when a service pays fees on behalf of a user. ## Example ```ts function getOwnerAddress(client: ClientWithIdentity): Address { return client.identity.address; } ``` ## See [ClientWithPayer](/api/type-aliases/ClientWithPayer) ## Properties ### identity ```ts identity: TransactionSigner; ``` # ClientWithPayer (/api/type-aliases/ClientWithPayer) ```ts type ClientWithPayer = object; ``` Represents a client that provides a default transaction payer. The payer is a TransactionSigner used to sign and pay for transactions. Clients implementing this interface can automatically fund transactions without requiring callers to specify a fee payer explicitly. Unlike [ClientWithIdentity](/api/type-aliases/ClientWithIdentity), which describes the signer whose assets the application is acting upon, the payer describes the signer responsible for paying transaction fees as well as storage costs β€” i.e. the minimum balance required to keep newly created accounts alive based on their size. In many apps the payer and identity refer to the same signer, but they can differ β€” for example, when a service pays fees on behalf of a user. ## Example ```ts function createTransfer(client: ClientWithPayer, recipient: Address, amount: Lamports) { const feePayer = client.payer; // Use feePayer.address as the transaction fee payer } ``` ## See [ClientWithIdentity](/api/type-aliases/ClientWithIdentity) ## Properties ### payer ```ts payer: TransactionSigner; ``` # ClientWithRpc (/api/type-aliases/ClientWithRpc) ```ts type ClientWithRpc = object; ``` Represents a client that provides access to a Solana RPC endpoint. The RPC interface allows making JSON-RPC calls to a Solana validator, such as fetching account data, sending transactions, and querying blockchain state. ## Example ```ts import { SolanaRpcApi } from '@solana/rpc-api'; async function getBalance(client: ClientWithRpc, address: Address) { const { value: balance } = await client.rpc.getBalance(address).send(); return balance; } ``` ## Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------------------------------------------------------------------------------------- | | `TRpcMethods` | The RPC methods available on this client. Use specific method types from `@solana/rpc-api` for the Solana JSON-RPC API. | ## Properties ### rpc ```ts rpc: Rpc; ``` # ClientWithRpcSubscriptions (/api/type-aliases/ClientWithRpcSubscriptions) ```ts type ClientWithRpcSubscriptions = object; ``` Represents a client that provides access to Solana RPC subscriptions. RPC subscriptions enable real-time notifications from the Solana validator, such as account changes, slot updates, and transaction confirmations. ## Example ```ts import { SolanaRpcSubscriptionsApi } from '@solana/rpc-subscriptions-api'; async function subscribeToAccount( client: ClientWithRpcSubscriptions, address: Address, ) { const subscription = await client.rpcSubscriptions.accountNotifications(address).subscribe(); for await (const notification of subscription) { console.log('Account changed:', notification); } } ``` ## Type Parameters | Type Parameter | Description | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `TRpcSubscriptionsMethods` | The subscription methods available on this client. Use specific method types from `@solana/rpc-subscriptions-api` for the Solana subscription API. | ## Properties ### rpcSubscriptions ```ts rpcSubscriptions: RpcSubscriptions; ``` # ClientWithSubscribeToIdentity (/api/type-aliases/ClientWithSubscribeToIdentity) ```ts type ClientWithSubscribeToIdentity = object; ``` Represents a client that advertises `client.identity` as reactive. A plugin that can mutate `client.identity` over time installs this sibling function so that reactive consumers can re-read the capability without having to know which plugin installed it. The listener is invoked whenever the observable value of `client.identity` may have changed; consumers should re-read `client.identity` to get the current value. ## Example ```ts import { type ClientWithIdentity, type ClientWithSubscribeToIdentity } from '@solana/plugin-interfaces'; function observeIdentity(client: ClientWithIdentity & ClientWithSubscribeToIdentity) { return client.subscribeToIdentity(() => { console.log('identity is now', client.identity); }); } ``` ## See * [ClientWithIdentity](/api/type-aliases/ClientWithIdentity) * [ClientWithSubscribeToPayer](/api/type-aliases/ClientWithSubscribeToPayer) ## Properties ### subscribeToIdentity ```ts readonly subscribeToIdentity: SubscribeToFn; ``` Registers a listener to be called whenever `client.identity` may have changed. Returns an unsubscribe function. # ClientWithSubscribeToPayer (/api/type-aliases/ClientWithSubscribeToPayer) ```ts type ClientWithSubscribeToPayer = object; ``` Represents a client that advertises `client.payer` as reactive. A plugin that can mutate `client.payer` over time installs this sibling function so that reactive consumers can re-read the capability without having to know which plugin installed it. The listener is invoked whenever the observable value of `client.payer` may have changed; consumers should re-read `client.payer` to get the current value. ## Example ```ts import { type ClientWithPayer, type ClientWithSubscribeToPayer } from '@solana/plugin-interfaces'; function observePayer(client: ClientWithPayer & ClientWithSubscribeToPayer) { return client.subscribeToPayer(() => { console.log('payer is now', client.payer); }); } ``` ## See * [ClientWithPayer](/api/type-aliases/ClientWithPayer) * [ClientWithSubscribeToIdentity](/api/type-aliases/ClientWithSubscribeToIdentity) ## Properties ### subscribeToPayer ```ts readonly subscribeToPayer: SubscribeToFn; ``` Registers a listener to be called whenever `client.payer` may have changed. Returns an unsubscribe function. # ClientWithTransactionPlanning (/api/type-aliases/ClientWithTransactionPlanning) ```ts type ClientWithTransactionPlanning = object; ``` Represents a client that can plan transactions from instruction inputs. Transaction planning converts high-level instruction plans into concrete transaction messages, handling concerns like blockhash fetching, transaction splitting for size limits, and instruction ordering. ## Example ```ts async function prepareTransfer(client: ClientWithTransactionPlanning) { const instructions = [createTransferInstruction(...)]; // Plan a single transaction const message = await client.planTransaction(instructions); // Or plan potentially multiple transactions if needed const plan = await client.planTransactions(instructions); } ``` ## Properties ### planTransaction ```ts planTransaction: (input, config?) => Promise; ``` Plans a single transaction from the given instruction input. Use this when you expect all instructions to fit in a single transaction. #### Parameters | Parameter | Type | Description | | --------- | ---------------------- | --------------------------------------------------------------- | | `input` | `InstructionPlanInput` | The instruction plan input (instructions or instruction plans). | | `config?` | `Config` | Optional configuration including an abort signal. | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`SingleTransactionPlan`\[`"message"`]> A promise resolving to the planned transaction message. #### See InstructionPlanInput *** ### planTransactions ```ts planTransactions: (input, config?) => Promise; ``` Plans one or more transactions from the given instruction input. Use this when instructions might need to be split across multiple transactions due to size limits. #### Parameters | Parameter | Type | Description | | --------- | ---------------------- | --------------------------------------------------------------- | | `input` | `InstructionPlanInput` | The instruction plan input (instructions or instruction plans). | | `config?` | `Config` | Optional configuration including an abort signal. | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TransactionPlan`> A promise resolving to the full transaction plan. #### See InstructionPlanInput # ClientWithTransactionSending (/api/type-aliases/ClientWithTransactionSending) ```ts type ClientWithTransactionSending = object; ``` Represents a client that can send transactions to the Solana network. Transaction sending handles signing, submission, and confirmation of transactions. It supports flexible input formats including instructions, instruction plans, transaction messages or transaction plans. ## Example ```ts async function executeTransfer(client: ClientWithTransactionSending) { const instructions = [createTransferInstruction(...)]; // Send a single transaction const result = await client.sendTransaction(instructions); console.log(`Transaction confirmed: ${result.context.signature}`); // Or send potentially multiple transactions const results = await client.sendTransactions(instructions); } ``` ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TContext` *extends* `TransactionPlanResultContext` | `TransactionPlanResultContextWithSignature` | The context attached to the results. It defaults to TransactionPlanResultContextWithSignature, which guarantees a `context.signature` on every successful result. Supply a different context to change or drop that guarantee β€” for instance, a client whose executor records extra fields on the context. | ## Properties ### sendTransaction ```ts sendTransaction: (input, config?) => Promise>; ``` Sends a single transaction to the network. Accepts flexible input: instructions, instruction plans, a single transaction message or a single transaction plan. #### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | `input` | \| `InstructionPlanInput` \| `SingleTransactionPlan` \| `SingleTransactionPlan`\[`"message"`] | Instructions, a transaction plan, or a transaction message. | | `config?` | `Config` | Optional configuration including an abort signal. | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`SuccessfulSingleTransactionPlanResult`\<`TContext`>> A promise resolving to the successful transaction result. #### See * InstructionPlanInput * SingleTransactionPlan *** ### sendTransactions ```ts sendTransactions: (input, config?) => Promise>; ``` Sends one or more transactions to the network. Accepts flexible input: instructions, instruction plans, transaction messages or transaction plans. #### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------ | ------------------------------------------------- | | `input` | `InstructionPlanInput` \| `TransactionPlanInput` | Any instruction or a transaction plan input. | | `config?` | `Config` | Optional configuration including an abort signal. | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TransactionPlanResult`\<`TContext`>> A promise resolving to the results for all transactions. #### See * InstructionPlanInput * TransactionPlanInput # ClientWithTransactionSigning (/api/type-aliases/ClientWithTransactionSigning) ```ts type ClientWithTransactionSigning = object; ``` Represents a client that can sign transactions without submitting them to the network. Transaction signing accepts the same flexible inputs as [ClientWithTransactionSending](/api/type-aliases/ClientWithTransactionSending) β€” instructions, instruction plans, transaction messages or transaction plans β€” but stops short of sending the resulting transactions. Use it to hand transactions off to another party, such as an authority wallet signing a transaction that a relayer will pay for and submit later. ## Example ```ts async function signTransfer(client: ClientWithTransactionSigning<{ transaction: Transaction }>) { const instructions = [createTransferInstruction(...)]; // Sign a single transaction const result = await client.signTransaction(instructions); const transaction = result.context.transaction; // Or sign potentially multiple transactions const results = await client.signTransactions(instructions); } ``` ## See [ClientWithTransactionSending](/api/type-aliases/ClientWithTransactionSending) ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TContext` *extends* `TransactionPlanResultContext` | `TransactionPlanResultContext` | The context attached to the results. The interface makes no claim about what that context contains: it is entirely decided by the plugin providing the capability, which would typically guarantee a `context.transaction` on successful results. Note that this differs from [ClientWithTransactionSending](/api/type-aliases/ClientWithTransactionSending), whose default context preserves the `context.signature` guarantee that predates configurable contexts. | ## Properties ### signTransaction ```ts signTransaction: (input, config?) => Promise>; ``` Signs a single transaction without sending it. Accepts flexible input: instructions, instruction plans, a single transaction message or a single transaction plan. #### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | `input` | \| `InstructionPlanInput` \| `SingleTransactionPlan` \| `SingleTransactionPlan`\[`"message"`] | Instructions, a transaction plan, or a transaction message. | | `config?` | `Config` | Optional configuration including an abort signal. | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`SuccessfulSingleTransactionPlanResult`\<`TContext`>> A promise resolving to the successful transaction result, carrying the `TContext` the client was parameterised with. #### See * InstructionPlanInput * SingleTransactionPlan *** ### signTransactions ```ts signTransactions: (input, config?) => Promise>; ``` Signs one or more transactions without sending them. Accepts flexible input: instructions, instruction plans, transaction messages or transaction plans. #### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------ | ------------------------------------------------- | | `input` | `InstructionPlanInput` \| `TransactionPlanInput` | Any instruction or a transaction plan input. | | `config?` | `Config` | Optional configuration including an abort signal. | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TransactionPlanResult`\<`TContext`>> A promise resolving to the results for all transactions. Successful leaves carry the `TContext` the client was parameterised with. #### See * InstructionPlanInput * TransactionPlanInput # ClusterUrl (/api/type-aliases/ClusterUrl) ```ts type ClusterUrl = | DevnetUrl | MainnetUrl | TestnetUrl | string; ``` # Codec (/api/type-aliases/Codec) ```ts type Codec = | FixedSizeCodec | VariableSizeCodec; ``` An object that can encode and decode a value to and from a byte array. A `Codec` can be either: * A [FixedSizeCodec](/api/interfaces/FixedSizeCodec), where all encoded values have the same fixed size. * A [VariableSizeCodec](/api/interfaces/VariableSizeCodec), where encoded values can vary in size. ## Type Parameters | Type Parameter | Default type | | ----------------------- | ------------ | | `TFrom` | - | | `TTo` *extends* `TFrom` | `TFrom` | ## Example ```ts const codec: Codec; const bytes = codec.encode('hello'); const value = codec.decode(bytes); // 'hello' ``` ## Remarks For convenience, codecs can encode looser types than they decode. That is, type [TFrom](#tfrom) can be a superset of type [TTo](#tto). For instance, a `Codec` can encode both `bigint` and `number` values, but will always decode to a `bigint`. ```ts const codec: Codec; const bytes = codec.encode(42); const value = codec.decode(bytes); // 42n ``` It is worth noting that codecs are the union of encoders and decoders. This means that a `Codec` can be combined from an `Encoder` and a `Decoder` using the [combineCodec](/api/functions/combineCodec) function. This is particularly useful for library authors who want to expose all three types of objects to their users. ```ts const encoder: Encoder; const decoder: Decoder; const codec: Codec = combineCodec(encoder, decoder); ``` Aside from combining encoders and decoders, codecs can also be created from scratch using the [createCodec](/api/functions/createCodec) function but it is more common to compose multiple codecs together using the various helpers of the `@solana/codecs` package. For instance, here's how you might create a `Codec` for a `Person` object type that contains a `name` string and an `age` number: ```ts import { getStructCodec, addCodecSizePrefix, getUtf8Codec, getU32Codec } from '@solana/codecs'; type Person = { name: string; age: number }; const getPersonCodec = (): Codec => getStructCodec([ ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], ['age', getU32Codec()], ]); ``` Note that composed `Codec` types are clever enough to understand whether they are fixed-size or variable-size. In the example above, `getU32Codec()` is a fixed-size codec, while `addCodecSizePrefix(getUtf8Codec(), getU32Codec())` is a variable-size codec. This makes the final `Person` codec a variable-size codec. ## See * [FixedSizeCodec](/api/interfaces/FixedSizeCodec) * [VariableSizeCodec](/api/interfaces/VariableSizeCodec) * [combineCodec](/api/functions/combineCodec) * [createCodec](/api/functions/createCodec) # Commitment (/api/type-aliases/Commitment) ```ts type Commitment = "confirmed" | "finalized" | "processed"; ``` A union of all possible commitment statuses -- each a measure of the network confirmation and stake levels on a particular block. Read more about the statuses themselves, [here](https://docs.solana.com/cluster/commitments). # CompiledTransactionMessage (/api/type-aliases/CompiledTransactionMessage) ```ts type CompiledTransactionMessage = | LegacyCompiledTransactionMessage | V0CompiledTransactionMessage | V1CompiledTransactionMessage; ``` A transaction message in a form suitable for encoding for execution on the network. You can not fully reconstruct a source message from a compiled message without extra information. In particular, supporting details about the lifetime constraint and the concrete addresses of accounts sourced from account lookup tables are lost to compilation. # CompiledTransactionMessageWithLifetime (/api/type-aliases/CompiledTransactionMessageWithLifetime) ```ts type CompiledTransactionMessageWithLifetime = Readonly<{ lifetimeToken: ReturnType; }>; ``` # CompressedData (/api/type-aliases/CompressedData) ```ts type CompressedData = NominalType<"compressionFormat", TFormat> & T; ``` Use this to produce a new type that satisfies the original type, but adds extra type information that marks the type as containing compressed data. ## Type Parameters | Type Parameter | Description | | --------------------------------------- | ----------------------------------------------------- | | `T` | The base type to mark as representing compressed data | | `TFormat` *extends* `CompressionFormat` | The compression format of the underlying data | ## Example ```ts const untaggedData = new Uint8Array([/* ... */]); const compressedData = untaggedData as CompressedData; compressedData satisfies CompressedData; // OK untaggedData satisfies CompressedData; // ERROR ``` # Config (/api/type-aliases/Config) ```ts type Config = Readonly<{ sendBufferHighWatermark: number; signal: AbortSignal; url: string; }>; ``` # CreateReactiveStoreWithInitialValueAndSlotTrackingConfig (/api/type-aliases/CreateReactiveStoreWithInitialValueAndSlotTrackingConfig) ```ts type CreateReactiveStoreWithInitialValueAndSlotTrackingConfig = Readonly<{ initialValueMapper: (value) => TItem; initialValueSource: ReactiveActionSource>; streamSource: ReactiveStreamSource>; streamValueMapper: (value) => TItem; }>; ``` Configuration for [createReactiveStoreWithInitialValueAndSlotTracking](/api/functions/createReactiveStoreWithInitialValueAndSlotTracking). Pairs a one-shot initial-value source with an ongoing stream source so the resulting store can hydrate from the initial response and keep up to date with notifications, slot-deduplicating the two sources. ## Type Parameters | Type Parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `TInitialValue` | The value type produced by `initialValueSource` (inside the [SolanaRpcResponse](/api/type-aliases/SolanaRpcResponse) envelope). | | `TStreamValue` | The value type emitted by `streamSource` (inside the [SolanaRpcResponse](/api/type-aliases/SolanaRpcResponse) envelope). | | `TItem` | The unified item type the store holds, produced by the two value mappers. | ## See [createReactiveStoreWithInitialValueAndSlotTracking](/api/functions/createReactiveStoreWithInitialValueAndSlotTracking) # DataSlice (/api/type-aliases/DataSlice) ```ts type DataSlice = Readonly<{ length: number; offset: number; }>; ``` # DecimalFixedPoint (/api/type-aliases/DecimalFixedPoint) ```ts type DecimalFixedPoint = object; ``` A fixed-point number whose scale is a power of 10. The stored `raw` bigint represents the mathematical value `raw / 10 ** decimals`. Decimal fixed-point is the natural representation for quantities that users reason about in base-10 terms, such as token amounts, currency, or probabilities with decimal precision. ## Example An unsigned 64-bit USDC amount with 6 decimals of precision: ```ts type Usdc = DecimalFixedPoint<'unsigned', 64, 6>; ``` ## See * [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) * [Signedness](/api/type-aliases/Signedness) ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------- | --------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | Whether the value can be negative. | | `TTotalBits` *extends* `number` | The total number of bits used to store the raw value. | | `TDecimals` *extends* `number` | The number of decimal digits to the right of the decimal point. | ## Properties ### decimals ```ts readonly decimals: TDecimals; ``` *** ### kind ```ts readonly kind: "decimalFixedPoint"; ``` *** ### raw ```ts readonly raw: bigint; ``` *** ### signedness ```ts readonly signedness: TSignedness; ``` *** ### totalBits ```ts readonly totalBits: TTotalBits; ``` # DecodedRpcTransaction (/api/type-aliases/DecodedRpcTransaction) ```ts type DecodedRpcTransaction = Readonly<{ compiledMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime; loadedAddresses: LoadedAddresses; transaction?: Transaction; }>; ``` The result of decoding a confirmed-transaction RPC response: the CompiledTransactionMessage (always with a `lifetimeToken` carrying the recent blockhash), the loaded ALT addresses pulled from `meta` (if any), and β€” for `'base64'` and `'base58'` responses β€” the wire-format Transaction. `transaction` is omitted for `encoding: 'json'` responses: the server has already decompiled the wire format, so there are no message bytes to round-trip. If you need a re-encodable Transaction, fetch the response with `encoding: 'base64'`. ## Example ```ts const { compiledMessage, loadedAddresses, transaction } = decodeTransactionFromRpcResponse(rpcResponse); ``` # Decoder (/api/type-aliases/Decoder) ```ts type Decoder = | FixedSizeDecoder | VariableSizeDecoder; ``` An object that can decode a byte array into a value of type [TTo](#tto). An `Decoder` can be either: * A [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder), where all byte arrays have the same fixed size. * A [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder), where byte arrays can vary in size. ## Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ## Examples Getting the decoded value from a byte array. ```ts const decoder: Decoder; const value = decoder.decode(bytes); ``` Reading the decoded value from a byte array at a specific offset and getting the offset of the next byte to read. ```ts const decoder: Decoder; const [value, nextOffset] = decoder.read('hello', bytes, 20); ``` ## Remarks You may create `Decoders` manually using the [createDecoder](/api/functions/createDecoder) function but it is more common to compose multiple `Decoders` together using the various helpers of the `@solana/codecs` package. For instance, here's how you might create an `Decoder` for a `Person` object type that contains a `name` string and an `age` number: ```ts import { getStructDecoder, addDecoderSizePrefix, getUtf8Decoder, getU32Decoder } from '@solana/codecs'; type Person = { name: string; age: number }; const getPersonDecoder = (): Decoder => getStructDecoder([ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())], ['age', getU32Decoder()], ]); ``` Note that composed `Decoder` types are clever enough to understand whether they are fixed-size or variable-size. In the example above, `getU32Decoder()` is a fixed-size decoder, while `addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())` is a variable-size decoder. This makes the final `Person` decoder a variable-size decoder. ## See * [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) * [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) * [createDecoder](/api/functions/createDecoder) # DecompileTransactionMessageConfig (/api/type-aliases/DecompileTransactionMessageConfig) ```ts type DecompileTransactionMessageConfig = object; ``` ## Properties ### addressesByLookupTableAddress? ```ts optional addressesByLookupTableAddress?: AddressesByLookupTableAddress; ``` Only used for V0 transactions. If the compiled message loads addresses from one or more address lookup tables, you will have to supply a map of those tables to an array of the addresses they contained at the time that the transaction message was constructed. #### See decompileTransactionMessageFetchingLookupTables if you do not already have this. *** ### lastValidBlockHeight? ```ts optional lastValidBlockHeight?: bigint; ``` If the compiled message has a blockhash-based lifetime constraint, you will have to supply the block height after which that blockhash is no longer valid for use as a lifetime constraint. # DefaultRpcSubscriptionsChannelConfig (/api/type-aliases/DefaultRpcSubscriptionsChannelConfig) ```ts type DefaultRpcSubscriptionsChannelConfig = Readonly<{ intervalMs?: number; maxSubscriptionsPerChannel?: number; minChannels?: number; sendBufferHighWatermark?: number; url: TClusterUrl; }>; ``` ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | # DefaultRpcSubscriptionsTransportConfig (/api/type-aliases/DefaultRpcSubscriptionsTransportConfig) ```ts type DefaultRpcSubscriptionsTransportConfig = Readonly<{ createChannel: RpcSubscriptionsChannelCreatorFromClusterUrl; }>; ``` ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | # DependentStructDecoderBuilder (/api/type-aliases/DependentStructDecoderBuilder) ```ts type DependentStructDecoderBuilder = object; ``` A fluent builder that accumulates field decoders for a struct whose later fields may depend on the values of earlier ones. Each call to [\`field\`](#field) returns a new builder whose accumulated field type is widened by the newly added field. Call [\`build\`](#build) to obtain the final [Decoder](/api/type-aliases/Decoder) once every field has been declared. The builder tracks at the type level whether the struct decoded so far has a fixed size. Adding a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) preserves that property, while adding a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) or a [field factory](/api/type-aliases/DependentStructDecoderFieldFactory) drops the builder to variable size and it stays variable thereafter. Instances of this type are immutable. Calling `field` does not mutate the receiver; it returns a new builder. ## See [createDependentStructDecoder](/api/functions/createDependentStructDecoder) ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TFields` *extends* [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `unknown`> | The shape of the struct that has been accumulated so far. | | `TIsFixedSize` *extends* `boolean` | `true` while every field added so far is a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder), `false` once any variable size decoder or factory has been added. | ## Methods ### build() ```ts build(): TIsFixedSize extends true ? FixedSizeDecoder> : VariableSizeDecoder>; ``` Finalizes the builder and returns a [Decoder](/api/type-aliases/Decoder) that decodes each declared field in turn, in the order they were added. Returns a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) when every field has been added with a fixed size decoder, and a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) otherwise. #### Returns `TIsFixedSize` *extends* `true` ? [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`DrainOuterGeneric`\<`TFields`>> : [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`DrainOuterGeneric`\<`TFields`>> *** ### field() #### Call Signature ```ts field(name, decoder): DependentStructDecoderBuilder, false>; ``` Adds a field decoded by a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). Drops the builder to variable size; subsequent [field](#field) calls cannot raise it back to fixed size. Adding a field that has already been declared on this builder is a compile time error. ##### Type Parameters | Type Parameter | | -------------------------- | | `TName` *extends* `string` | | `TValue` | ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `name` | `TName` *extends* keyof `TFields` ? `never` : `TName` | | `decoder` | [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TValue`> | ##### Returns `DependentStructDecoderBuilder`\<`DrainOuterGeneric`\<`TFields` & `{ [K in string]: TValue }`>, `false`> #### Call Signature ```ts field(name, factory): DependentStructDecoderBuilder, false>; ``` Adds a field whose decoder is built from a frozen snapshot of the fields that precede it. Drops the builder to variable size since the byte length of the produced decoder cannot be known at type time. Adding a field that has already been declared on this builder is a compile time error. ##### Type Parameters | Type Parameter | | -------------------------- | | `TName` *extends* `string` | | `TValue` | ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------ | | `name` | `TName` *extends* keyof `TFields` ? `never` : `TName` | | `factory` | [`DependentStructDecoderFieldFactory`](/api/type-aliases/DependentStructDecoderFieldFactory)\<`TFields`, `TValue`> | ##### Returns `DependentStructDecoderBuilder`\<`DrainOuterGeneric`\<`TFields` & `{ [K in string]: TValue }`>, `false`> #### Call Signature ```ts field(name, decoder): DependentStructDecoderBuilder, TIsFixedSize>; ``` Adds a field decoded by a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder). Preserves the fixed size property of the builder. Adding a field that has already been declared on this builder is a compile time error. ##### Type Parameters | Type Parameter | | -------------------------- | | `TName` *extends* `string` | | `TValue` | ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------- | | `name` | `TName` *extends* keyof `TFields` ? `never` : `TName` | | `decoder` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TValue`> | ##### Returns `DependentStructDecoderBuilder`\<`DrainOuterGeneric`\<`TFields` & `{ [K in string]: TValue }`>, `TIsFixedSize`> # DependentStructDecoderFieldFactory (/api/type-aliases/DependentStructDecoderFieldFactory) ```ts type DependentStructDecoderFieldFactory = (fields) => Decoder; ``` A function that builds a [Decoder](/api/type-aliases/Decoder) for a struct field whose shape depends on the values of previously decoded fields in the same struct. The function receives a frozen snapshot of all fields that have been decoded so far, in declaration order, and must return the [Decoder](/api/type-aliases/Decoder) that should be used to read the current field from the byte stream. ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- | | `TPriorFields` *extends* [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `unknown`> | The shape of the fields that have already been decoded by the time this factory is invoked. | | `TValue` | The type of the value produced by the returned decoder. | ## Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------- | | `fields` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<`TPriorFields`> | ## Returns [`Decoder`](/api/type-aliases/Decoder)\<`TValue`> ## See [createDependentStructDecoder](/api/functions/createDependentStructDecoder) # DevnetUrl (/api/type-aliases/DevnetUrl) ```ts type DevnetUrl = string & object; ``` ## Type Declaration | Name | Type | | ---------- | ---------- | | `~cluster` | `"devnet"` | # DiscriminatedUnion (/api/type-aliases/DiscriminatedUnion) ```ts type DiscriminatedUnion = { [P in TDiscriminatorProperty]: TDiscriminatorValue }; ``` Represents a discriminated union using a specific discriminator property. A discriminated union is a TypeScript-friendly way to represent Rust-like enums. Each variant in the union is distinguished by a shared discriminator property. ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------- | ------------ | --------------------------------------- | | `TDiscriminatorProperty` *extends* `string` | `"__kind"` | The name of the discriminator property. | | `TDiscriminatorValue` *extends* `string` | `string` | The type of the discriminator value. | ## Example ```ts type Message = | { __kind: 'Quit' } // Empty variant | { __kind: 'Write'; fields: [string] } // Tuple variant | { __kind: 'Move'; x: number; y: number }; // Struct variant ``` # DiscriminatedUnionCodecConfig (/api/type-aliases/DiscriminatedUnionCodecConfig) ```ts type DiscriminatedUnionCodecConfig = object; ``` Defines the configuration for discriminated union codecs. This configuration controls how the discriminator is stored and named. ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `TDiscriminatorProperty` *extends* `string` | `"__kind"` | The property name of the discriminator. | | `TDiscriminatorSize` | \| [`NumberCodec`](/api/type-aliases/NumberCodec) \| [`NumberDecoder`](/api/type-aliases/NumberDecoder) \| [`NumberEncoder`](/api/type-aliases/NumberEncoder) | The codec used for the discriminator prefix. | ## Properties ### discriminator? ```ts optional discriminator?: TDiscriminatorProperty; ``` The property name of the discriminator. #### Default Value `__kind` *** ### size? ```ts optional size?: TDiscriminatorSize; ``` The codec used to encode/decode the discriminator prefix. #### Default Value `u8` prefix # EncodedString (/api/type-aliases/EncodedString) ```ts type EncodedString = NominalType<"stringEncoding", TEncoding> & T; ``` Use this to produce a new type that satisfies the original string type, but adds extra type information that marks the string as being encoded in a particular format. ## Type Parameters | Type Parameter | Description | | -------------------------------------- | --------------------------------- | | `T` *extends* `string` | The underlying string type | | `TEncoding` *extends* `StringEncoding` | The encoding format of the string | ## Example ```ts const untaggedString = 'dv1ZAGvdsz5hHLwWXsVnM94hWf1pjbKVau1QVkaMJ92'; const encodedString = untaggedString as EncodedString; encodedString satisfies EncodedString<'dv1ZAGvdsz5hHLwWXsVnM94hWf1pjbKVau1QVkaMJ92', 'base58'>; // OK encodedString satisfies EncodedString; // OK encodedString satisfies EncodedString; // ERROR untaggedString satisfies EncodedString; // ERROR ``` # Encoder (/api/type-aliases/Encoder) ```ts type Encoder = | FixedSizeEncoder | VariableSizeEncoder; ``` An object that can encode a value of type [TFrom](#tfrom) into a [ReadonlyUint8Array](/api/interfaces/ReadonlyUint8Array). An `Encoder` can be either: * A [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder), where all encoded values have the same fixed size. * A [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder), where encoded values can vary in size. ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ## Examples Encoding a value into a new byte array. ```ts const encoder: Encoder; const bytes = encoder.encode('hello'); ``` Writing the encoded value into an existing byte array. ```ts const encoder: Encoder; const bytes = new Uint8Array(100); const nextOffset = encoder.write('hello', bytes, 20); ``` ## Remarks You may create `Encoders` manually using the [createEncoder](/api/functions/createEncoder) function but it is more common to compose multiple `Encoders` together using the various helpers of the `@solana/codecs` package. For instance, here's how you might create an `Encoder` for a `Person` object type that contains a `name` string and an `age` number: ```ts import { getStructEncoder, addEncoderSizePrefix, getUtf8Encoder, getU32Encoder } from '@solana/codecs'; type Person = { name: string; age: number }; const getPersonEncoder = (): Encoder => getStructEncoder([ ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())], ['age', getU32Encoder()], ]); ``` Note that composed `Encoder` types are clever enough to understand whether they are fixed-size or variable-size. In the example above, `getU32Encoder()` is a fixed-size encoder, while `addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())` is a variable-size encoder. This makes the final `Person` encoder a variable-size encoder. ## See * [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder) * [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder) * [createEncoder](/api/functions/createEncoder) # EnumCodecConfig (/api/type-aliases/EnumCodecConfig) ```ts type EnumCodecConfig = object; ``` Defines the configuration options for enum codecs. The `size` option determines the numerical encoding used for the enum's discriminant. By default, enums are stored as a `u8` (1 byte). The `useValuesAsDiscriminators` option allows mapping the actual enum values as discriminators instead of using their positional index. ## Type Parameters | Type Parameter | Description | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `TDiscriminator` *extends* \| [`NumberCodec`](/api/type-aliases/NumberCodec) \| [`NumberDecoder`](/api/type-aliases/NumberDecoder) \| [`NumberEncoder`](/api/type-aliases/NumberEncoder) | A number codec, encoder, or decoder used for the discriminant. | ## Properties ### size? ```ts optional size?: TDiscriminator; ``` The codec used to encode/decode the enum discriminator. #### Default Value `u8` discriminator. *** ### useValuesAsDiscriminators? ```ts optional useValuesAsDiscriminators?: boolean; ``` If set to `true`, the enum values themselves will be used as discriminators. This is only valid for numerical enum values. #### Default Value `false` # Epoch (/api/type-aliases/Epoch) ```ts type Epoch = bigint; ``` # ExcludeTransactionMessageDurableNonceLifetime (/api/type-aliases/ExcludeTransactionMessageDurableNonceLifetime) ```ts type ExcludeTransactionMessageDurableNonceLifetime = TTransactionMessage extends TransactionMessageWithDurableNonceLifetime ? ExcludeTransactionMessageLifetime : TTransactionMessage; ``` A helper type to exclude the durable nonce lifetime constraint from a transaction message. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | # ExcludeTransactionMessageLifetime (/api/type-aliases/ExcludeTransactionMessageLifetime) ```ts type ExcludeTransactionMessageLifetime = TTransactionMessage extends unknown ? Omit : never; ``` A helper type to exclude any lifetime constraint from a transaction message. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | # ExcludeTransactionMessageWithinSizeLimit (/api/type-aliases/ExcludeTransactionMessageWithinSizeLimit) ```ts type ExcludeTransactionMessageWithinSizeLimit = Omit; ``` Helper type that removes the `TransactionMessageWithinSizeLimit` flag from a transaction message. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | # ExtendedClient (/api/type-aliases/ExtendedClient) ```ts type ExtendedClient = { [K in keyof (Omit & TAdditions)]: (Omit & TAdditions)[K] } & object; ``` The result of extending a client of type `TClient` with additional properties of type `TAdditions`. Structurally equivalent to `Omit & TAdditions` β€” keys present on both `TClient` and `TAdditions` are replaced by the `TAdditions` version β€” but expressed as a single homomorphic mapped type so the inferred type displays as a flat object literal rather than a deeply nested chain of `Omit<...>` intersections. Optional (`?`) and `readonly` modifiers from both sides are preserved. Plugin authors who write their own merging helpers can reuse this type to keep the inferred shape of their plugin's output legible in editor tooltips and error messages. ## Type Parameters | Type Parameter | Description | | ------------------------------- | ------------------------------------------- | | `TClient` *extends* `object` | The type of the client being extended. | | `TAdditions` *extends* `object` | The type of the properties being merged in. | ## Example ```ts function withRpc(client: TClient, endpoint: string): ExtendedClient { return extendClient(client, { rpc: createSolanaRpc(endpoint) }); } ``` ## See [extendClient](/api/functions/extendClient) # F64UnsafeSeeDocumentation (/api/type-aliases/F64UnsafeSeeDocumentation) ```ts type F64UnsafeSeeDocumentation = number; ``` # FailedSingleTransactionPlanResult (/api/type-aliases/FailedSingleTransactionPlanResult) ```ts type FailedSingleTransactionPlanResult = object; ``` A [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) with a 'failed' status. This type represents a single transaction that failed during execution. It includes the original planned message, the [Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) that caused the failure, and a context object in which every field is optional β€” including [TransactionMessage](/api/type-aliases/TransactionMessage), [Signature](/api/type-aliases/Signature), and [Transaction](/api/type-aliases/Transaction) fields that may or may not be populated depending on how far execution progressed before the failure. You may use the [failedSingleTransactionPlanResult](/api/functions/failedSingleTransactionPlanResult) helper to create objects of this type. ## Example Creating a failed result from a transaction message and error. ```ts const result = failedSingleTransactionPlanResult( transactionMessage, new Error('Transaction simulation failed'), ); result satisfies FailedSingleTransactionPlanResult; result.error; // The error that caused the failure. ``` ## See * [failedSingleTransactionPlanResult](/api/functions/failedSingleTransactionPlanResult) * [isFailedSingleTransactionPlanResult](/api/functions/isFailedSingleTransactionPlanResult) * [assertIsFailedSingleTransactionPlanResult](/api/functions/assertIsFailedSingleTransactionPlanResult) ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with the result. | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | The type of the transaction message. | ## Properties ### context ```ts context: Readonly>; ``` *** ### error ```ts error: Error; ``` *** ### kind ```ts kind: "single"; ``` *** ### plannedMessage ```ts plannedMessage: TTransactionMessage; ``` *** ### planType ```ts planType: "transactionPlanResult"; ``` *** ### status ```ts status: "failed"; ``` # FixedPointCodecConfig (/api/type-aliases/FixedPointCodecConfig) ```ts type FixedPointCodecConfig = object; ``` Configuration options for fixed-point codecs. ## Properties ### endian? ```ts optional endian?: "be" | "le"; ``` Whether values are serialized in little- or big-endian byte order. #### Default Value `'le'` # FixedPointToStringOptions (/api/type-aliases/FixedPointToStringOptions) ```ts type FixedPointToStringOptions = object; ``` Options accepted by `binaryFixedPointToString` and `decimalFixedPointToString` to control the emitted representation. * `decimals`: caps the number of fractional digits in the output. When this is lower than the value's native precision the raw value is rescaled using `rounding` (defaults to `'strict'`, which throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` on inexact results). When higher, the extra precision is zero-padded only if `padTrailingZeros` is also set. * `padTrailingZeros`: emits exactly as many fractional digits as requested by `decimals`. When `decimals` is omitted, pads to the value's native scale (`decimals` for decimal values, `fractionalBits` for binary values β€” the length of the exact base-10 expansion). Defaults to `false`, which trims trailing zeros (and drops the decimal point altogether for whole numbers). * `rounding`: only consulted when `decimals` forces a scale-down. Defaults to `'strict'`. ## Properties ### decimals? ```ts optional decimals?: number; ``` *** ### padTrailingZeros? ```ts optional padTrailingZeros?: boolean; ``` *** ### rounding? ```ts optional rounding?: RoundingMode; ``` # FixedSizeNumberCodec (/api/type-aliases/FixedSizeNumberCodec) ```ts type FixedSizeNumberCodec = | FixedSizeCodec | FixedSizeCodec; ``` Represents a fixed-size codec for encoding and decoding numbers and bigints. This codec uses a specific number of bytes (`TSize`) for serialization. The encoded value can be either a `number` or `bigint`, but the decoded value will always be a `number` or `bigint`, depending on the implementation. ## Type Parameters | Type Parameter | Default type | Description | | -------------------------- | ------------ | --------------------------------------------------- | | `TSize` *extends* `number` | `number` | The number of bytes used for encoding and decoding. | ## See [NumberCodec](/api/type-aliases/NumberCodec) # FixedSizeNumberDecoder (/api/type-aliases/FixedSizeNumberDecoder) ```ts type FixedSizeNumberDecoder = | FixedSizeDecoder | FixedSizeDecoder; ``` Represents a fixed-size decoder for numbers and bigints. This decoder reads a fixed number of bytes (`TSize`) and converts them into a `number` or `bigint`. ## Type Parameters | Type Parameter | Default type | Description | | -------------------------- | ------------ | ------------------------------------------ | | `TSize` *extends* `number` | `number` | The number of bytes expected for decoding. | ## See [NumberDecoder](/api/type-aliases/NumberDecoder) # FixedSizeNumberEncoder (/api/type-aliases/FixedSizeNumberEncoder) ```ts type FixedSizeNumberEncoder = FixedSizeEncoder; ``` Represents a fixed-size encoder for numbers and bigints. This encoder serializes values using an exact number of bytes, defined by `TSize`. ## Type Parameters | Type Parameter | Default type | Description | | -------------------------- | ------------ | -------------------------------------- | | `TSize` *extends* `number` | `number` | The number of bytes used for encoding. | ## See [NumberEncoder](/api/type-aliases/NumberEncoder) # Flatten (/api/type-aliases/Flatten) ```ts type Flatten = T extends infer Item[] ? Item : never; ``` ## Type Parameters | Type Parameter | | -------------- | | `T` | # FullySignedOffchainMessageEnvelope (/api/type-aliases/FullySignedOffchainMessageEnvelope) ```ts type FullySignedOffchainMessageEnvelope = NominalType<"offchainMessageEnvelopeSignedness", "fullySigned">; ``` Represents an offchain message envelope that is signed by all of its required signers. # FullySignedTransaction (/api/type-aliases/FullySignedTransaction) ```ts type FullySignedTransaction = NominalType<"transactionSignedness", "fullySigned">; ``` Represents a transaction that is signed by all of its required signers. Being fully signed is a prerequisite of functions designed to land transactions on the network. # GetAccountInfoApi (/api/type-aliases/GetAccountInfoApi) ```ts type GetAccountInfoApi = object; ``` ## Methods ### getAccountInfo() #### Call Signature ```ts getAccountInfo(address, config): SolanaRpcResponse>; ``` Fetches information associated with the account at the given address. If the account has data, it will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; }> | ##### Returns `SolanaRpcResponse`\<`GetAccountInfoApiResponse`\<`AccountInfoWithBase64EncodedData`>> ##### See [https://solana.com/docs/rpc/http/getaccountinfo](https://solana.com/docs/rpc/http/getaccountinfo) #### Call Signature ```ts getAccountInfo(address, config): SolanaRpcResponse>; ``` Fetches information associated with the account at the given address. If the account has data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64+zstd"`; }> | ##### Returns `SolanaRpcResponse`\<`GetAccountInfoApiResponse`\<`AccountInfoWithBase64EncodedZStdCompressedData`>> ##### See [https://solana.com/docs/rpc/http/getaccountinfo](https://solana.com/docs/rpc/http/getaccountinfo) #### Call Signature ```ts getAccountInfo(address, config): SolanaRpcResponse>; ``` Fetches information associated with the account at the given address. If the account has data, the server will attempt to process it using a parser specific to the account's owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; }> | ##### Returns `SolanaRpcResponse`\<`GetAccountInfoApiResponse`\<`AccountInfoWithJsonData`>> ##### See [https://solana.com/docs/rpc/http/getaccountinfo](https://solana.com/docs/rpc/http/getaccountinfo) #### Call Signature ```ts getAccountInfo(address, config): SolanaRpcResponse>; ``` Fetches information associated with the account at the given address. If the account has data, it will be returned in the response as a tuple whose first element is a base58-encoded string. If the account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; }> | ##### Returns `SolanaRpcResponse`\<`GetAccountInfoApiResponse`\<`AccountInfoWithBase58EncodedData`>> ##### See [https://solana.com/docs/rpc/http/getaccountinfo](https://solana.com/docs/rpc/http/getaccountinfo) #### Call Signature ```ts getAccountInfo(address, config?): SolanaRpcResponse>; ``` Fetches information associated with the account at the given address. If the account has data, it will be returned in the response as a base58-encoded string. If the account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config?` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }>, `"encoding"`> | ##### Returns `SolanaRpcResponse`\<`GetAccountInfoApiResponse`\<`AccountInfoWithBase58Bytes`>> ##### See [https://solana.com/docs/rpc/http/getaccountinfo](https://solana.com/docs/rpc/http/getaccountinfo) # GetAgGenesisCertApi (/api/type-aliases/GetAgGenesisCertApi) ```ts type GetAgGenesisCertApi = object; ``` ## Methods ### getAgGenesisCert() ```ts getAgGenesisCert(): | Readonly<{ block: Readonly<{ blockId: readonly number[]; slot: Slot; }>; signature: Readonly<{ bitmap: readonly number[]; signature: readonly number[]; }>; }> | null; ``` Returns the Alpenglow genesis certificate, or `null` if the node does not have one. #### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `block`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockId`: readonly `number`\[]; `slot`: `Slot`; }>; `signature`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `bitmap`: readonly `number`\[]; `signature`: readonly `number`\[]; }>; }> \| `null` The certificate over the block at which the Alpenglow consensus protocol was activated. #### See [https://solana.com/docs/rpc/http/getaggenesiscert](https://solana.com/docs/rpc/http/getaggenesiscert) # GetBalanceApi (/api/type-aliases/GetBalanceApi) ```ts type GetBalanceApi = object; ``` ## Methods ### getBalance() ```ts getBalance(address, config?): GetBalanceApiResponse; ``` Fetches the Lamport balance of the account at the given address. #### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `minContextSlot?`: `Slot`; }> | #### Returns `GetBalanceApiResponse` #### See [https://solana.com/docs/rpc/http/getbalance](https://solana.com/docs/rpc/http/getbalance) # GetBlockApi (/api/type-aliases/GetBlockApi) ```ts type GetBlockApi = object; ``` ## Methods ### getBlock() #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: `false`; `transactionDetails`: `"none"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards?`: `true`; `transactionDetails`: `"none"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ signatures: readonly Base58EncodedBytes[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: `false`; `transactionDetails`: `"signatures"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `signatures`: readonly `Base58EncodedBytes`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ signatures: readonly Base58EncodedBytes[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards?`: `true`; `transactionDetails`: `"signatures"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `signatures`: readonly `Base58EncodedBytes`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `rewards`: `false`; `transactionDetails`: `"accounts"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: `false`; `transactionDetails`: `"accounts"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `true`; `transactionDetails`: `"accounts"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards?`: `true`; `transactionDetails`: `"accounts"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `rewards`: `false`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `rewards`: `false`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `true`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `rewards?`: `true`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `rewards`: `false`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `rewards`: `false`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `true`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `rewards?`: `true`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `rewards`: `false`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `rewards`: `false`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `rewards?`: `boolean`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `rewards`: `false`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `rewards`: `false`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `maxSupportedTransactionVersion`: `GetBlockMaxSupportedTransactionVersion`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) #### Call Signature ```ts getBlock(slot, config?): | Readonly<{ blockhash: Blockhash; blockHeight: bigint; blockTime: UnixTimestamp; parentSlot: Slot; previousBlockhash: Blockhash; }> & Readonly<{ rewards: readonly Reward[]; }> & Readonly<{ transactions: readonly TTransaction[]; }> | null; ``` Returns identity and transaction information about a confirmed block in the ledger ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `slot` | `bigint` | | `config?` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`Commitment`, `"processed"`>; `encoding?`: `GetBlockEncoding`; `maxSupportedTransactionVersion?`: `GetBlockMaxSupportedTransactionVersion`; `rewards?`: `boolean`; `transactionDetails?`: `GetBlockTransactionDetailsMode`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `transactionDetails?`: `"full"`; }> | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `blockhash`: `Blockhash`; `blockHeight`: `bigint`; `blockTime`: `UnixTimestamp`; `parentSlot`: `Slot`; `previousBlockhash`: `Blockhash`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `rewards`: readonly `Reward`\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactions`: readonly `TTransaction`\[]; }> \| `null` ##### See [https://solana.com/docs/rpc/http/getblock](https://solana.com/docs/rpc/http/getblock) # GetBlockCommitmentApi (/api/type-aliases/GetBlockCommitmentApi) ```ts type GetBlockCommitmentApi = object; ``` ## Methods ### getBlockCommitment() ```ts getBlockCommitment(slot): GetBlockCommitmentApiResponse; ``` Returns the amount of cluster stake in Lamports that has voted on a particular block, as well as the stake attributed to each vote account. #### Parameters | Parameter | Type | | --------- | -------- | | `slot` | `bigint` | #### Returns `GetBlockCommitmentApiResponse` #### See [https://solana.com/docs/rpc/http/getblockcommitment](https://solana.com/docs/rpc/http/getblockcommitment) # GetBlockHeightApi (/api/type-aliases/GetBlockHeightApi) ```ts type GetBlockHeightApi = object; ``` ## Methods ### getBlockHeight() ```ts getBlockHeight(config?): bigint; ``` Returns the current block height of the node #### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `minContextSlot?`: `Slot`; }> | #### Returns `bigint` #### See [https://solana.com/docs/rpc/http/getblockheight](https://solana.com/docs/rpc/http/getblockheight) # GetBlockProductionApi (/api/type-aliases/GetBlockProductionApi) ```ts type GetBlockProductionApi = object; ``` ## Methods ### getBlockProduction() #### Call Signature ```ts getBlockProduction(config): SolanaRpcResponse>>; ``` Returns a validator's leader slot count and the number of blocks it produced, in the given slot range ##### Type Parameters | Type Parameter | | ------------------------------- | | `TIdentity` *extends* `Address` | ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `range?`: `SlotRange`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `identity`: `TIdentity`; }> | ##### Returns `SolanaRpcResponse`\<`GetBlockProductionApiResponse`\<`BlockProductionWithSingleIdentity`\<`TIdentity`>>> ##### See [https://solana.com/docs/rpc/http/getblockproduction](https://solana.com/docs/rpc/http/getblockproduction) #### Call Signature ```ts getBlockProduction(config?): SolanaRpcResponse>; ``` Returns each validator's leader slot count and the number of blocks they produced, in the given slot range ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `range?`: `SlotRange`; }> | ##### Returns `SolanaRpcResponse`\<`GetBlockProductionApiResponse`\<`BlockProductionWithAllIdentities`>> ##### See [https://solana.com/docs/rpc/http/getblockproduction](https://solana.com/docs/rpc/http/getblockproduction) # GetBlockTimeApi (/api/type-aliases/GetBlockTimeApi) ```ts type GetBlockTimeApi = object; ``` ## Methods ### getBlockTime() ```ts getBlockTime(blockNumber): UnixTimestamp; ``` Returns the estimated production time of a block. Each validator reports their UTC time to the ledger on a regular interval by intermittently adding a timestamp to a vote for a particular block. A requested block's time is calculated from the stake-weighted mean of the vote timestamps in a set of recent blocks recorded on the ledger. #### Parameters | Parameter | Type | Description | | ------------- | -------- | -------------------------------- | | `blockNumber` | `bigint` | Block number, identified by slot | #### Returns `UnixTimestamp` Estimated production time, as Unix timestamp (seconds since the Unix epoch) #### See [https://solana.com/docs/rpc/http/getblocktime](https://solana.com/docs/rpc/http/getblocktime) # GetBlocksApi (/api/type-aliases/GetBlocksApi) ```ts type GetBlocksApi = object; ``` ## Methods ### getBlocks() ```ts getBlocks( startSlotInclusive, endSlotInclusive?, config?): GetBlocksApiResponse; ``` Returns a list of confirmed blocks between two slots (inclusive). #### Parameters | Parameter | Type | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `startSlotInclusive` | `bigint` | The first slot for which to return a confirmed block | | `endSlotInclusive?` | `bigint` | The last slot for which to return a confirmed block. Must be no more than 500,000 blocks higher than the start slot. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Exclude`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers)\<`Commitment`, `"processed"`>; }> | - | #### Returns `GetBlocksApiResponse` #### See [https://solana.com/docs/rpc/http/getblocks](https://solana.com/docs/rpc/http/getblocks) # GetBlocksWithLimitApi (/api/type-aliases/GetBlocksWithLimitApi) ```ts type GetBlocksWithLimitApi = object; ``` ## Methods ### getBlocksWithLimit() ```ts getBlocksWithLimit( startSlotInclusive, limit, config?): GetBlocksWithLimitApiResponse; ``` Returns a list of confirmed blocks starting at the given slot (inclusive). Returns up to the number of blocks specified by the limit. #### Parameters | Parameter | Type | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `startSlotInclusive` | `bigint` | The first slot for which to return a confirmed block | | `limit` | `number` | The maximum number of blocks to return (between 0 and 500,000). Specifying 0 will result in an empty array being returned. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: [`Exclude`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers)\<`Commitment`, `"processed"`>; }> | - | #### Returns `GetBlocksWithLimitApiResponse` #### See [https://solana.com/docs/rpc/http/getblockswithlimit](https://solana.com/docs/rpc/http/getblockswithlimit) # GetClusterNodesApi (/api/type-aliases/GetClusterNodesApi) ```ts type GetClusterNodesApi = object; ``` ## Methods ### getClusterNodes() ```ts getClusterNodes(): GetClusterNodesApiResponse; ``` Returns information about all the nodes participating in the cluster. #### Returns `GetClusterNodesApiResponse` #### See [https://solana.com/docs/rpc/http/getclusternodes](https://solana.com/docs/rpc/http/getclusternodes) # GetDiscriminatedUnionVariant (/api/type-aliases/GetDiscriminatedUnionVariant) ```ts type GetDiscriminatedUnionVariant = Extract>; ``` Extracts a variant from a discriminated union based on its discriminator value. ## Type Parameters | Type Parameter | Description | | ---------------------------------------------------------------------------------------------------------- | --------------------------------------- | | `TUnion` *extends* [`DiscriminatedUnion`](/api/type-aliases/DiscriminatedUnion)\<`TDiscriminatorProperty`> | The discriminated union type. | | `TDiscriminatorProperty` *extends* `string` | The property used as the discriminator. | | `TDiscriminatorValue` *extends* `TUnion`\[`TDiscriminatorProperty`] | The specific variant to extract. | ## Example ```ts type Message = | { __kind: 'Quit' } | { __kind: 'Write'; fields: [string] } | { __kind: 'Move'; x: number; y: number }; type ClickEvent = GetDiscriminatedUnionVariant; // -> { __kind: 'Move'; x: number; y: number } ``` # GetDiscriminatedUnionVariantContent (/api/type-aliases/GetDiscriminatedUnionVariantContent) ```ts type GetDiscriminatedUnionVariantContent = Omit, TDiscriminatorProperty>; ``` Extracts a variant from a discriminated union without its discriminator property. ## Type Parameters | Type Parameter | Description | | ---------------------------------------------------------------------------------------------------------- | --------------------------------------- | | `TUnion` *extends* [`DiscriminatedUnion`](/api/type-aliases/DiscriminatedUnion)\<`TDiscriminatorProperty`> | The discriminated union type. | | `TDiscriminatorProperty` *extends* `string` | The property used as the discriminator. | | `TDiscriminatorValue` *extends* `TUnion`\[`TDiscriminatorProperty`] | The specific variant to extract. | ## Example ```ts type Message = | { __kind: 'Quit' } | { __kind: 'Write'; fields: [string] } | { __kind: 'Move'; x: number; y: number }; type MoveContent = GetDiscriminatedUnionVariantContent; // -> { x: number; y: number } ``` # GetEpochInfoApi (/api/type-aliases/GetEpochInfoApi) ```ts type GetEpochInfoApi = object; ``` ## Methods ### getEpochInfo() ```ts getEpochInfo(config?): GetEpochInfoApiResponse; ``` Returns information about the current epoch. #### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `minContextSlot?`: `Slot`; }> | #### Returns `GetEpochInfoApiResponse` #### See [https://solana.com/docs/rpc/http/getepochinfo](https://solana.com/docs/rpc/http/getepochinfo) # GetEpochScheduleApi (/api/type-aliases/GetEpochScheduleApi) ```ts type GetEpochScheduleApi = object; ``` ## Methods ### getEpochSchedule() ```ts getEpochSchedule(): GetEpochScheduleApiResponse; ``` Returns the epoch schedule information from this cluster's genesis config #### Returns `GetEpochScheduleApiResponse` #### See [https://solana.com/docs/rpc/http/getepochschedule](https://solana.com/docs/rpc/http/getepochschedule) # GetFeeForMessageApi (/api/type-aliases/GetFeeForMessageApi) ```ts type GetFeeForMessageApi = object; ``` ## Methods ### getFeeForMessage() ```ts getFeeForMessage(message, config?): SolanaRpcResponse; ``` Returns the fee the network will charge for a particular message #### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | | `message` | `TransactionMessageBytesBase64` | A transaction message encoded as a base64 string | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `minContextSlot?`: `Slot`; }> | - | #### Returns `SolanaRpcResponse`\<`GetFeeForMessageApiResponse`> The fee that the network will charge to process the message, in Lamports, as computed at the specified blockhash. #### See [https://solana.com/docs/rpc/http/getfeeformessage](https://solana.com/docs/rpc/http/getfeeformessage) # GetFirstAvailableBlockApi (/api/type-aliases/GetFirstAvailableBlockApi) ```ts type GetFirstAvailableBlockApi = object; ``` ## Methods ### getFirstAvailableBlock() ```ts getFirstAvailableBlock(): bigint; ``` Returns the slot of the lowest confirmed block available on the node. Different nodes may offer more or less historical block data, depending on their configuration. An appropriately configured node should be able to access all blocks, from genesis onward. When it is not, this method will tell you the slot of the lowest block available. #### Returns `bigint` #### See [https://solana.com/docs/rpc/http/getfirstavailableblock](https://solana.com/docs/rpc/http/getfirstavailableblock) # GetGenesisHashApi (/api/type-aliases/GetGenesisHashApi) ```ts type GetGenesisHashApi = object; ``` ## Methods ### getGenesisHash() ```ts getGenesisHash(): Base58EncodedBytes; ``` Returns the genesis hash. #### Returns `Base58EncodedBytes` A SHA-256 hash of the network's genesis config. #### See [https://solana.com/docs/rpc/http/getgenesishash](https://solana.com/docs/rpc/http/getgenesishash) # GetHealthApi (/api/type-aliases/GetHealthApi) ```ts type GetHealthApi = object; ``` ## Methods ### getHealth() ```ts getHealth(): "ok"; ``` Returns the health status of the node. A healthy node is one that is within *n* slots of the latest cluster-confirmed slot, where *n* is a node-configurable parameter with a [default of 128](https://github.com/anza-xyz/agave/blob/a080c4bb157f48b268b74cf5dd2f3de39db7dc5d/rpc-client-types/src/request.rs#L157). #### Returns `"ok"` The string "ok" if the node is healthy. #### Throws if the node is unhealthy. The specifics of the error response are unstable and may change in the future. #### See [https://solana.com/docs/rpc/http/gethealth](https://solana.com/docs/rpc/http/gethealth) # GetHighestSnapshotSlotApi (/api/type-aliases/GetHighestSnapshotSlotApi) ```ts type GetHighestSnapshotSlotApi = object; ``` ## Methods ### getHighestSnapshotSlot() ```ts getHighestSnapshotSlot(): GetHighestSnapshotSlotApiResponse; ``` Returns the highest slot information that the node has snapshots for. This will find the highest full snapshot slot, and the highest incremental snapshot slot based on the full snapshot slot, if there is one. #### Returns `GetHighestSnapshotSlotApiResponse` #### See [https://solana.com/docs/rpc/http/gethighestsnapshotslot](https://solana.com/docs/rpc/http/gethighestsnapshotslot) # GetIdentityApi (/api/type-aliases/GetIdentityApi) ```ts type GetIdentityApi = object; ``` ## Methods ### getIdentity() ```ts getIdentity(): GetIdentityApiResponse; ``` Returns the identity pubkey for the current node. #### Returns `GetIdentityApiResponse` #### See [https://solana.com/docs/rpc/http/getidentity](https://solana.com/docs/rpc/http/getidentity) # GetInflationGovernorApi (/api/type-aliases/GetInflationGovernorApi) ```ts type GetInflationGovernorApi = object; ``` ## Methods ### getInflationGovernor() ```ts getInflationGovernor(config?): GetInflationGovernorApiResponse; ``` Returns the current inflation governor. #### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | #### Returns `GetInflationGovernorApiResponse` #### See [https://solana.com/docs/rpc/http/getinflationgovernor](https://solana.com/docs/rpc/http/getinflationgovernor) # GetInflationRateApi (/api/type-aliases/GetInflationRateApi) ```ts type GetInflationRateApi = object; ``` ## Methods ### getInflationRate() ```ts getInflationRate(): GetInflationRateApiResponse; ``` Returns the specific inflation values for the current epoch. #### Returns `GetInflationRateApiResponse` #### See [https://solana.com/docs/rpc/http/getinflationrate](https://solana.com/docs/rpc/http/getinflationrate) # GetInflationRewardApi (/api/type-aliases/GetInflationRewardApi) ```ts type GetInflationRewardApi = object; ``` ## Methods ### getInflationReward() ```ts getInflationReward(addresses, config?): GetInflationRewardApiResponse; ``` Returns the inflation / staking reward for a list of addresses for an epoch. #### Parameters | Parameter | Type | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `addresses` | readonly `Address`\[] | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `epoch?`: `bigint`; `minContextSlot?`: `Slot`; }> | #### Returns `GetInflationRewardApiResponse` #### See [https://solana.com/docs/rpc/http/getinflationreward](https://solana.com/docs/rpc/http/getinflationreward) # GetLargestAccountsApi (/api/type-aliases/GetLargestAccountsApi) ```ts type GetLargestAccountsApi = object; ``` ## Methods ### getLargestAccounts() ```ts getLargestAccounts(config?): SolanaRpcResponse; ``` Returns the 20 largest accounts, by Lamports | Lamport balance. Results may be cached up to two hours. #### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `filter?`: `"circulating"` \| `"nonCirculating"`; }> | #### Returns `SolanaRpcResponse`\<`GetLargestAccountsApiResponse`> #### See [https://solana.com/docs/rpc/http/getlargestaccounts](https://solana.com/docs/rpc/http/getlargestaccounts) # GetLatestBlockhashApi (/api/type-aliases/GetLatestBlockhashApi) ```ts type GetLatestBlockhashApi = object; ``` ## Methods ### getLatestBlockhash() ```ts getLatestBlockhash(config?): SolanaRpcResponse; ``` Returns the blockhash of the latest block. #### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `minContextSlot?`: `Slot`; }> | #### Returns `SolanaRpcResponse`\<`GetLatestBlockhashApiResponse`> #### See [https://solana.com/docs/rpc/http/getlatestblockhash](https://solana.com/docs/rpc/http/getlatestblockhash) # GetLeaderScheduleApi (/api/type-aliases/GetLeaderScheduleApi) ```ts type GetLeaderScheduleApi = object; ``` ## Methods ### getLeaderSchedule() #### Call Signature ```ts getLeaderSchedule(slot, config): | Readonly<{ [TAddress in Address]?: bigint[] }> | null; ``` Fetch the leader schedule of a particular validator. ##### Type Parameters | Type Parameter | | ------------------------------- | | `TIdentity` *extends* `Address` | ##### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | `slot` | `bigint` | A slot that will be used to select the epoch for which to return the leader schedule. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `identity`: `Address`; }> | - | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<`{ [TAddress in Address]?: bigint[] }`> \| `null` A dictionary having a single key representing the specified validator identity, and its corresponding leader slot indices as values relative to the first slot in the requested epoch, or `null` if there is no epoch that corresponds to the given slot. ##### See [https://solana.com/docs/rpc/http/getleaderschedule](https://solana.com/docs/rpc/http/getleaderschedule) #### Call Signature ```ts getLeaderSchedule(slot, config?): GetLeaderScheduleApiResponseWithAllIdentities | null; ``` Fetch the leader schedule for all validators. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- | | `slot` | `bigint` | A slot that will be used to select the epoch for which to return the leader schedule. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | - | ##### Returns `GetLeaderScheduleApiResponseWithAllIdentities` | `null` A dictionary of validator identities as base-58 encoded strings, and their corresponding leader slot indices as values relative to the first slot in the requested epoch, or `null` if there is no epoch that corresponds to the given slot. ##### See [https://solana.com/docs/rpc/http/getleaderschedule](https://solana.com/docs/rpc/http/getleaderschedule) #### Call Signature ```ts getLeaderSchedule(slot, config): GetLeaderScheduleApiResponseWithSingleIdentity; ``` Fetch the leader schedule of a particular validator. ##### Type Parameters | Type Parameter | | ------------------------------- | | `TIdentity` *extends* `Address` | ##### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `slot` | `null` | When `null`, orders the leader schedule for the current epoch. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `identity`: `Address`; }> | - | ##### Returns `GetLeaderScheduleApiResponseWithSingleIdentity`\<`TIdentity`> A dictionary having a single key representing the specified validator identity, and its corresponding leader slot indices as values relative to the first slot in the current epoch. ##### See [https://solana.com/docs/rpc/http/getleaderschedule](https://solana.com/docs/rpc/http/getleaderschedule) #### Call Signature ```ts getLeaderSchedule(slot?, config?): GetLeaderScheduleApiResponseWithAllIdentities; ``` Fetch the leader schedule of all validators. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------- | | `slot?` | `null` | When `null`, orders the leader schedule for the current epoch. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | - | ##### Returns `GetLeaderScheduleApiResponseWithAllIdentities` A dictionary of validator identities as base-58 encoded strings, and their corresponding leader slot indices as values relative to the first slot in the current epoch. ##### See [https://solana.com/docs/rpc/http/getleaderschedule](https://solana.com/docs/rpc/http/getleaderschedule) # GetMaxRetransmitSlotApi (/api/type-aliases/GetMaxRetransmitSlotApi) ```ts type GetMaxRetransmitSlotApi = object; ``` ## Methods ### getMaxRetransmitSlot() ```ts getMaxRetransmitSlot(): bigint; ``` Get the max slot seen from retransmit stage. #### Returns `bigint` #### See [https://solana.com/docs/rpc/http/getmaxretransmitslot](https://solana.com/docs/rpc/http/getmaxretransmitslot) # GetMaxShredInsertSlotApi (/api/type-aliases/GetMaxShredInsertSlotApi) ```ts type GetMaxShredInsertSlotApi = object; ``` ## Methods ### getMaxShredInsertSlot() ```ts getMaxShredInsertSlot(): bigint; ``` Get the max slot seen from after shred insert. #### Returns `bigint` #### See [https://solana.com/docs/rpc/http/getmaxshredinsertslot](https://solana.com/docs/rpc/http/getmaxshredinsertslot) # GetMinimumBalanceConfig (/api/type-aliases/GetMinimumBalanceConfig) ```ts type GetMinimumBalanceConfig = object; ``` Configuration options for [ClientWithGetMinimumBalance.getMinimumBalance](/api/type-aliases/ClientWithGetMinimumBalance#getminimumbalance). ## Properties ### withoutHeader? ```ts optional withoutHeader?: boolean; ``` When `true`, the 128-byte account header is not added to the provided `space` value. By default, the account header (128 bytes) is included in the minimum balance computation on top of the provided `space`. Set this to `true` if the provided `space` already accounts for the header or if you want the minimum balance for the data portion only. #### See @solana/accounts#BASE\_ACCOUNT\_SIZE | BASE\_ACCOUNT\_SIZE for the account header size constant. # GetMinimumBalanceForRentExemptionApi (/api/type-aliases/GetMinimumBalanceForRentExemptionApi) ```ts type GetMinimumBalanceForRentExemptionApi = object; ``` ## Methods ### getMinimumBalanceForRentExemption() ```ts getMinimumBalanceForRentExemption(size, config?): Lamports; ``` Returns the minimum balance required to exempt an account from rent collection. #### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | | `size` | `bigint` | The number of bytes of account data for which an exemption from rent collection is being sought. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | - | #### Returns `Lamports` The minimum Lamports | Lamport balance required to grant an account of the specified size an exemption from rent collection. #### See [https://solana.com/docs/rpc/http/getminimumbalanceforrentexemption](https://solana.com/docs/rpc/http/getminimumbalanceforrentexemption) # GetMultipleAccountsApi (/api/type-aliases/GetMultipleAccountsApi) ```ts type GetMultipleAccountsApi = object; ``` ## Methods ### getMultipleAccounts() #### Call Signature ```ts getMultipleAccounts(addresses, config): SolanaRpcResponse; ``` Fetches information associated with the accounts at the given addresses. If the accounts have data, it will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------- | | `addresses` | readonly `Address`\[] | A maximum of 100 addresses for which to fetch account data | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetMultipleAccountsApiResponseBase` & `AccountInfoWithBase64EncodedData` | `null`\[]> ##### See [https://solana.com/docs/rpc/http/getmultipleaccounts](https://solana.com/docs/rpc/http/getmultipleaccounts) #### Call Signature ```ts getMultipleAccounts(addresses, config): SolanaRpcResponse; ``` Fetches information associated with the accounts at the given addresses. If the accounts have data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | `addresses` | readonly `Address`\[] | A maximum of 100 addresses for which to fetch account data | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64+zstd"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetMultipleAccountsApiResponseBase` & `AccountInfoWithBase64EncodedZStdCompressedData` | `null`\[]> ##### See [https://solana.com/docs/rpc/http/getmultipleaccounts](https://solana.com/docs/rpc/http/getmultipleaccounts) #### Call Signature ```ts getMultipleAccounts(addresses, config): SolanaRpcResponse; ``` Fetches information associated with the accounts at the given addresses. If the accounts have data, the server will attempt to process it using a parser specific to each account's owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | `addresses` | readonly `Address`\[] | A maximum of 100 addresses for which to fetch account data | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetMultipleAccountsApiResponseBase` & `AccountInfoWithJsonData` | `null`\[]> ##### See [https://solana.com/docs/rpc/http/getmultipleaccounts](https://solana.com/docs/rpc/http/getmultipleaccounts) #### Call Signature ```ts getMultipleAccounts(addresses, config): SolanaRpcResponse; ``` Fetches information associated with the accounts at the given addresses. If the accounts have data, it will be returned in the response as a tuple whose first element is a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------- | | `addresses` | readonly `Address`\[] | A maximum of 100 addresses for which to fetch account data | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetMultipleAccountsApiResponseBase` & `AccountInfoWithBase58EncodedData` | `null`\[]> ##### See [https://solana.com/docs/rpc/http/getmultipleaccounts](https://solana.com/docs/rpc/http/getmultipleaccounts) #### Call Signature ```ts getMultipleAccounts(addresses, config?): SolanaRpcResponse; ``` Fetches information associated with the accounts at the given addresses. If the accounts have data, it will be returned in the response as a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | `addresses` | readonly `Address`\[] | A maximum of 100 addresses for which to fetch account data | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetMultipleAccountsApiResponseBase` & `AccountInfoWithBase64EncodedData` | `null`\[]> ##### See [https://solana.com/docs/rpc/http/getmultipleaccounts](https://solana.com/docs/rpc/http/getmultipleaccounts) # GetProgramAccountsApi (/api/type-aliases/GetProgramAccountsApi) ```ts type GetProgramAccountsApi = object; ``` ## Methods ### getProgramAccounts() #### Call Signature ```ts getProgramAccounts(program, config): SolanaRpcResponse[]>; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, it will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `withContext`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoWithPubkey`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`>\[]> ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) #### Call Signature ```ts getProgramAccounts(program, config): Readonly<{ account: TAccount; pubkey: Address; }>[]; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, it will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `withContext?`: `boolean`; }> | ##### Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `account`: `TAccount`; `pubkey`: `Address`; }>\[] ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) #### Call Signature ```ts getProgramAccounts(program, config): SolanaRpcResponse[]>; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64+zstd"`; `withContext`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoWithPubkey`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`>\[]> ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) #### Call Signature ```ts getProgramAccounts(program, config): Readonly<{ account: TAccount; pubkey: Address; }>[]; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64+zstd"`; `withContext?`: `boolean`; }> | ##### Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `account`: `TAccount`; `pubkey`: `Address`; }>\[] ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) #### Call Signature ```ts getProgramAccounts(program, config): SolanaRpcResponse[]>; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, the server will attempt to process it using a parser specific to the owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `withContext`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoWithPubkey`\<`AccountInfoBase` & `AccountInfoWithJsonData`>\[]> ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) #### Call Signature ```ts getProgramAccounts(program, config): Readonly<{ account: TAccount; pubkey: Address; }>[]; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, the server will attempt to process it using a parser specific to the owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `withContext?`: `boolean`; }> | ##### Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `account`: `TAccount`; `pubkey`: `Address`; }>\[] ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) #### Call Signature ```ts getProgramAccounts(program, config): SolanaRpcResponse[]>; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, it will be returned in the response as a tuple whose first element is a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `withContext`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoWithPubkey`\<`AccountInfoBase` & `AccountInfoWithBase58EncodedData`>\[]> ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) #### Call Signature ```ts getProgramAccounts(program, config): Readonly<{ account: TAccount; pubkey: Address; }>[]; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, it will be returned in the response as a tuple whose first element is a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `withContext?`: `boolean`; }> | ##### Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `account`: `TAccount`; `pubkey`: `Address`; }>\[] ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) #### Call Signature ```ts getProgramAccounts(program, config): SolanaRpcResponse[]>; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, it will be returned in the response as a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `withContext`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`AccountInfoWithPubkey`\<`AccountInfoBase` & `AccountInfoWithBase58Bytes`>\[]> ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) #### Call Signature ```ts getProgramAccounts(program, config?): Readonly<{ account: TAccount; pubkey: Address; }>[]; ``` Fetches information associated with all accounts owned by the program at the given address. If the accounts have data, it will be returned in the response as a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `program` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `filters?`: readonly (`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`)\[]; `minContextSlot?`: `Slot`; `withContext?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `withContext?`: `boolean`; }> | ##### Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `account`: `TAccount`; `pubkey`: `Address`; }>\[] ##### See [https://solana.com/docs/rpc/http/getprogramaccounts](https://solana.com/docs/rpc/http/getprogramaccounts) # GetProgramAccountsDatasizeFilter (/api/type-aliases/GetProgramAccountsDatasizeFilter) ```ts type GetProgramAccountsDatasizeFilter = Readonly<{ dataSize: bigint; }>; ``` # GetProgramAccountsMemcmpFilter (/api/type-aliases/GetProgramAccountsMemcmpFilter) ```ts type GetProgramAccountsMemcmpFilter = Readonly<{ memcmp: | ProgramNotificationsMemcmpFilterBase58 | ProgramNotificationsMemcmpFilterBase64; }>; ``` # GetRecentPerformanceSamplesApi (/api/type-aliases/GetRecentPerformanceSamplesApi) ```ts type GetRecentPerformanceSamplesApi = object; ``` ## Methods ### getRecentPerformanceSamples() ```ts getRecentPerformanceSamples(limit?): GetRecentPerformanceSamplesApiResponse; ``` Returns a list of recent performance samples, in reverse slot order. Performance samples are taken every 60 seconds and include the number of transactions and slots that occur in a given time window. #### Parameters | Parameter | Type | Description | | --------- | -------- | -------------------------------------------- | | `limit?` | `number` | Number of samples to return. Maximum of 720. | #### Returns `GetRecentPerformanceSamplesApiResponse` #### See [https://solana.com/docs/rpc/http/getrecentperformancesamples](https://solana.com/docs/rpc/http/getrecentperformancesamples) # GetRecentPrioritizationFeesApi (/api/type-aliases/GetRecentPrioritizationFeesApi) ```ts type GetRecentPrioritizationFeesApi = object; ``` ## Methods ### getRecentPrioritizationFees() ```ts getRecentPrioritizationFees(addresses?): GetRecentPrioritizationFeesApiResponse; ``` Returns a list of the smallest prioritization fees paid in recent blocks. Currently, a node's prioritization-fee cache stores data from up to 150 blocks. #### Parameters | Parameter | Type | Description | | ------------ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `addresses?` | readonly `Address`\[] | A maximum of 128 addresses. When supplied, the response will reflect the prioritization fee paid for transactions which take a write-lock on all of them. | #### Returns `GetRecentPrioritizationFeesApiResponse` #### See [https://solana.com/docs/rpc/http/getrecentprioritizationfees](https://solana.com/docs/rpc/http/getrecentprioritizationfees) # GetSignatureStatusesApi (/api/type-aliases/GetSignatureStatusesApi) ```ts type GetSignatureStatusesApi = object; ``` ## Methods ### getSignatureStatuses() ```ts getSignatureStatuses(signatures, config?): SolanaRpcResponse; ``` Returns the statuses of a list of signatures. Each signature uniquely identifies a transaction by virtue of being the first or only signature in its list of signatures. #### Parameters | Parameter | Type | Description | | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `signatures` | readonly `Signature`\[] | An array of transaction signatures to confirm, as base-58 encoded strings (up to a maximum of 256) | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `searchTransactionHistory?`: `boolean`; }> | - | #### Returns `SolanaRpcResponse`\<`GetSignatureStatusesApiResponse`> #### See [https://solana.com/docs/rpc/http/getsignaturestatuses](https://solana.com/docs/rpc/http/getsignaturestatuses) # GetSignaturesForAddressApi (/api/type-aliases/GetSignaturesForAddressApi) ```ts type GetSignaturesForAddressApi = object; ``` ## Methods ### getSignaturesForAddress() #### Call Signature ```ts getSignaturesForAddress(address, config?): GetSignaturesForAddressApiResponse; ``` Returns signatures for confirmed transactions that load the given address. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `before?`: `Signature`; `commitment?`: `AllowedCommitmentForGetSignaturesForAddress`; `limit?`: `number`; `minContextSlot?`: `Slot`; `until?`: `Signature`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `before`: `Signature`; }> | ##### Returns `GetSignaturesForAddressApiResponse` Signatures in reverse chronological order starting from before, but excluding, the signature supplied. ##### See [https://solana.com/docs/rpc/http/getsignaturesforaddress](https://solana.com/docs/rpc/http/getsignaturesforaddress) #### Call Signature ```ts getSignaturesForAddress(address, config?): GetSignaturesForAddressApiResponse; ``` Returns signatures for confirmed transactions that load the given address. ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `before?`: `Signature`; `commitment?`: `AllowedCommitmentForGetSignaturesForAddress`; `limit?`: `number`; `minContextSlot?`: `Slot`; `until?`: `Signature`; }> | ##### Returns `GetSignaturesForAddressApiResponse` Signatures in reverse chronological order starting from the most recent confirmed block. ##### See [https://solana.com/docs/rpc/http/getsignaturesforaddress](https://solana.com/docs/rpc/http/getsignaturesforaddress) # GetSlotApi (/api/type-aliases/GetSlotApi) ```ts type GetSlotApi = object; ``` ## Methods ### getSlot() ```ts getSlot(config?): bigint; ``` Returns the slot that has reached the given or default commitment level. #### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `minContextSlot?`: `Slot`; }> | #### Returns `bigint` #### See [https://solana.com/docs/rpc/http/getslot](https://solana.com/docs/rpc/http/getslot) # GetSlotLeaderApi (/api/type-aliases/GetSlotLeaderApi) ```ts type GetSlotLeaderApi = object; ``` ## Methods ### getSlotLeader() ```ts getSlotLeader(config?): GetSlotLeaderApiResponse; ``` Returns the current slot leader. #### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `minContextSlot?`: `Slot`; }> | #### Returns `GetSlotLeaderApiResponse` The address of the validator that has been granted the opportunity to create the block for the current slot. #### See [https://solana.com/docs/rpc/http/getslotleader](https://solana.com/docs/rpc/http/getslotleader) # GetSlotLeadersApi (/api/type-aliases/GetSlotLeadersApi) ```ts type GetSlotLeadersApi = object; ``` ## Methods ### getSlotLeaders() ```ts getSlotLeaders(startSlotInclusive, limit): GetSlotLeadersApiResponse; ``` Returns the slot leaders for a given slot range. #### Parameters | Parameter | Type | Description | | -------------------- | -------- | -------------------------- | | `startSlotInclusive` | `bigint` | Start slot, as u64 integer | | `limit` | `number` | Limit (between 1 and 5000) | #### Returns `GetSlotLeadersApiResponse` The addresses of the validators that have been granted the opportunity to create the blocks for each slot in the range provided #### See [https://solana.com/docs/rpc/http/getslotleaders](https://solana.com/docs/rpc/http/getslotleaders) # GetStakeMinimumDelegationApi (/api/type-aliases/GetStakeMinimumDelegationApi) ```ts type GetStakeMinimumDelegationApi = object; ``` ## Methods ### getStakeMinimumDelegation() ```ts getStakeMinimumDelegation(config?): SolanaRpcResponse; ``` Returns the minimum amount of stake that can be delegated to a validator, in Lamports. #### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | #### Returns `SolanaRpcResponse`\<`GetStakeMinimumDelegationApiResponse`> #### See [https://solana.com/docs/rpc/http/getstakeminimumdelegation](https://solana.com/docs/rpc/http/getstakeminimumdelegation) # GetSupplyApi (/api/type-aliases/GetSupplyApi) ```ts type GetSupplyApi = object; ``` ## Methods ### getSupply() #### Call Signature ```ts getSupply(config): SolanaRpcResponse; ``` Returns information about the current supply, excluding the list of non-circulating accounts. ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `excludeNonCirculatingAccountsList?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `excludeNonCirculatingAccountsList`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`GetSupplyApiResponseWithoutNonCirculatingAccounts`> ##### See [https://solana.com/docs/rpc/http/getsupply](https://solana.com/docs/rpc/http/getsupply) #### Call Signature ```ts getSupply(config?): SolanaRpcResponse; ``` Returns information about the current supply. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `excludeNonCirculatingAccountsList?`: `boolean`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `excludeNonCirculatingAccountsList?`: `false`; }> | ##### Returns `SolanaRpcResponse`\<`GetSupplyApiResponseWithNonCirculatingAccounts`> ##### See [https://solana.com/docs/rpc/http/getsupply](https://solana.com/docs/rpc/http/getsupply) # GetTokenAccountBalanceApi (/api/type-aliases/GetTokenAccountBalanceApi) ```ts type GetTokenAccountBalanceApi = object; ``` ## Methods ### getTokenAccountBalance() ```ts getTokenAccountBalance(address, config?): SolanaRpcResponse; ``` Returns the balance of an SPL Token account. #### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | | `address` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | #### Returns `SolanaRpcResponse`\<`GetTokenAccountBalanceApiResponse`> #### See [https://solana.com/docs/rpc/http/gettokenaccountbalance](https://solana.com/docs/rpc/http/gettokenaccountbalance) # GetTokenAccountsByDelegateApi (/api/type-aliases/GetTokenAccountsByDelegateApi) ```ts type GetTokenAccountsByDelegateApi = object; ``` ## Methods ### getTokenAccountsByDelegate() #### Call Signature ```ts getTokenAccountsByDelegate( delegate, filter, config): SolanaRpcResponse>; ``` Returns all SPL Token accounts for which transfer authority over some quantity of tokens has been delegated to the supplied address. The accounts' data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | | `delegate` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByDelegateResponse`\<`AccountInfoWithBase64EncodedData`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbydelegate](https://solana.com/docs/rpc/http/gettokenaccountsbydelegate) #### Call Signature ```ts getTokenAccountsByDelegate( delegate, filter, config): SolanaRpcResponse>; ``` Returns all SPL Token accounts for which transfer authority over some quantity of tokens has been delegated to the supplied address. The accounts' data will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `delegate` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64+zstd"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByDelegateResponse`\<`AccountInfoWithBase64EncodedZStdCompressedData`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbydelegate](https://solana.com/docs/rpc/http/gettokenaccountsbydelegate) #### Call Signature ```ts getTokenAccountsByDelegate( delegate, filter, config): SolanaRpcResponse>; ``` Returns all SPL Token accounts for which transfer authority over some quantity of tokens has been delegated to the supplied address. The server will attempt to process the accounts' data using a parser specific to each account's owning token program. ##### Parameters | Parameter | Type | Description | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `delegate` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByDelegateResponse`\<`TokenAccountInfoWithJsonData`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbydelegate](https://solana.com/docs/rpc/http/gettokenaccountsbydelegate) #### Call Signature ```ts getTokenAccountsByDelegate( delegate, filter, config): SolanaRpcResponse>; ``` Returns all SPL Token accounts for which transfer authority over some quantity of tokens has been delegated to the supplied address. The accounts' data will be returned in the response as a tuple whose first element is a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | Description | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | | `delegate` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByDelegateResponse`\<`AccountInfoWithBase58EncodedData`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbydelegate](https://solana.com/docs/rpc/http/gettokenaccountsbydelegate) #### Call Signature ```ts getTokenAccountsByDelegate( delegate, filter, config?): SolanaRpcResponse>; ``` Returns all SPL Token accounts for which transfer authority over some quantity of tokens has been delegated to the supplied address. The accounts' data will be returned in the response as a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | Description | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `delegate` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByDelegateResponse`\<`AccountInfoWithBase58Bytes`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbydelegate](https://solana.com/docs/rpc/http/gettokenaccountsbydelegate) # GetTokenAccountsByOwnerApi (/api/type-aliases/GetTokenAccountsByOwnerApi) ```ts type GetTokenAccountsByOwnerApi = object; ``` ## Methods ### getTokenAccountsByOwner() #### Call Signature ```ts getTokenAccountsByOwner( owner, filter, config): SolanaRpcResponse>; ``` Returns all SPL Token accounts owned by the supplied address. The accounts' data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | | `owner` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByOwnerResponse`\<`AccountInfoWithBase64EncodedData`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbyowner](https://solana.com/docs/rpc/http/gettokenaccountsbyowner) #### Call Signature ```ts getTokenAccountsByOwner( owner, filter, config): SolanaRpcResponse>; ``` Returns all SPL Token accounts owned by the supplied address. The accounts' data will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `owner` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64+zstd"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByOwnerResponse`\<`AccountInfoWithBase64EncodedZStdCompressedData`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbyowner](https://solana.com/docs/rpc/http/gettokenaccountsbyowner) #### Call Signature ```ts getTokenAccountsByOwner( owner, filter, config): SolanaRpcResponse>; ``` Returns all SPL Token accounts owned by the supplied address. The server will attempt to process the accounts' data using a parser specific to each account's owning token program. ##### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `owner` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByOwnerResponse`\<`TokenAccountInfoWithJsonData`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbyowner](https://solana.com/docs/rpc/http/gettokenaccountsbyowner) #### Call Signature ```ts getTokenAccountsByOwner( owner, filter, config): SolanaRpcResponse>; ``` Returns all SPL Token accounts owned by the supplied address. The accounts' data will be returned in the response as a tuple whose first element is a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | | `owner` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByOwnerResponse`\<`AccountInfoWithBase58EncodedData`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbyowner](https://solana.com/docs/rpc/http/gettokenaccountsbyowner) #### Call Signature ```ts getTokenAccountsByOwner( owner, filter, config?): SolanaRpcResponse>; ``` Returns all SPL Token accounts owned by the supplied address. The accounts' data will be returned in the response as a base58-encoded string. If any account contains more than 129 bytes of data, this method will raise an error. ##### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `owner` | `Address` | - | | `filter` | `AccountsFilter` | Limits the results to either token accounts associated with a particular mint, or token accounts owned by a certain token program. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding?`: `"base58"` \| `"base64"` \| `"base64+zstd"` \| `"jsonParsed"`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `dataSlice?`: `DataSlice`; }> | - | ##### Returns `SolanaRpcResponse`\<`GetTokenAccountsByOwnerResponse`\<`AccountInfoWithBase58Bytes`>> ##### See [https://solana.com/docs/rpc/http/gettokenaccountsbyowner](https://solana.com/docs/rpc/http/gettokenaccountsbyowner) # GetTokenLargestAccountsApi (/api/type-aliases/GetTokenLargestAccountsApi) ```ts type GetTokenLargestAccountsApi = object; ``` ## Methods ### getTokenLargestAccounts() ```ts getTokenLargestAccounts(tokenMint, config?): SolanaRpcResponse; ``` Returns the 20 largest token accounts whose mint is equal to the address supplied. #### Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------------------------------------ | | `tokenMint` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | #### Returns `SolanaRpcResponse`\<`GetTokenLargestAccountsApiResponse`> #### See [https://solana.com/docs/rpc/http/gettokenlargestaccounts](https://solana.com/docs/rpc/http/gettokenlargestaccounts) # GetTokenSupplyApi (/api/type-aliases/GetTokenSupplyApi) ```ts type GetTokenSupplyApi = object; ``` ## Methods ### getTokenSupply() ```ts getTokenSupply(tokenMint, config?): SolanaRpcResponse; ``` Returns the total supply of the token mint supplied. #### Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------------------------------------ | | `tokenMint` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | #### Returns `SolanaRpcResponse`\<`GetTokenSupplyApiResponse`> #### See [https://solana.com/docs/rpc/http/gettokensupply](https://solana.com/docs/rpc/http/gettokensupply) # GetTransactionApi (/api/type-aliases/GetTransactionApi) ```ts type GetTransactionApi = object; ``` ## Methods ### getTransaction() #### Call Signature ```ts getTransaction(signature, config): | GetTransactionApiResponseJsonParsed | null; ``` Returns details of the confirmed transaction identified by the given signature. ##### Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------- | ------------ | | `TMaxSupportedTransactionVersion` *extends* `void` \| `TransactionVersion` | `void` | ##### Parameters | Parameter | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `signature` | `Signature` | A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a transaction by virtue of being the first or only signature in its list of signatures. Materializes the transaction as structured TransactionJson which the server will attempt to further process using account parsers and parsers specific to the transaction instructions' owning program. Whenever an instruction parser is successful, instruction will consist of parsed data as JSON. Otherwise, the instruction will materialize as a list of accounts, a program address, and base64-encoded instruction data. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `TMaxSupportedTransactionVersion`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; }> | - | ##### Returns \| [`GetTransactionApiResponseJsonParsed`](/api/type-aliases/GetTransactionApiResponseJsonParsed)\<`TMaxSupportedTransactionVersion`> \| `null` ##### See [https://solana.com/docs/rpc/http/gettransaction](https://solana.com/docs/rpc/http/gettransaction) #### Call Signature ```ts getTransaction(signature, config): | GetTransactionApiResponseBase64 | null; ``` Returns details of the confirmed transaction identified by the given signature. ##### Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------- | ------------ | | `TMaxSupportedTransactionVersion` *extends* `void` \| `TransactionVersion` | `void` | ##### Parameters | Parameter | Type | Description | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `signature` | `Signature` | A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a transaction by virtue of being the first or only signature in its list of signatures. Materializes the transaction as a tuple whose first element is the bytes of the wire transaction as a base64-encoded string. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `TMaxSupportedTransactionVersion`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; }> | - | ##### Returns \| [`GetTransactionApiResponseBase64`](/api/type-aliases/GetTransactionApiResponseBase64)\<`TMaxSupportedTransactionVersion`> \| `null` ##### See [https://solana.com/docs/rpc/http/gettransaction](https://solana.com/docs/rpc/http/gettransaction) #### Call Signature ```ts getTransaction(signature, config): | GetTransactionApiResponseBase58 | null; ``` Returns details of the confirmed transaction identified by the given signature. ##### Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------- | ------------ | | `TMaxSupportedTransactionVersion` *extends* `void` \| `TransactionVersion` | `void` | ##### Parameters | Parameter | Type | Description | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `signature` | `Signature` | A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a transaction by virtue of being the first or only signature in its list of signatures. Materializes the transaction as a tuple whose first element is the bytes of the wire transaction as a base58-encoded string. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `TMaxSupportedTransactionVersion`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; }> | - | ##### Returns \| [`GetTransactionApiResponseBase58`](/api/type-aliases/GetTransactionApiResponseBase58)\<`TMaxSupportedTransactionVersion`> \| `null` ##### See [https://solana.com/docs/rpc/http/gettransaction](https://solana.com/docs/rpc/http/gettransaction) #### Call Signature ```ts getTransaction(signature, config?): | GetTransactionApiResponseJson | null; ``` Returns details of the confirmed transaction identified by the given signature. ##### Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------- | ------------ | | `TMaxSupportedTransactionVersion` *extends* `void` \| `TransactionVersion` | `void` | ##### Parameters | Parameter | Type | Description | | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `signature` | `Signature` | A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a transaction by virtue of being the first or only signature in its list of signatures. Materializes the transaction as structured TransactionJson. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `encoding`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `TMaxSupportedTransactionVersion`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; }> | - | ##### Returns \| [`GetTransactionApiResponseJson`](/api/type-aliases/GetTransactionApiResponseJson)\<`TMaxSupportedTransactionVersion`> \| `null` ##### See [https://solana.com/docs/rpc/http/gettransaction](https://solana.com/docs/rpc/http/gettransaction) # GetTransactionApiResponseBase58 (/api/type-aliases/GetTransactionApiResponseBase58) ```ts type GetTransactionApiResponseBase58 = GetTransactionApiResponseEnvelope & object; ``` The shape of a non-null `getTransaction` response when called with `encoding: 'base58'`. ## Type Declaration | Name | Type | | ------------- | -------------------------------------------------------------- | | `meta` | `TransactionMetaNotParsed`\<`TMaxSupportedTransactionVersion`> | | `transaction` | `Base58EncodedDataResponse` | ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------- | ------------ | | `TMaxSupportedTransactionVersion` *extends* `TransactionVersion` \| `void` | `void` | # GetTransactionApiResponseBase64 (/api/type-aliases/GetTransactionApiResponseBase64) ```ts type GetTransactionApiResponseBase64 = GetTransactionApiResponseEnvelope & object; ``` The shape of a non-null `getTransaction` response when called with `encoding: 'base64'`. ## Type Declaration | Name | Type | | ------------- | -------------------------------------------------------------- | | `meta` | `TransactionMetaNotParsed`\<`TMaxSupportedTransactionVersion`> | | `transaction` | `Base64EncodedDataResponse` | ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------- | ------------ | | `TMaxSupportedTransactionVersion` *extends* `TransactionVersion` \| `void` | `void` | # GetTransactionApiResponseJson (/api/type-aliases/GetTransactionApiResponseJson) ```ts type GetTransactionApiResponseJson = GetTransactionApiResponseEnvelope & object; ``` The shape of a non-null `getTransaction` response when called with `encoding: 'json'` (the default). ## Type Declaration | Name | Type | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `meta` | `TransactionMetaNotParsed`\<`TMaxSupportedTransactionVersion`> | | `transaction` | `TransactionJson` & `TMaxSupportedTransactionVersion` *extends* `void` ? [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `never`> : `TransactionAddressTableLookups` | ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------- | ------------ | | `TMaxSupportedTransactionVersion` *extends* `TransactionVersion` \| `void` | `void` | # GetTransactionApiResponseJsonParsed (/api/type-aliases/GetTransactionApiResponseJsonParsed) ```ts type GetTransactionApiResponseJsonParsed = GetTransactionApiResponseEnvelope & object; ``` The shape of a non-null `getTransaction` response when called with `encoding: 'jsonParsed'`. Inner instructions and instruction data are parsed by the server when a parser is registered for the program. ## Type Declaration | Name | Type | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `meta` | `TransactionMetaBase` & `TransactionMetaInnerInstructionsParsed` \| `null` | | `transaction` | `TransactionJsonParsed` & `TMaxSupportedTransactionVersion` *extends* `void` ? [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `never`> : `TransactionAddressTableLookups` | ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------- | ------------ | | `TMaxSupportedTransactionVersion` *extends* `TransactionVersion` \| `void` | `void` | # GetTransactionCountApi (/api/type-aliases/GetTransactionCountApi) ```ts type GetTransactionCountApi = object; ``` ## Methods ### getTransactionCount() ```ts getTransactionCount(config?): bigint; ``` Returns the current number of transactions to have achieved a given level of commitment. #### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `minContextSlot?`: `Slot`; }> | #### Returns `bigint` #### See [https://solana.com/docs/rpc/http/gettransactioncount](https://solana.com/docs/rpc/http/gettransactioncount) # GetTransactionsForAddressApi (/api/type-aliases/GetTransactionsForAddressApi) ```ts type GetTransactionsForAddressApi = object; ``` ## Methods ### getTransactionsForAddress() #### Call Signature ```ts getTransactionsForAddress(address, config): GetTransactionsForAddressApiResponse>; ``` Returns full transactions, parsed as JSON, for confirmed transactions that load the given address. Because `maxSupportedTransactionVersion` is set, each result carries a `version`, its `meta` carries `loadedAddresses`, and its message carries `addressTableLookups`. Each instruction the server is able to parse will materialize as parsed data; otherwise it will materialize as a list of accounts, a program address, and base58-encoded instruction data. Note: Check your RPC provider for support for this method. ##### Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `AllowedCommitmentForGetTransactionsForAddress`; `filters?`: `GetTransactionsForAddressFilters`; `limit?`: `number`; `minContextSlot?`: `Slot`; `paginationToken?`: `string`; `sortOrder?`: `"asc"` \| `"desc"`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `maxSupportedTransactionVersion`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; `transactionDetails`: `"full"`; }> | ##### Returns `GetTransactionsForAddressApiResponse`\<`GetTransactionsForAddressFullJsonParsed`\<`GetTransactionsForAddressMaxSupportedTransactionVersion`>> #### Call Signature ```ts getTransactionsForAddress(address, config): GetTransactionsForAddressApiResponse>; ``` Returns full transactions, parsed as JSON, for confirmed transactions that load the given address. Because `maxSupportedTransactionVersion` is omitted, only legacy transactions are returned and no `version` property is present. Each instruction the server is able to parse will materialize as parsed data; otherwise it will materialize as a list of accounts, a program address, and base58-encoded instruction data. Note: Check your RPC provider for support for this method. ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `AllowedCommitmentForGetTransactionsForAddress`; `filters?`: `GetTransactionsForAddressFilters`; `limit?`: `number`; `minContextSlot?`: `Slot`; `paginationToken?`: `string`; `sortOrder?`: `"asc"` \| `"desc"`; }> & [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; `transactionDetails`: `"full"`; }> | ##### Returns `GetTransactionsForAddressApiResponse`\<`GetTransactionsForAddressFullJsonParsed`\<`void`>> #### Call Signature ```ts getTransactionsForAddress(address, config): GetTransactionsForAddressApiResponse>; ``` Returns full transactions, as base64-encoded wire transactions, for confirmed transactions that load the given address. Because `maxSupportedTransactionVersion` is set, each result carries a `version` and its `meta` carries `loadedAddresses`. Note: Check your RPC provider for support for this method. ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `AllowedCommitmentForGetTransactionsForAddress`; `filters?`: `GetTransactionsForAddressFilters`; `limit?`: `number`; `minContextSlot?`: `Slot`; `paginationToken?`: `string`; `sortOrder?`: `"asc"` \| `"desc"`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `maxSupportedTransactionVersion`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; `transactionDetails`: `"full"`; }> | ##### Returns `GetTransactionsForAddressApiResponse`\<`GetTransactionsForAddressFullEncoded`\<`GetTransactionsForAddressMaxSupportedTransactionVersion`, `Base64EncodedDataResponse`>> #### Call Signature ```ts getTransactionsForAddress(address, config): GetTransactionsForAddressApiResponse>; ``` Returns full transactions, as base64-encoded wire transactions, for confirmed transactions that load the given address. Because `maxSupportedTransactionVersion` is omitted, only legacy transactions are returned and no `version` property is present. Note: Check your RPC provider for support for this method. ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `AllowedCommitmentForGetTransactionsForAddress`; `filters?`: `GetTransactionsForAddressFilters`; `limit?`: `number`; `minContextSlot?`: `Slot`; `paginationToken?`: `string`; `sortOrder?`: `"asc"` \| `"desc"`; }> & [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; `transactionDetails`: `"full"`; }> | ##### Returns `GetTransactionsForAddressApiResponse`\<`GetTransactionsForAddressFullEncoded`\<`void`, `Base64EncodedDataResponse`>> #### Call Signature ```ts getTransactionsForAddress(address, config): GetTransactionsForAddressApiResponse>; ``` Returns full transactions, as base58-encoded wire transactions, for confirmed transactions that load the given address. Because `maxSupportedTransactionVersion` is set, each result carries a `version` and its `meta` carries `loadedAddresses`. Note: Check your RPC provider for support for this method. ##### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `AllowedCommitmentForGetTransactionsForAddress`; `filters?`: `GetTransactionsForAddressFilters`; `limit?`: `number`; `minContextSlot?`: `Slot`; `paginationToken?`: `string`; `sortOrder?`: `"asc"` \| `"desc"`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `maxSupportedTransactionVersion`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; `transactionDetails`: `"full"`; }> | ##### Returns `GetTransactionsForAddressApiResponse`\<`GetTransactionsForAddressFullEncoded`\<`GetTransactionsForAddressMaxSupportedTransactionVersion`, `Base58EncodedDataResponse`>> #### Call Signature ```ts getTransactionsForAddress(address, config): GetTransactionsForAddressApiResponse>; ``` Returns full transactions, as base58-encoded wire transactions, for confirmed transactions that load the given address. Because `maxSupportedTransactionVersion` is omitted, only legacy transactions are returned and no `version` property is present. Note: Check your RPC provider for support for this method. ##### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `AllowedCommitmentForGetTransactionsForAddress`; `filters?`: `GetTransactionsForAddressFilters`; `limit?`: `number`; `minContextSlot?`: `Slot`; `paginationToken?`: `string`; `sortOrder?`: `"asc"` \| `"desc"`; }> & [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; `transactionDetails`: `"full"`; }> | ##### Returns `GetTransactionsForAddressApiResponse`\<`GetTransactionsForAddressFullEncoded`\<`void`, `Base58EncodedDataResponse`>> #### Call Signature ```ts getTransactionsForAddress(address, config): GetTransactionsForAddressApiResponse>; ``` Returns full transactions, as structured JSON, for confirmed transactions that load the given address. Because `maxSupportedTransactionVersion` is set, each result carries a `version`, its `meta` carries `loadedAddresses`, and its message carries `addressTableLookups`. Note: Check your RPC provider for support for this method. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `AllowedCommitmentForGetTransactionsForAddress`; `filters?`: `GetTransactionsForAddressFilters`; `limit?`: `number`; `minContextSlot?`: `Slot`; `paginationToken?`: `string`; `sortOrder?`: `"asc"` \| `"desc"`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `maxSupportedTransactionVersion`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; `transactionDetails`: `"full"`; }> | ##### Returns `GetTransactionsForAddressApiResponse`\<`GetTransactionsForAddressFullJson`\<`GetTransactionsForAddressMaxSupportedTransactionVersion`>> #### Call Signature ```ts getTransactionsForAddress(address, config): GetTransactionsForAddressApiResponse>; ``` Returns full transactions, as structured JSON, for confirmed transactions that load the given address. Because `maxSupportedTransactionVersion` is omitted, only legacy transactions are returned and no `version` property is present. Note: Check your RPC provider for support for this method. ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `AllowedCommitmentForGetTransactionsForAddress`; `filters?`: `GetTransactionsForAddressFilters`; `limit?`: `number`; `minContextSlot?`: `Slot`; `paginationToken?`: `string`; `sortOrder?`: `"asc"` \| `"desc"`; }> & [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"base58"` \| `"base64"` \| `"json"` \| `"jsonParsed"`; `maxSupportedTransactionVersion?`: `GetTransactionsForAddressMaxSupportedTransactionVersion`; }>, `"maxSupportedTransactionVersion"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding?`: `"json"`; `transactionDetails`: `"full"`; }> | ##### Returns `GetTransactionsForAddressApiResponse`\<`GetTransactionsForAddressFullJson`\<`void`>> #### Call Signature ```ts getTransactionsForAddress(address, config?): GetTransactionsForAddressApiResponse; ``` Returns signature-level results for confirmed transactions that load the given address. This is the default mode. It combines the discovery step of [GetSignaturesForAddressApi.getSignaturesForAddress](/api/type-aliases/GetSignaturesForAddressApi#getsignaturesforaddress) with server-side filtering, sorting and cursor-based pagination. Note: Check your RPC provider for support for this method. ##### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `AllowedCommitmentForGetTransactionsForAddress`; `filters?`: `GetTransactionsForAddressFilters`; `limit?`: `number`; `minContextSlot?`: `Slot`; `paginationToken?`: `string`; `sortOrder?`: `"asc"` \| `"desc"`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `transactionDetails?`: `"signatures"`; }> | ##### Returns `GetTransactionsForAddressApiResponse`\<`GetTransactionsForAddressSignature`> ##### Example ```ts const { data, paginationToken } = await rpc .getTransactionsForAddress(address, { filters: { status: 'succeeded' }, limit: 100, sortOrder: 'desc', }) .send(); ``` # GetVersionApi (/api/type-aliases/GetVersionApi) ```ts type GetVersionApi = object; ``` ## Methods ### getVersion() ```ts getVersion(): GetVersionApiResponse; ``` Returns the current Solana version running on the node. #### Returns `GetVersionApiResponse` #### See [https://solana.com/docs/rpc/http/getversion](https://solana.com/docs/rpc/http/getversion) # GetVoteAccountsApi (/api/type-aliases/GetVoteAccountsApi) ```ts type GetVoteAccountsApi = object; ``` ## Methods ### getVoteAccounts() ```ts getVoteAccounts(config?): GetVoteAccountsApiResponse; ``` Returns the account info and associated stake for all the voting accounts in the current bank. #### Type Parameters | Type Parameter | | ---------------------------------- | | `TVoteAccount` *extends* `Address` | #### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `delinquentSlotDistance?`: `bigint`; `keepUnstakedDelinquents?`: `boolean`; `votePubkey?`: `TVoteAddress`; }> | #### Returns `GetVoteAccountsApiResponse`\<`TVoteAccount`> #### See [https://solana.com/docs/rpc/http/getvoteaccounts](https://solana.com/docs/rpc/http/getvoteaccounts) # GrindKeyPairMatches (/api/type-aliases/GrindKeyPairMatches) ```ts type GrindKeyPairMatches = | RegExp | ((address) => boolean); ``` A function or [RegExp](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) used to test whether a candidate base58-encoded address produced from a generated key pair satisfies the grind criteria. * When a `RegExp` is provided, its literal characters (outside of escape sequences, character classes, quantifiers, and groups) are validated up front to ensure they are all in the base58 alphabet. This catches common typos like `/^ab0/` before any key generation takes place. * When a function is provided, it is used as-is with no validation. Use this form when you need arbitrary matching logic that falls outside what a simple regex can express. ## See * [grindKeyPair](/api/functions/grindKeyPair) * [grindKeyPairs](/api/functions/grindKeyPairs) # GrindKeyPairsConfig (/api/type-aliases/GrindKeyPairsConfig) ```ts type GrindKeyPairsConfig = Readonly<{ abortSignal?: AbortSignal; amount?: number; concurrency?: number; extractable?: boolean; matches: GrindKeyPairMatches; }>; ``` Configuration object accepted by [grindKeyPairs](/api/functions/grindKeyPairs). ## See * [grindKeyPairs](/api/functions/grindKeyPairs) * [GrindKeyPairMatches](/api/type-aliases/GrindKeyPairMatches) # InstructionPlan (/api/type-aliases/InstructionPlan) ```ts type InstructionPlan = | MessagePackerInstructionPlan | ParallelInstructionPlan | SequentialInstructionPlan | SingleInstructionPlan; ``` A set of instructions with constraints on how they can be executed. This is structured as a recursive tree of plans in order to allow for parallel execution, sequential execution and combinations of both. Namely the following plans are supported: * [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan) - A plan that contains a single instruction. This is a simple instruction wrapper and the simplest leaf in this tree. * [ParallelInstructionPlan](/api/type-aliases/ParallelInstructionPlan) - A plan that contains other plans that can be executed in parallel. * [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) - A plan that contains other plans that must be executed sequentially. It also defines whether the plan is divisible meaning that instructions inside it can be split into separate transactions. * [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) - A plan that can dynamically pack instructions into transaction messages. Helpers are provided for each of these plans to make it easier to create them. ## Example ```ts const myInstructionPlan: InstructionPlan = parallelInstructionPlan([ sequentialInstructionPlan([instructionA, instructionB]), instructionC, instructionD, ]); ``` ## See * [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan) * [ParallelInstructionPlan](/api/type-aliases/ParallelInstructionPlan) * [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) * [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) # InstructionPlanInput (/api/type-aliases/InstructionPlanInput) ```ts type InstructionPlanInput = | Instruction | InstructionPlan | readonly ( | Instruction | InstructionPlan)[]; ``` A flexible input type that can be used to create an [InstructionPlan](/api/type-aliases/InstructionPlan). This type accepts: * A single [Instruction](/api/interfaces/Instruction). * An existing [InstructionPlan](/api/type-aliases/InstructionPlan). * An array of instructions and/or instruction plans. Use the [parseInstructionPlanInput](/api/functions/parseInstructionPlanInput) function to convert this input into a proper [InstructionPlan](/api/type-aliases/InstructionPlan). ## Examples Using a single instruction. ```ts const input: InstructionPlanInput = myInstruction; ``` Use as argument type in a function that will parse it into an InstructionPlan. ```ts function myFunction(input: InstructionPlanInput) { const plan = parseInstructionPlanInput(input); // Use the plan... } ``` ## See * [parseInstructionPlanInput](/api/functions/parseInstructionPlanInput) * [InstructionPlan](/api/type-aliases/InstructionPlan) # InstructionTrace (/api/type-aliases/InstructionTrace) ```ts type InstructionTrace = | Readonly<{ index: number; kind: "outer"; }> | Readonly<{ innerIndex: number; kind: "inner"; outerIndex: number; stackHeight?: number; }>; ``` The location of an instruction within a transaction. * `kind: 'outer'` β€” a top-level instruction in the transaction message. `index` is its position in the compiled message's instructions. * `kind: 'inner'` β€” an instruction emitted via cross-program invocation. `outerIndex` is the index of the outer instruction that triggered the CPI chain; `innerIndex` is the position within that outer instruction's inner-instruction group. ## Example ```ts function describe(trace: InstructionTrace): string { return trace.kind === 'outer' ? `outer[${trace.index}]` : `inner[outer=${trace.outerIndex}, idx=${trace.innerIndex}]`; } ``` # InstructionWithByteDelta (/api/type-aliases/InstructionWithByteDelta) ```ts type InstructionWithByteDelta = object; ``` An instruction that tracks how many bytes it adds or removes from on-chain accounts. The `byteDelta` indicates the net change in account storage size. A positive value means bytes are being allocated, while a negative value means bytes are being freed. This is useful for calculating how much balance a storage payer must have for a transaction to succeed. ## Properties ### byteDelta ```ts byteDelta: number; ``` # IntegerOverflowHandler (/api/type-aliases/IntegerOverflowHandler) ```ts type IntegerOverflowHandler = (request, keyPath, value) => void; ``` ## Parameters | Parameter | Type | | --------- | -------------------------------------- | | `request` | `RpcRequest` | | `keyPath` | [`KeyPath`](/api/type-aliases/KeyPath) | | `value` | `bigint` | ## Returns `void` # IsBlockhashValidApi (/api/type-aliases/IsBlockhashValidApi) ```ts type IsBlockhashValidApi = object; ``` ## Methods ### isBlockhashValid() ```ts isBlockhashValid(blockhash, config?): SolanaRpcResponse; ``` Returns whether a blockhash is still valid or not. The last 300 blockhashes produced are considered valid. This equates to an age of \~2 minutes. #### Parameters | Parameter | Type | Description | | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | `blockhash` | `Blockhash` | A SHA-256 hash as base-58 encoded string | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `minContextSlot?`: `Slot`; }> | - | #### Returns `SolanaRpcResponse`\<`IsBlockhashValidApiResponse`> #### See [https://solana.com/docs/rpc/http/isblockhashvalid](https://solana.com/docs/rpc/http/isblockhashvalid) # JsonParsedAddressLookupTableAccount (/api/type-aliases/JsonParsedAddressLookupTableAccount) ```ts type JsonParsedAddressLookupTableAccount = RpcParsedInfo<{ addresses: readonly Address[]; authority?: Address; deactivationSlot: StringifiedBigInt; lastExtendedSlot: StringifiedBigInt; lastExtendedSlotStartIndex: number; }>; ``` # JsonParsedBpfUpgradeableLoaderProgramAccount (/api/type-aliases/JsonParsedBpfUpgradeableLoaderProgramAccount) ```ts type JsonParsedBpfUpgradeableLoaderProgramAccount = | RpcParsedType<"program", JsonParsedBpfProgramAccount> | RpcParsedType<"programData", JsonParsedBpfProgramDataAccount>; ``` # JsonParsedConfigProgramAccount (/api/type-aliases/JsonParsedConfigProgramAccount) ```ts type JsonParsedConfigProgramAccount = | RpcParsedType<"stakeConfig", JsonParsedStakeConfigAccount> | RpcParsedType<"validatorInfo", JsonParsedValidatorInfoAccount>; ``` # JsonParsedNonceAccount (/api/type-aliases/JsonParsedNonceAccount) ```ts type JsonParsedNonceAccount = RpcParsedInfo<{ authority: Address; blockhash: Blockhash; feeCalculator: Readonly<{ lamportsPerSignature: StringifiedBigInt; }>; }>; ``` # JsonParsedStakeProgramAccount (/api/type-aliases/JsonParsedStakeProgramAccount) ```ts type JsonParsedStakeProgramAccount = | RpcParsedType<"delegated", JsonParsedStakeAccount> | RpcParsedType<"initialized", JsonParsedStakeAccount>; ``` # JsonParsedSysvarAccount (/api/type-aliases/JsonParsedSysvarAccount) ```ts type JsonParsedSysvarAccount = | RpcParsedType<"clock", JsonParsedClockAccount> | RpcParsedType<"epochRewards", JsonParsedEpochRewardsAccount> | RpcParsedType<"epochSchedule", JsonParsedEpochScheduleAccount> | RpcParsedType<"fees", JsonParsedFeesAccount_DEPRECATED> | RpcParsedType<"lastRestartSlot", JsonParsedLastRestartSlotAccount> | RpcParsedType<"recentBlockhashes", JsonParsedRecentBlockhashesAccount_DEPRECATED> | RpcParsedType<"rent", JsonParsedRentAccount | JsonParsedRentAccount_DEPRECATED> | RpcParsedType<"slotHashes", JsonParsedSlotHashesAccount> | RpcParsedType<"slotHistory", JsonParsedSlotHistoryAccount> | RpcParsedType<"stakeHistory", JsonParsedStakeHistoryAccount>; ``` # JsonParsedTokenAccount (/api/type-aliases/JsonParsedTokenAccount) ```ts type JsonParsedTokenAccount = Readonly<{ closeAuthority?: Address; delegate?: Address; delegatedAmount?: TokenAmount; extensions?: readonly unknown[]; isNative: boolean; mint: Address; owner: Address; rentExemptReserve?: TokenAmount; state: TokenAccountState; tokenAmount: TokenAmount; }>; ``` # JsonParsedTokenProgramAccount (/api/type-aliases/JsonParsedTokenProgramAccount) ```ts type JsonParsedTokenProgramAccount = | RpcParsedType<"account", JsonParsedTokenAccount> | RpcParsedType<"mint", JsonParsedMintAccount> | RpcParsedType<"multisig", JsonParsedMultisigAccount>; ``` # JsonParsedVoteAccount (/api/type-aliases/JsonParsedVoteAccount) ```ts type JsonParsedVoteAccount = RpcParsedInfo<{ authorizedVoters: Readonly<{ authorizedVoter: Address; epoch: Epoch; }>[]; authorizedWithdrawer: Address; blockRevenueCollector: Address; blockRevenueCommissionBps: number; blsPubkeyCompressed: string | null; commission: number; epochCredits: Readonly<{ credits: StringifiedBigInt; epoch: Epoch; previousCredits: StringifiedBigInt; }>[]; inflationRewardsCollector: Address; inflationRewardsCommissionBps: number; lastTimestamp: Readonly<{ slot: Slot; timestamp: UnixTimestamp; }>; nodePubkey: Address; pendingDelegatorRewards: StringifiedBigInt; priorVoters: Readonly<{ authorizedPubkey: Address; epochOfLastAuthorizedSwitch: Epoch; targetEpoch: Epoch; }>[]; rootSlot: Slot | null; votes: Readonly<{ confirmationCount: number; latency: number; slot: Slot; }>[]; }>; ``` # KeyPairSigner (/api/type-aliases/KeyPairSigner) ```ts type KeyPairSigner = MessagePartialSigner & TransactionPartialSigner & object; ``` Defines a signer that uses a CryptoKeyPair to sign messages and transactions. It implements both the [MessagePartialSigner](/api/type-aliases/MessagePartialSigner) and [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner) interfaces and keeps track of the CryptoKeyPair instance used to sign messages and transactions. ## Type Declaration | Name | Type | | --------- | --------------- | | `keyPair` | `CryptoKeyPair` | ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ----------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define a signer having a particular address. | ## Example ```ts import { generateKeyPairSigner } from '@solana/signers'; const signer = generateKeyPairSigner(); signer.address; // Address; signer.keyPair; // CryptoKeyPair; const [messageSignatures] = await signer.signMessages([message]); const [transactionSignatures] = await signer.signTransactions([transaction]); ``` ## See * [generateKeyPairSigner](/api/functions/generateKeyPairSigner) * [createSignerFromKeyPair](/api/functions/createSignerFromKeyPair) * [createKeyPairSignerFromBytes](/api/functions/createKeyPairSignerFromBytes) * [createKeyPairSignerFromPrivateKeyBytes](/api/functions/createKeyPairSignerFromPrivateKeyBytes) * [isKeyPairSigner](/api/functions/isKeyPairSigner) * [assertIsKeyPairSigner](/api/functions/assertIsKeyPairSigner) # KeyPath (/api/type-aliases/KeyPath) ```ts type KeyPath = ReadonlyArray; ``` # KeyPathWildcard (/api/type-aliases/KeyPathWildcard) ```ts type KeyPathWildcard = object; ``` ## Properties ### \_\_keyPathWildcard:@solana/kit ```ts readonly __keyPathWildcard:@solana/kit: unique symbol; ``` # Lamports (/api/type-aliases/Lamports) ```ts type Lamports = Brand; ``` Represents an integer value denominated in Lamports (ie. $1 \times 10^{-9}$ β—Ž). It is represented as a `bigint` in client code and an `u64` in server code. # LegacyCompiledTransactionMessage (/api/type-aliases/LegacyCompiledTransactionMessage) ```ts type LegacyCompiledTransactionMessage = Readonly<{ header: ReturnType; instructions: ReturnType; staticAccounts: Address[]; version: "legacy"; }>; ``` # LiteralUnionCodecConfig (/api/type-aliases/LiteralUnionCodecConfig) ```ts type LiteralUnionCodecConfig = object; ``` Defines the configuration options for literal union codecs. A literal union codec encodes values from a predefined set of literals. The `size` option determines the numerical encoding used for the discriminant. By default, literals are stored as a `u8` (1 byte). ## Type Parameters | Type Parameter | Default type | Description | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `TDiscriminator` | \| [`NumberCodec`](/api/type-aliases/NumberCodec) \| [`NumberDecoder`](/api/type-aliases/NumberDecoder) \| [`NumberEncoder`](/api/type-aliases/NumberEncoder) | A number codec, encoder, or decoder used for the discriminant. | ## Properties ### size? ```ts optional size?: TDiscriminator; ``` The codec used to encode/decode the discriminator. #### Default Value `u8` discriminator. # LoadedAddresses (/api/type-aliases/LoadedAddresses) ```ts type LoadedAddresses = Readonly<{ readonly: readonly Address[]; writable: readonly Address[]; }>; ``` Loaded ALT addresses as returned by `getTransaction`'s `meta.loadedAddresses`. The two arrays are kept in the same order the runtime uses to resolve instruction account indices. ## Example ```ts const loaded: LoadedAddresses = rpcResponse.meta?.loadedAddresses ?? { readonly: [], writable: [], }; ``` # LogsNotificationsApi (/api/type-aliases/LogsNotificationsApi) ```ts type LogsNotificationsApi = object; ``` ## Methods ### logsNotifications() #### Call Signature ```ts logsNotifications(filter, config?): LogsNotificationsApiNotification; ``` Subscribe to receive notifications containing the logs of all non-vote transactions. ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | | `filter` | `"all"` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | ##### Returns `LogsNotificationsApiNotification` ##### See [https://solana.com/docs/rpc/websocket/logssubscribe](https://solana.com/docs/rpc/websocket/logssubscribe) #### Call Signature ```ts logsNotifications(filter, config?): LogsNotificationsApiNotification; ``` Subscribe to receive notifications containing the logs of all transactions. ##### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | | `filter` | `"allWithVotes"` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | ##### Returns `LogsNotificationsApiNotification` ##### See [https://solana.com/docs/rpc/websocket/logssubscribe](https://solana.com/docs/rpc/websocket/logssubscribe) #### Call Signature ```ts logsNotifications(filter, config?): LogsNotificationsApiNotification; ``` Subscribe to receive notifications containing the logs of transactions that mention the supplied program or account. ##### Parameters | Parameter | Type | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | \{ `mentions`: \[`Address`]; } | - | | `filter.mentions` | \[`Address`] | This filter matches when a transaction mentions the single address provided. This filter currently only supports one address per method call. Listing additional addresses will result in an error. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | - | ##### Returns `LogsNotificationsApiNotification` ##### See [https://solana.com/docs/rpc/websocket/logssubscribe](https://solana.com/docs/rpc/websocket/logssubscribe) # MainnetUrl (/api/type-aliases/MainnetUrl) ```ts type MainnetUrl = string & object; ``` ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"mainnet"` | # MapCodecConfig (/api/type-aliases/MapCodecConfig) ```ts type MapCodecConfig = object; ``` Defines the configuration options for map codecs. The `size` option determines how the number of entries in the map is stored. It can be: * A [NumberCodec](/api/type-aliases/NumberCodec) to prefix the map with its size. * A fixed number of entries. * `'remainder'`, which infers the number of entries based on the remaining bytes. This option is only available for fixed-size keys and values. ## Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | `TPrefix` *extends* \| [`NumberCodec`](/api/type-aliases/NumberCodec) \| [`NumberDecoder`](/api/type-aliases/NumberDecoder) \| [`NumberEncoder`](/api/type-aliases/NumberEncoder) | A number codec, encoder, or decoder used for the size prefix. | ## Properties ### size? ```ts optional size?: ArrayLikeCodecSize; ``` The size of the map. #### Default Value ```ts u32 prefix. ``` # MaybeAccount (/api/type-aliases/MaybeAccount) ```ts type MaybeAccount = | { address: Address; exists: false; } | Account & object; ``` Represents an account that may or may not exist on-chain. When the account exists, it is represented as an [Account](/api/interfaces/Account) type with an additional `exists` attribute set to `true`. When it does not exist, it is represented by an object containing only the address of the account and an `exists` attribute set to `false`. ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TData` *extends* \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) \| `object` | - | The nature of this account's data. It can be represented as either a `Uint8Array` – meaning the account is encoded – or a custom data type – meaning the account is decoded. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ## Example ```ts // Account exists const myExistingAccount: MaybeAccount = { exists: true, address: address('1234..5678'), data: { name: 'Alice', age: 30 }, // ... }; // Account does not exist const myMissingAccount: MaybeAccount = { exists: false, address: address('8765..4321'), }; ``` # MaybeEncodedAccount (/api/type-aliases/MaybeEncodedAccount) ```ts type MaybeEncodedAccount = MaybeAccount; ``` Represents an encoded account that may or may not exist on-chain. When the account exists, it is represented as an [Account](/api/interfaces/Account) type having its `TData` type parameter set to `Uint8Array` with an additional `exists` attribute set to `true`. When it does not exist, it is represented by an object containing only the address of the account and an `exists` attribute set to `false`. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ## Example ```ts // Encoded account exists const myExistingAccount: MaybeEncodedAccount<'1234..5678'> = { exists: true, address: address('1234..5678'), data: new Uint8Array([1, 2, 3]), // ... }; // Encoded account does not exist const myMissingAccount: MaybeEncodedAccount<'8765..4321'> = { exists: false, address: address('8765..4321'), }; ``` # MessageModifyingSigner (/api/type-aliases/MessageModifyingSigner) ```ts type MessageModifyingSigner = Readonly<{ address: Address; modifyAndSignMessages: Promise[]>; }>; ``` A signer interface that *potentially* modifies the content of the provided [SignableMessages](/api/type-aliases/SignableMessage) before signing them. For instance, this enables wallets to prefix or suffix nonces to the messages they sign. For each message, instead of returning a [SignatureDictionary](/api/type-aliases/SignatureDictionary), the MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages function returns an updated [SignableMessage](/api/type-aliases/SignableMessage) with a potentially modified content and signature dictionary. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ----------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define a signer having a particular address. | ## Example ```ts const signer: MessageModifyingSigner<'1234..5678'> = { address: address('1234..5678'), modifyAndSignMessages: async ( messages: SignableMessage[] ): Promise => { // My custom signing logic. }, }; ``` ## Remarks Here are the main characteristics of this signer interface: * **Sequential**. Contrary to partial signers, these cannot be executed in parallel as each call can modify the content of the message. * **First signers**. For a given message, a modifying signer must always be used before a partial signer as the former will likely modify the message and thus impact the outcome of the latter. * **Potential conflicts**. If more than one modifying signer is provided, the second signer may invalidate the signature of the first one. However, modifying signers may decide not to modify a message based on the existence of signatures for that message. ## See * [SignableMessage](/api/type-aliases/SignableMessage) * [createSignableMessage](/api/functions/createSignableMessage) * [isMessageModifyingSigner](/api/functions/isMessageModifyingSigner) * [assertIsMessageModifyingSigner](/api/functions/assertIsMessageModifyingSigner) # MessageModifyingSignerConfig (/api/type-aliases/MessageModifyingSignerConfig) ```ts type MessageModifyingSignerConfig = BaseSignerConfig; ``` The configuration to optionally provide when calling the MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages method. ## See [BaseSignerConfig](/api/type-aliases/BaseSignerConfig) # MessagePacker (/api/type-aliases/MessagePacker) ```ts type MessagePacker = Readonly<{ done: () => boolean; packMessageToCapacity: (transactionMessage, config?) => TransactionMessage & TransactionMessageWithFeePayer; }>; ``` The message packer returned by the [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan). It offers a `packMessageToCapacity(transactionMessage)` method that packs as many instructions as possible into the provided transaction message, while still being able to fit into the transaction size limit and the default or configured instruction-count limit. It returns the updated transaction message with the packed instructions or throws an error if the current transaction message cannot accommodate this plan. The `done()` method checks whether there are more instructions to pack into transaction messages. ## Example ```ts let plan: MessagePackerInstructionPlan; const messagePacker = plan.getMessagePacker(); while (!messagePacker.done()) { try { transactionMessage = messagePacker.packMessageToCapacity(transactionMessage); } catch (error) { // The current transaction message cannot be used to pack this plan. // We should create a new one and try again. } } ``` ## See [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) # MessagePackerInstructionPlan (/api/type-aliases/MessagePackerInstructionPlan) ```ts type MessagePackerInstructionPlan = Readonly<{ getMessagePacker: () => MessagePacker; kind: "messagePacker"; planType: "instructionPlan"; }>; ``` A plan that can dynamically pack instructions into transaction messages. This plan provides a [MessagePacker](/api/type-aliases/MessagePacker) via the `getMessagePacker` method, which enables instructions to be dynamically packed into the provided transaction message until there are no more instructions to pack. The returned [MessagePacker](/api/type-aliases/MessagePacker) offers a `packMessageToCapacity(message)` method that packs the provided message β€” when possible β€” and a `done()` method that checks whether there are more instructions to pack. Several helper functions are provided to create objects of this type such as [getLinearMessagePackerInstructionPlan](/api/functions/getLinearMessagePackerInstructionPlan) or [getMessagePackerInstructionPlanFromInstructions](/api/functions/getMessagePackerInstructionPlanFromInstructions). ## Examples **An message packer plan for a write instruction that uses as many bytes as possible.** ```ts const plan = getLinearMessagePackerInstructionPlan({ totalLength: dataToWrite.length, getInstruction: (offset, length) => getWriteInstruction({ offset, data: dataToWrite.slice(offset, offset + length), }), }); plan satisfies MessagePackerInstructionPlan; ``` **A message packer plan for multiple realloc instructions.** ```ts const plan = getReallocMessagePackerInstructionPlan({ totalSize: additionalDataSize, getInstruction: (size) => getExtendInstruction({ length: size }), }); plan satisfies MessagePackerInstructionPlan; ``` **Using a message packer plan.** ```ts let plan: MessagePackerInstructionPlan; const messagePacker = plan.getMessagePacker(); while (!messagePacker.done()) { try { transactionMessage = messagePacker.packMessageToCapacity(transactionMessage); } catch (error) { // The current transaction message cannot be used to pack this plan. // We should create a new one and try again. } } ``` ## See * [getLinearMessagePackerInstructionPlan](/api/functions/getLinearMessagePackerInstructionPlan) * [getMessagePackerInstructionPlanFromInstructions](/api/functions/getMessagePackerInstructionPlanFromInstructions) * [getReallocMessagePackerInstructionPlan](/api/functions/getReallocMessagePackerInstructionPlan) # MessagePartialSigner (/api/type-aliases/MessagePartialSigner) ```ts type MessagePartialSigner = Readonly<{ address: Address; signMessages: Promise>[]>; }>; ``` A signer interface that signs an array of [SignableMessages](/api/type-aliases/SignableMessage) without modifying their content. It defines a MessagePartialSigner#signMessages | signMessages function that returns a [SignatureDictionary](/api/type-aliases/SignatureDictionary) for each provided message. Such signature dictionaries are expected to be merged with the existing ones if any. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ----------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define a signer having a particular address. | ## Example ```ts const signer: MessagePartialSigner<'1234..5678'> = { address: address('1234..5678'), signMessages: async ( messages: SignableMessage[] ): Promise => { // My custom signing logic. }, }; ``` ## Remarks Here are the main characteristics of this signer interface: * **Parallel**. When multiple signers sign the same message, we can perform this operation in parallel to obtain all their signatures. * **Flexible order**. The order in which we use these signers for a given message doesn’t matter. ## See * [SignableMessage](/api/type-aliases/SignableMessage) * [createSignableMessage](/api/functions/createSignableMessage) * [isMessagePartialSigner](/api/functions/isMessagePartialSigner) * [assertIsMessagePartialSigner](/api/functions/assertIsMessagePartialSigner) # MessagePartialSignerConfig (/api/type-aliases/MessagePartialSignerConfig) ```ts type MessagePartialSignerConfig = BaseSignerConfig; ``` The configuration to optionally provide when calling the MessagePartialSigner#signMessages | signMessages method. ## See [BaseSignerConfig](/api/type-aliases/BaseSignerConfig) # MessageSigner (/api/type-aliases/MessageSigner) ```ts type MessageSigner = | MessageModifyingSigner | MessagePartialSigner; ``` Defines a signer capable of signing messages. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## See * [MessageModifyingSigner](/api/type-aliases/MessageModifyingSigner) For signers that can modify messages before signing them. * [MessagePartialSigner](/api/type-aliases/MessagePartialSigner) For signers that can be used in parallel. * [isMessageSigner](/api/functions/isMessageSigner) * [assertIsMessageSigner](/api/functions/assertIsMessageSigner) # MetaWithInnerInstructions (/api/type-aliases/MetaWithInnerInstructions) ```ts type MetaWithInnerInstructions = Readonly<{ innerInstructions?: readonly RpcInnerInstructionsGroup[] | null; }>; ``` The minimum shape of `getTransaction`'s `meta` field that this helper needs. Accepting a structural type keeps callers free to pass the full RPC response without coupling to a specific overload. ## Example ```ts const inner = getInnerInstructionsFromMeta(rpcResponse.meta, accountMetas); ``` # MicroLamports (/api/type-aliases/MicroLamports) ```ts type MicroLamports = Brand; ``` # MinimumLedgerSlotApi (/api/type-aliases/MinimumLedgerSlotApi) ```ts type MinimumLedgerSlotApi = object; ``` ## Methods ### minimumLedgerSlot() ```ts minimumLedgerSlot(): bigint; ``` Returns the lowest slot about which the node has information. Different nodes may offer more or less historical slot data, depending on their configuration. An appropriately configured node should be able to access all slots, from genesis onward. When it is not, this method will tell you the lowest slot available. #### Returns `bigint` #### See [https://solana.com/docs/rpc/http/minimumledgerslot](https://solana.com/docs/rpc/http/minimumledgerslot) # NominalType (/api/type-aliases/NominalType) ```ts type NominalType = { readonly [K in `__${TKey}:@solana/kit`]: TMarker }; ``` Use this to produce a nominal type. This can be intersected with other base types to produce custom branded types. ## Type Parameters | Type Parameter | Description | | ---------------------------- | ------------------------------------------------------------------------------- | | `TKey` *extends* `string` | The name of the nominal type. This distinguishes one nominal type from another. | | `TMarker` *extends* `string` | The type of the value the nominal type can take. | ## Example ```ts type SweeteningSubstance = 'aspartame' | 'cane-sugar' | 'stevia'; type Sweetener = NominalType<'sweetener', T>; // This function accepts sweetened foods, except those with aspartame. declare function eat(food: string & Sweetener>): void; const artificiallySweetenedDessert = 'ice-cream' as string & Sweetener<'aspartame'>; eat(artificiallySweetenedDessert); // ERROR ``` # Nonce (/api/type-aliases/Nonce) ```ts type Nonce = Brand; ``` Represents a string that is particularly known to be the base58-encoded value of a nonce. ## Type Parameters | Type Parameter | Default type | | -------------------------------- | ------------ | | `TNonceValue` *extends* `string` | `string` | # NonceLifetimeConstraint (/api/type-aliases/NonceLifetimeConstraint) ```ts type NonceLifetimeConstraint = Readonly<{ nonce: Nonce; }>; ``` A constraint which, when applied to a transaction message, makes that transaction message eligible to land on the network. The transaction message will continue to be eligible to land until the network considers the `nonce` to have advanced. This can happen when the nonce account in which this nonce is found is destroyed, or the nonce value within changes. ## Type Parameters | Type Parameter | Default type | | -------------------------------- | ------------ | | `TNonceValue` *extends* `string` | `string` | # None (/api/type-aliases/None) ```ts type None = Readonly<{ __option: "None"; }>; ``` Represents an [Option](/api/type-aliases/Option) that contains no value. This type mirrors Rust’s `None`, indicating the absence of a value. For more details, see [Option](/api/type-aliases/Option). ## Example Creating a `None` value. ```ts const empty = none(); isNone(empty); // true isSome(empty); // false ``` ## See * [Option](/api/type-aliases/Option) * [none](/api/functions/none) * [isNone](/api/functions/isNone) # NoopSigner (/api/type-aliases/NoopSigner) ```ts type NoopSigner = MessagePartialSigner & TransactionPartialSigner; ``` Defines a Noop (No-Operation) signer that pretends to partially sign messages and transactions. For a given Address, a Noop Signer can be created to offer an implementation of both the [MessagePartialSigner](/api/type-aliases/MessagePartialSigner) and [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner) interfaces such that they do not sign anything. Namely, signing a transaction or a message with a `NoopSigner` will return an empty `SignatureDictionary`. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ---------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define a Noop signer having a particular address. | ## Example ```ts import { address } from '@solana/addresses'; import { createNoopSigner } from '@solana/signers'; const signer = createNoopSigner(address('1234..5678')); const [messageSignatures] = await signer.signMessages([message]); const [transactionSignatures] = await signer.signTransactions([transaction]); // ^ Both messageSignatures and transactionSignatures are empty. ``` ## Remarks This signer may be useful: * For testing purposes. * For indicating that a given account is a signer and taking the responsibility to provide the signature for that account ourselves. For instance, if we need to send the transaction to a server that will sign it and send it for us. ## See [createNoopSigner](/api/functions/createNoopSigner) # NullableCodecConfig (/api/type-aliases/NullableCodecConfig) ```ts type NullableCodecConfig = object; ``` Defines the configuration options for nullable codecs. This configuration controls how nullable values are encoded and decoded. By default, nullable values are prefixed with a `u8` (0 = `null`, 1 = present). The `noneValue` and `prefix` options allow customizing this behavior. ## See * [getNullableEncoder](/api/functions/getNullableEncoder) * [getNullableDecoder](/api/functions/getNullableDecoder) * [getNullableCodec](/api/functions/getNullableCodec) ## Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `TPrefix` *extends* \| [`NumberCodec`](/api/type-aliases/NumberCodec) \| [`NumberDecoder`](/api/type-aliases/NumberDecoder) \| [`NumberEncoder`](/api/type-aliases/NumberEncoder) | A number codec, encoder, or decoder used as the presence prefix. | ## Properties ### noneValue? ```ts optional noneValue?: ReadonlyUint8Array | "zeroes"; ``` Specifies how `null` values are represented in the encoded data. * By default, `null` values are omitted from encoding. * `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec. * Custom byte array: `null` values are replaced with a predefined byte sequence. This results in a variable-size codec. #### Default Value No explicit `noneValue` is used; `null` values are omitted. *** ### prefix? ```ts optional prefix?: TPrefix | null; ``` The presence prefix used to distinguish between `null` and present values. * By default, a `u8` prefix is used (`0 = null`, `1 = present`). * Custom number codec: Allows defining a different number size for the prefix. * `null`: No prefix is used; `noneValue` (if provided) determines `null`. If no `noneValue` is set, `null` is identified by the absence of bytes. #### Default Value `u8` prefix. # NumberCodec (/api/type-aliases/NumberCodec) ```ts type NumberCodec = | Codec | Codec; ``` Represents a codec for encoding and decoding numbers and bigints. * The encoded value can be either a `number` or a `bigint`. * The decoded value will always be either a `number` or `bigint`, depending on the implementation. ## See [FixedSizeNumberCodec](/api/type-aliases/FixedSizeNumberCodec) # NumberCodecConfig (/api/type-aliases/NumberCodecConfig) ```ts type NumberCodecConfig = object; ``` Configuration options for number codecs that use more than one byte. This configuration applies to all number codecs except `u8` and `i8`, allowing the user to specify the endianness of serialization. ## Properties ### endian? ```ts optional endian?: Endian; ``` Specifies whether numbers should be encoded in little-endian or big-endian format. #### Default Value `Endian.Little` # NumberDecoder (/api/type-aliases/NumberDecoder) ```ts type NumberDecoder = | Decoder | Decoder; ``` Represents a decoder for numbers and bigints. This type supports decoding values as either `number` or `bigint`, depending on the implementation. ## See [FixedSizeNumberDecoder](/api/type-aliases/FixedSizeNumberDecoder) # NumberEncoder (/api/type-aliases/NumberEncoder) ```ts type NumberEncoder = Encoder; ``` Represents an encoder for numbers and bigints. This type allows encoding values that are either `number` or `bigint`. Depending on the specific implementation, the encoded output may have a fixed or variable size. ## See [FixedSizeNumberEncoder](/api/type-aliases/FixedSizeNumberEncoder) # OffCurveAddress (/api/type-aliases/OffCurveAddress) ```ts type OffCurveAddress = AffinePoint, "invalid">; ``` Represents an [Address](/api/type-aliases/Address) that validates as being off-curve. Functions that require off-curve addresses should specify their inputs in terms of this type. Whenever you need to validate an address as being off-curve, use the [offCurveAddress](/api/functions/offCurveAddress), [assertIsOffCurveAddress](/api/functions/assertIsOffCurveAddress), or [isOffCurveAddress](/api/functions/isOffCurveAddress) functions in this package. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | # OffchainMessage (/api/type-aliases/OffchainMessage) ```ts type OffchainMessage = | OffchainMessageV0 | OffchainMessageV1; ``` # OffchainMessageApplicationDomain (/api/type-aliases/OffchainMessageApplicationDomain) ```ts type OffchainMessageApplicationDomain = Brand, "OffchainMessageApplicationDomain">; ``` A 32-byte array identifying the application requesting off-chain message signing. This may be any arbitrary bytes. For instance the on-chain address of a program, DAO instance, Candy Machine, et cetera. This field SHOULD be displayed to users as a base58-encoded ASCII string rather than interpreted otherwise. # OffchainMessageBytes (/api/type-aliases/OffchainMessageBytes) ```ts type OffchainMessageBytes = Brand; ``` # OffchainMessageContent (/api/type-aliases/OffchainMessageContent) ```ts type OffchainMessageContent = | OffchainMessageContentRestrictedAsciiOf1232BytesMax | OffchainMessageContentUtf8Of1232BytesMax | OffchainMessageContentUtf8Of65535BytesMax; ``` # OffchainMessageContentRestrictedAsciiOf1232BytesMax (/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) ```ts type OffchainMessageContentRestrictedAsciiOf1232BytesMax = Readonly<{ format: RESTRICTED_ASCII_1232_BYTES_MAX; text: Brand; }>; ``` Describes message text that is no more than 1232 bytes long and made up of characters with ASCII character codes in the range \[0x20, 0x7e]. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TContent` *extends* `string` | `string` | ## Remarks This type aims to restrict text to that which can be clear-signed by hardware wallets that can only display ASCII characters onscreen. # OffchainMessageContentUtf8Of1232BytesMax (/api/type-aliases/OffchainMessageContentUtf8Of1232BytesMax) ```ts type OffchainMessageContentUtf8Of1232BytesMax = Readonly<{ format: UTF8_1232_BYTES_MAX; text: Brand; }>; ``` Describes message text that is no more than 1232 bytes long and mdae up of any UTF-8 characters. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TContent` *extends* `string` | `string` | # OffchainMessageContentUtf8Of65535BytesMax (/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) ```ts type OffchainMessageContentUtf8Of65535BytesMax = Readonly<{ format: UTF8_65535_BYTES_MAX; text: Brand; }>; ``` Describes message text that is no more than 65535 bytes long and mdae up of any UTF-8 characters. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TContent` *extends* `string` | `string` | # OffchainMessageSignatory (/api/type-aliases/OffchainMessageSignatory) ```ts type OffchainMessageSignatory = Readonly<{ address: Address; }>; ``` Represents an address that is required to sign an offchain message for it to be valid. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | # OffchainMessageSignatorySigner (/api/type-aliases/OffchainMessageSignatorySigner) ```ts type OffchainMessageSignatorySigner = MessageSigner; ``` Represents a Signer that is required to sign an offchain message for it to be valid. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | # OffchainMessageV0 (/api/type-aliases/OffchainMessageV0) ```ts type OffchainMessageV0 = BaseOffchainMessageV0 & OffchainMessageWithContent & OffchainMessageWithRequiredSignatories; ``` # OffchainMessageV1 (/api/type-aliases/OffchainMessageV1) ```ts type OffchainMessageV1 = BaseOffchainMessageV1 & OffchainMessageWithRequiredSignatories & Readonly<{ content: string; }>; ``` # OffchainMessageVersion (/api/type-aliases/OffchainMessageVersion) ```ts type OffchainMessageVersion = 0 | 1; ``` # OffchainMessageWithContent (/api/type-aliases/OffchainMessageWithContent) ```ts type OffchainMessageWithContent = | OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent | OffchainMessageWithUtf8Of1232BytesMaxContent | OffchainMessageWithUtf8Of65535BytesMaxContent; ``` A union of the formats a v0 message's contents can take. ## Remarks From v1 and onward, an offchain message has only one format: UTF-8 text of arbitrary length. # Offset (/api/type-aliases/Offset) ```ts type Offset = number; ``` Defines an offset in bytes. # Option (/api/type-aliases/Option) ```ts type Option = None | Some; ``` An implementation of the Rust `Option` type in JavaScript. In Rust, optional values are represented using `Option`, which can be either: * `Some(T)`, indicating a present value. * `None`, indicating the absence of a value. In JavaScript, this is typically represented as `T | null`. However, this approach fails with nested options. For example, `Option>` in Rust would translate to `T | null | null` in JavaScript, which is equivalent to `T | null`. This means there is no way to differentiate between `Some(None)` and `None`, making nested options impossible. This `Option` type helps solve this by mirroring Rust’s `Option` type. ```ts type Option = Some | None; type Some = { __option: 'Some'; value: T }; type None = { __option: 'None' }; ``` ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ## Example Here's how you can create `Option` values. To improve developer experience, helper functions are available. TypeScript can infer the type of `T` or it can be explicitly provided. ```ts // Create an option with a value. some('Hello World'); some(123); // Create an empty option. none(); none(); ``` ## See * [Some](/api/type-aliases/Some) * [None](/api/type-aliases/None) * [some](/api/functions/some) * [none](/api/functions/none) # OptionCodecConfig (/api/type-aliases/OptionCodecConfig) ```ts type OptionCodecConfig = object; ``` Defines the configuration options for [Option](/api/type-aliases/Option) codecs. The `getOptionCodec` function behaves similarly to getNullableCodec but encodes `Option` types instead of `T | null` types. This configuration controls how [None](/api/type-aliases/None) values are encoded and how presence is determined when decoding. ## See * [getOptionEncoder](/api/functions/getOptionEncoder) * [getOptionDecoder](/api/functions/getOptionDecoder) * [getOptionCodec](/api/functions/getOptionCodec) ## Type Parameters | Type Parameter | Description | | ----------------------------------------------------------------------- | ---------------------------------------------------------------- | | `TPrefix` *extends* `NumberCodec` \| `NumberDecoder` \| `NumberEncoder` | A number codec, encoder, or decoder used as the presence prefix. | ## Properties ### noneValue? ```ts optional noneValue?: ReadonlyUint8Array | "zeroes"; ``` Specifies how [None](/api/type-aliases/None) values are represented in the encoded data. * By default, [None](/api/type-aliases/None) values are omitted from encoding. * `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec for the item. * Custom byte array: [None](/api/type-aliases/None) values are replaced with a predefined byte sequence. This results in a variable-size codec. #### Default Value No explicit `noneValue` is used; [None](/api/type-aliases/None) values are omitted. *** ### prefix? ```ts optional prefix?: TPrefix | null; ``` The presence prefix used to distinguish between [None](/api/type-aliases/None) and present values. * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). * Custom number codec: Allows defining a different number size for the prefix. * `null`: No prefix is used; `noneValue` (if provided) determines [None](/api/type-aliases/None). If no `noneValue` is set, [None](/api/type-aliases/None) is identified by the absence of bytes. #### Default Value `u8` prefix. # OptionOrNullable (/api/type-aliases/OptionOrNullable) ```ts type OptionOrNullable = Option | T | null; ``` A flexible type that allows working with [Option](/api/type-aliases/Option) values or nullable values. It defines a looser type that can be used when encoding [Options](/api/type-aliases/Option). This allows us to pass `null` or the nested value directly whilst still supporting the Option type for use-cases that need more type safety. ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ## Example Accepting both `Option` and `T | null` as input. ```ts function double(value: OptionOrNullable) { const option = isOption(value) ? value : wrapNullable(value); return isSome(option) ? option.value * 2 : 'No value'; } double(42); // 84 double(some(21)); // 42 double(none()); // "No value" double(null); // "No value" ``` ## See * [Option](/api/type-aliases/Option) * [isOption](/api/functions/isOption) * [wrapNullable](/api/functions/wrapNullable) # OverloadImplementations (/api/type-aliases/OverloadImplementations) ```ts type OverloadImplementations = Overloads; ``` ## Type Parameters | Type Parameter | | ----------------------- | | `T` | | `U` *extends* keyof `T` | # Overloads (/api/type-aliases/Overloads) ```ts type Overloads = Overloads31; ``` ## Type Parameters | Type Parameter | | -------------- | | `T` | # ParallelInstructionPlan (/api/type-aliases/ParallelInstructionPlan) ```ts type ParallelInstructionPlan = Readonly<{ kind: "parallel"; plans: InstructionPlan[]; planType: "instructionPlan"; }>; ``` A plan wrapping other plans that can be executed in parallel. This means direct children of this plan can be executed in separate parallel transactions without consequence. However, the children themselves can define additional constraints for that specific branch of the tree β€” such as the [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan). You may use the [parallelInstructionPlan](/api/functions/parallelInstructionPlan) helper to create objects of this type. ## Examples **Simple parallel plan with two instructions.** ```ts const plan = parallelInstructionPlan([instructionA, instructionB]); plan satisfies ParallelInstructionPlan; ``` **Parallel plan with nested sequential plans.** Here, instructions A and B must be executed sequentially and so must instructions C and D, but both pairs can be executed in parallel. ```ts const plan = parallelInstructionPlan([ sequentialInstructionPlan([instructionA, instructionB]), sequentialInstructionPlan([instructionC, instructionD]), ]); plan satisfies ParallelInstructionPlan; ``` ## See [parallelInstructionPlan](/api/functions/parallelInstructionPlan) # ParallelTransactionPlan (/api/type-aliases/ParallelTransactionPlan) ```ts type ParallelTransactionPlan = Readonly<{ kind: "parallel"; plans: TransactionPlan[]; planType: "transactionPlan"; }>; ``` A plan wrapping other plans that can be executed in parallel. This means direct children of this plan can be executed in separate parallel transactions without causing any side effects. However, the children themselves can define additional constraints for that specific branch of the tree β€” such as the [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan). You may use the [parallelTransactionPlan](/api/functions/parallelTransactionPlan) helper to create objects of this type. ## Examples Simple parallel plan with two transaction messages. ```ts const plan = parallelTransactionPlan([messageA, messageB]); plan satisfies ParallelTransactionPlan; ``` Parallel plan with nested sequential plans. Here, messages A and B must be executed sequentially and so must messages C and D, but both pairs can be executed in parallel. ```ts const plan = parallelTransactionPlan([ sequentialTransactionPlan([messageA, messageB]), sequentialTransactionPlan([messageC, messageD]), ]); plan satisfies ParallelTransactionPlan; ``` ## See [parallelTransactionPlan](/api/functions/parallelTransactionPlan) # ParallelTransactionPlanResult (/api/type-aliases/ParallelTransactionPlanResult) ```ts type ParallelTransactionPlanResult = Readonly<{ kind: "parallel"; plans: TransactionPlanResult[]; planType: "transactionPlanResult"; }>; ``` A result for a parallel transaction plan. This represents the execution result of a [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan) and contains child results that were executed in parallel. You may use the [parallelTransactionPlanResult](/api/functions/parallelTransactionPlanResult) helper to create objects of this type. ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | The type of the transaction message | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The type of single transaction plan results in this tree | ## Example ```ts const result = parallelTransactionPlanResult([ singleResultA, singleResultB, ]); result satisfies ParallelTransactionPlanResult; ``` ## See [parallelTransactionPlanResult](/api/functions/parallelTransactionPlanResult) # PendingRpcRequest (/api/type-aliases/PendingRpcRequest) ```ts type PendingRpcRequest = object; ``` Pending requests are the result of calling a supported method on a [Rpc](/api/type-aliases/Rpc) object. They encapsulate all of the information necessary to make the request without actually making it. Calling the [\`send(options)\`](#send) method on a PendingRpcRequest\ will trigger the request and return a promise for `TResponse`. Calling the [\`reactiveStore()\`](#reactivestore) method will return a ReactiveActionStore compatible with `useSyncExternalStore`, Svelte stores, and other reactive primitives. The store is returned in the `idle` state β€” call `dispatch()` to fire the request. ## Type Parameters | Type Parameter | | -------------- | | `TResponse` | ## Methods ### reactiveStore() ```ts reactiveStore(): ReactiveActionStore<[], TResponse>; ``` Synchronously returns a ReactiveActionStore in the `idle` state, ready to dispatch the underlying request. Compatible with `useSyncExternalStore` and other reactive primitives that expect a `{ subscribe, getState }` contract. Call `dispatch()` to fire the request (again on retry), or `reset()` to abort the in-flight call and return to `status: 'idle'`. Unlike [PendingRpcRequest.send](#send), this method does not fire the request on creation β€” the caller is responsible for dispatching. This makes signal handling uniform: attach a caller-provided cancellation source per dispatch via `store.withSignal(signal).dispatch(...)`. #### Returns `ReactiveActionStore`\<\[], `TResponse`> #### Example ```ts const store = rpc.getAccountInfo(address).reactiveStore(); store.withSignal(AbortSignal.timeout(5_000)).dispatch(); // fire with a per-attempt timeout const state = useSyncExternalStore(store.subscribe, store.getState); if (state.status === 'error') return ; if (state.status === 'running' && !state.data) return ; return ; ``` *** ### send() ```ts send(options?): Promise; ``` #### Parameters | Parameter | Type | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `options?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `abortSignal?`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); }> | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TResponse`> # PendingRpcSubscriptionsRequest (/api/type-aliases/PendingRpcSubscriptionsRequest) ```ts type PendingRpcSubscriptionsRequest = object; ``` Pending subscriptions are the result of calling a supported method on a [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) object. They encapsulate all of the information necessary to make the subscription without actually making it. Calling the [\`subscribe(options)\`](#subscribe) method on a PendingRpcSubscriptionsRequest\ will trigger the subscription and return a promise for an async iterable that vends `TNotifications`. Calling the [\`reactiveStore()\`](#reactivestore) method will return a ReactiveStreamStore compatible with `useSyncExternalStore`, Svelte stores, and other reactive primitives. The returned store is in `status: 'idle'`; the caller is responsible for invoking ReactiveStreamStore.connect | \`connect()\` to open the underlying stream. Attach a caller-provided cancellation source via ReactiveStreamStore.withSignal | \`withSignal()\`. ## Type Parameters | Type Parameter | | --------------- | | `TNotification` | ## Methods ### reactiveStore() ```ts reactiveStore(): ReactiveStreamStore; ``` Synchronously returns a ReactiveStreamStore that holds the latest notification. Compatible with `useSyncExternalStore` and other reactive primitives that expect a `{ subscribe, getState }` contract. The returned store is in `status: 'idle'` β€” call ReactiveStreamStore.connect | \`connect()\` to open the subscription; a follow-up `connect()` after an error reopens it. Attach a caller-provided cancellation source via ReactiveStreamStore.withSignal | \`withSignal()\`. #### Returns `ReactiveStreamStore`\<`TNotification`> #### Example ```ts const store = rpc.accountNotifications(address).reactiveStore(); // Per-connection timeout β€” fresh clock per attempt: store.withSignal(AbortSignal.timeout(30_000)).connect(); // React β€” the unified snapshot has stable identity per update. const state = useSyncExternalStore(store.subscribe, store.getState); if (state.status === 'error') return ; if (state.status === 'loading' || state.status === 'idle') return ; return ; ``` *** ### subscribe() ```ts subscribe(options): Promise>; ``` Triggers the subscription and returns a promise for an async iterable of notifications. Use `for await...of` to consume notifications as they arrive. Abort the signal to unsubscribe. #### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------- | | `options` | [`RpcSubscribeOptions`](/api/type-aliases/RpcSubscribeOptions) | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`AsyncIterable`\<`TNotification`, `any`, `any`>> #### Example ```ts const notifications = await rpc.accountNotifications(address).subscribe({ abortSignal }); for await (const notification of notifications) { console.log('Account changed:', notification); } ``` # ProgramDerivedAddress (/api/type-aliases/ProgramDerivedAddress) ```ts type ProgramDerivedAddress = Readonly<[Address, ProgramDerivedAddressBump]>; ``` A tuple representing a program derived address (derived from the address of some program and a set of seeds) and the associated bump seed used to ensure that the address, as derived, does not fall on the Ed25519 curve. Whenever you need to validate an arbitrary tuple as one that represents a program derived address, use the [assertIsProgramDerivedAddress](/api/functions/assertIsProgramDerivedAddress) or [isProgramDerivedAddress](/api/functions/isProgramDerivedAddress) functions in this package. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | # ProgramDerivedAddressBump (/api/type-aliases/ProgramDerivedAddressBump) ```ts type ProgramDerivedAddressBump = Brand; ``` Represents an integer in the range \[0,255] used in the derivation of a program derived address to ensure that it does not fall on the Ed25519 curve. # ProgramNotificationsApi (/api/type-aliases/ProgramNotificationsApi) ```ts type ProgramNotificationsApi = object; ``` ## Methods ### programNotifications() #### Call Signature ```ts programNotifications(programId, config): ProgramNotificationsApiNotificationBase; ``` Subscribe for notifications when there is a change in the Lamports or data of any account owned by the program at the given address changes. The notification format is the same as seen in the GetProgramAccountsApi.getProgramAccounts RPC HTTP method. If the account has data, it will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `programId` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `filters?`: readonly [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`>\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64"`; }> | ##### Returns `ProgramNotificationsApiNotificationBase`\<`AccountInfoWithBase64EncodedData`> ##### See [https://solana.com/docs/rpc/websocket/programsubscribe](https://solana.com/docs/rpc/websocket/programsubscribe) #### Call Signature ```ts programNotifications(programId, config): ProgramNotificationsApiNotificationBase; ``` Subscribe for notifications when there is a change in the Lamports or data of any account owned by the program at the given address changes. The notification format is the same as seen in the GetProgramAccountsApi.getProgramAccounts RPC HTTP method. If the account has data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `programId` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `filters?`: readonly [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`>\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base64+zstd"`; }> | ##### Returns `ProgramNotificationsApiNotificationBase`\<`AccountInfoWithBase64EncodedZStdCompressedData`> ##### See [https://solana.com/docs/rpc/websocket/programsubscribe](https://solana.com/docs/rpc/websocket/programsubscribe) #### Call Signature ```ts programNotifications(programId, config): ProgramNotificationsApiNotificationBase; ``` Subscribe for notifications when there is a change in the Lamports or data of any account owned by the program at the given address changes. The notification format is the same as seen in the GetProgramAccountsApi.getProgramAccounts RPC HTTP method. If the account has data, the server will attempt to process it using a parser specific to the account's owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `programId` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `filters?`: readonly [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`>\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"jsonParsed"`; }> | ##### Returns `ProgramNotificationsApiNotificationBase`\<`AccountInfoWithJsonData`> ##### See [https://solana.com/docs/rpc/websocket/programsubscribe](https://solana.com/docs/rpc/websocket/programsubscribe) #### Call Signature ```ts programNotifications(programId, config): ProgramNotificationsApiNotificationBase; ``` Subscribe for notifications when there is a change in the Lamports or data of any account owned by the program at the given address changes. The notification format is the same as seen in the GetProgramAccountsApi.getProgramAccounts RPC HTTP method. If the account has data, it will be returned in the response as a tuple whose first element is a base58-encoded string. If the account contains more than 129 bytes of data, the `data` field will materialize as the string `"error: data too large for bs58 encoding"`. ##### Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `programId` | `Address` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `filters?`: readonly [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`>\[]; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `encoding`: `"base58"`; }> | ##### Returns `ProgramNotificationsApiNotificationBase`\<`AccountInfoWithBase58EncodedData`> ##### See [https://solana.com/docs/rpc/websocket/programsubscribe](https://solana.com/docs/rpc/websocket/programsubscribe) #### Call Signature ```ts programNotifications(programId, config?): ProgramNotificationsApiNotificationBase; ``` Subscribe for notifications when there is a change in the Lamports or data of any account owned by the program at the given address changes. The notification format is the same as seen in the GetProgramAccountsApi.getProgramAccounts RPC HTTP method. If the account has data, it will be returned in the response as a base58-encoded string. If the account contains more than 129 bytes of data, the `data` field will materialize as the string `"error: data too large for bs58 encoding"`. ##### Parameters | Parameter | Type | | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `programId` | `Address` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `filters?`: readonly [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<`GetProgramAccountsDatasizeFilter` \| `GetProgramAccountsMemcmpFilter`>\[]; }> | ##### Returns `ProgramNotificationsApiNotificationBase`\<`AccountInfoWithBase58Bytes`> ##### See [https://solana.com/docs/rpc/websocket/programsubscribe](https://solana.com/docs/rpc/websocket/programsubscribe) # ReactiveActionSource (/api/type-aliases/ReactiveActionSource) ```ts type ReactiveActionSource = object; ``` Duck-type for objects that build a [ReactiveActionStore](/api/type-aliases/ReactiveActionStore) on demand via `reactiveStore()`. Satisfied by `PendingRpcRequest`. The `[]` argument tuple is intentional β€” the operation's arguments are already baked into the pending request, so each `dispatch()` re-fires the same call. The returned store is in the `idle` state β€” the caller is responsible for calling `dispatch()` to fire the first attempt. Attach a caller-provided cancellation source per dispatch via `store.withSignal(signal).dispatch(...)` β€” see [ReactiveActionStore.withSignal](/api/type-aliases/ReactiveActionStore#withsignal). ## Example ```ts function bind(source: ReactiveActionSource) { const store = source.reactiveStore(); // Per-attempt timeout, fresh signal per call: store.withSignal(AbortSignal.timeout(30_000)).dispatch(); return store; } ``` ## See * [ReactiveActionStore](/api/type-aliases/ReactiveActionStore) * [ReactiveStreamSource](/api/type-aliases/ReactiveStreamSource) ## Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------- | | `T` | The value type resolved by the wrapped operation. | ## Methods ### reactiveStore() ```ts reactiveStore(): ReactiveActionStore<[], T>; ``` #### Returns [`ReactiveActionStore`](/api/type-aliases/ReactiveActionStore)\<\[], `T`> # ReactiveActionState (/api/type-aliases/ReactiveActionState) ```ts type ReactiveActionState = | { data: TResult | undefined; error: unknown; status: "error"; } | { data: TResult | undefined; error: unknown; status: "running"; } | { data: TResult; error: undefined; status: "success"; } | { data: undefined; error: undefined; status: "idle"; }; ``` Discriminated state of a [ReactiveActionStore](/api/type-aliases/ReactiveActionStore), keyed by [ReactiveActionStatus](/api/type-aliases/ReactiveActionStatus). `data` holds the most recent successful result and `error` holds the most recent failure. Both persist through subsequent `running` states so call sites can keep rendering stale content while a retry is in flight. `success` clears `error`; only `reset()` clears `data`. ## Type Parameters | Type Parameter | | -------------- | | `TResult` | # ReactiveActionStatus (/api/type-aliases/ReactiveActionStatus) ```ts type ReactiveActionStatus = "error" | "idle" | "running" | "success"; ``` Lifecycle status of a [ReactiveActionStore](/api/type-aliases/ReactiveActionStore). # ReactiveActionStore (/api/type-aliases/ReactiveActionStore) ```ts type ReactiveActionStore = object; ``` A framework-agnostic state machine that wraps an async function and exposes a `{ dispatch, getState, subscribe, reset }` contract. Bridges trivially into `useSyncExternalStore`, Svelte stores, Vue's `shallowRef`, and similar reactive primitives. ## See [createReactiveActionStore](/api/functions/createReactiveActionStore) ## Type Parameters | Type Parameter | | --------------------------------------- | | `TArgs` *extends* readonly `unknown`\[] | | `TResult` | ## Properties ### dispatch ```ts readonly dispatch: (...args) => void; ``` Fire-and-forget dispatch. Returns `undefined` synchronously and never throws β€” failures surface on state as `{ status: 'error' }`, and superseded or `reset()`-aborted calls produce no state update. Use from UI event handlers; there's no promise to handle or `.catch`. #### Parameters | Parameter | Type | | --------- | ------- | | ...`args` | `TArgs` | #### Returns `void` #### See * [ReactiveActionStore.dispatchAsync](#dispatchasync) when you need the resolved value or propagated errors. * [ReactiveActionStore.withSignal](#withsignal) to attach a caller-provided `AbortSignal` to a dispatch. *** ### dispatchAsync ```ts readonly dispatchAsync: (...args) => Promise; ``` Promise-returning dispatch for imperative callers. Resolves with the wrapped function's result on success. Rejects with the thrown error on failure, and with an `AbortError` when the call is superseded or `reset()` is invoked β€” filter those with `isAbortError` from `@solana/promises`. #### Parameters | Parameter | Type | | --------- | ------- | | ...`args` | `TArgs` | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TResult`> *** ### getState ```ts readonly getState: () => ReactiveActionState; ``` Returns the current lifecycle snapshot: `{ data, error, status }`. The returned object has stable identity between state changes, making it safe to pass directly as the `getSnapshot` argument to React's `useSyncExternalStore`. #### Returns [`ReactiveActionState`](/api/type-aliases/ReactiveActionState)\<`TResult`> #### See [ReactiveActionState](/api/type-aliases/ReactiveActionState) *** ### reset ```ts readonly reset: () => void; ``` Aborts any in-flight dispatch and resets the state to `{ status: 'idle' }`. #### Returns `void` *** ### subscribe ```ts readonly subscribe: (listener) => () => void; ``` Registers a listener called on every state change. Returns an unsubscribe function. #### Parameters | Parameter | Type | | ---------- | ------------ | | `listener` | () => `void` | #### Returns () => `void` *** ### withSignal ```ts readonly withSignal: (signal) => object; ``` Returns a thin wrapper exposing `dispatch` / `dispatchAsync` that compose `signal` with the store's internal per-dispatch controller via `AbortSignal.any` β€” aborting either cancels the in-flight call. Aborting the caller-provided signal surfaces the abort reason on state as `{ status: 'error' }`; the internal controller path (supersession by a newer dispatch or `reset()`) is silent by design so the newer dispatch owns state. Use this to attach a caller-provided cancellation source (per-attempt timeout, shared kill switch, parent-context signal) without touching the bare `dispatch` / `dispatchAsync` API. * Per-attempt timeout: `store.withSignal(AbortSignal.timeout(5_000)).dispatch(args)` β€” fresh clock per call. * Permanent kill switch: hold one `AbortController`, bind the wrapper once (`const killable = store.withSignal(killCtrl.signal)`), and use `killable.dispatch(...)` everywhere; aborting the controller cancels in-flight and short-circuits future calls. The wrapper exposes only `dispatch` / `dispatchAsync` β€” `getState` / `subscribe` / `reset` remain store-level concerns on the parent. #### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `signal` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | #### Returns `object` | Name | Type | | ----------------- | -------------------------------------------------------------------------------------------------------------------------- | | `dispatch()` | (...`args`) => `void` | | `dispatchAsync()` | (...`args`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TResult`> | # ReactiveState (/api/type-aliases/ReactiveState) ```ts type ReactiveState = | { data: T | undefined; error: unknown; status: "error"; } | { data: T | undefined; error: unknown; status: "loading"; } | { data: T; error: undefined; status: "loaded"; } | { data: undefined; error: undefined; status: "idle"; }; ``` The lifecycle state of a [ReactiveStreamStore](/api/type-aliases/ReactiveStreamStore) as a single snapshot. * `idle`: the store has not yet been connected, or has been reset via [\`reset()\`](/api/type-aliases/ReactiveStreamStore#reset). Call [\`connect()\`](/api/type-aliases/ReactiveStreamStore#connect) to open the underlying stream. * `loading`: a connection is in progress. `data` and `error` are preserved from the previous connection (if any) β€” stale-while-revalidate UX. A subsequent `loaded` clears `error`; a subsequent `error` replaces it. * `loaded`: a value has been received and no error is active. * `error`: the stream failed. `data` holds the last known value (or `undefined` if none ever arrived) and `error` holds the failure. ## Type Parameters | Type Parameter | | -------------- | | `T` | # ReactiveStreamSource (/api/type-aliases/ReactiveStreamSource) ```ts type ReactiveStreamSource = object; ``` Duck-type for objects that build a [ReactiveStreamStore](/api/type-aliases/ReactiveStreamStore) on demand via a `reactiveStore()` method. Satisfied by `PendingRpcSubscriptionsRequest`. Reactive-framework bindings (e.g. React's `useSubscription`) consume this duck-type so they don't have to name a concrete producer type. The returned store is in `status: 'idle'` β€” the caller is responsible for invoking [\`connect()\`](/api/type-aliases/ReactiveStreamStore#connect) to open the underlying stream. Attach a caller-provided cancellation source via [\`withSignal()\`](/api/type-aliases/ReactiveStreamStore#withsignal) β€” `store.withSignal(signal).connect()`. ## Example ```ts function bindWithTimeout(source: ReactiveStreamSource) { const store = source.reactiveStore(); store.withSignal(AbortSignal.timeout(30_000)).connect(); return store; } ``` ## See * [ReactiveStreamStore](/api/type-aliases/ReactiveStreamStore) * [ReactiveActionSource](/api/type-aliases/ReactiveActionSource) ## Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------------------- | | `T` | The value type emitted by the resulting stream store. | ## Methods ### reactiveStore() ```ts reactiveStore(): ReactiveStreamStore; ``` #### Returns [`ReactiveStreamStore`](/api/type-aliases/ReactiveStreamStore)\<`T`> # ReactiveStreamStore (/api/type-aliases/ReactiveStreamStore) ```ts type ReactiveStreamStore = object; ``` A reactive store that holds the latest value published to a data channel and allows external systems to subscribe to changes. Compatible with `useSyncExternalStore`, Svelte stores, Solid's `from()`, and other reactive primitives that expect a `{ subscribe, getState }` contract. The store starts in `status: 'idle'`. Call [\`connect()\`](#connect) to open the underlying stream; the store transitions through `loading` β†’ `loaded` (or `error`). Subsequent `connect()` calls also pass through `loading` while preserving the last known `data` and `error` (stale-while-revalidate). ## Example ```ts // React β€” the unified state snapshot has stable identity per update, making it suitable as // the second argument to `useSyncExternalStore`. const state = useSyncExternalStore(store.subscribe, store.getState); useEffect(() => { store.connect(); return () => store.reset(); }, [store]); if (state.status === 'error') return ; if (state.status === 'loading' || state.status === 'idle') return ; return ; ``` ## See [createReactiveStoreFromDataPublisherFactory](/api/functions/createReactiveStoreFromDataPublisherFactory) ## Type Parameters | Type Parameter | | -------------- | | `T` | ## Methods ### connect() ```ts connect(): void; ``` Open the underlying stream. Aborts any currently active connection, invokes the configured factory, and transitions the store to `loading` (preserving the last known `data` and `error` for stale-while-revalidate) before settling into `loaded` (on data) or `error` (on failure). #### Returns `void` *** ### getState() ```ts getState(): ReactiveState; ``` Returns the current lifecycle snapshot: `{ data, error, status }`. The returned object has stable identity between state changes, making it safe to pass directly as the `getSnapshot` argument to React's `useSyncExternalStore`. #### Returns [`ReactiveState`](/api/type-aliases/ReactiveState)\<`T`> #### See [ReactiveState](/api/type-aliases/ReactiveState) *** ### reset() ```ts reset(): void; ``` Aborts any currently active connection and resets the store to `{ status: 'idle' }`. Both `data` and `error` are cleared. Use this to tear down the connection without permanently killing the store β€” a follow-up [\`connect()\`](#connect) will open a fresh stream. #### Returns `void` *** ### subscribe() ```ts subscribe(callback): () => void; ``` Registers a callback to be called whenever the state changes or an error is received. Returns an unsubscribe function. Safe to call multiple times. #### Parameters | Parameter | Type | | ---------- | ------------ | | `callback` | () => `void` | #### Returns () => `void` *** ### withSignal() ```ts withSignal(signal): object; ``` Returns a thin wrapper exposing `connect()` that composes `signal` with the store's internal per-connection controller via `AbortSignal.any` β€” aborting either tears down the active connection. Aborting the caller-provided signal surfaces the abort reason on state as `{ status: 'error' }`; the internal controller path (supersession by a newer `connect()` or `reset()`) is silent by design so the newer call owns state. Use this to attach a caller-provided cancellation source (per-connection timeout, shared kill switch, parent-context signal) without touching the bare `connect()` API. * Per-connection timeout: `store.withSignal(AbortSignal.timeout(30_000)).connect()` β€” fresh clock per call. * Permanent kill switch: hold one `AbortController`, bind the wrapper once (`const killable = store.withSignal(killCtrl.signal)`), and use `killable.connect()` everywhere; aborting the controller cancels the active connection and short-circuits future calls through the bound wrapper. The wrapper exposes only `connect()` β€” `getState` / `subscribe` / `reset` remain store-level concerns on the parent. #### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `signal` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | #### Returns `object` | Name | Type | | ----------- | ------------ | | `connect()` | () => `void` | # ReadonlyAccount (/api/type-aliases/ReadonlyAccount) ```ts type ReadonlyAccount = AccountMeta & object; ``` ## Type Declaration | Name | Type | | ------ | ----------------------------------------------------------------------- | | `role` | [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) | ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## See [AccountMeta](/api/interfaces/AccountMeta) # ReadonlyAccountLookup (/api/type-aliases/ReadonlyAccountLookup) ```ts type ReadonlyAccountLookup = AccountLookupMeta & object; ``` ## Type Declaration | Name | Type | | ------ | ----------------------------------------------------------------------- | | `role` | [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) | ## Type Parameters | Type Parameter | Default type | | ---------------------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | | `TLookupTableAddress` *extends* `string` | `string` | ## See [AccountLookupMeta](/api/interfaces/AccountLookupMeta) # ReadonlySignerAccount (/api/type-aliases/ReadonlySignerAccount) ```ts type ReadonlySignerAccount = AccountMeta & object; ``` ## Type Declaration | Name | Type | | ------ | ------------------------------------------------------------------------------------- | | `role` | [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) | ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## See [AccountMeta](/api/interfaces/AccountMeta) # RequestAirdropApi (/api/type-aliases/RequestAirdropApi) ```ts type RequestAirdropApi = object; ``` ## Methods ### requestAirdrop() ```ts requestAirdrop( recipientAccount, lamports, config?): Signature; ``` Requests an airdrop of Lamports to the specified address. This method is offered by test clusters as a way to obtain SOL tokens to pay transaction fees. #### Parameters | Parameter | Type | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------ | | `recipientAccount` | `Address` | | `lamports` | `Lamports` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; }> | #### Returns `Signature` The signature of the airdrop transaction, as a base-58 encoded string. #### See [https://solana.com/docs/rpc/http/requestairdrop](https://solana.com/docs/rpc/http/requestairdrop) # RequestResult (/api/type-aliases/RequestResult) ```ts type RequestResult = object; ``` Reactive state for a one-shot request managed by [useRequest](/api/functions/useRequest). Lifecycle: starts at `fetching` (or `disabled` when the source is `null`) and auto-fires on mount; transitions to `success` on success or `error` on failure. `refresh()` re-fires the request β€” while a re-fire is in flight, `status` returns to `fetching` and the stale `data` and/or `error` from the prior outcome remain populated (stale-while-revalidate). ## Type Parameters | Type Parameter | Description | | -------------- | --------------------------------------------- | | `T` | The value the underlying request resolves to. | ## Properties ### data ```ts data: T | undefined; ``` The most recent successful value, or `undefined` if no call has succeeded yet (or while disabled). Persists across subsequent refreshes (including failed ones) until a new success replaces it or `reset()` clears the store. *** ### error ```ts error: unknown; ``` The error from the most recent failed call, or `undefined` if no call has failed (or while disabled). Persists across subsequent refreshes until a new success clears it. May coexist with `data` when a successful attempt is followed by a failing one. *** ### refresh ```ts refresh: (options?) => void; ``` Re-fire the request. By default each call mints a fresh signal from `getAbortSignal` (if configured) and threads it through the underlying store's `withSignal(signal).dispatch()`. Pass `{ abortSignal }` to override the configured factory for just this attempt. Pass `{ abortSignal: undefined }` to opt out of the factory entirely for this attempt and fire with no caller-provided signal. Stable reference. #### Parameters | Parameter | Type | | ---------------------- | --------------------------------------------------------------------------------------------- | | `options?` | \{ `abortSignal?`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); } | | `options.abortSignal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | #### Returns `void` *** ### status ```ts status: "disabled" | "error" | "fetching" | "success"; ``` Lifecycle status as a discriminated string: * `fetching`: a request is in flight. `data` and `error` carry whatever stale content was available before this attempt (both `undefined` on the first attempt; either or both populated on a refresh after a prior outcome). * `success`: most recent call succeeded; `data` holds the result. * `error`: most recent call failed; `error` holds the reason. * `disabled`: source was `null`. # RequestTransformerConfig (/api/type-aliases/RequestTransformerConfig) ```ts type RequestTransformerConfig = Readonly<{ defaultCommitment?: Commitment; onIntegerOverflow?: IntegerOverflowHandler; }>; ``` # ResolvedInstruction (/api/type-aliases/ResolvedInstruction) ```ts type ResolvedInstruction = Instruction; ``` An outer transaction instruction with its account indices resolved to full AccountMetas and its data exposed as a `ReadonlyUint8Array`. Following the kit `Instruction` conventions, `accounts` and `data` are present only when non-empty, so `isInstructionWithAccounts` and `isInstructionWithData` from `@solana/instructions` behave as expected and can be used to narrow before passing the instruction to the auto-generated `parseXInstruction` helpers. ## Type Parameters | Type Parameter | Default type | | ------------------------------------ | ------------ | | `TProgramAddress` *extends* `string` | `string` | ## Example ```ts for (const ix of getInstructionsFromCompiledTransactionMessage(compiled)) { // `ix` is a `ResolvedInstruction` β€” usable with `isInstructionForProgram` // directly, and with the auto-generated `identifyXInstruction` helpers // after narrowing `data`. if (isInstructionWithData(ix)) { identifyTokenInstruction(ix); } } ``` # ResolvedInstructionAccount (/api/type-aliases/ResolvedInstructionAccount) ```ts type ResolvedInstructionAccount = object; ``` Represents a resolved account input for an instruction. During instruction building, account inputs are resolved to this type which captures both the account value and whether it should be marked as writable. The value can be an Address, a ProgramDerivedAddress, a TransactionSigner, or `null` for optional accounts. ## Example ```ts const mintAccount: ResolvedInstructionAccount = { value: mintAddress, isWritable: true, }; ``` ## Type Parameters | Type Parameter | Default type | Description | | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------- | | `TAddress` *extends* `string` | `string` | The address type, defaults to `string`. | | `TValue` *extends* \| `Address`\<`TAddress`> \| `ProgramDerivedAddress`\<`TAddress`> \| `TransactionSigner`\<`TAddress`> \| `null` | \| `Address`\<`TAddress`> \| `ProgramDerivedAddress`\<`TAddress`> \| `TransactionSigner`\<`TAddress`> \| `null` | The type of the resolved value. | ## Properties ### isWritable ```ts isWritable: boolean; ``` *** ### value ```ts value: TValue; ``` # ResourceLimitsEstimate (/api/type-aliases/ResourceLimitsEstimate) ```ts type ResourceLimitsEstimate = TTransactionMessage extends object ? object : object; ``` The estimated resource limits for a transaction message. `computeUnitLimit` is always returned. For version 1 transaction messages, `loadedAccountsDataSizeLimit` is also required. For legacy and version 0 messages, the `loadedAccountsDataSizeLimit` is returned when the RPC includes it in the simulation result, but is not required β€” callers that don't apply it can ignore the field. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | # ResponseTransformerConfig (/api/type-aliases/ResponseTransformerConfig) ```ts type ResponseTransformerConfig = Readonly<{ allowedNumericKeyPaths?: AllowedNumericKeypaths; }>; ``` ## Type Parameters | Type Parameter | | -------------- | | `TApi` | # Reward (/api/type-aliases/Reward) ```ts type Reward = | Readonly<{ rewardType: "Fee" | "Rent"; }> & RewardBase | Readonly<{ commission: number; rewardType: "Staking" | "Voting"; }> & RewardBase; ``` # RootNotificationsApi (/api/type-aliases/RootNotificationsApi) ```ts type RootNotificationsApi = object; ``` ## Methods ### rootNotifications() ```ts rootNotifications(): bigint; ``` Subscribe to receive notifications anytime a new root is set by the validator. #### Returns `bigint` The number of the rooted slot #### See [https://solana.com/docs/rpc/websocket/rootsubscribe](https://solana.com/docs/rpc/websocket/rootsubscribe) # RoundingMode (/api/type-aliases/RoundingMode) ```ts type RoundingMode = "ceil" | "floor" | "round" | "strict" | "trunc"; ``` Rounding mode used by fixed-point operations that must coerce an exact mathematical result into a value with fewer bits of precision. Applies to factories that accept lossy inputs, as well as to downscaling rescales and divisions. * `'floor'` rounds toward negative infinity. * `'ceil'` rounds toward positive infinity. * `'trunc'` rounds toward zero, discarding the fractional part. * `'round'` rounds to the nearest representable value, with ties rounded away from zero. That is, `0.5` rounds to `1`, `-0.5` rounds to `-1`, and `-1.5` rounds to `-2`. This is symmetric around zero and differs from JavaScript's `Math.round`, which breaks ties toward positive infinity. * `'strict'` rejects any input that would require rounding and throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` instead of coercing the result. # Rpc (/api/type-aliases/Rpc) ```ts type Rpc = { [TMethodName in keyof TRpcMethods]: PendingRpcRequestBuilder> }; ``` An object that exposes all of the functions described by `TRpcMethods`. Calling each method returns a [PendingRpcRequest\](/api/type-aliases/PendingRpcRequest) where `TResponse` is that method's response type. ## Type Parameters | Type Parameter | | -------------- | | `TRpcMethods` | # RpcApi (/api/type-aliases/RpcApi) ```ts type RpcApi = { [MethodName in keyof TRpcMethods]: RpcReturnTypeMapper }; ``` For each of `TRpcMethods`, this object exposes a method with the same name that maps between its input arguments and a [RpcPlan\](/api/type-aliases/RpcPlan) that implements the execution of a JSON RPC request to fetch `TResponse`. ## Type Parameters | Type Parameter | | -------------- | | `TRpcMethods` | # RpcApiConfig (/api/type-aliases/RpcApiConfig) ```ts type RpcApiConfig = Readonly<{ requestTransformer?: RpcRequestTransformer; responseTransformer?: RpcResponseTransformer; }>; ``` # RpcConfig (/api/type-aliases/RpcConfig) ```ts type RpcConfig = Readonly<{ api: RpcApi; transport: TRpcTransport; }>; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------- | | `TRpcMethods` | | `TRpcTransport` *extends* [`RpcTransport`](/api/type-aliases/RpcTransport) | # RpcDevnet (/api/type-aliases/RpcDevnet) ```ts type RpcDevnet = Rpc & object; ``` A [Rpc](/api/type-aliases/Rpc) that supports the RPC methods available on the devnet cluster. This is useful in cases where you need to make assertions about the suitability of a RPC for a given purpose. For example, you might like to make it a type error to combine certain types with RPCs belonging to certain clusters, at compile time. ## Type Declaration | Name | Type | | ---------- | ---------- | | `~cluster` | `"devnet"` | ## Type Parameters | Type Parameter | | -------------- | | `TRpcMethods` | ## Example ```ts async function getSpecialAccountInfo( address: Address<'ReAL1111111111111111111111111111'>, rpc: RpcMainnet, ): Promise; async function getSpecialAccountInfo( address: Address<'TeST1111111111111111111111111111'>, rpc: RpcDevnet | RpcTestnet, ): Promise; async function getSpecialAccountInfo(address: Address, rpc: Rpc): Promise { /* ... */ } const rpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); await getSpecialAccountInfo(address('ReAL1111111111111111111111111111'), rpc); // ERROR ``` # RpcFromTransport (/api/type-aliases/RpcFromTransport) ```ts type RpcFromTransport = TRpcTransport extends RpcTransportDevnet ? RpcDevnet : TRpcTransport extends RpcTransportTestnet ? RpcTestnet : TRpcTransport extends RpcTransportMainnet ? RpcMainnet : Rpc; ``` Given a [RpcTransport](/api/type-aliases/RpcTransport) and a set of RPC methods denoted by `TRpcMethods`, this utility type will resolve to a [Rpc](/api/type-aliases/Rpc) that supports those methods on as specific a cluster as possible. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------- | | `TRpcMethods` | | `TRpcTransport` *extends* [`RpcTransport`](/api/type-aliases/RpcTransport) | ## Example ```ts function createCustomRpc( transport: TRpcTransport, ): RpcFromTransport { /* ... */ } const transport = createDefaultRpcTransport({ url: mainnet('http://rpc.company') }); transport satisfies RpcTransportMainnet; // OK const rpc = createCustomRpc(transport); rpc satisfies RpcMainnet; // OK ``` # RpcMainnet (/api/type-aliases/RpcMainnet) ```ts type RpcMainnet = Rpc & object; ``` A [Rpc](/api/type-aliases/Rpc) that supports the RPC methods available on the mainnet cluster. This is useful in cases where you need to make assertions about the suitability of a RPC for a given purpose. For example, you might like to make it a type error to combine certain types with RPCs belonging to certain clusters, at compile time. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"mainnet"` | ## Type Parameters | Type Parameter | | -------------- | | `TRpcMethods` | ## Example ```ts async function getSpecialAccountInfo( address: Address<'ReAL1111111111111111111111111111'>, rpc: RpcMainnet, ): Promise; async function getSpecialAccountInfo( address: Address<'TeST1111111111111111111111111111'>, rpc: RpcDevnet | RpcTestnet, ): Promise; async function getSpecialAccountInfo(address: Address, rpc: Rpc): Promise { /* ... */ } const rpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); await getSpecialAccountInfo(address('ReAL1111111111111111111111111111'), rpc); // ERROR ``` # RpcParsedInfo (/api/type-aliases/RpcParsedInfo) ```ts type RpcParsedInfo = Readonly<{ info: TInfo; }>; ``` ## Type Parameters | Type Parameter | | -------------- | | `TInfo` | # RpcParsedType (/api/type-aliases/RpcParsedType) ```ts type RpcParsedType = Readonly<{ info: TInfo; type: TType; }>; ``` ## Type Parameters | Type Parameter | | -------------------------- | | `TType` *extends* `string` | | `TInfo` | # RpcPlan (/api/type-aliases/RpcPlan) ```ts type RpcPlan = object; ``` This type allows an [RpcApi](/api/type-aliases/RpcApi) to describe how a particular request should be issued to the JSON RPC server. Given a function that was called on a [Rpc](/api/type-aliases/Rpc), this object exposes an `execute` function that dictates which request will be sent, how the underlying transport will be used, and how the responses will be transformed. This function accepts a [RpcTransport](/api/type-aliases/RpcTransport) and an `AbortSignal` and asynchronously returns a RpcResponse. This gives us the opportunity to: * define the `payload` from the requested method name and parameters before passing it to the transport. * call the underlying transport zero, one or multiple times depending on the use-case (e.g. caching or aggregating multiple responses). * transform the response from the JSON RPC server, in case it does not match the `TResponse` specified by the [PendingRpcRequest\](/api/type-aliases/PendingRpcRequest) returned from that function. ## Type Parameters | Type Parameter | | -------------- | | `TResponse` | ## Properties ### execute ```ts execute: (config) => Promise>; ``` #### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `signal?`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); `transport`: [`RpcTransport`](/api/type-aliases/RpcTransport); }> | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`RpcResponse`\<`TResponse`>> # RpcRequest (/api/type-aliases/RpcRequest) ```ts type RpcRequest = object; ``` Describes the elements of a Rpc or RpcSubscriptions request. ## Type Parameters | Type Parameter | Default type | | -------------- | ------------ | | `TParams` | `unknown` | ## Properties ### methodName ```ts readonly methodName: string; ``` Rhe name of the RPC method or subscription requested *** ### params ```ts readonly params: TParams; ``` The parameters to be passed to the RPC server # RpcRequestTransformer (/api/type-aliases/RpcRequestTransformer) ```ts type RpcRequestTransformer = (request) => RpcRequest; ``` A function that accepts a [RpcRequest](/api/type-aliases/RpcRequest) and returns another [RpcRequest](/api/type-aliases/RpcRequest). This allows the RpcApi to transform the request before it is sent to the RPC server. ## Type Parameters | Type Parameter | | -------------- | | `TParams` | ## Parameters | Parameter | Type | | --------- | -------------------------------------------------------- | | `request` | [`RpcRequest`](/api/type-aliases/RpcRequest)\<`TParams`> | ## Returns [`RpcRequest`](/api/type-aliases/RpcRequest) # RpcResponse (/api/type-aliases/RpcResponse) ```ts type RpcResponse = TResponse; ``` Represents the response from a RPC server. This could be any sort of data which is why RpcResponse defaults to `unknown`. You may use a type parameter to specify the shape of the response β€” e.g. `RpcResponse<{ result: number }>`. ## Type Parameters | Type Parameter | Default type | | -------------- | ------------ | | `TResponse` | `unknown` | # RpcResponseData (/api/type-aliases/RpcResponseData) ```ts type RpcResponseData = HasIdentifier & Readonly< | { error: RpcErrorResponsePayload; } | { result: TResponse; }>; ``` ## Type Parameters | Type Parameter | | -------------- | | `TResponse` | # RpcResponseTransformer (/api/type-aliases/RpcResponseTransformer) ```ts type RpcResponseTransformer = (response, request) => TResponse; ``` A function that accepts a [RpcResponse](/api/type-aliases/RpcResponse) and returns another [RpcResponse](/api/type-aliases/RpcResponse). This allows the RpcApi to transform the response before it is returned to the caller. ## Type Parameters | Type Parameter | Default type | | -------------- | ------------ | | `TResponse` | `unknown` | ## Parameters | Parameter | Type | | ---------- | -------------------------------------------- | | `response` | `unknown` | | `request` | [`RpcRequest`](/api/type-aliases/RpcRequest) | ## Returns `TResponse` # RpcSendOptions (/api/type-aliases/RpcSendOptions) ```ts type RpcSendOptions = Readonly<{ abortSignal?: AbortSignal; }>; ``` # RpcSubscribeOptions (/api/type-aliases/RpcSubscribeOptions) ```ts type RpcSubscribeOptions = Readonly<{ abortSignal: AbortSignal; }>; ``` # RpcSubscriptionChannelEvents (/api/type-aliases/RpcSubscriptionChannelEvents) ```ts type RpcSubscriptionChannelEvents = object; ``` ## Type Parameters | Type Parameter | | ----------------- | | `TInboundMessage` | ## Events ### error ```ts error: SolanaError; ``` Fires when the channel closes unexpectedly. *** ### message ```ts message: TInboundMessage; ``` Fires on every message received from the remote end. # RpcSubscriptions (/api/type-aliases/RpcSubscriptions) ```ts type RpcSubscriptions = { [TMethodName in keyof TRpcSubscriptionsMethods]: PendingRpcSubscriptionsRequestBuilder> }; ``` An object that exposes all of the functions described by `TRpcSubscriptionsMethods`. Calling each method returns a [PendingRpcSubscriptionsRequest\](/api/type-aliases/PendingRpcSubscriptionsRequest) where `TNotification` is that method's notification type. ## Type Parameters | Type Parameter | | -------------------------- | | `TRpcSubscriptionsMethods` | # RpcSubscriptionsApi (/api/type-aliases/RpcSubscriptionsApi) ```ts type RpcSubscriptionsApi = { [MethodName in keyof TRpcSubscriptionMethods]: RpcSubscriptionsReturnTypeMapper }; ``` For each of `TRpcSubscriptionsMethods`, this object exposes a method with the same name that maps between its input arguments and a [RpcSubscriptionsPlan\](/api/type-aliases/RpcSubscriptionsPlan) that implements the execution of a JSON RPC subscription for `TNotifications`. ## Type Parameters | Type Parameter | | ------------------------- | | `TRpcSubscriptionMethods` | # RpcSubscriptionsApiConfig (/api/type-aliases/RpcSubscriptionsApiConfig) ```ts type RpcSubscriptionsApiConfig = Readonly<{ planExecutor: RpcSubscriptionsPlanExecutor>; requestTransformer?: RpcRequestTransformer; }>; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------------- | | `TApiMethods` *extends* [`RpcSubscriptionsApiMethods`](/api/interfaces/RpcSubscriptionsApiMethods) | # RpcSubscriptionsChannelCreator (/api/type-aliases/RpcSubscriptionsChannelCreator) ```ts type RpcSubscriptionsChannelCreator = (config) => Promise>; ``` A channel creator is a function that accepts an `AbortSignal`, returns a new [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel), and tears down the channel when the abort signal fires. ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | ## Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `abortSignal`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); }> | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`TOutboundMessage`, `TInboundMessage`>> # RpcSubscriptionsChannelCreatorDevnet (/api/type-aliases/RpcSubscriptionsChannelCreatorDevnet) ```ts type RpcSubscriptionsChannelCreatorDevnet = RpcSubscriptionsChannelCreator & object; ``` ## Type Declaration | Name | Type | | ---------- | ---------- | | `~cluster` | `"devnet"` | ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | # RpcSubscriptionsChannelCreatorFromClusterUrl (/api/type-aliases/RpcSubscriptionsChannelCreatorFromClusterUrl) ```ts type RpcSubscriptionsChannelCreatorFromClusterUrl = TClusterUrl extends DevnetUrl ? RpcSubscriptionsChannelCreatorDevnet : TClusterUrl extends TestnetUrl ? RpcSubscriptionsChannelCreatorTestnet : TClusterUrl extends MainnetUrl ? RpcSubscriptionsChannelCreatorMainnet : RpcSubscriptionsChannelCreator; ``` ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | | `TOutboundMessage` | | `TInboundMessage` | # RpcSubscriptionsChannelCreatorMainnet (/api/type-aliases/RpcSubscriptionsChannelCreatorMainnet) ```ts type RpcSubscriptionsChannelCreatorMainnet = RpcSubscriptionsChannelCreator & object; ``` ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"mainnet"` | ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | # RpcSubscriptionsChannelCreatorTestnet (/api/type-aliases/RpcSubscriptionsChannelCreatorTestnet) ```ts type RpcSubscriptionsChannelCreatorTestnet = RpcSubscriptionsChannelCreator & object; ``` ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"testnet"` | ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | # RpcSubscriptionsChannelCreatorWithCluster (/api/type-aliases/RpcSubscriptionsChannelCreatorWithCluster) ```ts type RpcSubscriptionsChannelCreatorWithCluster = | RpcSubscriptionsChannelCreatorDevnet | RpcSubscriptionsChannelCreatorMainnet | RpcSubscriptionsChannelCreatorTestnet; ``` ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | # RpcSubscriptionsChannelDevnet (/api/type-aliases/RpcSubscriptionsChannelDevnet) ```ts type RpcSubscriptionsChannelDevnet = RpcSubscriptionsChannel & object; ``` A [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel) that communicates with the devnet cluster. Such channels are understood to communicate with a RPC server that services devnet, and as such might only be accepted for use as the channel of a [RpcSubscriptionsTransportDevnet](/api/type-aliases/RpcSubscriptionsTransportDevnet). This is useful in cases where you need to make assertions about what capabilities a RPC offers. You can use the ability to assert on the type of RPC channel at compile time to prevent calling unimplemented methods or presuming the existence of unavailable programs or data. ## Type Declaration | Name | Type | | ---------- | ---------- | | `~cluster` | `"devnet"` | ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | # RpcSubscriptionsChannelFromClusterUrl (/api/type-aliases/RpcSubscriptionsChannelFromClusterUrl) ```ts type RpcSubscriptionsChannelFromClusterUrl = TClusterUrl extends DevnetUrl ? RpcSubscriptionsChannelDevnet : TClusterUrl extends TestnetUrl ? RpcSubscriptionsChannelTestnet : TClusterUrl extends MainnetUrl ? RpcSubscriptionsChannelMainnet : RpcSubscriptionsChannel; ``` Given a ClusterUrl, this utility type will resolve to as specific a [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel) as possible. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | | `TOutboundMessage` | | `TInboundMessage` | ## Example ```ts function createCustomSubscriptionsChannel( clusterUrl: TClusterUrl, ): RpcSubscriptionsChannelFromClusterUrl { /* ... */ } const channel = createCustomSubscriptionsChannel(testnet('ws://api.testnet.solana.com')); channel satisfies RpcSubscriptionsChannelTestnet; // OK ``` # RpcSubscriptionsChannelMainnet (/api/type-aliases/RpcSubscriptionsChannelMainnet) ```ts type RpcSubscriptionsChannelMainnet = RpcSubscriptionsChannel & object; ``` A [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel) that communicates with the mainnet cluster. Such channels are understood to communicate with a RPC server that services mainnet, and as such might only be accepted for use as the channel of a [RpcSubscriptionsTransportMainnet](/api/type-aliases/RpcSubscriptionsTransportMainnet). This is useful in cases where you need to make assertions about what capabilities a RPC offers. You can use the ability to assert on the type of RPC channel at compile time to prevent calling unimplemented methods or presuming the existence of unavailable programs or data. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"mainnet"` | ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | # RpcSubscriptionsChannelTestnet (/api/type-aliases/RpcSubscriptionsChannelTestnet) ```ts type RpcSubscriptionsChannelTestnet = RpcSubscriptionsChannel & object; ``` A [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel) that communicates with the testnet cluster. Such channels are understood to communicate with a RPC server that services testnet, and as such might only be accepted for use as the channel of a [RpcSubscriptionsTransportTestnet](/api/type-aliases/RpcSubscriptionsTransportTestnet). This is useful in cases where you need to make assertions about what capabilities a RPC offers. You can use the ability to assert on the type of RPC channel at compile time to prevent calling unimplemented methods or presuming the existence of unavailable programs or data. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"testnet"` | ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | # RpcSubscriptionsChannelWithCluster (/api/type-aliases/RpcSubscriptionsChannelWithCluster) ```ts type RpcSubscriptionsChannelWithCluster = | RpcSubscriptionsChannelDevnet | RpcSubscriptionsChannelMainnet | RpcSubscriptionsChannelTestnet; ``` ## Type Parameters | Type Parameter | | ------------------ | | `TOutboundMessage` | | `TInboundMessage` | # RpcSubscriptionsConfig (/api/type-aliases/RpcSubscriptionsConfig) ```ts type RpcSubscriptionsConfig = Readonly<{ api: RpcSubscriptionsApi; transport: RpcSubscriptionsTransport; }>; ``` ## Type Parameters | Type Parameter | | -------------- | | `TRpcMethods` | # RpcSubscriptionsDevnet (/api/type-aliases/RpcSubscriptionsDevnet) ```ts type RpcSubscriptionsDevnet = RpcSubscriptions & object; ``` A [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) that supports the RPC Subscriptions methods available on the devnet cluster. This is useful in cases where you need to make assertions about the suitability of a RPC for a given purpose. For example, you might like to make it a type error to combine certain types with RPCs belonging to certain clusters, at compile time. ## Type Declaration | Name | Type | | ---------- | ---------- | | `~cluster` | `"devnet"` | ## Type Parameters | Type Parameter | | -------------- | | `TRpcMethods` | ## Example ```ts async function subscribeToSpecialAccountNotifications( address: Address<'ReAL1111111111111111111111111111'>, rpcSubscriptions: RpcSubscriptionsMainnet, abortSignal: AbortSignal, ): Promise>; async function subscribeToSpecialAccountNotifications( address: Address<'TeST1111111111111111111111111111'>, rpcSubscriptions: RpcSubscriptionsDevnet | RpcTestnet, abortSignal: AbortSignal, ): Promise>; async function subscribeToSpecialAccountNotifications( address: Address, rpcSubscriptions: RpcSubscriptions, abortSignal: AbortSignal, ): Promise> { /* ... */ } const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('https://api.devnet.solana.com')); await subscribeToSpecialAccountNotifications(address('ReAL1111111111111111111111111111'), rpcSubscriptions); // ERROR ``` # RpcSubscriptionsFromTransport (/api/type-aliases/RpcSubscriptionsFromTransport) ```ts type RpcSubscriptionsFromTransport = TRpcSubscriptionsTransport extends RpcSubscriptionsTransportDevnet ? RpcSubscriptionsDevnet : TRpcSubscriptionsTransport extends RpcSubscriptionsTransportTestnet ? RpcSubscriptionsTestnet : TRpcSubscriptionsTransport extends RpcSubscriptionsTransportMainnet ? RpcSubscriptionsMainnet : RpcSubscriptions; ``` Given a [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport) and a set of RPC methods denoted by `TRpcMethods`, this utility type will resolve to a [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) that supports those methods on as specific a cluster as possible. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------------------------------------- | | `TRpcMethods` | | `TRpcSubscriptionsTransport` *extends* [`RpcSubscriptionsTransport`](/api/interfaces/RpcSubscriptionsTransport) | ## Example ```ts function createCustomRpcSubscriptions( transport: TRpcSubscriptionsTransport, ): RpcSubscriptionsFromTransport { /* ... */ } const transport = createDefaultRpcSubscriptionsTransport({ createChannel: createDefaultSolanaRpcSubscriptionsChannelCreator({ url: mainnet('ws://rpc.company'), }), }); transport satisfies RpcSubscriptionsTransportMainnet; // OK const rpcSubscriptions = createCustomRpcSubscriptions(transport); rpcSubscriptions satisfies RpcSubscriptionsMainnet; // OK ``` # RpcSubscriptionsMainnet (/api/type-aliases/RpcSubscriptionsMainnet) ```ts type RpcSubscriptionsMainnet = RpcSubscriptions & object; ``` A [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) that supports the RPC Subscriptions methods available on the mainnet cluster. This is useful in cases where you need to make assertions about the suitability of a RPC for a given purpose. For example, you might like to make it a type error to combine certain types with RPCs belonging to certain clusters, at compile time. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"mainnet"` | ## Type Parameters | Type Parameter | | -------------- | | `TRpcMethods` | ## Example ```ts async function subscribeToSpecialAccountNotifications( address: Address<'ReAL1111111111111111111111111111'>, rpcSubscriptions: RpcSubscriptionsMainnet, abortSignal: AbortSignal, ): Promise>; async function subscribeToSpecialAccountNotifications( address: Address<'TeST1111111111111111111111111111'>, rpcSubscriptions: RpcSubscriptionsDevnet | RpcTestnet, abortSignal: AbortSignal, ): Promise>; async function subscribeToSpecialAccountNotifications( address: Address, rpcSubscriptions: RpcSubscriptions, abortSignal: AbortSignal, ): Promise> { /* ... */ } const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('https://api.devnet.solana.com')); await subscribeToSpecialAccountNotifications(address('ReAL1111111111111111111111111111'), rpcSubscriptions); // ERROR ``` # RpcSubscriptionsPlan (/api/type-aliases/RpcSubscriptionsPlan) ```ts type RpcSubscriptionsPlan = Readonly<{ execute: (config) => Promise>>; request: RpcRequest; }>; ``` This type allows an [RpcSubscriptionsApi](/api/type-aliases/RpcSubscriptionsApi) to describe how a particular subscription should be issued to the JSON RPC server. Given a function that was called on a [RpcSubscriptions](/api/type-aliases/RpcSubscriptions), this object exposes an `execute` function that dictates which subscription request will be sent, how the underlying transport will be used, and how the notifications will be transformed. This function accepts a [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel) and an `AbortSignal` and asynchronously returns a DataPublisher. This gives us the opportunity to: * define the `payload` from the requested method name and parameters before passing it to the channel. * call the underlying channel zero, one or multiple times depending on the use-case (e.g. caching or coalescing multiple subscriptions). * transform the notification from the JSON RPC server, in case it does not match the `TNotification` specified by the [PendingRpcSubscriptionsRequest\](/api/type-aliases/PendingRpcSubscriptionsRequest) emitted from the publisher returned. ## Type Parameters | Type Parameter | | --------------- | | `TNotification` | # RpcSubscriptionsTestnet (/api/type-aliases/RpcSubscriptionsTestnet) ```ts type RpcSubscriptionsTestnet = RpcSubscriptions & object; ``` A [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) that supports the RPC Subscriptions methods available on the testnet cluster. This is useful in cases where you need to make assertions about the suitability of a RPC for a given purpose. For example, you might like to make it a type error to combine certain types with RPCs belonging to certain clusters, at compile time. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"testnet"` | ## Type Parameters | Type Parameter | | -------------- | | `TRpcMethods` | ## Example ```ts async function subscribeToSpecialAccountNotifications( address: Address<'ReAL1111111111111111111111111111'>, rpcSubscriptions: RpcSubscriptionsMainnet, abortSignal: AbortSignal, ): Promise>; async function subscribeToSpecialAccountNotifications( address: Address<'TeST1111111111111111111111111111'>, rpcSubscriptions: RpcSubscriptionsDevnet | RpcTestnet, abortSignal: AbortSignal, ): Promise>; async function subscribeToSpecialAccountNotifications( address: Address, rpcSubscriptions: RpcSubscriptions, abortSignal: AbortSignal, ): Promise> { /* ... */ } const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('https://api.devnet.solana.com')); await subscribeToSpecialAccountNotifications(address('ReAL1111111111111111111111111111'), rpcSubscriptions); // ERROR ``` # RpcSubscriptionsTransportDataEvents (/api/type-aliases/RpcSubscriptionsTransportDataEvents) ```ts type RpcSubscriptionsTransportDataEvents = object; ``` ## Type Parameters | Type Parameter | | --------------- | | `TNotification` | ## Events ### error ```ts error: SolanaError; ``` Fires when there is an error with the subscription or the channel. *** ### notification ```ts notification: TNotification; ``` Fires on every notification received. # RpcSubscriptionsTransportDevnet (/api/type-aliases/RpcSubscriptionsTransportDevnet) ```ts type RpcSubscriptionsTransportDevnet = RpcSubscriptionsTransport & object; ``` A [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport) that communicates with the devnet cluster. Such transports are understood to communicate with a RPC server that services devnet, and as such might only be accepted for use as the transport of a [RpcSubscriptionsDevnet](/api/type-aliases/RpcSubscriptionsDevnet). This is useful in cases where you need to make assertions about what capabilities a RPC offers. You can use the ability to assert on the type of RPC transport at compile time to prevent calling unimplemented methods or presuming the existence of unavailable programs or data. ## Type Declaration | Name | Type | | ---------- | ---------- | | `~cluster` | `"devnet"` | # RpcSubscriptionsTransportFromClusterUrl (/api/type-aliases/RpcSubscriptionsTransportFromClusterUrl) ```ts type RpcSubscriptionsTransportFromClusterUrl = TClusterUrl extends DevnetUrl ? RpcSubscriptionsTransportDevnet : TClusterUrl extends TestnetUrl ? RpcSubscriptionsTransportTestnet : TClusterUrl extends MainnetUrl ? RpcSubscriptionsTransportMainnet : RpcSubscriptionsTransport; ``` Given a ClusterUrl, this utility type will resolve to as specific a [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport) as possible. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Example ```ts function createCustomSubscriptionsTransport( clusterUrl: TClusterUrl, ): RpcSubscriptionsTransportFromClusterUrl { /* ... */ } const transport = createCustomSubscriptionsTransport(testnet('ws://api.testnet.solana.com')); transport satisfies RpcSubscriptionsTransportTestnet; // OK ``` # RpcSubscriptionsTransportMainnet (/api/type-aliases/RpcSubscriptionsTransportMainnet) ```ts type RpcSubscriptionsTransportMainnet = RpcSubscriptionsTransport & object; ``` A [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport) that communicates with the mainnet cluster. Such transports are understood to communicate with a RPC server that services mainnet, and as such might only be accepted for use as the transport of a [RpcSubscriptionsMainnet](/api/type-aliases/RpcSubscriptionsMainnet). This is useful in cases where you need to make assertions about what capabilities a RPC offers. You can use the ability to assert on the type of RPC transport at compile time to prevent calling unimplemented methods or presuming the existence of unavailable programs or data. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"mainnet"` | # RpcSubscriptionsTransportTestnet (/api/type-aliases/RpcSubscriptionsTransportTestnet) ```ts type RpcSubscriptionsTransportTestnet = RpcSubscriptionsTransport & object; ``` A [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport) that communicates with the testnet cluster. Such transports are understood to communicate with a RPC server that services testnet, and as such might only be accepted for use as the transport of a [RpcSubscriptionsTestnet](/api/type-aliases/RpcSubscriptionsTestnet). This is useful in cases where you need to make assertions about what capabilities a RPC offers. You can use the ability to assert on the type of RPC transport at compile time to prevent calling unimplemented methods or presuming the existence of unavailable programs or data. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"testnet"` | # RpcSubscriptionsTransportWithCluster (/api/type-aliases/RpcSubscriptionsTransportWithCluster) ```ts type RpcSubscriptionsTransportWithCluster = | RpcSubscriptionsTransportDevnet | RpcSubscriptionsTransportMainnet | RpcSubscriptionsTransportTestnet; ``` # RpcTestnet (/api/type-aliases/RpcTestnet) ```ts type RpcTestnet = Rpc & object; ``` A [Rpc](/api/type-aliases/Rpc) that supports the RPC methods available on the testnet cluster. This is useful in cases where you need to make assertions about the suitability of a RPC for a given purpose. For example, you might like to make it a type error to combine certain types with RPCs belonging to certain clusters, at compile time. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"testnet"` | ## Type Parameters | Type Parameter | | -------------- | | `TRpcMethods` | ## Example ```ts async function getSpecialAccountInfo( address: Address<'ReAL1111111111111111111111111111'>, rpc: RpcMainnet, ): Promise; async function getSpecialAccountInfo( address: Address<'TeST1111111111111111111111111111'>, rpc: RpcDevnet | RpcTestnet, ): Promise; async function getSpecialAccountInfo(address: Address, rpc: Rpc): Promise { /* ... */ } const rpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); await getSpecialAccountInfo(address('ReAL1111111111111111111111111111'), rpc); // ERROR ``` # RpcTransport (/api/type-aliases/RpcTransport) ```ts type RpcTransport = (config) => Promise; ``` A function that can act as a transport for a [Rpc](/api/type-aliases/Rpc). It need only return a promise for a response given the supplied config. ## Type Parameters | Type Parameter | | -------------- | | `TResponse` | ## Parameters | Parameter | Type | | --------- | -------- | | `config` | `Config` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TResponse`> # RpcTransportDevnet (/api/type-aliases/RpcTransportDevnet) ```ts type RpcTransportDevnet = RpcTransport & object; ``` A [RpcTransport](/api/type-aliases/RpcTransport) that communicates with the devnet cluster. Such transports are understood to communicate with a RPC server that services devnet, and as such might only be accepted for use as the transport of a [RpcDevnet](/api/type-aliases/RpcDevnet). This is useful in cases where you need to make assertions about what capabilities a RPC offers. For example, RPC methods like requestAirdrop are not available on mainnet. You can use the ability to assert on the type of RPC transport at compile time to prevent calling unimplemented methods or presuming the existence of unavailable capabilities. ## Type Declaration | Name | Type | | ---------- | ---------- | | `~cluster` | `"devnet"` | # RpcTransportFromClusterUrl (/api/type-aliases/RpcTransportFromClusterUrl) ```ts type RpcTransportFromClusterUrl = TClusterUrl extends DevnetUrl ? RpcTransportDevnet : TClusterUrl extends TestnetUrl ? RpcTransportTestnet : TClusterUrl extends MainnetUrl ? RpcTransportMainnet : RpcTransport; ``` Given a ClusterUrl, this utility type will resolve to as specific a [RpcTransport](/api/type-aliases/RpcTransport) as possible. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Example ```ts function createCustomTransport( clusterUrl: TClusterUrl, ): RpcTransportFromClusterUrl { /* ... */ } const transport = createCustomTransport(testnet('http://api.testnet.solana.com')); transport satisfies RpcTransportTestnet; // OK ``` # RpcTransportMainnet (/api/type-aliases/RpcTransportMainnet) ```ts type RpcTransportMainnet = RpcTransport & object; ``` A [RpcTransport](/api/type-aliases/RpcTransport) that communicates with the mainnet cluster. Such transports are understood to communicate with a RPC server that services mainnet, and as such might only be accepted for use as the transport of a [RpcMainnet](/api/type-aliases/RpcMainnet). This is useful in cases where you need to make assertions about what capabilities a RPC offers. For example, RPC methods like requestAirdrop are not available on mainnet. You can use the ability to assert on the type of RPC transport at compile time to prevent calling unimplemented methods or presuming the existence of unavailable capabilities. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"mainnet"` | # RpcTransportTestnet (/api/type-aliases/RpcTransportTestnet) ```ts type RpcTransportTestnet = RpcTransport & object; ``` A [RpcTransport](/api/type-aliases/RpcTransport) that communicates with the testnet cluster. Such transports are understood to communicate with a RPC server that services testnet, and as such might only be accepted for use as the transport of a [RpcTestnet](/api/type-aliases/RpcTestnet). This is useful in cases where you need to make assertions about what capabilities a RPC offers. For example, RPC methods like requestAirdrop are not available on mainnet. You can use the ability to assert on the type of RPC transport at compile time to prevent calling unimplemented methods or presuming the existence of unavailable capabilities. ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"testnet"` | # SelectedWalletAccountContextProviderProps (/api/type-aliases/SelectedWalletAccountContextProviderProps) ```ts type SelectedWalletAccountContextProviderProps = object & object; ``` ## Type Declaration | Name | Type | | ---------------------------------- | ------------------------ | | `filterWallets()` | (`wallet`) => `boolean` | | `stateSync` | `object` | | `stateSync.deleteSelectedWallet()` | () => `void` | | `stateSync.getSelectedWallet()` | () => `string` \| `null` | | `stateSync.storeSelectedWallet()` | (`accountKey`) => `void` | ## Type Declaration | Name | Type | | ---------- | ----------------- | | `children` | `React.ReactNode` | # SelectedWalletAccountContextValue (/api/type-aliases/SelectedWalletAccountContextValue) ```ts type SelectedWalletAccountContextValue = readonly [SelectedWalletAccountState, React.Dispatch>, UiWallet[]]; ``` # SelectedWalletAccountState (/api/type-aliases/SelectedWalletAccountState) ```ts type SelectedWalletAccountState = UiWalletAccount | undefined; ``` # SelfFetchFunctions (/api/type-aliases/SelfFetchFunctions) ```ts type SelfFetchFunctions = object; ``` Methods that allow a codec to fetch and decode accounts directly. These methods are added to codec objects via [addSelfFetchFunctions](/api/functions/addSelfFetchFunctions), enabling a fluent API where you can call `.fetch()` directly on a codec to retrieve and decode accounts in one step. ## Examples Fetching a single account and asserting it exists. ```ts const account = await myAccountCodec.fetch(address); // account.data is of type TTo. ``` Fetching a single account that may not exist. ```ts const maybeAccount = await myAccountCodec.fetchMaybe(address); if (maybeAccount.exists) { // maybeAccount.data is of type TTo. } ``` Fetching multiple accounts at once. ```ts const accounts = await myAccountCodec.fetchAll([addressA, addressB]); // All accounts exist. ``` ## See [addSelfFetchFunctions](/api/functions/addSelfFetchFunctions) ## Type Parameters | Type Parameter | Description | | -------------------------- | ------------------------------------- | | `TFrom` *extends* `object` | The type that the codec encodes from. | | `TTo` *extends* `TFrom` | The type that the codec decodes to. | ## Properties ### fetch ```ts readonly fetch: (address, config?) => Promise>; ``` Fetches and decodes a single account, throwing if it does not exist. #### Type Parameters | Type Parameter | | ----------------------------- | | `TAddress` *extends* `string` | #### Parameters | Parameter | Type | | --------- | ---------------------- | | `address` | `Address`\<`TAddress`> | | `config?` | `FetchAccountConfig` | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`Account`\<`TTo`, `TAddress`>> *** ### fetchAll ```ts readonly fetchAll: (addresses, config?) => Promise[]>; ``` Fetches and decodes multiple accounts, throwing if any do not exist. #### Parameters | Parameter | Type | | ----------- | --------------------- | | `addresses` | `Address`\[] | | `config?` | `FetchAccountsConfig` | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`Account`\<`TTo`>\[]> *** ### fetchAllMaybe ```ts readonly fetchAllMaybe: (addresses, config?) => Promise[]>; ``` Fetches and decodes multiple accounts, returning MaybeAccount for each. #### Parameters | Parameter | Type | | ----------- | --------------------- | | `addresses` | `Address`\[] | | `config?` | `FetchAccountsConfig` | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`MaybeAccount`\<`TTo`>\[]> *** ### fetchMaybe ```ts readonly fetchMaybe: (address, config?) => Promise>; ``` Fetches and decodes a single account, returning a MaybeAccount. #### Type Parameters | Type Parameter | | ----------------------------- | | `TAddress` *extends* `string` | #### Parameters | Parameter | Type | | --------- | ---------------------- | | `address` | `Address`\<`TAddress`> | | `config?` | `FetchAccountConfig` | #### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`MaybeAccount`\<`TTo`, `TAddress`>> # SelfPlanAndSendFunctions (/api/type-aliases/SelfPlanAndSendFunctions) ```ts type SelfPlanAndSendFunctions = object; ``` Methods that allow an instruction or instruction plan to plan and send itself. These methods are added to instruction or instruction plan objects via [addSelfPlanAndSendFunctions](/api/functions/addSelfPlanAndSendFunctions), enabling a fluent API where you can call `.sendTransaction()` directly on an instruction without passing it to a separate function. ## Examples Sending a transfer instruction directly. ```ts const result = await getTransferInstruction({ source, destination, amount }).sendTransaction(); ``` Planning multiple transactions from an instruction plan. ```ts const plan = await getComplexInstructionPlan(/* ... */).planTransactions(); ``` ## See [addSelfPlanAndSendFunctions](/api/functions/addSelfPlanAndSendFunctions) ## Properties ### planTransaction ```ts planTransaction: (config?) => ReturnType; ``` Plans a single transaction. #### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------ | | `config?` | [`Parameters`](https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype)\<`PlanTransaction`>\[`1`] | #### Returns [`ReturnType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype)\<`PlanTransaction`> *** ### planTransactions ```ts planTransactions: (config?) => ReturnType; ``` Plans one or more transactions. #### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Parameters`](https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype)\<`PlanTransactions`>\[`1`] | #### Returns [`ReturnType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype)\<`PlanTransactions`> *** ### sendTransaction ```ts sendTransaction: (config?) => ReturnType; ``` Sends a single transaction. #### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------ | | `config?` | [`Parameters`](https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype)\<`SendTransaction`>\[`1`] | #### Returns [`ReturnType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype)\<`SendTransaction`> *** ### sendTransactions ```ts sendTransactions: (config?) => ReturnType; ``` Sends one or more transactions. #### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Parameters`](https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype)\<`SendTransactions`>\[`1`] | #### Returns [`ReturnType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype)\<`SendTransactions`> # SendTransactionApi (/api/type-aliases/SendTransactionApi) ```ts type SendTransactionApi = object; ``` ## Methods ### sendTransaction() #### Call Signature ```ts sendTransaction(base64EncodedWireTransaction, config?): Signature; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `maxRetries?`: `bigint`; `minContextSlot?`: `Slot`; `preflightCommitment?`: `Commitment`; `skipPreflight?`: `boolean`; }> & `object` | ##### Returns `Signature` ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts sendTransaction(base64EncodedWireTransaction, config?): Signature; ``` Submits a signed transaction to the cluster for processing. This method does not alter the transaction in any way; it relays the transaction created by clients to the node as-is. If the node's RPC service receives the transaction, this method immediately succeeds, without waiting for any confirmations. A successful response from this method does not guarantee the transaction will be processed or confirmed by the cluster. While the RPC service will reasonably retry to submit it, the transaction could fail to be committed if the transaction's lifetime specifier (ie. its recent blockhash or nonce) expires before it lands. Use [GetSignatureStatusesApi.getSignatureStatuses](/api/type-aliases/GetSignatureStatusesApi#getsignaturestatuses) to ensure that a transaction has been processed and confirmed. Before submitting, the following preflight checks are performed: 1. The transaction signatures are verified 2. The transaction is simulated against the bank slot specified by the preflight commitment. On failure, an error will be returned. It is recommended to specify the same commitment and preflight commitment to avoid confusing behavior. You can disable preflight checks if desired. ##### Parameters | Parameter | Type | Description | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `maxRetries?`: `bigint`; `minContextSlot?`: `Slot`; `preflightCommitment?`: `Commitment`; `skipPreflight?`: `boolean`; }> & `object` | - | ##### Returns `Signature` The signature of the transaction, as a base-58 encoded string. This is the first signature in the transaction, which is used to uniquely identify it. You do not have to wait for this method to return to obtain the signature; you can extract it from the transaction before sending it. ##### See [https://solana.com/docs/rpc/http/sendtransaction](https://solana.com/docs/rpc/http/sendtransaction) # SendableTransaction (/api/type-aliases/SendableTransaction) ```ts type SendableTransaction = FullySignedTransaction & TransactionWithinSizeLimit; ``` Helper type that includes all transaction types required for the transaction to be sent to the network. ## See * [isSendableTransaction](/api/functions/isSendableTransaction) * [assertIsSendableTransaction](/api/functions/assertIsSendableTransaction) # SequentialInstructionPlan (/api/type-aliases/SequentialInstructionPlan) ```ts type SequentialInstructionPlan = Readonly<{ divisible: boolean; kind: "sequential"; plans: InstructionPlan[]; planType: "instructionPlan"; }>; ``` A plan wrapping other plans that must be executed sequentially. It also defines whether nested plans are divisible β€” meaning that the instructions inside them can be split into separate transactions. When `divisible` is `false`, the instructions inside the plan should all be executed atomically β€” either in a single transaction or in a transaction bundle. You may use the [sequentialInstructionPlan](/api/functions/sequentialInstructionPlan) and [nonDivisibleSequentialInstructionPlan](/api/functions/nonDivisibleSequentialInstructionPlan) helpers to create objects of this type. ## Examples **Simple sequential plan with two instructions.** ```ts const plan = sequentialInstructionPlan([instructionA, instructionB]); plan satisfies SequentialInstructionPlan; ``` **Non-divisible sequential plan with two instructions.** ```ts const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]); plan satisfies SequentialInstructionPlan & { divisible: false }; ``` **Sequential plan with nested parallel plans.** Here, instructions A and B can be executed in parallel, but they must both be finalized before instructions C and D can be sent β€” which can also be executed in parallel. ```ts const plan = sequentialInstructionPlan([ parallelInstructionPlan([instructionA, instructionB]), parallelInstructionPlan([instructionC, instructionD]), ]); plan satisfies SequentialInstructionPlan & { divisible: false }; ``` ## See * [sequentialInstructionPlan](/api/functions/sequentialInstructionPlan) * [nonDivisibleSequentialInstructionPlan](/api/functions/nonDivisibleSequentialInstructionPlan) # SequentialTransactionPlan (/api/type-aliases/SequentialTransactionPlan) ```ts type SequentialTransactionPlan = Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlan[]; planType: "transactionPlan"; }>; ``` A plan wrapping other plans that must be executed sequentially. It also defines whether nested plans are divisible β€” meaning that the transaction messages inside them can be split into separate batches. When `divisible` is `false`, the transaction messages inside the plan should all be executed atomically β€” usually in a transaction bundle. You may use the [sequentialTransactionPlan](/api/functions/sequentialTransactionPlan) and [nonDivisibleSequentialTransactionPlan](/api/functions/nonDivisibleSequentialTransactionPlan) helpers to create objects of this type. ## Examples Simple sequential plan with two transaction messages. ```ts const plan = sequentialTransactionPlan([messageA, messageB]); plan satisfies SequentialTransactionPlan; ``` Non-divisible sequential plan with two transaction messages. ```ts const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]); plan satisfies SequentialTransactionPlan & { divisible: false }; ``` Sequential plan with nested parallel plans. Here, messages A and B can be executed in parallel, but they must both be finalized before messages C and D can be sent β€” which can also be executed in parallel. ```ts const plan = sequentialTransactionPlan([ parallelTransactionPlan([messageA, messageB]), parallelTransactionPlan([messageC, messageD]), ]); ``` ## See * [sequentialTransactionPlan](/api/functions/sequentialTransactionPlan) * [nonDivisibleSequentialTransactionPlan](/api/functions/nonDivisibleSequentialTransactionPlan) # SequentialTransactionPlanResult (/api/type-aliases/SequentialTransactionPlanResult) ```ts type SequentialTransactionPlanResult = Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlanResult[]; planType: "transactionPlanResult"; }>; ``` A result for a sequential transaction plan. This represents the execution result of a [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) and contains child results that were executed sequentially. It also retains the divisibility property from the original plan. You may use the [sequentialTransactionPlanResult](/api/functions/sequentialTransactionPlanResult) and [nonDivisibleSequentialTransactionPlanResult](/api/functions/nonDivisibleSequentialTransactionPlanResult) helpers to create objects of this type. ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | The type of the transaction message | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The type of single transaction plan results in this tree | ## Examples ```ts const result = sequentialTransactionPlanResult([ singleResultA, singleResultB, ]); result satisfies SequentialTransactionPlanResult; ``` Non-divisible sequential result. ```ts const result = nonDivisibleSequentialTransactionPlanResult([ singleResultA, singleResultB, ]); result satisfies SequentialTransactionPlanResult & { divisible: false }; ``` ## See * [sequentialTransactionPlanResult](/api/functions/sequentialTransactionPlanResult) * [nonDivisibleSequentialTransactionPlanResult](/api/functions/nonDivisibleSequentialTransactionPlanResult) # SetCodecConfig (/api/type-aliases/SetCodecConfig) ```ts type SetCodecConfig = object; ``` Defines the configuration options for set codecs. This configuration allows specifying how the size of the set is encoded. The `size` option can be: * A [NumberCodec](/api/type-aliases/NumberCodec), [NumberEncoder](/api/type-aliases/NumberEncoder), or [NumberDecoder](/api/type-aliases/NumberDecoder) to store the size as a prefix. * A fixed number of items, enforcing a strict length. * The string `'remainder'` to infer the set size from the remaining bytes (only for fixed-size items). ## Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | | `TPrefix` *extends* \| [`NumberCodec`](/api/type-aliases/NumberCodec) \| [`NumberDecoder`](/api/type-aliases/NumberDecoder) \| [`NumberEncoder`](/api/type-aliases/NumberEncoder) | The type used for encoding the size of the set. | ## Properties ### size? ```ts optional size?: ArrayLikeCodecSize; ``` The size encoding strategy for the set. #### Default Value Uses a `u32` prefix. # SetTransactionLifetimeFromTransactionMessage (/api/type-aliases/SetTransactionLifetimeFromTransactionMessage) ```ts type SetTransactionLifetimeFromTransactionMessage = TTransactionMessage extends object ? TTransactionMessage["lifetimeConstraint"] extends TransactionMessageWithBlockhashLifetime["lifetimeConstraint"] ? TransactionWithBlockhashLifetime & TTransaction : TTransactionMessage["lifetimeConstraint"] extends TransactionMessageWithDurableNonceLifetime["lifetimeConstraint"] ? TransactionWithDurableNonceLifetime & TTransaction : TransactionWithLifetime & TTransaction : TTransaction; ``` Helper type that sets the lifetime constraint of a transaction to be the same as the lifetime constraint of the provided transaction message. If the transaction message has no explicit lifetime constraint, neither will the transaction. ## Type Parameters | Type Parameter | | ----------------------------------------------------------------------- | | `TTransaction` *extends* [`Transaction`](/api/type-aliases/Transaction) | | `TTransactionMessage` *extends* `TransactionMessage` | # SetTransactionWithinSizeLimitFromTransactionMessage (/api/type-aliases/SetTransactionWithinSizeLimitFromTransactionMessage) ```ts type SetTransactionWithinSizeLimitFromTransactionMessage = TTransactionMessage extends TransactionMessageWithinSizeLimit ? TransactionWithinSizeLimit & TTransaction : TTransaction; ``` Helper type that adds the `TransactionWithinSizeLimit` flag to a transaction if and only if the provided transaction message is also within the size limit. ## Type Parameters | Type Parameter | | ----------------------------------------------------------------------- | | `TTransaction` *extends* [`Transaction`](/api/type-aliases/Transaction) | | `TTransactionMessage` *extends* `TransactionMessage` | # SignableMessage (/api/type-aliases/SignableMessage) ```ts type SignableMessage = Readonly<{ content: Uint8Array; signatures: SignatureDictionary; }>; ``` Defines a message that needs signing and its current set of signatures if any. This interface allows [MessageModifyingSigners](/api/type-aliases/MessageModifyingSigner) to decide on whether or not they should modify the provided message depending on whether or not signatures already exist for such message. It also helps create a more consistent API by providing a structure analogous to transactions which also keep track of their [SignatureDictionary](/api/type-aliases/SignatureDictionary). ## Example ```ts import { createSignableMessage } from '@solana/signers'; const message = createSignableMessage(new Uint8Array([1, 2, 3])); message.content; // The content of the message as bytes. message.signatures; // The current set of signatures for this message. ``` ## See [createSignableMessage](/api/functions/createSignableMessage) # Signature (/api/type-aliases/Signature) ```ts type Signature = Brand, "Signature">; ``` A 64-byte Ed25519 signature as a base58-encoded string. # SignatureBytes (/api/type-aliases/SignatureBytes) ```ts type SignatureBytes = Brand; ``` A 64-byte Ed25519 signature. Whenever you need to verify that a particular signature is, in fact, the one that would have been produced by signing some known bytes using the private key associated with some known public key, use the [verifySignature](/api/functions/verifySignature) function in this package. # SignatureDictionary (/api/type-aliases/SignatureDictionary) ```ts type SignatureDictionary = Readonly>; ``` # SignatureNotificationsApi (/api/type-aliases/SignatureNotificationsApi) ```ts type SignatureNotificationsApi = object; ``` ## Methods ### signatureNotifications() #### Call Signature ```ts signatureNotifications(signature, config): | Readonly<{ context: Readonly<{ slot: Slot; }>; value: TValue; }> | Readonly<{ context: Readonly<{ slot: Slot; }>; value: TValue; }>; ``` Subscribe to a receive a notification when the transaction identified by the given signature is received by the cluster, then again when it reaches the specified level of commitment. This subscription will not issue notifications for events that have already happened. To fetch the commitment status of any transaction at a point in time use the GetSignatureStatusesApi.getSignatureStatuses | getSignatureStatuses method of the RPC API. ##### Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- | | `signature` | `Signature` | Transaction signature as base-58 encoded string | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `enableReceivedNotification`: `true`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `enableReceivedNotification?`: `boolean`; }> | - | ##### Returns \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `context`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `slot`: `Slot`; }>; `value`: `TValue`; }> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `context`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `slot`: `Slot`; }>; `value`: `TValue`; }> ##### See [https://solana.com/docs/rpc/websocket/signaturesubscribe](https://solana.com/docs/rpc/websocket/signaturesubscribe) #### Call Signature ```ts signatureNotifications(signature, config?): SignatureNotificationsApiNotificationProcessed; ``` Subscribe to a receive a notification when the transaction identified by the given signature reaches the specified level of commitment. This subscription will not issue notifications for events that have already happened. To fetch the commitment status of any transaction at a point in time use the GetSignatureStatusesApi.getSignatureStatuses | getSignatureStatuses method of the RPC API. ##### Parameters | Parameter | Type | Description | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | | `signature` | `Signature` | Transaction signature as base-58 encoded string | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `enableReceivedNotification?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `enableReceivedNotification?`: `boolean`; }> | - | ##### Returns `SignatureNotificationsApiNotificationProcessed` ##### See [https://solana.com/docs/rpc/websocket/signaturesubscribe](https://solana.com/docs/rpc/websocket/signaturesubscribe) # SignaturesMap (/api/type-aliases/SignaturesMap) ```ts type SignaturesMap = OrderedMap; ``` # SignedLamports (/api/type-aliases/SignedLamports) ```ts type SignedLamports = bigint; ``` # Signedness (/api/type-aliases/Signedness) ```ts type Signedness = "signed" | "unsigned"; ``` Whether a fixed-point number can represent negative values. * `'signed'` fixed-point numbers use two's-complement semantics and can represent both negative and non-negative values. * `'unsigned'` fixed-point numbers can only represent non-negative values but get one extra bit of positive range. ## See * [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) * [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) # SimulateTransactionApi (/api/type-aliases/SimulateTransactionApi) ```ts type SimulateTransactionApi = object; ``` ## Methods ### simulateTransaction() #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding?`: `"base64"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`> & `SimulateTransactionApiResponseWithInnerInstructions` & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding?`: `"base64"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`> & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding`: `"base64+zstd"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`> & `SimulateTransactionApiResponseWithInnerInstructions` & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding`: `"base64+zstd"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`> & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding`: `"jsonParsed"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithJsonData`> & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config?): SolanaRpcResponse & SimulateTransactionApiResponseBase & SimulateTransactionApiResponseWithInnerInstructions & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> | ##### Returns `SolanaRpcResponse`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: `null`; }> & `SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithInnerInstructions` & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config?): SolanaRpcResponse & SimulateTransactionApiResponseBase & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> | ##### Returns `SolanaRpcResponse`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: `null`; }> & `SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state, obtain the list of inner instructions run, if any, and replace the transaction's blockhash with the most recent one. If the listed accounts have data, it will be returned in the response as a tuple whose first element is a base64-encoded string. The replacement blockhash and the blockheight until which it is valid will be returned in the response. ##### Parameters | Parameter | Type | Description | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding?`: `"base64"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`> & `SimulateTransactionApiResponseWithInnerInstructions` & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state, and replace the transaction's blockhash with the most recent one. If the listed accounts have data, it will be returned in the response as a tuple whose first element is a base64-encoded string. The replacement blockhash and the blockheight until which it is valid will be returned in the response. ##### Parameters | Parameter | Type | Description | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding?`: `"base64"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`> & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state, obtain the list of inner instructions run, if any, and replace the transaction's blockhash with the most recent one. If the listed accounts have data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. The replacement blockhash and the blockheight until which it is valid will be returned in the response. ##### Parameters | Parameter | Type | Description | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding`: `"base64+zstd"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`> & `SimulateTransactionApiResponseWithInnerInstructions` & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state, and replace the transaction's blockhash with the most recent one. If the listed accounts have data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. The replacement blockhash and the blockheight until which it is valid will be returned in the response. ##### Parameters | Parameter | Type | Description | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding`: `"base64+zstd"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`> & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state, obtain the list of inner instructions run, if any, and replace the transaction's blockhash with the most recent one. If the listed accounts have data, the server will attempt to process it using a parser specific to each account's owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. The replacement blockhash and the blockheight until which it is valid will be returned in the response. ##### Parameters | Parameter | Type | Description | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding`: `"jsonParsed"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithJsonData`> & `SimulateTransactionApiResponseWithInnerInstructions` & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state, and replace the transaction's blockhash with the most recent one. If the listed accounts have data, the server will attempt to process it using a parser specific to each account's owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. The replacement blockhash and the blockheight until which it is valid will be returned in the response. ##### Parameters | Parameter | Type | Description | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding`: `"jsonParsed"`; }; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithJsonData`> & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseBase & SimulateTransactionApiResponseWithInnerInstructions & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` Simulate sending a transaction, obtain the list of inner instructions run, if any, and replace the transaction's blockhash with the most recent one. The replacement blockhash and the blockheight until which it is valid will be returned in the response. ##### Parameters | Parameter | Type | Description | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: `null`; }> & `SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithInnerInstructions` & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseBase & SimulateTransactionApiResponseWithReplacementBlockhash>; ``` Simulate sending a transaction, and replace the transaction's blockhash with the most recent one. The replacement blockhash and the blockheight until which it is valid will be returned in the response. ##### Parameters | Parameter | Type | Description | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash`: `true`; `sigVerify?`: `false`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: `null`; }> & `SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithReplacementBlockhash`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | Readonly\<\{ accounts: \{ addresses: readonly Address\[]; encoding?: "base64" \| undefined; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<...>) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`> & `SimulateTransactionApiResponseWithInnerInstructions`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding?`: `"base64"`; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<\{ replaceRecentBlockhash?: false \| undefined; sigVerify: true; }>) & Readonly\<...> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`>> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | Readonly\<\{ accounts: \{ addresses: readonly Address\[]; encoding: "base64+zstd"; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<...>) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`> & `SimulateTransactionApiResponseWithInnerInstructions`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding`: `"base64+zstd"`; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<\{ replaceRecentBlockhash?: false \| undefined; sigVerify: true; }>) & Readonly\<...> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`>> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | Readonly\<\{ accounts: \{ addresses: readonly Address\[]; encoding: "jsonParsed"; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<...>) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithJsonData`> & `SimulateTransactionApiResponseWithInnerInstructions`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config): SolanaRpcResponse>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: \{ `addresses`: readonly `Address`\[]; `encoding`: `"jsonParsed"`; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<\{ replaceRecentBlockhash?: false \| undefined; sigVerify: true; }>) & Readonly\<...> | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithJsonData`>> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config?): SolanaRpcResponse & SimulateTransactionApiResponseBase & SimulateTransactionApiResponseWithInnerInstructions>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config?` | (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<\{ replaceRecentBlockhash?: false \| undefined; sigVerify: true; }>) & Readonly\<...> & Readonly\<...> | ##### Returns `SolanaRpcResponse`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: `null`; }> & `SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithInnerInstructions`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base58EncodedWireTransaction, config?): SolanaRpcResponse & SimulateTransactionApiResponseBase>; ``` ##### Parameters | Parameter | Type | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `base58EncodedWireTransaction` | `Base58EncodedBytes` | | `config?` | (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<\{ replaceRecentBlockhash?: false \| undefined; sigVerify: true; }>) & Readonly\<...> | ##### Returns `SolanaRpcResponse`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: `null`; }> & `SimulateTransactionApiResponseBase`> ##### Deprecated Set `encoding` to `'base64'` when calling this method #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state, and obtain the list of inner instructions run, if any. If the listed accounts have data, it will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | Readonly\<\{ accounts: \{ addresses: readonly Address\[]; encoding?: "base64" \| undefined; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<...>) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`> & `SimulateTransactionApiResponseWithInnerInstructions`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state. If the listed accounts have data, it will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | Readonly\<\{ accounts: \{ addresses: readonly Address\[]; encoding?: "base64" \| undefined; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<...>) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedData`>> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state, and obtain the list of inner instructions run, if any. If the listed accounts have data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | Readonly\<\{ accounts: \{ addresses: readonly Address\[]; encoding: "base64+zstd"; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<...>) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`> & `SimulateTransactionApiResponseWithInnerInstructions`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state. If the listed accounts have data, it will first be compressed using [ZStandard](https://facebook.github.io/zstd/) and the result will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | Readonly\<\{ accounts: \{ addresses: readonly Address\[]; encoding: "base64+zstd"; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<...>) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithBase64EncodedZStdCompressedData`>> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseWithInnerInstructions>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state, and obtain the list of inner instructions run, if any. If the listed accounts have data, the server will attempt to process it using a parser specific to each account's owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | Readonly\<\{ accounts: \{ addresses: readonly Address\[]; encoding: "jsonParsed"; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<...>) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithJsonData`> & `SimulateTransactionApiResponseWithInnerInstructions`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse>; ``` Simulate sending a transaction, fetch a list of accounts in their post-simulation state. If the listed accounts have data, the server will attempt to process it using a parser specific to each account's owning program. If successful, the parsed data will be returned in the response as JSON. Otherwise, the raw account data will be returned in the response as a tuple whose first element is a base64-encoded string. ##### Parameters | Parameter | Type | Description | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | Readonly\<\{ accounts: \{ addresses: readonly Address\[]; encoding: "jsonParsed"; }; }> & (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<...>) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<`SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithAccounts`\<`AccountInfoBase` & `AccountInfoWithJsonData`>> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseBase & SimulateTransactionApiResponseWithInnerInstructions>; ``` Simulate sending a transaction, and obtain the list of inner instructions run, if any. ##### Parameters | Parameter | Type | Description | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | (Readonly\<\{ replaceRecentBlockhash?: boolean \| undefined; sigVerify?: false \| undefined; }> \| Readonly\<\{ replaceRecentBlockhash?: false \| undefined; sigVerify: true; }>) & Readonly\<...> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions`: `true`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: `null`; }> & `SimulateTransactionApiResponseBase` & `SimulateTransactionApiResponseWithInnerInstructions`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) #### Call Signature ```ts simulateTransaction(base64EncodedWireTransaction, config): SolanaRpcResponse & SimulateTransactionApiResponseBase>; ``` Simulate sending a transaction. ##### Parameters | Parameter | Type | Description | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `base64EncodedWireTransaction` | `Base64EncodedWireTransaction` | A fully signed transaction in wire format, as a base-64 encoded string. Use getBase64EncodedWireTransaction to obtain this. | | `config` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash?`: `boolean`; `sigVerify?`: `false`; }> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `replaceRecentBlockhash?`: `false`; `sigVerify`: `true`; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `commitment?`: `Commitment`; `innerInstructions?`: `boolean`; `minContextSlot?`: `Slot`; }> & `object` | - | ##### Returns `SolanaRpcResponse`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accounts`: `null`; }> & `SimulateTransactionApiResponseBase`> ##### See [https://solana.com/docs/rpc/http/simulatetransaction](https://solana.com/docs/rpc/http/simulatetransaction) # SingleInstructionPlan (/api/type-aliases/SingleInstructionPlan) ```ts type SingleInstructionPlan = Readonly<{ instruction: TInstruction; kind: "single"; planType: "instructionPlan"; }>; ``` A plan that contains a single instruction. This is a simple instruction wrapper that transforms an instruction into a plan. You may use the [singleInstructionPlan](/api/functions/singleInstructionPlan) helper to create objects of this type. ## Type Parameters | Type Parameter | Default type | | --------------------------------------------------------------------- | -------------------------------------------- | | `TInstruction` *extends* [`Instruction`](/api/interfaces/Instruction) | [`Instruction`](/api/interfaces/Instruction) | ## Example ```ts const plan = singleInstructionPlan(instructionA); plan satisfies SingleInstructionPlan; ``` ## See [singleInstructionPlan](/api/functions/singleInstructionPlan) # SingleTransactionPlan (/api/type-aliases/SingleTransactionPlan) ```ts type SingleTransactionPlan = Readonly<{ kind: "single"; message: TTransactionMessage; planType: "transactionPlan"; }>; ``` A plan that contains a single transaction message. This is a simple transaction message wrapper that transforms a message into a plan. You may use the [singleTransactionPlan](/api/functions/singleTransactionPlan) helper to create objects of this type. ## Type Parameters | Type Parameter | Default type | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | ## Example ```ts const plan = singleTransactionPlan(transactionMessage); plan satisfies SingleTransactionPlan; ``` ## See [singleTransactionPlan](/api/functions/singleTransactionPlan) # SingleTransactionPlanResult (/api/type-aliases/SingleTransactionPlanResult) ```ts type SingleTransactionPlanResult = | CanceledSingleTransactionPlanResult | FailedSingleTransactionPlanResult | SuccessfulSingleTransactionPlanResult; ``` A result for a single transaction plan. This represents the execution result of a [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan) and contains the original transaction message along with its execution status. You may use the [successfulSingleTransactionPlanResult](/api/functions/successfulSingleTransactionPlanResult), [failedSingleTransactionPlanResult](/api/functions/failedSingleTransactionPlanResult), or [canceledSingleTransactionPlanResult](/api/functions/canceledSingleTransactionPlanResult) helpers to create objects of this type. ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | The type of the transaction message | ## Examples Successful result with a signature in its context. ```ts const result = successfulSingleTransactionPlanResult( transactionMessage, { signature }, ); result satisfies SingleTransactionPlanResult; ``` Failed result with an error. ```ts const result = failedSingleTransactionPlanResult( transactionMessage, new SolanaError(SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE), ); result satisfies SingleTransactionPlanResult; ``` Canceled result. ```ts const result = canceledSingleTransactionPlanResult(transactionMessage); result satisfies SingleTransactionPlanResult; ``` ## See * [successfulSingleTransactionPlanResult](/api/functions/successfulSingleTransactionPlanResult) * [failedSingleTransactionPlanResult](/api/functions/failedSingleTransactionPlanResult) * [canceledSingleTransactionPlanResult](/api/functions/canceledSingleTransactionPlanResult) # Slot (/api/type-aliases/Slot) ```ts type Slot = bigint; ``` # SlotNotificationsApi (/api/type-aliases/SlotNotificationsApi) ```ts type SlotNotificationsApi = object; ``` ## Methods ### slotNotifications() ```ts slotNotifications(): SlotNotificationsApiNotification; ``` Subscribe to receive notifications anytime a slot is processed by the validator. #### Returns `SlotNotificationsApiNotification` #### See [https://solana.com/docs/rpc/websocket/slotsubscribe](https://solana.com/docs/rpc/websocket/slotsubscribe) # SlotsUpdatesNotificationsApi (/api/type-aliases/SlotsUpdatesNotificationsApi) ```ts type SlotsUpdatesNotificationsApi = object; ``` ## Methods ### slotsUpdatesNotifications() ```ts slotsUpdatesNotifications(): Readonly; ``` Subscribe to receive a notification from the validator on a variety of updates on every slot. This subscription is unstable. The format of this subscription may change in the future, and may not be supported by every node. #### Returns `Readonly` #### See [https://solana.com/docs/rpc/websocket/slotsupdatessubscribe](https://solana.com/docs/rpc/websocket/slotsupdatessubscribe) # Sol (/api/type-aliases/Sol) ```ts type Sol = DecimalFixedPoint<"unsigned", 64, 9>; ``` The canonical fixed-point shape for SOL amounts: unsigned 64-bit with 9 decimals. Since 1 SOL equals `10 ** 9` Lamports, a `Sol` value's `raw` bigint is exactly the corresponding Lamports count. # SolanaErrorCode (/api/type-aliases/SolanaErrorCode) ```ts type SolanaErrorCode = | typeof SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT | typeof SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT | typeof SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND | typeof SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED | typeof SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS | typeof SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH | typeof SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY | typeof SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS | typeof SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE | typeof SOLANA_ERROR__ADDRESSES__MALFORMED_PDA | typeof SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED | typeof SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED | typeof SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE | typeof SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER | typeof SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE | typeof SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED | typeof SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE | typeof SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY | typeof SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS | typeof SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH | typeof SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE | typeof SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY | typeof SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH | typeof SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH | typeof SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH | typeof SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE | typeof SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH | typeof SOLANA_ERROR__CODECS__INVALID_CONSTANT | typeof SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT | typeof SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT | typeof SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT | typeof SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS | typeof SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES | typeof SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE | typeof SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE | typeof SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE | typeof SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE | typeof SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE | typeof SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES | typeof SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE | typeof SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED | typeof SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION | typeof SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS | typeof SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION | typeof SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS | typeof SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW | typeof SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO | typeof SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS | typeof SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS | typeof SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS | typeof SOLANA_ERROR__FIXED_POINTS__INVALID_STRING | typeof SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS | typeof SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO | typeof SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE | typeof SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH | typeof SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS | typeof SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED | typeof SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE | typeof SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA | typeof SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN | typeof SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE | typeof SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT | typeof SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH | typeof SOLANA_ERROR__INVALID_NONCE | typeof SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING | typeof SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE | typeof SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR | typeof SOLANA_ERROR__JSON_RPC__INVALID_PARAMS | typeof SOLANA_ERROR__JSON_RPC__INVALID_REQUEST | typeof SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND | typeof SOLANA_ERROR__JSON_RPC__PARSE_ERROR | typeof SOLANA_ERROR__JSON_RPC__SCAN_ERROR | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION | typeof SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX | typeof SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH | typeof SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH | typeof SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH | typeof SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY | typeof SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE | typeof SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT | typeof SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE | typeof SOLANA_ERROR__MALFORMED_BIGINT_STRING | typeof SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR | typeof SOLANA_ERROR__MALFORMED_NUMBER_STRING | typeof SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED | typeof SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT | typeof SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION | typeof SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS | typeof SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL | typeof SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE | typeof SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE | typeof SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE | typeof SOLANA_ERROR__REACT__MISSING_CAPABILITY | typeof SOLANA_ERROR__REACT__MISSING_PROVIDER | typeof SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR | typeof SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD | typeof SOLANA_ERROR__RPC__INTEGER_OVERFLOW | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID | typeof SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS | typeof SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER | typeof SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS | typeof SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING | typeof SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION | typeof SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED | typeof SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED | typeof SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR | typeof SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT | typeof SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED | typeof SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED | typeof SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED | typeof SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED | typeof SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED | typeof SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE | typeof SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING | typeof SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION | typeof SOLANA_ERROR__TRANSACTION__CANNOT_DECODE_EMPTY_TRANSACTION_BYTES | typeof SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES | typeof SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES | typeof SOLANA_ERROR__TRANSACTION__COMPUTE_UNIT_LIMIT_OUT_OF_RANGE | typeof SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_LOADED_ACCOUNTS_DATA_SIZE_LIMIT | typeof SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT | typeof SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING | typeof SOLANA_ERROR__TRANSACTION__INSTRUCTION_HEADERS_PAYLOADS_MISMATCH | typeof SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS | typeof SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND | typeof SOLANA_ERROR__TRANSACTION__INVALID_HEAP_SIZE | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE | typeof SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES | typeof SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH | typeof SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE | typeof SOLANA_ERROR__TRANSACTION__SIGNATURE_COUNT_TOO_HIGH_FOR_TRANSACTION_BYTES | typeof SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING | typeof SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNT_ADDRESSES | typeof SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNTS_IN_INSTRUCTION | typeof SOLANA_ERROR__TRANSACTION__TOO_MANY_INSTRUCTIONS | typeof SOLANA_ERROR__TRANSACTION__TOO_MANY_SIGNER_ADDRESSES | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE | typeof SOLANA_ERROR__TRANSACTION__VERSION_ZERO_MUST_BE_ENCODED_WITH_SIGNATURES_FIRST | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND | typeof SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND | typeof SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED | typeof SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND | typeof SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP | typeof SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE | typeof SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT | typeof SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED | typeof SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED | typeof SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED | typeof SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE | typeof SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE | typeof SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT | typeof SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION | typeof SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE | typeof SOLANA_ERROR__WALLET__ACCOUNT_NOT_AVAILABLE | typeof SOLANA_ERROR__WALLET__NO_SIGNER_CONNECTED | typeof SOLANA_ERROR__WALLET__NOT_CONNECTED | typeof SOLANA_ERROR__WALLET__SIGNER_NOT_AVAILABLE; ``` A union of every Solana error code # SolanaErrorCodeWithCause (/api/type-aliases/SolanaErrorCodeWithCause) ```ts type SolanaErrorCodeWithCause = | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE | typeof SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT | typeof SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS; ``` Errors of this type are understood to have an optional [SolanaError](/api/classes/SolanaError) nested inside as `cause`. # SolanaErrorCodeWithDeprecatedCause (/api/type-aliases/SolanaErrorCodeWithDeprecatedCause) ```ts type SolanaErrorCodeWithDeprecatedCause = typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN; ``` Errors of this type have a deprecated `cause` property. Consumers should use the error's `context` instead to access relevant error information. # SolanaRpcApi (/api/type-aliases/SolanaRpcApi) ```ts type SolanaRpcApi = SolanaRpcApiForTestClusters; ``` Represents the RPC methods available on test clusters. For instance, the test clusters support the [RequestAirdropApi](/api/type-aliases/RequestAirdropApi) while mainnet does not. # SolanaRpcApiDevnet (/api/type-aliases/SolanaRpcApiDevnet) ```ts type SolanaRpcApiDevnet = SolanaRpcApiForTestClusters; ``` Represents the RPC methods available on the devnet cluster. For instance, the devnet cluster supports the [RequestAirdropApi](/api/type-aliases/RequestAirdropApi) while mainnet does not. # SolanaRpcApiFromClusterUrl (/api/type-aliases/SolanaRpcApiFromClusterUrl) ```ts type SolanaRpcApiFromClusterUrl = SolanaRpcApiFromTransport>; ``` Given a ClusterUrl this utility type will resolve to a union of all the methods of the Solana RPC API supported by the URL's cluster. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Example ```ts function createSolanaRpcFromClusterUrl( clusterUrl: TClusterUrl, ): Rpc, RpcTransportFromClusterUrl> { /* ... */ } const rpc = createSolanaRpcFromClusterUrl(mainnet('http://rpc.company')); rpc satisfies Rpc; // OK ``` # SolanaRpcApiFromTransport (/api/type-aliases/SolanaRpcApiFromTransport) ```ts type SolanaRpcApiFromTransport = TTransport extends RpcTransportDevnet ? SolanaRpcApiDevnet : TTransport extends RpcTransportTestnet ? SolanaRpcApiTestnet : TTransport extends RpcTransportMainnet ? SolanaRpcApiMainnet : SolanaRpcApi; ``` Given a [RpcTransport](/api/type-aliases/RpcTransport) this utility type will resolve to a union of all the methods of the Solana RPC API supported by the transport's cluster. ## Type Parameters | Type Parameter | | ----------------------------------------------------------------------- | | `TTransport` *extends* [`RpcTransport`](/api/type-aliases/RpcTransport) | ## Example ```ts function createSolanaRpcFromTransport( transport: TTransport, ): RpcFromTransport, TTransport> { /* ... */ } const transport = createDefaultRpcTransport({ url: mainnet('http://rpc.company') }); transport satisfies RpcTransportMainnet; // OK const rpc = createSolanaRpcFromTransport(transport); rpc satisfies RpcMainnet; // OK ``` # SolanaRpcApiMainnet (/api/type-aliases/SolanaRpcApiMainnet) ```ts type SolanaRpcApiMainnet = SolanaRpcApiForAllClusters; ``` Represents the RPC methods available on the mainnet cluster. For instance, the mainnet cluster does not support the [RequestAirdropApi](/api/type-aliases/RequestAirdropApi) whereas test clusters do. # SolanaRpcApiTestnet (/api/type-aliases/SolanaRpcApiTestnet) ```ts type SolanaRpcApiTestnet = SolanaRpcApiForTestClusters; ``` Represents the RPC methods available on the testnet cluster. For instance, the testnet cluster supports the [RequestAirdropApi](/api/type-aliases/RequestAirdropApi) while mainnet does not. # SolanaRpcResponse (/api/type-aliases/SolanaRpcResponse) ```ts type SolanaRpcResponse = Readonly<{ context: Readonly<{ slot: Slot; }>; value: TValue; }>; ``` ## Type Parameters | Type Parameter | | -------------- | | `TValue` | # SolanaRpcSubscriptionsApi (/api/type-aliases/SolanaRpcSubscriptionsApi) ```ts type SolanaRpcSubscriptionsApi = AccountNotificationsApi & LogsNotificationsApi & ProgramNotificationsApi & RootNotificationsApi & SignatureNotificationsApi & SlotNotificationsApi; ``` # SolanaRpcSubscriptionsApiUnstable (/api/type-aliases/SolanaRpcSubscriptionsApiUnstable) ```ts type SolanaRpcSubscriptionsApiUnstable = BlockNotificationsApi & SlotsUpdatesNotificationsApi & VoteNotificationsApi; ``` # Some (/api/type-aliases/Some) ```ts type Some = Readonly<{ __option: "Some"; value: T; }>; ``` Represents an [Option](/api/type-aliases/Option) that contains a value. This type mirrors Rust’s `Some(T)`, indicating that a value is present. For more details, see [Option](/api/type-aliases/Option). ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ## Example Creating a `Some` value. ```ts const value = some(42); isSome(value); // true isNone(value); // false ``` ## See * [Option](/api/type-aliases/Option) * [some](/api/functions/some) * [isSome](/api/functions/isSome) # StringifiedBigInt (/api/type-aliases/StringifiedBigInt) ```ts type StringifiedBigInt = Brand; ``` This type represents a `bigint` which has been encoded as a string for transit over a transport that does not support `bigint` values natively. The JSON-RPC is such a transport. # StringifiedNumber (/api/type-aliases/StringifiedNumber) ```ts type StringifiedNumber = Brand; ``` This type represents a number which has been encoded as a string for transit over a transport where loss of precision when using the native number type is a concern. The JSON-RPC is such a transport. # SubscribeToFn (/api/type-aliases/SubscribeToFn) ```ts type SubscribeToFn = (listener) => () => void; ``` Registers a listener for changes to a reactive client capability. Returns an unsubscribe function. Calling the returned unsubscribe more than once is safe β€” it must be idempotent. ## Parameters | Parameter | Type | | ---------- | ------------ | | `listener` | () => `void` | ## Returns () => `void` # SubscriptionResult (/api/type-aliases/SubscriptionResult) ```ts type SubscriptionResult = object; ``` Reactive state for a subscription managed by [useSubscription](/api/functions/useSubscription) (and other stream-store hooks built on top of it). Lifecycle: starts at `loading` (or `disabled` when the source is `null`) and opens the underlying stream on mount; transitions to `loaded` on the first notification or `error` on failure. `reconnect()` re-opens the stream β€” while a reconnect is in flight, `status` returns to `loading` and the stale `data` and/or `error` from the prior connection remain populated (stale-while-revalidate). ## Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------------- | | `T` | The notification type emitted by the underlying source. | ## Properties ### data ```ts data: T | undefined; ``` The latest notification. `undefined` on the first load and while disabled. On `loading` after a prior outcome, on `error`, and on a subsequent reconnect, holds the last received notification. *** ### error ```ts error: unknown; ``` Error from the subscription, or `undefined`. On `loading` after a prior `error`, holds the stale error so UIs can keep showing the failure context (e.g. a banner) while the reconnect is in flight. A subsequent `loaded` clears it. *** ### reconnect ```ts reconnect: (options?) => void; ``` Re-open the stream. By default each call mints a fresh signal from `getAbortSignal` (if configured) and threads it through the underlying store's `withSignal(signal).connect()`. Pass `{ abortSignal }` to override the configured factory for just this attempt. Pass `{ abortSignal: undefined }` to opt out of the factory entirely for this attempt and open with no caller-provided signal. Stable reference. Safe to put in `onClick` handlers or effect deps β€” typically wired up to a "Reconnect" button when `status === 'error'`. Calls `store.connect()` under the hood, so it always (re)opens the stream regardless of current status; the bridge transitions back through `loading` while preserving stale data and error. #### Parameters | Parameter | Type | | ---------------------- | --------------------------------------------------------------------------------------------- | | `options?` | \{ `abortSignal?`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); } | | `options.abortSignal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | #### Returns `void` *** ### status ```ts status: "disabled" | "error" | "loaded" | "loading"; ``` Lifecycle status as a discriminated string: * `loading`: a connection is in progress. On the first connection, `data` and `error` are `undefined`. After a reconnect, `data` and `error` hold the last known values from the previous connection (stale-while-revalidate). * `loaded`: at least one notification has arrived. * `error`: the subscription failed; `data` holds the last known value (if any). * `disabled`: source was `null` β€” no subscription was opened. # SuccessfulSingleTransactionPlanResult (/api/type-aliases/SuccessfulSingleTransactionPlanResult) ```ts type SuccessfulSingleTransactionPlanResult = object; ``` A [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) with a 'successful' status. This type represents a single transaction that was successfully executed. It includes the original planned message and a context object. That context defaults to [TransactionPlanResultContextWithSignature](/api/type-aliases/TransactionPlanResultContextWithSignature) β€” a required transaction [Signature](/api/type-aliases/Signature), and optionally the [TransactionMessage](/api/type-aliases/TransactionMessage) and the full [Transaction](/api/type-aliases/Transaction) object β€” but a different `TContext` may drop the signature requirement entirely. You may use the [successfulSingleTransactionPlanResult](/api/functions/successfulSingleTransactionPlanResult) helper to create objects of this type. ## Example Creating a successful result from a transaction message and signature. ```ts const result = successfulSingleTransactionPlanResult( transactionMessage, { signature }, ); result satisfies SuccessfulSingleTransactionPlanResult; result.context.signature; // The transaction signature. ``` ## See * [successfulSingleTransactionPlanResult](/api/functions/successfulSingleTransactionPlanResult) * [isSuccessfulSingleTransactionPlanResult](/api/functions/isSuccessfulSingleTransactionPlanResult) * [assertIsSuccessfulSingleTransactionPlanResult](/api/functions/assertIsSuccessfulSingleTransactionPlanResult) ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with the result. | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | The type of the transaction message. | ## Properties ### context ```ts context: Readonly; ``` *** ### kind ```ts kind: "single"; ``` *** ### plannedMessage ```ts plannedMessage: TTransactionMessage; ``` *** ### planType ```ts planType: "transactionPlanResult"; ``` *** ### status ```ts status: "successful"; ``` # SuccessfulTransactionPlanResult (/api/type-aliases/SuccessfulTransactionPlanResult) ```ts type SuccessfulTransactionPlanResult = TransactionPlanResult>; ``` A [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) where all single transaction results are successful. This type represents a transaction plan result tree where every [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) has a 'successful' status. It can be used to ensure that an entire execution completed without any failures or cancellations. Note: This is different from [SuccessfulSingleTransactionPlanResult](/api/type-aliases/SuccessfulSingleTransactionPlanResult) which represents a single successful transaction, whereas this type represents an entire plan result tree (which may contain parallel/sequential structures) where all leaf nodes are successful. ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | The type of the transaction message | ## See * [isSuccessfulTransactionPlanResult](/api/functions/isSuccessfulTransactionPlanResult) * [assertIsSuccessfulTransactionPlanResult](/api/functions/assertIsSuccessfulTransactionPlanResult) * [SuccessfulSingleTransactionPlanResult](/api/type-aliases/SuccessfulSingleTransactionPlanResult) # SysvarClock (/api/type-aliases/SysvarClock) ```ts type SysvarClock = Readonly<{ epoch: Epoch; epochStartTimestamp: UnixTimestamp; leaderScheduleEpoch: Epoch; slot: Slot; unixTimestamp: UnixTimestamp; }>; ``` Contains data on cluster time, including the current slot, epoch, and estimated wall-clock Unix timestamp. It is updated every slot. # SysvarEpochRewards (/api/type-aliases/SysvarEpochRewards) ```ts type SysvarEpochRewards = Readonly<{ active: boolean; distributedRewards: Lamports; distributionStartingBlockHeight: bigint; numPartitions: bigint; parentBlockhash: Blockhash; totalPoints: bigint; totalRewards: Lamports; }>; ``` Tracks whether the rewards period (including calculation and distribution) is in progress, as well as the details needed to resume distribution when starting from a snapshot during the rewards period. The sysvar is repopulated at the start of the first block of each epoch. Therefore, the sysvar contains data about the current epoch until a new epoch begins. # SysvarEpochSchedule (/api/type-aliases/SysvarEpochSchedule) ```ts type SysvarEpochSchedule = Readonly<{ firstNormalEpoch: Epoch; firstNormalSlot: Slot; leaderScheduleSlotOffset: bigint; slotsPerEpoch: bigint; warmup: boolean; }>; ``` Includes the number of slots per epoch, timing of leader schedule selection, and information about epoch warm-up time. # SysvarLastRestartSlot (/api/type-aliases/SysvarLastRestartSlot) ```ts type SysvarLastRestartSlot = Readonly<{ lastRestartSlot: Slot; }>; ``` Information about the last restart slot (hard fork). The `LastRestartSlot` sysvar provides access to the last restart slot kept in the bank fork for the slot on the fork that executes the current transaction. In case there was no fork it returns `0`. # SysvarRecentBlockhashes (/api/type-aliases/SysvarRecentBlockhashes) ```ts type SysvarRecentBlockhashes = Entry[]; ``` Information about recent blocks and their fee calculators. ## Deprecated Transaction fees should be determined with the GetFeeForMessageApi.getFeeForMessage RPC method. For additional context see the [Comprehensive Compute Fees proposal](https://docs.anza.xyz/proposals/comprehensive-compute-fees/). # SysvarRent (/api/type-aliases/SysvarRent) ```ts type SysvarRent = Readonly<{ burnPercent: number; exemptionThreshold: F64UnsafeSeeDocumentation; lamportsPerByteYear: Lamports; }>; ``` Configuration for network rent. # SysvarSlotHashes (/api/type-aliases/SysvarSlotHashes) ```ts type SysvarSlotHashes = Entry[]; ``` The most recent hashes of a slot's parent banks. # SysvarSlotHistory (/api/type-aliases/SysvarSlotHistory) ```ts type SysvarSlotHistory = object; ``` A bitvector of slots present over the last epoch. ## Properties ### bits ```ts bits: bigint[]; ``` A vector of 64-bit numbers which, when their bits are strung together, represent a record of non-skipped slots. The bit in position (slot % MAX\_ENTRIES) is 0 if the slot was skipped and 1 otherwise, valid only when the candidate slot is less than `nextSlot` and greater than or equal to `MAX_ENTRIES - nextSlot`. *** ### nextSlot ```ts nextSlot: Slot; ``` The number of the slot one newer than tracked by the bitvector # SysvarStakeHistory (/api/type-aliases/SysvarStakeHistory) ```ts type SysvarStakeHistory = Entry[]; ``` History of stake activations and de-activations. # TestnetUrl (/api/type-aliases/TestnetUrl) ```ts type TestnetUrl = string & object; ``` ## Type Declaration | Name | Type | | ---------- | ----------- | | `~cluster` | `"testnet"` | # TokenAmount (/api/type-aliases/TokenAmount) ```ts type TokenAmount = Readonly<{ amount: StringifiedBigInt; decimals: number; uiAmount: number | null; uiAmountString: StringifiedNumber; }>; ``` # TokenBalance (/api/type-aliases/TokenBalance) ```ts type TokenBalance = Readonly<{ accountIndex: number; mint: Address; owner?: Address; programId?: Address; uiTokenAmount: TokenAmount; }>; ``` # TracedInstruction (/api/type-aliases/TracedInstruction) ```ts type TracedInstruction = Readonly<{ trace: InstructionTrace; }> & ResolvedInstruction; ``` A [ResolvedInstruction](/api/type-aliases/ResolvedInstruction) carrying its location in the transaction as a `trace` property. Because a `TracedInstruction` is itself a [ResolvedInstruction](/api/type-aliases/ResolvedInstruction), it can be passed directly to the auto-generated `@solana-program/*` `identifyXInstruction` / `parseXInstruction` helpers, and to `isInstructionForProgram` from `@solana/instructions`. ## Type Parameters | Type Parameter | Default type | | ------------------------------------ | ------------ | | `TProgramAddress` *extends* `string` | `string` | ## Example ```ts import { isInstructionForProgram, isInstructionWithData } from '@solana/instructions'; import { TOKEN_PROGRAM_ADDRESS, identifyTokenInstruction } from '@solana-program/token'; for (const ix of walkInstructions({ compiledMessage, meta, loadedAddresses })) { if (isInstructionForProgram(ix, TOKEN_PROGRAM_ADDRESS) && isInstructionWithData(ix)) { // `ix.programAddress` is narrowed to TOKEN_PROGRAM_ADDRESS and `ix.data` is present. identifyTokenInstruction(ix); console.log(ix.trace.kind); } } ``` # TrackedDataResult (/api/type-aliases/TrackedDataResult) ```ts type TrackedDataResult = object; ``` Reactive state for tracked data managed by [useTrackedData](/api/functions/useTrackedData). Lifecycle: starts at `loading` (or `disabled` when the spec is `null`) and fires both the initial RPC request and the subscription on mount; transitions to `loaded` on the first value (from either source β€” the underlying store slot-dedupes so out-of-order arrivals never regress) or `error` on failure. `refresh()` re-runs the whole pair β€” while a refresh is in flight, `status` returns to `loading` and the stale `data` and/or `error` from the prior outcome remain populated (stale-while-revalidate). ## Type Parameters | Type Parameter | Description | | -------------- | --------------------------------------------------------------------------------- | | `T` | The unified item type held by the store, produced by the two mappers in the spec. | ## Properties ### data ```ts data: SolanaRpcResponse | undefined; ``` The latest value, slot-deduped across the initial RPC and the subscription, exactly as the underlying kit primitive emits it: a `SolanaRpcResponse` envelope (`{ context: { slot }, value }`). The primitive guarantees the envelope shape, so callers can read `data.value` and `data.context.slot` directly without a runtime check. `undefined` on the first load and while disabled. On `loading` after a prior outcome, on `error`, and on a subsequent refresh, holds the last received envelope so UIs can show stale data rather than flashing to blank. *** ### error ```ts error: unknown; ``` Error from either source, or `undefined`. Only the first error per connection window is captured (the underlying store drops subsequent errors until the next `refresh()` / connect). On `loading` after a prior `error`, holds the stale error so UIs can keep showing the failure context while the refresh is in flight. A subsequent `loaded` clears it. *** ### refresh ```ts refresh: (options?) => void; ``` Re-run both the initial RPC request and the subscription. By default each call mints a fresh signal from `getAbortSignal` (if configured) and threads it through the underlying store's `withSignal(signal).connect()`. Pass `{ abortSignal }` to override the configured factory for just this attempt. Pass `{ abortSignal: undefined }` to opt out of the factory entirely for this attempt and run with no caller-provided signal. Stable reference. Safe to put in `onClick` handlers or effect deps β€” typically wired up to a "Refresh" or "Retry" button. Calls `store.connect()` under the hood, so it always (re)runs the pair regardless of current status; the bridge transitions back through `loading` while preserving stale `data` and `error`. #### Parameters | Parameter | Type | | ---------------------- | --------------------------------------------------------------------------------------------- | | `options?` | \{ `abortSignal?`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); } | | `options.abortSignal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | #### Returns `void` *** ### status ```ts status: "disabled" | "error" | "loaded" | "loading"; ``` Lifecycle status as a discriminated string: * `loading`: an attempt is in progress. On the first attempt, `data` and `error` are `undefined`. After a refresh, `data` and `error` hold the last known values from the previous attempt (stale-while-revalidate). * `loaded`: a value has arrived from either source and `error` is `undefined`. * `error`: the attempt failed; `data` holds the last known value (if any). * `disabled`: spec was `null` β€” no work was started. # TrackedDataSpec (/api/type-aliases/TrackedDataSpec) ```ts type TrackedDataSpec = CreateReactiveStoreWithInitialValueAndSlotTrackingConfig; ``` React-local alias for the Kit primitive's config. Lets the call site name the input shape as `TrackedDataSpec` instead of the verbose `CreateReactiveStoreWithInitialValueAndSlotTrackingConfig<...>`. ## Type Parameters | Type Parameter | Description | | --------------- | --------------------------------------------------------------------------- | | `TInitialValue` | The value inside the initial RPC `SolanaRpcResponse` envelope. | | `TStreamValue` | The value inside subscription `SolanaRpcResponse` notifications. | | `TItem` | The unified item type produced by the two mappers and stored in the result. | # Transaction (/api/type-aliases/Transaction) ```ts type Transaction = Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }>; ``` # TransactionBlockhashLifetime (/api/type-aliases/TransactionBlockhashLifetime) ```ts type TransactionBlockhashLifetime = object; ``` A constraint which, when applied to a transaction, makes that transaction eligible to land on the network. The transaction will continue to be eligible to land until the network considers the `blockhash` to be expired. This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash is considered valid, or when the network switches to a fork where that blockhash is not present. ## Properties ### blockhash ```ts blockhash: Blockhash; ``` A recent blockhash observed by the transaction proposer. The transaction will be considered eligible to land until the network determines this blockhash to be too old, or has switched to a fork where it is not present. *** ### lastValidBlockHeight ```ts lastValidBlockHeight: Slot; ``` This is the block height beyond which the network will consider the blockhash to be too old to make a transaction eligible to land. # TransactionConfig (/api/type-aliases/TransactionConfig) ```ts type TransactionConfig = Readonly<{ computeUnitLimit: number | null; heapSize: number | null; loadedAccountsDataSizeLimit: number | null; priorityFee: Lamports | null; }>; ``` The compute budget a version 1 transaction message declares inline, in place of the `ComputeBudget` program instructions used by legacy and version 0 transaction messages. # TransactionDurableNonceLifetime (/api/type-aliases/TransactionDurableNonceLifetime) ```ts type TransactionDurableNonceLifetime = object; ``` A constraint which, when applied to a transaction, makes that transaction eligible to land on the network. The transaction will continue to be eligible to land until the network considers the `nonce` to have advanced. This can happen when the nonce account in which this nonce is found is destroyed, or the nonce value within changes. ## Properties ### nonce ```ts nonce: Nonce; ``` A value contained in the account with address `nonceAccountAddress` at the time the transaction was prepared. The transaction will be considered eligible to land until the nonce account ceases to exist or contain this value. *** ### nonceAccountAddress ```ts nonceAccountAddress: Address; ``` The account that contains the `nonce` value # TransactionError (/api/type-aliases/TransactionError) ```ts type TransactionError = | "AccountBorrowOutstanding" | "AccountInUse" | "AccountLoadedTwice" | "AccountNotFound" | "AddressLookupTableNotFound" | "AlreadyProcessed" | "BlockhashNotFound" | "CallChainTooDeep" | "ClusterMaintenance" | "InsufficientFundsForFee" | "InvalidAccountForFee" | "InvalidAccountIndex" | "InvalidAddressLookupTableData" | "InvalidAddressLookupTableIndex" | "InvalidAddressLookupTableOwner" | "InvalidLoadedAccountsDataSizeLimit" | "InvalidProgramForExecution" | "InvalidRentPayingAccount" | "InvalidWritableAccount" | "MaxLoadedAccountsDataSizeExceeded" | "MissingSignatureForFee" | "ProgramAccountNotFound" | "ResanitizationNeeded" | "SanitizeFailure" | "SignatureFailure" | "TooManyAccountLocks" | "UnbalancedTransaction" | "UnsupportedVersion" | "WouldExceedAccountDataBlockLimit" | "WouldExceedAccountDataTotalLimit" | "WouldExceedMaxAccountCostLimit" | "WouldExceedMaxBlockCostLimit" | "WouldExceedMaxVoteCostLimit" | { DuplicateInstruction: InstructionIndex; } | { InstructionError: [InstructionIndex, InstructionError]; } | { InsufficientFundsForRent: { account_index: AccountIndex; }; } | { ProgramExecutionTemporarilyRestricted: { account_index: AccountIndex; }; }; ``` # TransactionForAccounts (/api/type-aliases/TransactionForAccounts) ```ts type TransactionForAccounts = TMaxSupportedTransactionVersion extends void ? Readonly<{ meta: TransactionForAccountsMetaBase | null; transaction: Readonly<{ accountKeys: readonly TransactionParsedAccountLegacy[]; }> & TransactionWithSignatures; }> : Readonly<{ meta: TransactionForAccountsMetaBase | null; transaction: Readonly<{ accountKeys: readonly TransactionParsedAccountVersioned[]; }> & TransactionWithSignatures; version: TransactionVersion; }>; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------- | | `TMaxSupportedTransactionVersion` *extends* `TransactionVersion` \| `void` | # TransactionForFullBase58 (/api/type-aliases/TransactionForFullBase58) ```ts type TransactionForFullBase58 = TMaxSupportedTransactionVersion extends void ? Readonly<{ meta: | TransactionForFullMetaBase & TransactionForFullMetaInnerInstructionsUnparsed | null; transaction: Base58EncodedDataResponse; }> : Readonly<{ meta: | TransactionForFullMetaBase & TransactionForFullMetaInnerInstructionsUnparsed & TransactionForFullMetaLoadedAddresses | null; transaction: Base58EncodedDataResponse; version: TransactionVersion; }>; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------- | | `TMaxSupportedTransactionVersion` *extends* `TransactionVersion` \| `void` | # TransactionForFullBase64 (/api/type-aliases/TransactionForFullBase64) ```ts type TransactionForFullBase64 = TMaxSupportedTransactionVersion extends void ? Readonly<{ meta: | TransactionForFullMetaBase & TransactionForFullMetaInnerInstructionsUnparsed | null; transaction: Base64EncodedDataResponse; }> : Readonly<{ meta: | TransactionForFullMetaBase & TransactionForFullMetaInnerInstructionsUnparsed & TransactionForFullMetaLoadedAddresses | null; transaction: Base64EncodedDataResponse; version: TransactionVersion; }>; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------- | | `TMaxSupportedTransactionVersion` *extends* `TransactionVersion` \| `void` | # TransactionForFullJson (/api/type-aliases/TransactionForFullJson) ```ts type TransactionForFullJson = TMaxSupportedTransactionVersion extends void ? Readonly<{ meta: | TransactionForFullMetaBase & TransactionForFullMetaInnerInstructionsUnparsed | null; transaction: TransactionForFullTransactionJsonBase; }> : Readonly<{ meta: | TransactionForFullMetaBase & TransactionForFullMetaInnerInstructionsUnparsed & TransactionForFullMetaLoadedAddresses | null; transaction: TransactionForFullTransactionAddressTableLookups & TransactionForFullTransactionJsonBase; version: TransactionVersion; }>; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------- | | `TMaxSupportedTransactionVersion` *extends* `TransactionVersion` \| `void` | # TransactionForFullJsonParsed (/api/type-aliases/TransactionForFullJsonParsed) ```ts type TransactionForFullJsonParsed = TMaxSupportedTransactionVersion extends void ? Readonly<{ meta: | TransactionForFullMetaBase & TransactionForFullMetaInnerInstructionsParsed | null; transaction: TransactionForFullTransactionJsonParsedBase & object; }> : Readonly<{ meta: | TransactionForFullMetaBase & TransactionForFullMetaInnerInstructionsParsed & TransactionForFullMetaLoadedAddresses | null; transaction: TransactionForFullTransactionJsonParsedBase & object; version: TransactionVersion; }>; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------- | | `TMaxSupportedTransactionVersion` *extends* `TransactionVersion` \| `void` | # TransactionForFullMetaInnerInstructionsParsed (/api/type-aliases/TransactionForFullMetaInnerInstructionsParsed) ```ts type TransactionForFullMetaInnerInstructionsParsed = Readonly<{ innerInstructions: readonly Readonly<{ index: number; instructions: readonly (ParsedTransactionInstruction | PartiallyDecodedTransactionInstruction)[]; }>[]; }>; ``` # TransactionForFullMetaInnerInstructionsUnparsed (/api/type-aliases/TransactionForFullMetaInnerInstructionsUnparsed) ```ts type TransactionForFullMetaInnerInstructionsUnparsed = Readonly<{ innerInstructions: readonly Readonly<{ index: number; instructions: readonly TransactionInstruction[]; }>[]; }>; ``` # TransactionFromTransactionMessage (/api/type-aliases/TransactionFromTransactionMessage) ```ts type TransactionFromTransactionMessage = SetTransactionWithinSizeLimitFromTransactionMessage, TTransactionMessage>; ``` Helper type that creates a `Transaction` type as narrow as possible from the provided `TransactionMessage` type. ## Type Parameters | Type Parameter | | ---------------------------------------------------- | | `TTransactionMessage` *extends* `TransactionMessage` | # TransactionMessage (/api/type-aliases/TransactionMessage) ```ts type TransactionMessage = LegacyTransactionMessage | V0TransactionMessage | V1TransactionMessage; ``` # TransactionMessageBytes (/api/type-aliases/TransactionMessageBytes) ```ts type TransactionMessageBytes = Brand; ``` # TransactionMessageBytesBase64 (/api/type-aliases/TransactionMessageBytesBase64) ```ts type TransactionMessageBytesBase64 = Brand, "TransactionMessageBytesBase64">; ``` # TransactionMessageWithLifetime (/api/type-aliases/TransactionMessageWithLifetime) ```ts type TransactionMessageWithLifetime = | TransactionMessageWithBlockhashLifetime | TransactionMessageWithDurableNonceLifetime; ``` A transaction message with any valid lifetime constraint. # TransactionMessageWithSigners (/api/type-aliases/TransactionMessageWithSigners) ```ts type TransactionMessageWithSigners = Partial | TransactionMessageWithNonSignerFeePayer, "feePayer">> & Readonly<{ instructions: readonly Instruction & InstructionWithSigners[]; }>; ``` A TransactionMessage type extension that accept [TransactionSigners](/api/type-aliases/TransactionSigner). Namely, it allows: * a [TransactionSigner](/api/type-aliases/TransactionSigner) to be used as the fee payer and * [InstructionWithSigners](/api/interfaces/InstructionWithSigners) to be used in its instructions. ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | | `TSigner` *extends* [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TAddress`> | [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TAddress`> | Optionally provide a narrower type for [TransactionSigners](/api/type-aliases/TransactionSigner). | | `TAccounts` *extends* readonly `AccountMetaWithSigner`\<`TSigner`>\[] | readonly `AccountMetaWithSigner`\<`TSigner`>\[] | Optionally provide a narrower type for the account metas. | ## Example ```ts import { Instruction } from '@solana/instructions'; import { TransactionMessage } from '@solana/transaction-messages'; import { generateKeyPairSigner, InstructionWithSigners, TransactionMessageWithSigners } from '@solana/signers'; const signer = await generateKeyPairSigner(); const firstInstruction: Instruction = { ... }; const secondInstruction: InstructionWithSigners = { ... }; const transactionMessage: TransactionMessage & TransactionMessageWithSigners = { feePayer: signer, instructions: [firstInstruction, secondInstruction], } ``` # TransactionMessageWithSingleSendingSigner (/api/type-aliases/TransactionMessageWithSingleSendingSigner) ```ts type TransactionMessageWithSingleSendingSigner = Brand; ``` Defines a transaction message with exactly one [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner). This type is used to narrow the type of transaction messages that have been checked to have exactly one sending signer. ## Example ```ts import { assertIsTransactionMessageWithSingleSendingSigner } from '@solana/signers'; assertIsTransactionMessageWithSingleSendingSigner(transactionMessage); transactionMessage satisfies TransactionMessageWithSingleSendingSigner; ``` ## See * [isTransactionMessageWithSingleSendingSigner](/api/functions/isTransactionMessageWithSingleSendingSigner) * [assertIsTransactionMessageWithSingleSendingSigner](/api/functions/assertIsTransactionMessageWithSingleSendingSigner) # TransactionMessageWithinSizeLimit (/api/type-aliases/TransactionMessageWithinSizeLimit) ```ts type TransactionMessageWithinSizeLimit = NominalType<"transactionSize", "withinLimit">; ``` A type guard that checks if a transaction message is within the size limit when compiled into a transaction. # TransactionModifyingSigner (/api/type-aliases/TransactionModifyingSigner) ```ts type TransactionModifyingSigner = Readonly<{ address: Address; modifyAndSignTransactions: Promise & TransactionWithinSizeLimit & TransactionWithLifetime[]>; }>; ``` A signer interface that potentially modifies the provided Transaction | Transactions before signing them. For instance, this enables wallets to inject additional instructions into the transaction before signing them. For each transaction, instead of returning a [SignatureDictionary](/api/type-aliases/SignatureDictionary), its TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions function returns an updated Transaction with a potentially modified set of instructions and signature dictionary. The returned transaction must be within the transaction size limit, and include a `lifetimeConstraint`. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ----------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define a signer having a particular address. | ## Example ```ts const signer: TransactionModifyingSigner<'1234..5678'> = { address: address('1234..5678'), modifyAndSignTransactions: async ( transactions: Transaction[] ): Promise<(Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[]> => { // My custom signing logic. }, }; ``` ## Remarks Here are the main characteristics of this signer interface: * **Sequential**. Contrary to partial signers, these cannot be executed in parallel as each call can modify the provided transactions. * **First signers**. For a given transaction, a modifying signer must always be used before a partial signer as the former will likely modify the transaction and thus impact the outcome of the latter. * **Potential conflicts**. If more than one modifying signer is provided, the second signer may invalidate the signature of the first one. However, modifying signers may decide not to modify a transaction based on the existence of signatures for that transaction. ## See * [isTransactionModifyingSigner](/api/functions/isTransactionModifyingSigner) * [assertIsTransactionModifyingSigner](/api/functions/assertIsTransactionModifyingSigner) # TransactionModifyingSignerConfig (/api/type-aliases/TransactionModifyingSignerConfig) ```ts type TransactionModifyingSignerConfig = BaseTransactionSignerConfig; ``` The configuration to optionally provide when calling the TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions method. ## See [BaseTransactionSignerConfig](/api/interfaces/BaseTransactionSignerConfig) # TransactionPartialSigner (/api/type-aliases/TransactionPartialSigner) ```ts type TransactionPartialSigner = Readonly<{ address: Address; signTransactions: Promise>[]>; }>; ``` A signer interface that signs an array of Transaction | Transactions without modifying their content. It defines a TransactionPartialSigner#signTransactions | signTransactions function that returns a [SignatureDictionary](/api/type-aliases/SignatureDictionary) for each provided transaction. Such signature dictionaries are expected to be merged with the existing ones if any. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ----------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define a signer having a particular address. | ## Example ```ts const signer: TransactionPartialSigner<'1234..5678'> = { address: address('1234..5678'), signTransactions: async ( transactions: Transaction[] ): Promise => { // My custom signing logic. }, }; ``` ## Remarks Here are the main characteristics of this signer interface: * **Parallel**. It returns a signature dictionary for each provided transaction without modifying them, making it possible for multiple partial signers to sign the same transaction in parallel. * **Flexible order**. The order in which we use these signers for a given transaction doesn’t matter. ## See * [isTransactionPartialSigner](/api/functions/isTransactionPartialSigner) * [assertIsTransactionPartialSigner](/api/functions/assertIsTransactionPartialSigner) # TransactionPartialSignerConfig (/api/type-aliases/TransactionPartialSignerConfig) ```ts type TransactionPartialSignerConfig = BaseTransactionSignerConfig; ``` The configuration to optionally provide when calling the TransactionPartialSigner#signTransactions | signTransactions method. ## See [BaseTransactionSignerConfig](/api/interfaces/BaseTransactionSignerConfig) # TransactionPlan (/api/type-aliases/TransactionPlan) ```ts type TransactionPlan = | ParallelTransactionPlan | SequentialTransactionPlan | SingleTransactionPlan; ``` A set of transaction messages with constraints on how they can be executed. This is structured as a recursive tree of plans to allow for parallel execution, sequential execution and combinations of both. Namely, the following plans are supported: * [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan) - A plan that contains a single transaction message. This is the simplest leaf in this tree. * [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan) - A plan that contains other plans that can be executed in parallel. * [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) - A plan that contains other plans that must be executed sequentially. It also defines whether the plan is divisible meaning that transaction messages inside it can be split into separate batches. Helpers are provided for each of these plans to make it easier to create them. ## Example ```ts const myTransactionPlan: TransactionPlan = parallelTransactionPlan([ sequentialTransactionPlan([messageA, messageB]), messageC, ]); ``` ## See * [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan) * [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan) * [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) # TransactionPlanExecutor (/api/type-aliases/TransactionPlanExecutor) ```ts type TransactionPlanExecutor = (transactionPlan, config?) => Promise>; ``` Executes a transaction plan and returns the execution results. This function traverses the transaction plan tree, executing each transaction message and collecting results that mirror the structure of the original plan. The zero-argument spelling defaults `TContext` to [TransactionPlanResultContextWithSignature](/api/type-aliases/TransactionPlanResultContextWithSignature), so its results guarantee a `context.signature` on every successful single result β€” but a different `TContext` may drop that guarantee entirely. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results. | ## Parameters | Parameter | Type | Description | | --------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | `transactionPlan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to execute. | | `config?` | \{ `abortSignal?`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); } | Optional configuration object that can include an `AbortSignal` to cancel execution. | | `config.abortSignal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | - | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`>> A promise that resolves to the execution results. ## See * [TransactionPlan](/api/type-aliases/TransactionPlan) * [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) * [createTransactionPlanExecutor](/api/functions/createTransactionPlanExecutor) # TransactionPlanExecutorConfig (/api/type-aliases/TransactionPlanExecutorConfig) ```ts type TransactionPlanExecutorConfig = object; ``` Configuration object for creating a new transaction plan executor. ## See * [createTransactionPlanExecutor](/api/functions/createTransactionPlanExecutor) * [createTransactionPlanExecutorWithConcurrentLeaves](/api/functions/createTransactionPlanExecutorWithConcurrentLeaves) ## Type Parameters | Type Parameter | Default type | | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | ## Properties ### executeTransactionMessage ```ts executeTransactionMessage: ExecuteTransactionMessage; ``` Called whenever a transaction message must be executed. It should return the context that the successful result must carry β€” every property `TContext` promises, which by default includes a `signature`. # TransactionPlanInput (/api/type-aliases/TransactionPlanInput) ```ts type TransactionPlanInput = | SingleTransactionPlan["message"] | TransactionPlan | readonly ( | SingleTransactionPlan["message"] | TransactionPlan)[]; ``` A flexible input type that can be used to create a [TransactionPlan](/api/type-aliases/TransactionPlan). This type accepts: * A single [TransactionMessage](/api/type-aliases/TransactionMessage) with a fee payer. * An existing [TransactionPlan](/api/type-aliases/TransactionPlan). * An array of transaction messages and/or transaction plans. Use the [parseTransactionPlanInput](/api/functions/parseTransactionPlanInput) function to convert this input into a proper [TransactionPlan](/api/type-aliases/TransactionPlan). ## Examples Using a single transaction message. ```ts const input: TransactionPlanInput = myTransactionMessage; ``` Use as argument type in a function that will parse it into a TransactionPlan. ```ts function myFunction(input: TransactionPlanInput) { const plan = parseTransactionPlanInput(input); // Use the plan... } ``` ## See * [parseTransactionPlanInput](/api/functions/parseTransactionPlanInput) * [TransactionPlan](/api/type-aliases/TransactionPlan) # TransactionPlanResult (/api/type-aliases/TransactionPlanResult) ```ts type TransactionPlanResult = | ParallelTransactionPlanResult | SequentialTransactionPlanResult | TSingle; ``` The result of executing a transaction plan. This is structured as a recursive tree of results that mirrors the structure of the original transaction plan, capturing the execution status at each level. Namely, the following result types are supported: * [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) - A result for a single transaction message containing its execution status. * [ParallelTransactionPlanResult](/api/type-aliases/ParallelTransactionPlanResult) - A result containing other results that were executed in parallel. * [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) - A result containing other results that were executed sequentially. It also retains the divisibility property from the original plan. ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | The type of the transaction message | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The type of single transaction plan results in this tree | ## See * [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) * [ParallelTransactionPlanResult](/api/type-aliases/ParallelTransactionPlanResult) * [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) # TransactionPlanResultContext (/api/type-aliases/TransactionPlanResultContext) ```ts type TransactionPlanResultContext = object; ``` The context object associated with a [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). This type defines the shape of custom context that can be attached to transaction plan results. It allows arbitrary additional properties that consumers can use to pass along extra data with their results. Note that base context fields such as `message`, `signature`, and `transaction` are not part of this type. They come from the context a result is parameterised with, which defaults to [TransactionPlanResultContextWithSignature](/api/type-aliases/TransactionPlanResultContextWithSignature). Supply a different context to change or drop those guarantees. ## Index Signature ```ts [key: string | number | symbol]: unknown ``` ## See * [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) * [SuccessfulSingleTransactionPlanResult](/api/type-aliases/SuccessfulSingleTransactionPlanResult) * [FailedSingleTransactionPlanResult](/api/type-aliases/FailedSingleTransactionPlanResult) * [CanceledSingleTransactionPlanResult](/api/type-aliases/CanceledSingleTransactionPlanResult) * [TransactionPlanResultContextWithSignature](/api/type-aliases/TransactionPlanResultContextWithSignature) # TransactionPlanResultContextWithSignature (/api/type-aliases/TransactionPlanResultContextWithSignature) ```ts type TransactionPlanResultContextWithSignature = TransactionPlanResultContext & object; ``` A [TransactionPlanResultContext](/api/type-aliases/TransactionPlanResultContext) that is guaranteed to include a [Signature](/api/type-aliases/Signature). This is the default context for every transaction plan result type, which is why a successful result exposes a required `context.signature` unless a different context is supplied. ## Type Declaration | Name | Type | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `message?` | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | | `signature` | [`Signature`](/api/type-aliases/Signature) | | `transaction?` | [`Transaction`](/api/type-aliases/Transaction) | ## Example Intersect this type into a custom context to keep the signature guarantee alongside your own properties. ```ts const executor = createTransactionPlanExecutor< TransactionPlanResultContextWithSignature & { startedAt: number } >({ executeTransactionMessage: async (context, message) => { const startedAt = Date.now(); context.startedAt = startedAt; const signature = await sendAndConfirm(message); return { signature, startedAt }; }, }); ``` ## See [TransactionPlanResultContext](/api/type-aliases/TransactionPlanResultContext) # TransactionPlanResultSummary (/api/type-aliases/TransactionPlanResultSummary) ```ts type TransactionPlanResultSummary = Readonly<{ canceledTransactions: CanceledSingleTransactionPlanResult[]; failedTransactions: FailedSingleTransactionPlanResult[]; successful: boolean; successfulTransactions: SuccessfulSingleTransactionPlanResult[]; }>; ``` A summary of a [TransactionPlanResult](/api/type-aliases/TransactionPlanResult), categorizing transactions by their execution status. * `successful`: Indicates whether all transactions were successful (i.e., no failed or canceled transactions). * `successfulTransactions`: An array of successful transactions, each including its signature. * `failedTransactions`: An array of failed transactions, each including the error that caused the failure. * `canceledTransactions`: An array of canceled transactions. ## Type Parameters | Type Parameter | Default type | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer) | # TransactionPlanner (/api/type-aliases/TransactionPlanner) ```ts type TransactionPlanner = (instructionPlan, config?) => Promise; ``` Plans one or more transactions according to the provided instruction plan. ## Parameters | Parameter | Type | Description | | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `instructionPlan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to be planned and executed. | | `config?` | \{ `abortSignal?`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); `maxInstructionsPerTransaction?`: `number`; } | Optional configuration object for the planning process. | | `config.abortSignal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | - | | `config.maxInstructionsPerTransaction?` | `number` | Maximum number of instructions allowed in each planned transaction. Must be a positive integer no greater than `64` β€” the number of top-level instructions the transaction format can encode. Larger values throw [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_INVALID\_MAX\_INSTRUCTIONS\_PER\_TRANSACTION](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION). Defaults to 16. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`TransactionPlan`](/api/type-aliases/TransactionPlan)> ## See * [InstructionPlan](/api/type-aliases/InstructionPlan) * [TransactionPlan](/api/type-aliases/TransactionPlan) # TransactionPlannerConfig (/api/type-aliases/TransactionPlannerConfig) ```ts type TransactionPlannerConfig = object; ``` Configuration object for creating a new transaction planner. ## See [createTransactionPlanner](/api/functions/createTransactionPlanner) ## Properties ### createTransactionMessage ```ts createTransactionMessage: CreateTransactionMessage; ``` Called whenever a new transaction message is needed. *** ### maxInstructionsPerTransaction? ```ts optional maxInstructionsPerTransaction?: number; ``` Maximum number of instructions allowed in each planned transaction. This includes any instructions already present in messages returned by `createTransactionMessage` and any instructions added by `onTransactionMessageUpdated`. Must be a positive integer no greater than `64` β€” the number of top-level instructions the transaction format can encode. Larger values throw [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_INVALID\_MAX\_INSTRUCTIONS\_PER\_TRANSACTION](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION). Defaults to 16. *** ### onTransactionMessageUpdated? ```ts optional onTransactionMessageUpdated?: OnTransactionMessageUpdated; ``` Called whenever a transaction message is updated β€” e.g. new instructions were added. This function must return the updated transaction message back β€” even if no changes were made. # TransactionSendingSigner (/api/type-aliases/TransactionSendingSigner) ```ts type TransactionSendingSigner = Readonly<{ address: Address; signAndSendTransactions: Promise; }>; ``` A signer interface that signs one or multiple transactions before sending them immediately to the blockchain. It defines a TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions function that returns the transaction signature (i.e. its identifier) for each provided Transaction. This interface is required for PDA wallets and other types of wallets that don't provide an interface for signing transactions without sending them. Note that it is also possible for such signers to modify the provided transactions before signing and sending them. This enables use cases where the modified transactions cannot be shared with the app and thus must be sent directly. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ----------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define a signer having a particular address. | ## Example ```ts const myTransactionSendingSigner: TransactionSendingSigner<'1234..5678'> = { address: address('1234..5678'), signAndSendTransactions: async (transactions: Transaction[]): Promise => { // My custom signing logic. }, }; ``` ## Remarks Here are the main characteristics of this signer interface: * **Single signer**. Since this signer also sends the provided transactions, we can only use a single TransactionSendingSigner for a given set of transactions. * **Last signer**. Trivially, that signer must also be the last one used. * **Potential conflicts**. Since signers may decide to modify the given transactions before sending them, they may invalidate previous signatures. However, signers may decide not to modify a transaction based on the existence of signatures for that transaction. * **Potential confirmation**. Whilst this is not required by this interface, it is also worth noting that most wallets will also wait for the transaction to be confirmed (typically with a `confirmed` commitment) before notifying the app that they are done. ## See * [isTransactionSendingSigner](/api/functions/isTransactionSendingSigner) * [assertIsTransactionSendingSigner](/api/functions/assertIsTransactionSendingSigner) # TransactionSendingSignerConfig (/api/type-aliases/TransactionSendingSignerConfig) ```ts type TransactionSendingSignerConfig = BaseTransactionSignerConfig; ``` The configuration to optionally provide when calling the TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions method. ## See [BaseTransactionSignerConfig](/api/interfaces/BaseTransactionSignerConfig) # TransactionSigner (/api/type-aliases/TransactionSigner) ```ts type TransactionSigner = | TransactionModifyingSigner | TransactionPartialSigner | TransactionSendingSigner; ``` Defines a signer capable of signing transactions. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## See * [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) For signers that can modify transactions before signing them. * [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner) For signers that can be used in parallel. * [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) For signers that send transactions after signing them. * [isTransactionSigner](/api/functions/isTransactionSigner) * [assertIsTransactionSigner](/api/functions/assertIsTransactionSigner) # TransactionStatus (/api/type-aliases/TransactionStatus) ```ts type TransactionStatus = | { Err: TransactionError; } | { Ok: null; }; ``` ## Deprecated # TransactionVersion (/api/type-aliases/TransactionVersion) ```ts type TransactionVersion = "legacy" | 0 | 1; ``` # TransactionWithBlockhashLifetime (/api/type-aliases/TransactionWithBlockhashLifetime) ```ts type TransactionWithBlockhashLifetime = object; ``` A transaction whose lifetime is determined by the age of a blockhash observed on the network. The transaction will continue to be eligible to land until the network considers the `blockhash` to be expired. ## Properties ### lifetimeConstraint ```ts readonly lifetimeConstraint: TransactionBlockhashLifetime; ``` # TransactionWithDurableNonceLifetime (/api/type-aliases/TransactionWithDurableNonceLifetime) ```ts type TransactionWithDurableNonceLifetime = object; ``` A transaction whose lifetime is determined by a nonce. The transaction will continue to be eligible to land until the network considers the `nonce` to have advanced. This can happen when the nonce account in which this nonce is found is destroyed, or the nonce value within changes. ## Properties ### lifetimeConstraint ```ts readonly lifetimeConstraint: TransactionDurableNonceLifetime; ``` # TransactionWithLastValidBlockHeight (/api/type-aliases/TransactionWithLastValidBlockHeight) ```ts type TransactionWithLastValidBlockHeight = Omit & object; ``` ## Type Declaration | Name | Type | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `lifetimeConstraint` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`TransactionWithBlockhashLifetime`\[`"lifetimeConstraint"`], `"blockhash"`> | # TransactionWithLifetime (/api/type-aliases/TransactionWithLifetime) ```ts type TransactionWithLifetime = object; ``` A transaction whose ability to land on the network is determined by some evanescent criteria. This describes a window of time after which a transaction is constructed and before which it will no longer be accepted by the network. No transaction can land on Solana without having a `lifetimeConstraint` set. ## Properties ### lifetimeConstraint ```ts readonly lifetimeConstraint: | TransactionBlockhashLifetime | TransactionDurableNonceLifetime; ``` # TransactionWithinSizeLimit (/api/type-aliases/TransactionWithinSizeLimit) ```ts type TransactionWithinSizeLimit = NominalType<"transactionSize", "withinLimit">; ``` A type guard that checks if a transaction is within the size limit. # TraversalState (/api/type-aliases/TraversalState) ```ts type TraversalState = Readonly<{ keyPath: KeyPath; }>; ``` # TupleCodecConfig (/api/type-aliases/TupleCodecConfig) ```ts type TupleCodecConfig = object; ``` Defines the configuration options for tuple codecs. ## Properties ### description? ```ts optional description?: string; ``` An optional description for the codec, that will be used in error messages. # UnionToIntersection (/api/type-aliases/UnionToIntersection) ```ts type UnionToIntersection = T extends unknown ? (x) => unknown : never extends (x) => unknown ? R : never; ``` ## Type Parameters | Type Parameter | | -------------- | | `T` | # UnixTimestamp (/api/type-aliases/UnixTimestamp) ```ts type UnixTimestamp = Brand; ``` This type represents a Unix timestamp in *seconds*. It is represented as a `bigint` in client code and an `i64` in server code. # UnwrapRpcResponse (/api/type-aliases/UnwrapRpcResponse) ```ts type UnwrapRpcResponse = T extends SolanaRpcResponse ? U : T; ``` Unwraps `SolanaRpcResponse` β†’ `U` at the type level so callers can surface the inner value without losing static type information. Values that are not wrapped in a `SolanaRpcResponse` envelope pass through unchanged. Pairs with [isSolanaRpcResponse](/api/functions/isSolanaRpcResponse) for runtime detection. ## Type Parameters | Type Parameter | Description | | -------------- | --------------------------- | | `T` | The raw notification shape. | ## Example ```ts type AccountValue = UnwrapRpcResponse>; // ^? { lamports: bigint } type AccountValue = UnwrapRpcResponse<{ lamports: bigint }>; // ^? { lamports: bigint } ``` # UnwrappedOption (/api/type-aliases/UnwrappedOption) ```ts type UnwrappedOption = T extends Some ? UnwrappedOption : T extends None ? U : T extends UnUnwrappables ? T : T extends object ? { [key in keyof T]: UnwrappedOption } : T extends infer TItem[] ? UnwrappedOption[] : T; ``` A type that recursively unwraps nested [Option](/api/type-aliases/Option) types. This type resolves all nested [Option](/api/type-aliases/Option) values, ensuring that deeply wrapped values are properly extracted. * If `T` is an [Option](/api/type-aliases/Option), it resolves to the contained value. * If `T` is a known primitive or immutable type, it remains unchanged. * If `T` is an object or array, it recursively unwraps any options found. The fallback type `U` (default: `null`) is used in place of `None` values. ## Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | --------------------------------------------------------- | | `T` | - | The type to be unwrapped. | | `U` | `null` | The fallback type for `None` values (defaults to `null`). | ## Examples Resolving nested `Option` types. ```ts UnwrappedOption>>; // string UnwrappedOption; // null ``` Resolving options inside objects and arrays. ```ts UnwrappedOption<{ a: Some; b: None }>; // { a: number; b: null } UnwrappedOption<[Some, None]>; // [number, null] ``` ## See [unwrapOptionRecursively](/api/functions/unwrapOptionRecursively) # UseClientCapabilityConfig (/api/type-aliases/UseClientCapabilityConfig) ```ts type UseClientCapabilityConfig = Readonly<{ capability: string | readonly string[]; hookName: string; providerHint: string; }>; ``` Configuration for [useClientCapability](/api/functions/useClientCapability). # UseRequestOptions (/api/type-aliases/UseRequestOptions) ```ts type UseRequestOptions = object; ``` Options accepted by [useRequest](/api/functions/useRequest). ## Properties ### getAbortSignal? ```ts optional getAbortSignal?: () => AbortSignal; ``` Factory invoked on every attempt (initial fire + every `refresh()`). The returned signal is attached to that attempt via the underlying store's `withSignal(signal).dispatch()`, so aborting it cancels just the current attempt. The most common use is per-attempt timeouts: `getAbortSignal: () => AbortSignal.timeout(5000)` gives every attempt its own 5-second clock that resets on `refresh()`. Held in a ref synced to the latest render's closure β€” there is no need to memoize an inline factory. #### Returns [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) # UseSubscriptionOptions (/api/type-aliases/UseSubscriptionOptions) ```ts type UseSubscriptionOptions = object; ``` Options accepted by [useSubscription](/api/functions/useSubscription). ## Properties ### getAbortSignal? ```ts optional getAbortSignal?: () => AbortSignal; ``` Factory invoked on every connection (initial subscribe + every `reconnect()`). The returned signal is attached to that connection via the underlying store's `withSignal(signal).connect()`, so aborting it tears down that connection. The most common use is per-connection timeouts: `getAbortSignal: () => AbortSignal.timeout(30_000)` gives every connection its own 30-second clock that resets on `reconnect()`. Held in a ref synced to the latest render's closure β€” there is no need to memoize an inline factory. #### Returns [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) # UseTrackedDataOptions (/api/type-aliases/UseTrackedDataOptions) ```ts type UseTrackedDataOptions = object; ``` Options accepted by [useTrackedData](/api/functions/useTrackedData). ## Properties ### getAbortSignal? ```ts optional getAbortSignal?: () => AbortSignal; ``` Factory invoked on every attempt (initial run + every `refresh()`). The returned signal is attached to that attempt via the underlying store's `withSignal(signal).connect()`, so aborting it tears down both the in-flight RPC request and the subscription for that attempt. The most common use is per-attempt timeouts: `getAbortSignal: () => AbortSignal.timeout(30_000)` gives every attempt its own 30-second clock that resets on `refresh()`. Held in a ref synced to the latest render's closure β€” there is no need to memoize an inline factory. #### Returns [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) # V0CompiledTransactionMessage (/api/type-aliases/V0CompiledTransactionMessage) ```ts type V0CompiledTransactionMessage = Readonly<{ addressTableLookups?: ReturnType; header: ReturnType; instructions: ReturnType; staticAccounts: Address[]; version: 0; }>; ``` # V1CompiledTransactionMessage (/api/type-aliases/V1CompiledTransactionMessage) ```ts type V1CompiledTransactionMessage = Readonly<{ configMask: number; configValues: ReturnType; header: ReturnType; instructionHeaders: ReturnType[]; instructionPayloads: ReturnType[]; numInstructions: number; numStaticAccounts: number; staticAccounts: Address[]; version: 1; }>; ``` # V1TransactionConfig (/api/type-aliases/V1TransactionConfig) ```ts type V1TransactionConfig = object; ``` Configuration options for transaction messages. These options allow fine-grained control over transaction resource usage and prioritization. All fields are optional and will be encoded into the transaction when present. ## Properties ### computeUnitLimit? ```ts optional computeUnitLimit?: number; ``` Maximum number of compute units the transaction may consume. Unlike legacy and version 0 transactions, which fall back to 200,000 compute units per instruction when no `SetComputeUnitLimit` instruction is present, a version 1 transaction that leaves this field unset is budgeted **zero** compute units and will fail at execution. Set it explicitly on every version 1 transaction. The maximum allowed value is 1,400,000 CUs. *** ### heapSize? ```ts optional heapSize?: number; ``` Requested heap frame size in bytes for the transaction's execution. *** ### loadedAccountsDataSizeLimit? ```ts optional loadedAccountsDataSizeLimit?: number; ``` Maximum size in bytes for loaded account data. As with [V1TransactionConfig.computeUnitLimit](#computeunitlimit), leaving this field unset budgets **zero** bytes rather than applying a default, so any transaction that loads account data must set it explicitly. *** ### priorityFeeLamports? ```ts optional priorityFeeLamports?: bigint; ``` Total priority fee in lamports to pay for transaction prioritization. Unlike legacy and version 0 transactions, where the priority fee is derived from a price per compute unit, this is the total fee paid for the whole transaction. If not specified, no priority fee is paid. # VoteNotificationsApi (/api/type-aliases/VoteNotificationsApi) ```ts type VoteNotificationsApi = object; ``` ## Methods ### voteNotifications() ```ts voteNotifications(): VoteNotificationsApiNotification; ``` Subscribe to receive notifications anytime a new vote is observed in gossip. These votes are pre-consensus therefore there is no guarantee these votes will enter the ledger. This subscription is unstable and only available if the validator was started with the `--rpc-pubsub-enable-vote-subscription` flag. The format of this subscription may change in the future. #### Returns `VoteNotificationsApiNotification` #### See [https://solana.com/docs/rpc/websocket/votesubscribe](https://solana.com/docs/rpc/websocket/votesubscribe) # WritableAccount (/api/type-aliases/WritableAccount) ```ts type WritableAccount = AccountMeta & object; ``` ## Type Declaration | Name | Type | | ------ | ----------------------------------------------------------------------- | | `role` | [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) | ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## See [AccountMeta](/api/interfaces/AccountMeta) # WritableAccountLookup (/api/type-aliases/WritableAccountLookup) ```ts type WritableAccountLookup = AccountLookupMeta & object; ``` ## Type Declaration | Name | Type | | ------ | ----------------------------------------------------------------------- | | `role` | [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) | ## Type Parameters | Type Parameter | Default type | | ---------------------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | | `TLookupTableAddress` *extends* `string` | `string` | ## See [AccountLookupMeta](/api/interfaces/AccountLookupMeta) # WritableSignerAccount (/api/type-aliases/WritableSignerAccount) ```ts type WritableSignerAccount = AccountMeta & object; ``` ## Type Declaration | Name | Type | | ------ | ------------------------------------------------------------------------------------- | | `role` | [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) | ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## See [AccountMeta](/api/interfaces/AccountMeta) # WriteKeyPairConfig (/api/type-aliases/WriteKeyPairConfig) ```ts type WriteKeyPairConfig = Readonly<{ unsafelyOverwriteExistingKeyPair?: boolean; }>; ``` Configuration options for writeKeyPair and [writeKeyPairSigner](/api/functions/writeKeyPairSigner). # ClientProvider (/api/functions/ClientProvider) ```ts function ClientProvider(__namedParameters): ReactElement; ``` Publishes a caller-owned Kit client to its subtree. Required for `useClient`, `useClientCapability`, and any plugin-specific hook that depends on a client capability. Plugin composition belongs in plain Kit β€” the provider does no composition, lifecycle management, or disposal; it is a value channel, not a lifecycle channel. When config changes at runtime (e.g. cluster toggle), rebuild the client in `useMemo` and pass the new reference; the subtree resubscribes against the new client identity. Async client support: when `client` is a promise (e.g. `createClient().use(asyncPlugin())`), the provider suspends the subtree via the nearest `` boundary until the promise resolves. On React 19 this delegates to `React.use(promise)`; on React 18 a thrown-promise shim keyed by promise identity preserves the same contract. ## Parameters | Parameter | Type | | ------------------- | -------------------------------------------------------------- | | `__namedParameters` | [`ClientProviderProps`](/api/type-aliases/ClientProviderProps) | ## Returns `ReactElement` ## Examples **Sync client** ```tsx import { createClient } from '@solana/kit'; import { ClientProvider } from '@solana/react'; const client = createClient(); // .use(...) plugins as needed function App() { return ( ); } ``` **Async client (Suspense)** ```tsx const clientPromise = useMemo( () => createClient().use(someAsyncPlugin()), [], ); }> ``` ## See [useClient](/api/functions/useClient) # SelectedWalletAccountContextProvider (/api/functions/SelectedWalletAccountContextProvider) ```ts function SelectedWalletAccountContextProvider(children): Element; ``` Saves the selected wallet account's storage key to a persistant storage. In future sessions it will try to return that same wallet account, or at least one from the same brand of wallet if the wallet from which it came is still in the Wallet Standard registry. ## Parameters | Parameter | Type | Description | | ---------- | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | `children` | [`SelectedWalletAccountContextProviderProps`](/api/type-aliases/SelectedWalletAccountContextProviderProps) | The child components that will have access to the selected wallet account context | ## Returns `Element` A React component that provides the selected wallet account context to its children # absoluteBinaryFixedPoint (/api/functions/absoluteBinaryFixedPoint) ```ts function absoluteBinaryFixedPoint< TSignedness, TTotalBits, TFractionalBits, >(a): BinaryFixedPoint; ``` Returns the absolute value of a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint). Unsigned inputs are returned unchanged. Throws `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW` when taking the absolute value of the minimum representable signed value, which has no positive counterpart in two's-complement. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------- | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> | ## Returns [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> ## See [negateBinaryFixedPoint](/api/functions/negateBinaryFixedPoint) # absoluteDecimalFixedPoint (/api/functions/absoluteDecimalFixedPoint) ```ts function absoluteDecimalFixedPoint( a, ): DecimalFixedPoint; ``` Returns the absolute value of a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint). Unsigned inputs are returned unchanged. Throws `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW` when taking the absolute value of the minimum representable signed value, which has no positive counterpart in two's-complement. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> | ## Returns [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> ## See [negateDecimalFixedPoint](/api/functions/negateDecimalFixedPoint) # addBinaryFixedPoint (/api/functions/addBinaryFixedPoint) ```ts function addBinaryFixedPoint( a, b, ): BinaryFixedPoint; ``` Adds two [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) values of the same shape and returns the result at the same shape. Throws `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH` if the two operands differ in signedness, total bits, or fractional bits, and `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW` if the sum does not fit the target shape. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> | | `b` | [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<[`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`>> | ## Returns [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> ## Example ```ts const usd = binaryFixedPoint('signed', 32, 16); addBinaryFixedPoint(usd('1.5'), usd('2.25')); // represents 3.75 ``` ## See [subtractBinaryFixedPoint](/api/functions/subtractBinaryFixedPoint) # addCodecSentinel (/api/functions/addCodecSentinel) ## Call Signature ```ts function addCodecSentinel( codec, sentinel, ): FixedSizeCodec; ``` Creates a Codec that writes a given `Uint8Array` sentinel after the encoded value and, when decoding, continues reading until the sentinel is found. This sets a limit on variable-size codecs and tells us when to stop decoding. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | ---------- | ------------------------------------------------------------------- | | `codec` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> | | `sentinel` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> ### Example ```ts const codec = addCodecSentinel(getUtf8Codec(), new Uint8Array([255, 255])); codec.encode('hello'); // 0x68656c6c6fffff // | β””-- Our sentinel. // β””-- Our encoded string. ``` ### Remarks Note that the sentinel *must not* be present in the encoded data and *must* be present in the decoded data for this to work. If this is not the case, dedicated errors will be thrown. ```ts const sentinel = new Uint8Array([108, 108]); // 'll' const codec = addCodecSentinel(getUtf8Codec(), sentinel); codec.encode('hello'); // Throws: sentinel is in encoded data. codec.decode(new Uint8Array([1, 2, 3])); // Throws: sentinel missing in decoded data. ``` Separate [addEncoderSentinel](/api/functions/addEncoderSentinel) and [addDecoderSentinel](/api/functions/addDecoderSentinel) functions are also available. ```ts const bytes = addEncoderSentinel(getUtf8Encoder(), sentinel).encode('hello'); const value = addDecoderSentinel(getUtf8Decoder(), sentinel).decode(bytes); ``` ### See * [addEncoderSentinel](/api/functions/addEncoderSentinel) * [addDecoderSentinel](/api/functions/addDecoderSentinel) ## Call Signature ```ts function addCodecSentinel( codec, sentinel, ): VariableSizeCodec; ``` Creates a Codec that writes a given `Uint8Array` sentinel after the encoded value and, when decoding, continues reading until the sentinel is found. This sets a limit on variable-size codecs and tells us when to stop decoding. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | ---------- | ---------------------------------------------------------- | | `codec` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | | `sentinel` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`> ### Example ```ts const codec = addCodecSentinel(getUtf8Codec(), new Uint8Array([255, 255])); codec.encode('hello'); // 0x68656c6c6fffff // | β””-- Our sentinel. // β””-- Our encoded string. ``` ### Remarks Note that the sentinel *must not* be present in the encoded data and *must* be present in the decoded data for this to work. If this is not the case, dedicated errors will be thrown. ```ts const sentinel = new Uint8Array([108, 108]); // 'll' const codec = addCodecSentinel(getUtf8Codec(), sentinel); codec.encode('hello'); // Throws: sentinel is in encoded data. codec.decode(new Uint8Array([1, 2, 3])); // Throws: sentinel missing in decoded data. ``` Separate [addEncoderSentinel](/api/functions/addEncoderSentinel) and [addDecoderSentinel](/api/functions/addDecoderSentinel) functions are also available. ```ts const bytes = addEncoderSentinel(getUtf8Encoder(), sentinel).encode('hello'); const value = addDecoderSentinel(getUtf8Decoder(), sentinel).decode(bytes); ``` ### See * [addEncoderSentinel](/api/functions/addEncoderSentinel) * [addDecoderSentinel](/api/functions/addDecoderSentinel) # addCodecSizePrefix (/api/functions/addCodecSizePrefix) ## Call Signature ```ts function addCodecSizePrefix( codec, prefix, ): FixedSizeCodec; ``` Stores the byte size of any given codec as an encoded number prefix. This sets a limit on variable-size codecs and tells us when to stop decoding. When encoding, the size of the encoded data is stored before the encoded data itself. When decoding, the size is read first to know how many bytes to read next. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------- | | `codec` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> | | `prefix` | `FixedSizeNumberCodec` | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> ### Example For example, say we want to bound a variable-size base-58 string using a `u32` size prefix. Here’s how you can use the `addCodecSizePrefix` function to achieve that. ```ts const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec()); getU32Base58Codec().encode('hello world'); // 0x0b00000068656c6c6f20776f726c64 // | β””-- Our encoded base-58 string. // β””-- Our encoded u32 size prefix. ``` ### Remarks Separate [addEncoderSizePrefix](/api/functions/addEncoderSizePrefix) and [addDecoderSizePrefix](/api/functions/addDecoderSizePrefix) functions are also available. ```ts const bytes = addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()).encode('hello'); const value = addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()).decode(bytes); ``` ### See * [addEncoderSizePrefix](/api/functions/addEncoderSizePrefix) * [addDecoderSizePrefix](/api/functions/addDecoderSizePrefix) ## Call Signature ```ts function addCodecSizePrefix( codec, prefix, ): VariableSizeCodec; ``` Stores the byte size of any given codec as an encoded number prefix. This sets a limit on variable-size codecs and tells us when to stop decoding. When encoding, the size of the encoded data is stored before the encoded data itself. When decoding, the size is read first to know how many bytes to read next. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | --------- | --------------------------------------------------- | | `codec` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | | `prefix` | `NumberCodec` | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`> ### Example For example, say we want to bound a variable-size base-58 string using a `u32` size prefix. Here’s how you can use the `addCodecSizePrefix` function to achieve that. ```ts const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec()); getU32Base58Codec().encode('hello world'); // 0x0b00000068656c6c6f20776f726c64 // | β””-- Our encoded base-58 string. // β””-- Our encoded u32 size prefix. ``` ### Remarks Separate [addEncoderSizePrefix](/api/functions/addEncoderSizePrefix) and [addDecoderSizePrefix](/api/functions/addDecoderSizePrefix) functions are also available. ```ts const bytes = addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()).encode('hello'); const value = addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()).decode(bytes); ``` ### See * [addEncoderSizePrefix](/api/functions/addEncoderSizePrefix) * [addDecoderSizePrefix](/api/functions/addDecoderSizePrefix) # addDecimalFixedPoint (/api/functions/addDecimalFixedPoint) ```ts function addDecimalFixedPoint( a, b, ): DecimalFixedPoint; ``` Adds two [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) values of the same shape and returns the result at the same shape. Throws `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH` if the two operands differ in signedness, total bits, or decimals, and `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW` if the sum does not fit the target shape. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> | | `b` | [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<[`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`>> | ## Returns [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> ## Example ```ts const usd = decimalFixedPoint('unsigned', 64, 2); addDecimalFixedPoint(usd('1.50'), usd('2.25')); // represents 3.75 ``` ## See [subtractDecimalFixedPoint](/api/functions/subtractDecimalFixedPoint) # addDecoderSentinel (/api/functions/addDecoderSentinel) ## Call Signature ```ts function addDecoderSentinel( decoder, sentinel, ): FixedSizeDecoder; ``` Creates a decoder that continues reading until a given `Uint8Array` sentinel is found. See [addCodecSentinel](/api/functions/addCodecSentinel) for more information. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | ---------- | -------------------------------------------------------------- | | `decoder` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> | | `sentinel` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> ### See [addCodecSentinel](/api/functions/addCodecSentinel) ## Call Signature ```ts function addDecoderSentinel( decoder, sentinel, ): VariableSizeDecoder; ``` Creates a decoder that continues reading until a given `Uint8Array` sentinel is found. See [addCodecSentinel](/api/functions/addCodecSentinel) for more information. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | ---------- | ---------------------------------------------------------- | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | | `sentinel` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`> ### See [addCodecSentinel](/api/functions/addCodecSentinel) # addDecoderSizePrefix (/api/functions/addDecoderSizePrefix) ## Call Signature ```ts function addDecoderSizePrefix( decoder, prefix, ): FixedSizeDecoder; ``` Bounds the size of the nested `decoder` by reading its encoded `prefix`. See [addCodecSizePrefix](/api/functions/addCodecSizePrefix) for more information. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------- | | `decoder` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> | | `prefix` | `FixedSizeNumberDecoder` | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> ### See [addCodecSizePrefix](/api/functions/addCodecSizePrefix) ## Call Signature ```ts function addDecoderSizePrefix( decoder, prefix, ): VariableSizeDecoder; ``` Bounds the size of the nested `decoder` by reading its encoded `prefix`. See [addCodecSizePrefix](/api/functions/addCodecSizePrefix) for more information. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | | `prefix` | `NumberDecoder` | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`> ### See [addCodecSizePrefix](/api/functions/addCodecSizePrefix) # addEncoderSentinel (/api/functions/addEncoderSentinel) ## Call Signature ```ts function addEncoderSentinel( encoder, sentinel, ): FixedSizeEncoder; ``` Creates an encoder that writes a `Uint8Array` sentinel after the encoded value. This is useful to delimit the encoded value when being read by a decoder. See [addCodecSentinel](/api/functions/addCodecSentinel) for more information. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ### Parameters | Parameter | Type | | ---------- | ---------------------------------------------------------------- | | `encoder` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> | | `sentinel` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> ### See [addCodecSentinel](/api/functions/addCodecSentinel) ## Call Signature ```ts function addEncoderSentinel( encoder, sentinel, ): VariableSizeEncoder; ``` Creates an encoder that writes a `Uint8Array` sentinel after the encoded value. This is useful to delimit the encoded value when being read by a decoder. See [addCodecSentinel](/api/functions/addCodecSentinel) for more information. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ### Parameters | Parameter | Type | | ---------- | ---------------------------------------------------------- | | `encoder` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | | `sentinel` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`> ### See [addCodecSentinel](/api/functions/addCodecSentinel) # addEncoderSizePrefix (/api/functions/addEncoderSizePrefix) ## Call Signature ```ts function addEncoderSizePrefix( encoder, prefix, ): FixedSizeEncoder; ``` Stores the size of the `encoder` in bytes as a prefix using the `prefix` encoder. See [addCodecSizePrefix](/api/functions/addCodecSizePrefix) for more information. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ### Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------- | | `encoder` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> | | `prefix` | `FixedSizeNumberEncoder` | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> ### See [addCodecSizePrefix](/api/functions/addCodecSizePrefix) ## Call Signature ```ts function addEncoderSizePrefix( encoder, prefix, ): VariableSizeEncoder; ``` Stores the size of the `encoder` in bytes as a prefix using the `prefix` encoder. See [addCodecSizePrefix](/api/functions/addCodecSizePrefix) for more information. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------ | | `encoder` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | | `prefix` | `NumberEncoder` | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`> ### See [addCodecSizePrefix](/api/functions/addCodecSizePrefix) # addSelfFetchFunctions (/api/functions/addSelfFetchFunctions) ```ts function addSelfFetchFunctions( client, codec, ): SelfFetchFunctions, InferTTo> & TCodec; ``` Adds self-fetching methods to a codec for retrieving and decoding accounts. This function augments the provided codec with methods that allow it to fetch accounts from the network and decode them in one step. It enables a fluent API where you can call methods like `.fetch()` directly on the codec. ## Type Parameters | Type Parameter | Description | | ----------------------------------- | ------------------------------- | | `TCodec` *extends* `AnyObjectCodec` | The codec type being augmented. | ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------- | -------------------------------------------------------- | | `client` | `ClientWithRpc`\<`GetAccountInfoApi` & `GetMultipleAccountsApi`> | A client that provides RPC access for fetching accounts. | | `codec` | `TCodec` | The codec to augment with self-fetch methods. | ## Returns [`SelfFetchFunctions`](/api/type-aliases/SelfFetchFunctions)\<`InferTFrom`\<`TCodec`>, `InferTTo`\<`TCodec`>> & `TCodec` The codec augmented with [SelfFetchFunctions](/api/type-aliases/SelfFetchFunctions) methods. ## Examples Adding self-fetch functions to an account codec. ```ts import { addSelfFetchFunctions } from '@solana/program-client-core'; const myAccountCodec = addSelfFetchFunctions(client, getMyAccountCodec()); // Fetch and decode an account in one step. const account = await myAccountCodec.fetch(accountAddress); ``` Handling accounts that may not exist. ```ts const myAccountCodec = addSelfFetchFunctions(client, getMyAccountCodec()); const maybeAccount = await myAccountCodec.fetchMaybe(accountAddress); if (maybeAccount.exists) { console.log('Account data:', maybeAccount.data); } else { console.log(`Account ${maybeAccount.address} does not exist`); } ``` Fetching multiple accounts at once. ```ts const myAccountCodec = addSelfFetchFunctions(client, getMyAccountCodec()); // Throws if any account does not exist. const accounts = await myAccountCodec.fetchAll([addressA, addressB, addressC]); // Returns MaybeAccount for each, allowing some to not exist. const maybeAccounts = await myAccountCodec.fetchAllMaybe([addressA, addressB]); ``` ## See [SelfFetchFunctions](/api/type-aliases/SelfFetchFunctions) # addSelfPlanAndSendFunctions (/api/functions/addSelfPlanAndSendFunctions) ```ts function addSelfPlanAndSendFunctions( client, input, ): SelfPlanAndSendFunctions & TItem; ``` Adds self-planning and self-sending methods to an instruction or instruction plan. This function augments the provided instruction or instruction plan with methods that allow it to plan and send itself using the provided client. It enables a fluent API where you can call methods like `.sendTransaction()` directly on the instruction. The function supports both synchronous inputs (instructions, instruction plans) and promise-like inputs, making it suitable for use with async instruction builders. ## Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | `TItem` *extends* \| `Instruction`\<`string`, readonly (`AccountMeta`\<`string`> \| `AccountLookupMeta`\<`string`, `string`>)\[]> \| `InstructionPlan` \| `PromiseLike`\<`Instruction`\<`string`, readonly (`AccountMeta`\<`string`> \| `AccountLookupMeta`\<`string`, `string`>)\[]>> \| `PromiseLike`\<`InstructionPlan`> | The type of the instruction, instruction plan, or a promise resolving to one. | ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | `client` | `ClientWithTransactionPlanning` & `ClientWithTransactionSending` | A client that provides transaction planning and sending capabilities. | | `input` | `TItem` | The instruction, instruction plan, or promise to augment with self-plan/send methods. | ## Returns [`SelfPlanAndSendFunctions`](/api/type-aliases/SelfPlanAndSendFunctions) & `TItem` The input augmented with [SelfPlanAndSendFunctions](/api/type-aliases/SelfPlanAndSendFunctions) methods. ## Examples Adding self-plan and send to a transfer instruction. ```ts import { addSelfPlanAndSendFunctions } from '@solana/program-client-core'; const transferInstruction = addSelfPlanAndSendFunctions( client, getTransferInstruction({ payer, source, destination, amount }) ); // Now you can send directly from the instruction. const result = await transferInstruction.sendTransaction(); ``` Using with an async instruction builder. ```ts const asyncInstruction = addSelfPlanAndSendFunctions( client, fetchAndBuildInstruction(/* ... */) ); // The promise is augmented with self-plan/send methods. const result = await asyncInstruction.sendTransaction(); ``` ## See [SelfPlanAndSendFunctions](/api/type-aliases/SelfPlanAndSendFunctions) # addSignersToInstruction (/api/functions/addSignersToInstruction) ```ts function addSignersToInstruction( signers, instruction, ): InstructionWithSigners & TInstruction; ``` Attaches the provided [TransactionSigners](/api/type-aliases/TransactionSigner) to the account metas of an instruction when applicable. For an account meta to match a provided signer it: * Must have a signer role (AccountRole.READONLY\_SIGNER or AccountRole.WRITABLE\_SIGNER). * Must have the same address as the provided signer. * Must not have an attached signer already. ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | | `TInstruction` *extends* `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]> | The inferred type of the instruction provided. | ## Parameters | Parameter | Type | | ------------- | -------------------------------------------------------------------------------------------------------- | | `signers` | [`TransactionSigner`](/api/type-aliases/TransactionSigner)\[] | | `instruction` | \| `TInstruction` \| [`InstructionWithSigners`](/api/interfaces/InstructionWithSigners) & `TInstruction` | ## Returns [`InstructionWithSigners`](/api/interfaces/InstructionWithSigners) & `TInstruction` ## Example ```ts import { AccountRole, Instruction } from '@solana/instructions'; import { addSignersToInstruction, TransactionSigner } from '@solana/signers'; const instruction: Instruction = { accounts: [ { address: '1111' as Address, role: AccountRole.READONLY_SIGNER }, { address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER }, ], // ... }; const signerA: TransactionSigner<'1111'>; const signerB: TransactionSigner<'2222'>; const instructionWithSigners = addSignersToInstruction( [signerA, signerB], instruction ); // instructionWithSigners.accounts[0].signer === signerA // instructionWithSigners.accounts[1].signer === signerB ``` # addSignersToTransactionMessage (/api/functions/addSignersToTransactionMessage) ```ts function addSignersToTransactionMessage( signers, transactionMessage, ): Partial< Pick< | TransactionMessageWithFeePayerSigner< string, TransactionSigner > | Readonly<{ feePayer: Readonly<{ address: Address; }> & Readonly<{ modifyAndSignTransactions?: undefined; signAndSendTransactions?: undefined; signTransactions?: undefined; }>; }>, 'feePayer' > > & Readonly<{ instructions: readonly Instruction< string, readonly ( | AccountLookupMeta | AccountMeta )[] > & InstructionWithSigners< TransactionSigner, readonly AccountMetaWithSigner< TransactionSigner >[] >[]; }> & TTransactionMessage; ``` Attaches the provided [TransactionSigners](/api/type-aliases/TransactionSigner) to the account metas of all instructions inside a transaction message and/or the transaction message fee payer, when applicable. For an account meta to match a provided signer it: * Must have a signer role (AccountRole.READONLY\_SIGNER or AccountRole.WRITABLE\_SIGNER). * Must have the same address as the provided signer. * Must not have an attached signer already. ## Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | | `TTransactionMessage` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `instructions`: readonly `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]>\[]; }> | The inferred type of the transaction message provided. | ## Parameters | Parameter | Type | | -------------------- | ------------------------------------------------------------- | | `signers` | [`TransactionSigner`](/api/type-aliases/TransactionSigner)\[] | | `transactionMessage` | `TTransactionMessage` | ## Returns [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Pick`](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)\< \| [`TransactionMessageWithFeePayerSigner`](/api/interfaces/TransactionMessageWithFeePayerSigner)\<`string`, [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `feePayer`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `modifyAndSignTransactions?`: `undefined`; `signAndSendTransactions?`: `undefined`; `signTransactions?`: `undefined`; }>; }>, `"feePayer"`>> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `instructions`: readonly `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> | `AccountMeta`\<`string`>)\[]> & [`InstructionWithSigners`](/api/interfaces/InstructionWithSigners)\<[`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>, readonly `AccountMetaWithSigner`\<[`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>>\[]>\[]; }> & `TTransactionMessage` ## Example ```ts import { AccountRole, Instruction } from '@solana/instructions'; import { TransactionMessage } from '@solana/transaction-messages'; import { addSignersToTransactionMessage, TransactionSigner } from '@solana/signers'; const instructionA: Instruction = { accounts: [{ address: '1111' as Address, role: AccountRole.READONLY_SIGNER }], // ... }; const instructionB: Instruction = { accounts: [{ address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER }], // ... }; const transactionMessage: TransactionMessage = { instructions: [instructionA, instructionB], // ... } const signerA: TransactionSigner<'1111'>; const signerB: TransactionSigner<'2222'>; const transactionMessageWithSigners = addSignersToTransactionMessage( [signerA, signerB], transactionMessage ); // transactionMessageWithSigners.instructions[0].accounts[0].signer === signerA // transactionMessageWithSigners.instructions[1].accounts[0].signer === signerB ``` # address (/api/functions/address) ```ts function address(putativeAddress): Address; ``` Combines *asserting* that a string is an address with *coercing* it to the [Address](/api/type-aliases/Address) type. It's most useful with untrusted input. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## Parameters | Parameter | Type | | ----------------- | ---------- | | `putativeAddress` | `TAddress` | ## Returns [`Address`](/api/type-aliases/Address)\<`TAddress`> ## Example ```ts import { address } from '@solana/addresses'; await transfer(address(fromAddress), address(toAddress), lamports(100000n)); ``` > \[!TIP] > When starting from a known-good address as a string, it's more efficient to typecast it rather > than to use the address helper, because the helper unconditionally performs validation on > its input. > > ```ts > import { Address } from '@solana/addresses'; > > const MEMO_PROGRAM_ADDRESS = > 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' as Address<'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'>; > ``` # airdropFactory (/api/functions/airdropFactory) ## Call Signature ```ts function airdropFactory(config): AirdropFunction; ``` Returns a function that you can call to airdrop a certain amount of [Lamports](/api/type-aliases/Lamports) to a Solana address. > \[!NOTE] This only works on test clusters. ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------- | ----------- | | `config` | `AirdropFactoryConfig`\<`"devnet"`> | - | ### Returns `AirdropFunction` ### Example ```ts import { address, airdropFactory, createSolanaRpc, createSolanaRpcSubscriptions, devnet, lamports } from '@solana/kit'; const rpc = createSolanaRpc(devnet('http://127.0.0.1:8899')); const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('ws://127.0.0.1:8900')); const airdrop = airdropFactory({ rpc, rpcSubscriptions }); await airdrop({ commitment: 'confirmed', recipientAddress: address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'), lamports: lamports(10_000_000n), }); ``` ## Call Signature ```ts function airdropFactory(config): AirdropFunction; ``` Returns a function that you can call to airdrop a certain amount of [Lamports](/api/type-aliases/Lamports) to a Solana address. > \[!NOTE] This only works on test clusters. ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------ | ----------- | | `config` | `AirdropFactoryConfig`\<`"mainnet"`> | - | ### Returns `AirdropFunction` ### Example ```ts import { address, airdropFactory, createSolanaRpc, createSolanaRpcSubscriptions, devnet, lamports } from '@solana/kit'; const rpc = createSolanaRpc(devnet('http://127.0.0.1:8899')); const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('ws://127.0.0.1:8900')); const airdrop = airdropFactory({ rpc, rpcSubscriptions }); await airdrop({ commitment: 'confirmed', recipientAddress: address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'), lamports: lamports(10_000_000n), }); ``` ## Call Signature ```ts function airdropFactory(config): AirdropFunction; ``` Returns a function that you can call to airdrop a certain amount of [Lamports](/api/type-aliases/Lamports) to a Solana address. > \[!NOTE] This only works on test clusters. ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------ | ----------- | | `config` | `AirdropFactoryConfig`\<`"testnet"`> | - | ### Returns `AirdropFunction` ### Example ```ts import { address, airdropFactory, createSolanaRpc, createSolanaRpcSubscriptions, devnet, lamports } from '@solana/kit'; const rpc = createSolanaRpc(devnet('http://127.0.0.1:8899')); const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('ws://127.0.0.1:8900')); const airdrop = airdropFactory({ rpc, rpcSubscriptions }); await airdrop({ commitment: 'confirmed', recipientAddress: address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'), lamports: lamports(10_000_000n), }); ``` # appendTransactionMessageInstruction (/api/functions/appendTransactionMessageInstruction) ```ts function appendTransactionMessageInstruction< TTransactionMessage, TInstruction, >( instruction, transactionMessage, ): AppendTransactionMessageInstructions< TTransactionMessage, [TInstruction] >; ``` Given an instruction, this method will return a new transaction message with that instruction having been added to the end of the list of existing instructions. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | | `TInstruction` *extends* `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]> | ## Parameters | Parameter | Type | | -------------------- | --------------------- | | `instruction` | `TInstruction` | | `transactionMessage` | `TTransactionMessage` | ## Returns `AppendTransactionMessageInstructions`\<`TTransactionMessage`, \[`TInstruction`]> ## See appendTransactionInstructions if you need to append multiple instructions to a transaction message. ## Example ```ts import { address } from '@solana/addresses'; import { getUtf8Encoder } from '@solana/codecs-strings'; import { appendTransactionMessageInstruction } from '@solana/transaction-messages'; const memoTransactionMessage = appendTransactionMessageInstruction( { data: getUtf8Encoder().encode('Hello world!'), programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), }, transactionMessage, ); ``` # appendTransactionMessageInstructionPlan (/api/functions/appendTransactionMessageInstructionPlan) ```ts function appendTransactionMessageInstructionPlan( instructionPlan, transactionMessage, ): AppendTransactionMessageInstructions; ``` Appends all instructions from an instruction plan to a transaction message. This function flattens the instruction plan into its leaf plans and sequentially appends each instruction to the provided transaction message. It handles both single instructions and message packer plans. Note that any [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) is assumed to only append instructions. If it modifies other properties of the transaction message, the type of the returned transaction message may not accurately reflect those changes. ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | The type of transaction message being modified. | ## Parameters | Parameter | Type | Description | | -------------------- | ------------------------------------------------------ | ----------------------------------------------------------- | | `instructionPlan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan containing the instructions to append. | | `transactionMessage` | `TTransactionMessage` | The transaction message to append instructions to. | ## Returns `AppendTransactionMessageInstructions`\<`TTransactionMessage`> The transaction message with all instructions from the plan appended. ## Examples Appending a simple instruction plan to a transaction message. ```ts import { appendTransactionMessageInstructionPlan } from '@solana/instruction-plans'; import { createTransactionMessage, setTransactionMessageFeePayer } from '@solana/transaction-messages'; const message = setTransactionMessageFeePayer(feePayer, createTransactionMessage({ version: 0 })); const plan = singleInstructionPlan(myInstruction); const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan); ``` Appending a sequential instruction plan. ```ts const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]); const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan); ``` ## See * [InstructionPlan](/api/type-aliases/InstructionPlan) * [flattenInstructionPlan](/api/functions/flattenInstructionPlan) # appendTransactionMessageInstructions (/api/functions/appendTransactionMessageInstructions) ```ts function appendTransactionMessageInstructions< TTransactionMessage, TInstructions, >( instructions, transactionMessage, ): AppendTransactionMessageInstructions< TTransactionMessage, TInstructions >; ``` Given an array of instructions, this method will return a new transaction message with those instructions having been added to the end of the list of existing instructions. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | | `TInstructions` *extends* readonly `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]>\[] | ## Parameters | Parameter | Type | | -------------------- | --------------------- | | `instructions` | `TInstructions` | | `transactionMessage` | `TTransactionMessage` | ## Returns `AppendTransactionMessageInstructions`\<`TTransactionMessage`, `TInstructions`> ## See appendTransactionInstruction if you only need to append one instruction to a transaction message. ## Example ```ts import { address } from '@solana/addresses'; import { appendTransactionMessageInstructions } from '@solana/transaction-messages'; const memoTransaction = appendTransactionMessageInstructions( [ { data: new TextEncoder().encode('Hello world!'), programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), }, { data: new TextEncoder().encode('How are you?'), programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), }, ], tx, ); ``` # areV1ConfigsEqual (/api/functions/areV1ConfigsEqual) ```ts function areV1ConfigsEqual(config1, config2): boolean; ``` Determines whether two transaction configs set the same value for every field. ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------- | ----------------------------- | | `config1` | [`V1TransactionConfig`](/api/type-aliases/V1TransactionConfig) | The first config to compare. | | `config2` | [`V1TransactionConfig`](/api/type-aliases/V1TransactionConfig) | The second config to compare. | ## Returns `boolean` `true` if all four fields are equal between the two configs, `false` otherwise. # assertAccountDecoded (/api/functions/assertAccountDecoded) ## Call Signature ```ts function assertAccountDecoded( account, ): asserts account is Account; ``` Asserts that an account stores decoded data, ie. not a `Uint8Array`. Note that it does not check the shape of the data matches the decoded type, only that it is not a `Uint8Array`. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TData` *extends* `object` | - | The type of this account's data. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `account` | [`Account`](/api/interfaces/Account)\< \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> \| `TData`, `TAddress`> | ### Returns `asserts account is Account` ### Example ```ts type MyAccountData = { name: string; age: number }; const myAccount: Account; assertAccountDecoded(myAccount); // now the account data can be used as MyAccountData account.data satisfies MyAccountData; ``` This is particularly useful for narrowing the result of fetching a JSON parsed account. ```ts const account: MaybeAccount = await fetchJsonParsedAccount( rpc, '1234..5678' as Address, ); assertAccountDecoded(account); // now we have a MaybeAccount account satisfies MaybeAccount; ``` ## Call Signature ```ts function assertAccountDecoded( account, ): asserts account is MaybeAccount; ``` Asserts that an account stores decoded data, ie. not a `Uint8Array`. Note that it does not check the shape of the data matches the decoded type, only that it is not a `Uint8Array`. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TData` *extends* `object` | - | The type of this account's data. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `account` | [`MaybeAccount`](/api/type-aliases/MaybeAccount)\< \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> \| `TData`, `TAddress`> | ### Returns `asserts account is MaybeAccount` ### Example ```ts type MyAccountData = { name: string; age: number }; const myAccount: Account; assertAccountDecoded(myAccount); // now the account data can be used as MyAccountData account.data satisfies MyAccountData; ``` This is particularly useful for narrowing the result of fetching a JSON parsed account. ```ts const account: MaybeAccount = await fetchJsonParsedAccount( rpc, '1234..5678' as Address, ); assertAccountDecoded(account); // now we have a MaybeAccount account satisfies MaybeAccount; ``` # assertAccountExists (/api/functions/assertAccountExists) ```ts function assertAccountExists( account, ): asserts account is BaseAccount & { address: Address; data: TData; } & { exists: true }; ``` Given a [MaybeAccount](/api/type-aliases/MaybeAccount), asserts that the account exists and allows it to be used as an [Account](/api/interfaces/Account) type going forward. ## Type Parameters | Type Parameter | Default type | Description | | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TData` *extends* \| `object` \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | - | The nature of this account's data. It can be represented as either a `Uint8Array` – meaning the account is encoded – or a custom data type – meaning the account is decoded. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------- | | `account` | [`MaybeAccount`](/api/type-aliases/MaybeAccount)\<`TData`, `TAddress`> | ## Returns `asserts account is BaseAccount & { address: Address; data: TData } & { exists: true }` ## Example ```ts const myAccount: MaybeEncodedAccount<'1234..5678'>; assertAccountExists(myAccount); // Now we can use myAccount as an `EncodedAccount` myAccount satisfies EncodedAccount<'1234..5678'>; ``` # assertAccountsDecoded (/api/functions/assertAccountsDecoded) ## Call Signature ```ts function assertAccountsDecoded( accounts, ): asserts accounts is Account[]; ``` Asserts that all input accounts store decoded data, ie. not a `Uint8Array`. As with [assertAccountDecoded](/api/functions/assertAccountDecoded) it does not check the shape of the data matches the decoded type, only that it is not a `Uint8Array`. ### Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TData` *extends* `object` | - | | `TAddress` *extends* `string` | `string` | ### Parameters | Parameter | Type | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `accounts` | [`Account`](/api/interfaces/Account)\< \| `TData` \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`>, `TAddress`>\[] | ### Returns `asserts accounts is Account[]` ### Example ```ts type MyAccountData = { name: string; age: number }; const myAccounts: Account[]; assertAccountsDecoded(myAccounts); // now the account data can be used as MyAccountData for (const a of account) { account.data satisfies MyAccountData; } ``` ## Call Signature ```ts function assertAccountsDecoded( accounts, ): asserts accounts is MaybeAccount[]; ``` Asserts that all input accounts store decoded data, ie. not a `Uint8Array`. As with [assertAccountDecoded](/api/functions/assertAccountDecoded) it does not check the shape of the data matches the decoded type, only that it is not a `Uint8Array`. ### Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TData` *extends* `object` | - | | `TAddress` *extends* `string` | `string` | ### Parameters | Parameter | Type | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `accounts` | [`MaybeAccount`](/api/type-aliases/MaybeAccount)\< \| `TData` \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`>, `TAddress`>\[] | ### Returns `asserts accounts is MaybeAccount[]` ### Example ```ts type MyAccountData = { name: string; age: number }; const myAccounts: Account[]; assertAccountsDecoded(myAccounts); // now the account data can be used as MyAccountData for (const a of account) { account.data satisfies MyAccountData; } ``` # assertAccountsExist (/api/functions/assertAccountsExist) ```ts function assertAccountsExist( accounts, ): asserts accounts is (BaseAccount & { address: Address; data: TData; } & { exists: true })[]; ``` Given an array of [MaybeAccounts](/api/type-aliases/MaybeAccount), asserts that all the accounts exist and allows them to be used as an array of [Accounts](/api/interfaces/Account) going forward. ## Type Parameters | Type Parameter | Default type | Description | | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TData` *extends* \| `object` \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | - | The nature of this account's data. It can be represented as either a `Uint8Array` – meaning the account is encoded – or a custom data type – meaning the account is decoded. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ## Parameters | Parameter | Type | | ---------- | ------------------------------------------------------------------------- | | `accounts` | [`MaybeAccount`](/api/type-aliases/MaybeAccount)\<`TData`, `TAddress`>\[] | ## Returns `asserts accounts is (BaseAccount & { address: Address; data: TData } & { exists: true })[]` ## Example ```ts const myAccounts: MaybeEncodedAccount
[]; assertAccountsExist(myAccounts); // Now we can use them as an array of `EncodedAccounts` for (const a of myAccounts) { a satisfies EncodedAccount
; } ``` # assertByteArrayHasEnoughBytesForCodec (/api/functions/assertByteArrayHasEnoughBytesForCodec) ```ts function assertByteArrayHasEnoughBytesForCodec( codecDescription, expected, bytes, offset?, ): void; ``` Asserts that a given byte array has enough bytes to decode (after the optional provided offset). Returns void if the byte array has at least the expected number of bytes but throws a [SolanaError](/api/classes/SolanaError) otherwise. ## Parameters | Parameter | Type | Description | | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | | `codecDescription` | `string` | A description of the codec used by the assertion error. | | `expected` | `number` | The minimum number of bytes expected in the byte array. | | `bytes` | \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | The byte array to check. | | `offset?` | `number` | The offset from which to start checking the byte array. | ## Returns `void` ## Example ```ts const bytes = new Uint8Array([0x01, 0x02, 0x03]); assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes); // OK assertByteArrayHasEnoughBytesForCodec('myCodec', 4, bytes); // Throws assertByteArrayHasEnoughBytesForCodec('myCodec', 2, bytes, 1); // OK assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes, 1); // Throws ``` # assertByteArrayIsNotEmptyForCodec (/api/functions/assertByteArrayIsNotEmptyForCodec) ```ts function assertByteArrayIsNotEmptyForCodec( codecDescription, bytes, offset?, ): void; ``` Asserts that a given byte array is not empty (after the optional provided offset). Returns void if the byte array is not empty but throws a [SolanaError](/api/classes/SolanaError) otherwise. ## Parameters | Parameter | Type | Description | | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `codecDescription` | `string` | A description of the codec used by the assertion error. | | `bytes` | \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | The byte array to check. | | `offset?` | `number` | The offset from which to start checking the byte array. If provided, the byte array is considered empty if it has no bytes after the offset. | ## Returns `void` ## Example ```ts const bytes = new Uint8Array([0x01, 0x02, 0x03]); assertByteArrayIsNotEmptyForCodec('myCodec', bytes); // OK assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 1); // OK assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 3); // Throws ``` # assertByteArrayOffsetIsNotOutOfRange (/api/functions/assertByteArrayOffsetIsNotOutOfRange) ```ts function assertByteArrayOffsetIsNotOutOfRange( codecDescription, offset, bytesLength, ): void; ``` Asserts that a given offset is within the byte array bounds. This range is between 0 and the byte array length and is inclusive. An offset equals to the byte array length is considered a valid offset as it allows the post-offset of codecs to signal the end of the byte array. ## Parameters | Parameter | Type | Description | | ------------------ | -------- | --------------------------------------------------------------------------- | | `codecDescription` | `string` | A description of the codec used by the assertion error. | | `offset` | `number` | The offset to check. | | `bytesLength` | `number` | The length of the byte array from which the offset should be within bounds. | ## Returns `void` ## Example ```ts const bytes = new Uint8Array([0x01, 0x02, 0x03]); assertByteArrayOffsetIsNotOutOfRange('myCodec', 0, bytes.length); // OK assertByteArrayOffsetIsNotOutOfRange('myCodec', 3, bytes.length); // OK assertByteArrayOffsetIsNotOutOfRange('myCodec', 4, bytes.length); // Throws ``` # assertContainsResolvableTransactionSendingSigner (/api/functions/assertContainsResolvableTransactionSendingSigner) ```ts function assertContainsResolvableTransactionSendingSigner( signers, ): void; ``` Asserts that the provided signers contain at least one [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) that can be unambiguously resolved. This means the signers must contain at least one sending signer, and at most one sending-only signer (i.e. a signer that implements [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) but not [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner) or [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner)). Composite signers that also implement other interfaces can be demoted to non-sending roles, so multiple composite sending signers are allowed. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------- | --------------------- | | `signers` | readonly [`TransactionSigner`](/api/type-aliases/TransactionSigner)\[] | The signers to check. | ## Returns `void` ## Throws SolanaError with code SOLANA\_ERROR\_\_SIGNER\_\_TRANSACTION\_SENDING\_SIGNER\_MISSING if no sending signer is found. ## Throws SolanaError with code SOLANA\_ERROR\_\_SIGNER\_\_TRANSACTION\_CANNOT\_HAVE\_MULTIPLE\_SENDING\_SIGNERS if more than one sending-only signer is found. ## Example ```ts assertContainsResolvableTransactionSendingSigner(mySigners); const signature = await signAndSendTransactionWithSigners(mySigners, compiledTransaction); ``` ## See * [signAndSendTransactionWithSigners](/api/functions/signAndSendTransactionWithSigners) * [assertIsTransactionMessageWithSingleSendingSigner](/api/functions/assertIsTransactionMessageWithSingleSendingSigner) # assertDigestCapabilityIsAvailable (/api/functions/assertDigestCapabilityIsAvailable) ```ts function assertDigestCapabilityIsAvailable(): void; ``` Throws an exception unless [\`crypto.subtle.digest()\`](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) is available in the current JavaScript environment. ## Returns `void` # assertIsAddress (/api/functions/assertIsAddress) ```ts function assertIsAddress( putativeAddress, ): asserts putativeAddress is Address; ``` From time to time you might acquire a string, that you expect to validate as an address or public key, from an untrusted network API or user input. Use this function to assert that such an arbitrary string is a base58-encoded address. ## Parameters | Parameter | Type | | ----------------- | -------- | | `putativeAddress` | `string` | ## Returns `asserts putativeAddress is Address` ## Example ```ts import { assertIsAddress } from '@solana/addresses'; // Imagine a function that fetches an account's balance when a user submits a form. function handleSubmit() { // We know only that what the user typed conforms to the `string` type. const address: string = accountAddressInput.value; try { // If this type assertion function doesn't throw, then // Typescript will upcast `address` to `Address`. assertIsAddress(address); // At this point, `address` is an `Address` that can be used with the RPC. const balanceInLamports = await rpc.getBalance(address).send(); } catch (e) { // `address` turned out not to be a base58-encoded address } } ``` # assertIsBinaryFixedPoint (/api/functions/assertIsBinaryFixedPoint) ```ts function assertIsBinaryFixedPoint< TSignedness, TTotalBits, TFractionalBits, >( value, signedness?, totalBits?, fractionalBits?, ): asserts value is BinaryFixedPoint< TSignedness, TTotalBits, TFractionalBits >; ``` Asserts that `value` is a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint). Every shape parameter is independently optional. Pass `undefined` (or simply omit trailing arguments) to leave a given field unconstrained. Throws `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH` if the value does not match the expected shape, or `SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE` if the `raw` bigint does not fit the claimed signedness and total bits. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------- | -------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | `number` | | `TFractionalBits` *extends* `number` | `number` | ## Parameters | Parameter | Type | | ----------------- | ----------------- | | `value` | `unknown` | | `signedness?` | `TSignedness` | | `totalBits?` | `TTotalBits` | | `fractionalBits?` | `TFractionalBits` | ## Returns `asserts value is BinaryFixedPoint` ## Example ```ts assertIsBinaryFixedPoint(value); // any binary fixed-point assertIsBinaryFixedPoint(value, 'signed'); // any signed binary assertIsBinaryFixedPoint(value, 'signed', 16, 15); // fully pinned assertIsBinaryFixedPoint(value, undefined, 16); // any binary with totalBits=16 ``` ## See * [isBinaryFixedPoint](/api/functions/isBinaryFixedPoint) * [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) # assertIsBlockhash (/api/functions/assertIsBlockhash) ```ts function assertIsBlockhash( putativeBlockhash, ): asserts putativeBlockhash is Blockhash; ``` From time to time you might acquire a string, that you expect to validate as a blockhash, from an untrusted network API or user input. Use this function to assert that such an arbitrary string is a base58-encoded blockhash. ## Parameters | Parameter | Type | | ------------------- | -------- | | `putativeBlockhash` | `string` | ## Returns `asserts putativeBlockhash is Blockhash` ## Example ```ts import { assertIsBlockhash } from '@solana/rpc-types'; // Imagine a function that determines whether a blockhash is fresh when a user submits a form. function handleSubmit() { // We know only that what the user typed conforms to the `string` type. const blockhash: string = blockhashInput.value; try { // If this type assertion function doesn't throw, then // Typescript will upcast `blockhash` to `Blockhash`. assertIsBlockhash(blockhash); // At this point, `blockhash` is a `Blockhash` that can be used with the RPC. const { value: isValid } = await rpc.isBlockhashValid(blockhash).send(); } catch (e) { // `blockhash` turned out not to be a base58-encoded blockhash } } ``` # assertIsCanceledSingleTransactionPlanResult (/api/functions/assertIsCanceledSingleTransactionPlanResult) ```ts function assertIsCanceledSingleTransactionPlanResult< TContext, TTransactionMessage, >( plan, ): asserts plan is CanceledSingleTransactionPlanResult< TContext, TTransactionMessage >; ``` Asserts that the given transaction plan result is a canceled [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result to assert. | ## Returns `asserts plan is CanceledSingleTransactionPlanResult` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a canceled single transaction plan result. ## Example ```ts const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message); assertIsCanceledSingleTransactionPlanResult(result); console.log('Transaction was canceled'); // TypeScript knows this is a canceled result. ``` ## See * [CanceledSingleTransactionPlanResult](/api/type-aliases/CanceledSingleTransactionPlanResult) * [isCanceledSingleTransactionPlanResult](/api/functions/isCanceledSingleTransactionPlanResult) # assertIsDecimalFixedPoint (/api/functions/assertIsDecimalFixedPoint) ```ts function assertIsDecimalFixedPoint( value, signedness?, totalBits?, decimals?, ): asserts value is DecimalFixedPoint< TSignedness, TTotalBits, TDecimals >; ``` Asserts that `value` is a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint). Every shape parameter is independently optional. Pass `undefined` (or simply omit trailing arguments) to leave a given field unconstrained. Throws `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH` if the value does not match the expected shape, or `SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE` if the `raw` bigint does not fit the claimed signedness and total bits. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------- | -------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | `number` | | `TDecimals` *extends* `number` | `number` | ## Parameters | Parameter | Type | | ------------- | ------------- | | `value` | `unknown` | | `signedness?` | `TSignedness` | | `totalBits?` | `TTotalBits` | | `decimals?` | `TDecimals` | ## Returns `asserts value is DecimalFixedPoint` ## Example ```ts assertIsDecimalFixedPoint(value); // any decimal fixed-point assertIsDecimalFixedPoint(value, 'unsigned'); // any unsigned decimal assertIsDecimalFixedPoint(value, 'unsigned', 64, 6); // fully pinned assertIsDecimalFixedPoint(value, undefined, 64); // any decimal with totalBits=64 ``` ## See * [isDecimalFixedPoint](/api/functions/isDecimalFixedPoint) * [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) # assertIsFailedSingleTransactionPlanResult (/api/functions/assertIsFailedSingleTransactionPlanResult) ```ts function assertIsFailedSingleTransactionPlanResult< TContext, TTransactionMessage, >( plan, ): asserts plan is FailedSingleTransactionPlanResult< TContext, TTransactionMessage >; ``` Asserts that the given transaction plan result is a failed [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result to assert. | ## Returns `asserts plan is FailedSingleTransactionPlanResult` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a failed single transaction plan result. ## Example ```ts const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error); assertIsFailedSingleTransactionPlanResult(result); console.log(result.error); // TypeScript knows this is a failed result. ``` ## See * [FailedSingleTransactionPlanResult](/api/type-aliases/FailedSingleTransactionPlanResult) * [isFailedSingleTransactionPlanResult](/api/functions/isFailedSingleTransactionPlanResult) # assertIsFixedSize (/api/functions/assertIsFixedSize) ## Call Signature ```ts function assertIsFixedSize( encoder, ): asserts encoder is FixedSizeEncoder; ``` Asserts that the given codec, encoder, or decoder is fixed-size. If the object is not fixed-size (i.e., it lacks a `fixedSize` property), this function throws a [SolanaError](/api/classes/SolanaError) with the code `SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH`. ### Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `encoder` | \| [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`> \| [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`> | ### Returns `asserts encoder is FixedSizeEncoder` ### Throws If the object is not fixed-size. ### Examples Asserting a fixed-size encoder. ```ts const encoder = getU32Encoder(); assertIsFixedSize(encoder); // Passes ``` Attempting to assert a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); assertIsFixedSize(encoder); // Throws SolanaError ``` ### Remarks This function is the assertion-based counterpart of [isFixedSize](/api/functions/isFixedSize). If you only need to check whether an object is fixed-size without throwing an error, use [isFixedSize](/api/functions/isFixedSize) instead. ### See [isFixedSize](/api/functions/isFixedSize) ## Call Signature ```ts function assertIsFixedSize( decoder, ): asserts decoder is FixedSizeDecoder; ``` Asserts that the given codec, encoder, or decoder is fixed-size. If the object is not fixed-size (i.e., it lacks a `fixedSize` property), this function throws a [SolanaError](/api/classes/SolanaError) with the code `SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH`. ### Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `decoder` | \| [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `TSize`> \| [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`> | ### Returns `asserts decoder is FixedSizeDecoder` ### Throws If the object is not fixed-size. ### Examples Asserting a fixed-size encoder. ```ts const encoder = getU32Encoder(); assertIsFixedSize(encoder); // Passes ``` Attempting to assert a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); assertIsFixedSize(encoder); // Throws SolanaError ``` ### Remarks This function is the assertion-based counterpart of [isFixedSize](/api/functions/isFixedSize). If you only need to check whether an object is fixed-size without throwing an error, use [isFixedSize](/api/functions/isFixedSize) instead. ### See [isFixedSize](/api/functions/isFixedSize) ## Call Signature ```ts function assertIsFixedSize( codec, ): asserts codec is FixedSizeCodec; ``` Asserts that the given codec, encoder, or decoder is fixed-size. If the object is not fixed-size (i.e., it lacks a `fixedSize` property), this function throws a [SolanaError](/api/classes/SolanaError) with the code `SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH`. ### Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `codec` | \| [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`> \| [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`> | ### Returns `asserts codec is FixedSizeCodec` ### Throws If the object is not fixed-size. ### Examples Asserting a fixed-size encoder. ```ts const encoder = getU32Encoder(); assertIsFixedSize(encoder); // Passes ``` Attempting to assert a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); assertIsFixedSize(encoder); // Throws SolanaError ``` ### Remarks This function is the assertion-based counterpart of [isFixedSize](/api/functions/isFixedSize). If you only need to check whether an object is fixed-size without throwing an error, use [isFixedSize](/api/functions/isFixedSize) instead. ### See [isFixedSize](/api/functions/isFixedSize) ## Call Signature ```ts function assertIsFixedSize( codec, ): asserts codec is { fixedSize: TSize }; ``` Asserts that the given codec, encoder, or decoder is fixed-size. If the object is not fixed-size (i.e., it lacks a `fixedSize` property), this function throws a [SolanaError](/api/classes/SolanaError) with the code `SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH`. ### Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------- | | `codec` | \| \{ `fixedSize`: `TSize`; } \| \{ `maxSize?`: `number`; } | ### Returns `asserts codec is { fixedSize: TSize }` ### Throws If the object is not fixed-size. ### Examples Asserting a fixed-size encoder. ```ts const encoder = getU32Encoder(); assertIsFixedSize(encoder); // Passes ``` Attempting to assert a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); assertIsFixedSize(encoder); // Throws SolanaError ``` ### Remarks This function is the assertion-based counterpart of [isFixedSize](/api/functions/isFixedSize). If you only need to check whether an object is fixed-size without throwing an error, use [isFixedSize](/api/functions/isFixedSize) instead. ### See [isFixedSize](/api/functions/isFixedSize) # assertIsFullySignedOffchainMessageEnvelope (/api/functions/assertIsFullySignedOffchainMessageEnvelope) ```ts function assertIsFullySignedOffchainMessageEnvelope( offchainMessage, ): asserts offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope; ``` From time to time you might acquire a [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope), that you expect to be fully signed, from an untrusted network API or user input. Use this function to assert that such an offchain message is fully signed. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------ | | `TEnvelope` *extends* [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope) | ## Parameters | Parameter | Type | | ----------------- | ----------- | | `offchainMessage` | `TEnvelope` | ## Returns `asserts offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope` ## Example ```ts import { assertIsFullySignedOffchainMessage } from '@solana/offchain-messages'; const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes); try { // If this type assertion function doesn't throw, then Typescript will upcast // `offchainMessageEnvelope` to `FullySignedOffchainMessageEnvelope`. assertIsFullySignedOffchainMessageEnvelope(offchainMessage); // At this point we know that the offchain message is signed by all required signers. } catch(e) { if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING)) { setError(`Missing signatures for ${e.context.addresses.join(', ')}`); } else { throw e; } } ``` # assertIsFullySignedTransaction (/api/functions/assertIsFullySignedTransaction) ```ts function assertIsFullySignedTransaction( transaction, ): asserts transaction is FullySignedTransaction & TTransaction; ``` From time to time you might acquire a [Transaction](/api/type-aliases/Transaction), that you expect to be fully signed, from an untrusted network API or user input. Use this function to assert that such a transaction is fully signed. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TTransaction` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> | ## Parameters | Parameter | Type | | ------------- | -------------- | | `transaction` | `TTransaction` | ## Returns `asserts transaction is FullySignedTransaction & TTransaction` ## Example ```ts import { assertIsFullySignedTransaction } from '@solana/transactions'; const transaction = getTransactionDecoder().decode(transactionBytes); try { // If this type assertion function doesn't throw, then Typescript will upcast `transaction` // to `FullySignedTransaction`. assertIsFullySignedTransaction(transaction); // At this point we know that the transaction is signed and can be sent to the network. await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); } catch(e) { if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) { setError(`Missing signatures for ${e.context.addresses.join(', ')}`); } throw; } ``` # assertIsInstructionForProgram (/api/functions/assertIsInstructionForProgram) ```ts function assertIsInstructionForProgram( instruction, programAddress, ): asserts instruction is TInstruction & { programAddress: Address; }; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TProgramAddress` *extends* `string` | | `TInstruction` *extends* [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | ## Parameters | Parameter | Type | | ---------------- | ---------------------------------------------------------- | | `instruction` | `TInstruction` | | `programAddress` | [`Address`](/api/type-aliases/Address)\<`TProgramAddress`> | ## Returns `asserts instruction is TInstruction & { programAddress: Address }` # assertIsInstructionWithAccounts (/api/functions/assertIsInstructionWithAccounts) ```ts function assertIsInstructionWithAccounts( instruction, ): asserts instruction is InstructionWithAccounts & TInstruction; ``` ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TAccounts` *extends* readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[] | readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[] | | `TInstruction` *extends* [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | ## Parameters | Parameter | Type | | ------------- | -------------- | | `instruction` | `TInstruction` | ## Returns `asserts instruction is InstructionWithAccounts & TInstruction` # assertIsInstructionWithData (/api/functions/assertIsInstructionWithData) ```ts function assertIsInstructionWithData( instruction, ): asserts instruction is InstructionWithData & TInstruction; ``` ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TData` *extends* [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | | `TInstruction` *extends* [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | ## Parameters | Parameter | Type | | ------------- | -------------- | | `instruction` | `TInstruction` | ## Returns `asserts instruction is InstructionWithData & TInstruction` # assertIsKeyPairSigner (/api/functions/assertIsKeyPairSigner) ```ts function assertIsKeyPairSigner( value, ): asserts value is Readonly<{ address: Address; signMessages: any; }> & Readonly<{ address: Address; signTransactions: any }> & { keyPair: CryptoKeyPair; } & TValue; ``` Asserts that the provided value implements the [KeyPairSigner](/api/type-aliases/KeyPairSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `asserts value is Readonly<{ address: Address; signMessages: any }> & Readonly<{ address: Address; signTransactions: any }> & { keyPair: CryptoKeyPair } & TValue` ## Example ```ts import { generateKeyPairSigner, assertIsKeyPairSigner } from '@solana/signers'; const signer = await generateKeyPairSigner(); assertIsKeyPairSigner(signer); // void assertIsKeyPairSigner({ address: address('1234..5678') }); // Throws an error. ``` # assertIsLamports (/api/functions/assertIsLamports) ```ts function assertIsLamports( putativeLamports, ): asserts putativeLamports is Lamports; ``` Lamport values returned from the RPC API conform to the type [Lamports](/api/type-aliases/Lamports). You can use a value of that type wherever a quantity of Lamports is expected. ## Parameters | Parameter | Type | | ------------------ | -------- | | `putativeLamports` | `bigint` | ## Returns `asserts putativeLamports is Lamports` ## Example From time to time you might acquire a number that you expect to be a quantity of Lamports, from an untrusted network API or user input. To assert that such an arbitrary number is usable as a quantity of Lamports, use this function. ```ts import { assertIsLamports } from '@solana/rpc-types'; // Imagine a function that creates a transfer instruction when a user submits a form. function handleSubmit() { // We know only that what the user typed conforms to the `number` type. const lamports: number = parseInt(quantityInput.value, 10); try { // If this type assertion function doesn't throw, then // Typescript will upcast `lamports` to `Lamports`. assertIsLamports(lamports); // At this point, `lamports` is a `Lamports` that can be used anywhere Lamports are expected. await transfer(fromAddress, toAddress, lamports); } catch (e) { // `lamports` turned out not to validate as a quantity of Lamports. } } ``` # assertIsMessageModifyingSigner (/api/functions/assertIsMessageModifyingSigner) ```ts function assertIsMessageModifyingSigner( value, ): asserts value is Readonly<{ address: Address; modifyAndSignMessages: any; }> & TValue; ``` Asserts that the provided value implements the [MessageModifyingSigner](/api/type-aliases/MessageModifyingSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `asserts value is Readonly<{ address: Address; modifyAndSignMessages: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { assertIsMessageModifyingSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; assertIsMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // void assertIsMessageModifyingSigner({ address }); // Throws an error. ``` ## See [isMessageModifyingSigner](/api/functions/isMessageModifyingSigner) # assertIsMessagePackerInstructionPlan (/api/functions/assertIsMessagePackerInstructionPlan) ```ts function assertIsMessagePackerInstructionPlan( plan, ): asserts plan is Readonly<{ getMessagePacker: () => MessagePacker; kind: 'messagePacker'; planType: 'instructionPlan'; }>; ``` Asserts that the given instruction plan is a [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------- | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to assert. | ## Returns `asserts plan is Readonly<{ getMessagePacker: () => MessagePacker; kind: "messagePacker"; planType: "instructionPlan" }>` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a message packer instruction plan. ## Example ```ts const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... */ }); assertIsMessagePackerInstructionPlan(plan); const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan. ``` ## See * [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) * [isMessagePackerInstructionPlan](/api/functions/isMessagePackerInstructionPlan) # assertIsMessagePartialSigner (/api/functions/assertIsMessagePartialSigner) ```ts function assertIsMessagePartialSigner( value, ): asserts value is Readonly<{ address: Address; signMessages: any; }> & TValue; ``` Asserts that the provided value implements the [MessagePartialSigner](/api/type-aliases/MessagePartialSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `asserts value is Readonly<{ address: Address; signMessages: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { assertIsMessagePartialSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; assertIsMessagePartialSigner({ address, signMessages: async () => {} }); // void assertIsMessagePartialSigner({ address }); // Throws an error. ``` ## See [isMessagePartialSigner](/api/functions/isMessagePartialSigner) # assertIsMessageSigner (/api/functions/assertIsMessageSigner) ```ts function assertIsMessageSigner( value, ): asserts value is MessageSigner & TValue; ``` Asserts that the provided value implements the [MessageSigner](/api/type-aliases/MessageSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `asserts value is MessageSigner & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { assertIsMessageSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; assertIsMessageSigner({ address, signMessages: async () => {} }); // void assertIsMessageSigner({ address, modifyAndSignMessages: async () => {} }); // void assertIsMessageSigner({ address }); // Throws an error. ``` ## See [isMessageSigner](/api/functions/isMessageSigner) # assertIsNonDivisibleSequentialInstructionPlan (/api/functions/assertIsNonDivisibleSequentialInstructionPlan) ```ts function assertIsNonDivisibleSequentialInstructionPlan( plan, ): asserts plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: InstructionPlan[]; planType: 'instructionPlan'; }> & { divisible: false }; ``` Asserts that the given instruction plan is a non-divisible [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan). A non-divisible sequential plan requires all its instructions to be executed atomically β€” either in a single transaction or in a transaction bundle. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------- | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to assert. | ## Returns `asserts plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: InstructionPlan[]; planType: "instructionPlan" }> & { divisible: false }` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a non-divisible sequential instruction plan. ## Example ```ts const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]); assertIsNonDivisibleSequentialInstructionPlan(plan); // All instructions must be executed atomically. ``` ## See * [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) * [isNonDivisibleSequentialInstructionPlan](/api/functions/isNonDivisibleSequentialInstructionPlan) # assertIsNonDivisibleSequentialTransactionPlan (/api/functions/assertIsNonDivisibleSequentialTransactionPlan) ```ts function assertIsNonDivisibleSequentialTransactionPlan( plan, ): asserts plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlan[]; planType: 'transactionPlan'; }> & { divisible: false }; ``` Asserts that the given transaction plan is a non-divisible [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan). A non-divisible sequential plan requires all its transaction messages to be executed atomically β€” usually in a transaction bundle. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------- | | `plan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to assert. | ## Returns `asserts plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlan[]; planType: "transactionPlan" }> & { divisible: false }` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a non-divisible sequential transaction plan. ## Example ```ts const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]); assertIsNonDivisibleSequentialTransactionPlan(plan); // All transaction messages must be executed atomically. ``` ## See * [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) * [isNonDivisibleSequentialTransactionPlan](/api/functions/isNonDivisibleSequentialTransactionPlan) # assertIsNonDivisibleSequentialTransactionPlanResult (/api/functions/assertIsNonDivisibleSequentialTransactionPlanResult) ```ts function assertIsNonDivisibleSequentialTransactionPlanResult< TContext, TTransactionMessage, TSingle, >( plan, ): asserts plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlanResult< TContext, TTransactionMessage, TSingle >[]; planType: 'transactionPlanResult'; }> & { divisible: false }; ``` Asserts that the given transaction plan result is a non-divisible [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult). A non-divisible sequential result indicates that the transactions were executed atomically β€” usually in a transaction bundle. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result to assert. | ## Returns `asserts plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlanResult[]; planType: "transactionPlanResult" }> & { divisible: false }` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a non-divisible sequential transaction plan result. ## Example ```ts const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]); assertIsNonDivisibleSequentialTransactionPlanResult(result); // Transactions were executed atomically. ``` ## See * [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) * [isNonDivisibleSequentialTransactionPlanResult](/api/functions/isNonDivisibleSequentialTransactionPlanResult) # assertIsOffCurveAddress (/api/functions/assertIsOffCurveAddress) ```ts function assertIsOffCurveAddress( putativeOffCurveAddress, ): asserts putativeOffCurveAddress is OffCurveAddress; ``` From time to time you might acquire an [Address](/api/type-aliases/Address), that you expect to validate as an off-curve address, from an untrusted source. Use this function to assert that such an address is off-curve. ## Type Parameters | Type Parameter | | ----------------------------------------------------------- | | `TAddress` *extends* [`Address`](/api/type-aliases/Address) | ## Parameters | Parameter | Type | | ------------------------- | ---------- | | `putativeOffCurveAddress` | `TAddress` | ## Returns `asserts putativeOffCurveAddress is OffCurveAddress` ## Example ```ts import { assertIsOffCurveAddress } from '@solana/addresses'; // Imagine a function that fetches an account's balance when a user submits a form. function handleSubmit() { // We know only that the input conforms to the `string` type. const address: string = accountAddressInput.value; try { // If this type assertion function doesn't throw, then // Typescript will upcast `address` to `Address`. assertIsAddress(address); // If this type assertion function doesn't throw, then // Typescript will upcast `address` to `OffCurveAddress`. assertIsOffCurveAddress(address); // At this point, `address` is an `OffCurveAddress` that can be used with the RPC. const balanceInLamports = await rpc.getBalance(address).send(); } catch (e) { // `address` turned out to NOT be a base58-encoded off-curve address } } ``` # assertIsOffchainMessageApplicationDomain (/api/functions/assertIsOffchainMessageApplicationDomain) ```ts function assertIsOffchainMessageApplicationDomain( putativeApplicationDomain, ): asserts putativeApplicationDomain is OffchainMessageApplicationDomain; ``` From time to time you might acquire a string, that you expect to validate as an offchain message application domain, from an untrusted network API or user input. Use this function to assert that such an arbitrary string is a base58-encoded application domain. ## Parameters | Parameter | Type | | --------------------------- | -------- | | `putativeApplicationDomain` | `string` | ## Returns `asserts putativeApplicationDomain is OffchainMessageApplicationDomain` ## Example ```ts import { assertIsOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages'; // Imagine a function that determines whether an application domain is valid. function handleSubmit() { // We know only that what the user typed conforms to the `string` type. const applicationDomain: string = applicationDomainInput.value; try { // If this type assertion function doesn't throw, then // Typescript will upcast `applicationDomain` to `OffchainMessageApplicationDomain`. assertIsOffchainMessageApplicationDomain(applicationDomain); // At this point, `applicationDomain` is a `OffchainMessageApplicationDomain` that can be // used to craft an offchain message. const offchainMessage: OffchainMessageV0 = { applicationDomain: offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'), // ... }; } catch (e) { // `applicationDomain` turned out not to be a base58-encoded application domain } } ``` # assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax (/api/functions/assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax) ```ts function assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax( putativeContent, ): asserts putativeContent is Readonly<{ format: RESTRICTED_ASCII_1232_BYTES_MAX; text: Brand< string, 'offchainMessageContentRestrictedAsciiOf1232BytesMax' >; }>; ``` In the event that you receive content of a v0 offchain message from an untrusted source, use this function to assert that it conforms to the [OffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) type. ## Parameters | Parameter | Type | | ------------------------ | ------------------------------------------------------------------------------------------------------------------ | | `putativeContent` | \{ `format`: [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat); `text`: `string`; } | | `putativeContent.format` | [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat) | | `putativeContent.text` | `string` | ## Returns `asserts putativeContent is Readonly<{ format: RESTRICTED_ASCII_1232_BYTES_MAX; text: Brand }>` ## See [OffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) for more detail. # assertIsOffchainMessageContentUtf8Of1232BytesMax (/api/functions/assertIsOffchainMessageContentUtf8Of1232BytesMax) ```ts function assertIsOffchainMessageContentUtf8Of1232BytesMax( putativeContent, ): asserts putativeContent is Readonly<{ format: UTF8_1232_BYTES_MAX; text: Brand; }>; ``` In the event that you receive content of a v0 offchain message from an untrusted source, use this function to assert that it conforms to the [OffchainMessageContentUtf8Of1232BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of1232BytesMax) type. ## Parameters | Parameter | Type | | ------------------------ | ------------------------------------------------------------------------------------------------------------------ | | `putativeContent` | \{ `format`: [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat); `text`: `string`; } | | `putativeContent.format` | [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat) | | `putativeContent.text` | `string` | ## Returns `asserts putativeContent is Readonly<{ format: UTF8_1232_BYTES_MAX; text: Brand }>` ## See [OffchainMessageContentUtf8Of1232BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of1232BytesMax) for more detail. # assertIsOffchainMessageContentUtf8Of65535BytesMax (/api/functions/assertIsOffchainMessageContentUtf8Of65535BytesMax) ```ts function assertIsOffchainMessageContentUtf8Of65535BytesMax( putativeContent, ): asserts putativeContent is Readonly<{ format: UTF8_65535_BYTES_MAX; text: Brand; }>; ``` In the event that you receive content of a v0 offchain message from an untrusted source, use this function to assert that it conforms to the [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) type. ## Parameters | Parameter | Type | | ------------------------ | ------------------------------------------------------------------------------------------------------------------ | | `putativeContent` | \{ `format`: [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat); `text`: `string`; } | | `putativeContent.format` | [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat) | | `putativeContent.text` | `string` | ## Returns `asserts putativeContent is Readonly<{ format: UTF8_65535_BYTES_MAX; text: Brand }>` ## See [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) for more detail. # assertIsOffchainMessageRestrictedAsciiOf1232BytesMax (/api/functions/assertIsOffchainMessageRestrictedAsciiOf1232BytesMax) ```ts function assertIsOffchainMessageRestrictedAsciiOf1232BytesMax( putativeMessage, ): asserts putativeMessage is OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent & Omit; ``` In the event that you receive a v0 offchain message from an untrusted source, use this function to assert that it is one whose content conforms to the [OffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) type. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------- | | `TMessage` *extends* [`OffchainMessageV0`](/api/type-aliases/OffchainMessageV0) | ## Parameters | Parameter | Type | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `putativeMessage` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`TMessage`, `"content"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `content`: \{ `format`: [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat); `text`: `string`; }; }> | ## Returns `asserts putativeMessage is OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent & Omit` ## See [OffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) for more detail. # assertIsOffchainMessageUtf8Of1232BytesMax (/api/functions/assertIsOffchainMessageUtf8Of1232BytesMax) ```ts function assertIsOffchainMessageUtf8Of1232BytesMax( putativeMessage, ): asserts putativeMessage is OffchainMessageWithUtf8Of1232BytesMaxContent & Omit; ``` In the event that you receive a v0 offchain message from an untrusted source, use this function to assert that it is one whose content conforms to the [offchainMessageContentUtf8Of1232BytesMax](/api/functions/offchainMessageContentUtf8Of1232BytesMax) type. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------- | | `TMessage` *extends* [`OffchainMessageV0`](/api/type-aliases/OffchainMessageV0) | ## Parameters | Parameter | Type | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `putativeMessage` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`TMessage`, `"content"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `content`: \{ `format`: [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat); `text`: `string`; }; `version`: `number`; }> | ## Returns `asserts putativeMessage is OffchainMessageWithUtf8Of1232BytesMaxContent & Omit` ## See [offchainMessageContentUtf8Of1232BytesMax](/api/functions/offchainMessageContentUtf8Of1232BytesMax) for more detail. # assertIsOffchainMessageUtf8Of65535BytesMax (/api/functions/assertIsOffchainMessageUtf8Of65535BytesMax) ```ts function assertIsOffchainMessageUtf8Of65535BytesMax( putativeMessage, ): asserts putativeMessage is OffchainMessageWithUtf8Of65535BytesMaxContent & Omit; ``` In the event that you receive a v0 offchain message from an untrusted source, use this function to assert that it is one whose content conforms to the [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) type. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------- | | `TMessage` *extends* [`OffchainMessageV0`](/api/type-aliases/OffchainMessageV0) | ## Parameters | Parameter | Type | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `putativeMessage` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`TMessage`, `"content"`> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `content`: \{ `format`: [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat); `text`: `string`; }; `version`: `number`; }> | ## Returns `asserts putativeMessage is OffchainMessageWithUtf8Of65535BytesMaxContent & Omit` ## See [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) for more detail. # assertIsParallelInstructionPlan (/api/functions/assertIsParallelInstructionPlan) ```ts function assertIsParallelInstructionPlan( plan, ): asserts plan is Readonly<{ kind: 'parallel'; plans: InstructionPlan[]; planType: 'instructionPlan'; }>; ``` Asserts that the given instruction plan is a [ParallelInstructionPlan](/api/type-aliases/ParallelInstructionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------- | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to assert. | ## Returns `asserts plan is Readonly<{ kind: "parallel"; plans: InstructionPlan[]; planType: "instructionPlan" }>` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a parallel instruction plan. ## Example ```ts const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]); assertIsParallelInstructionPlan(plan); console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan. ``` ## See * [ParallelInstructionPlan](/api/type-aliases/ParallelInstructionPlan) * [isParallelInstructionPlan](/api/functions/isParallelInstructionPlan) # assertIsParallelTransactionPlan (/api/functions/assertIsParallelTransactionPlan) ```ts function assertIsParallelTransactionPlan( plan, ): asserts plan is Readonly<{ kind: 'parallel'; plans: TransactionPlan[]; planType: 'transactionPlan'; }>; ``` Asserts that the given transaction plan is a [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------- | | `plan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to assert. | ## Returns `asserts plan is Readonly<{ kind: "parallel"; plans: TransactionPlan[]; planType: "transactionPlan" }>` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a parallel transaction plan. ## Example ```ts const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]); assertIsParallelTransactionPlan(plan); console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan. ``` ## See * [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan) * [isParallelTransactionPlan](/api/functions/isParallelTransactionPlan) # assertIsParallelTransactionPlanResult (/api/functions/assertIsParallelTransactionPlanResult) ```ts function assertIsParallelTransactionPlanResult< TContext, TTransactionMessage, TSingle, >( plan, ): asserts plan is Readonly<{ kind: 'parallel'; plans: TransactionPlanResult< TContext, TTransactionMessage, TSingle >[]; planType: 'transactionPlanResult'; }>; ``` Asserts that the given transaction plan result is a [ParallelTransactionPlanResult](/api/type-aliases/ParallelTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result to assert. | ## Returns `asserts plan is Readonly<{ kind: "parallel"; plans: TransactionPlanResult[]; planType: "transactionPlanResult" }>` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a parallel transaction plan result. ## Example ```ts const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]); assertIsParallelTransactionPlanResult(result); console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult. ``` ## See * [ParallelTransactionPlanResult](/api/type-aliases/ParallelTransactionPlanResult) * [isParallelTransactionPlanResult](/api/functions/isParallelTransactionPlanResult) # assertIsProgramDerivedAddress (/api/functions/assertIsProgramDerivedAddress) ```ts function assertIsProgramDerivedAddress( value, ): asserts value is readonly [ Address, ProgramDerivedAddressBump, ]; ``` In the event that you receive an address/bump-seed tuple from some untrusted source, use this function to assert that it conforms to the [ProgramDerivedAddress](/api/type-aliases/ProgramDerivedAddress) interface. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## Parameters | Parameter | Type | | --------- | --------- | | `value` | `unknown` | ## Returns `asserts value is readonly [Address, ProgramDerivedAddressBump]` ## See The [assertIsAddress](/api/functions/assertIsAddress) function for an example of how to use an assertion function. # assertIsSendableTransaction (/api/functions/assertIsSendableTransaction) ```ts function assertIsSendableTransaction( transaction, ): asserts transaction is FullySignedTransaction & TransactionWithinSizeLimit & TTransaction; ``` Asserts that a given transaction has all the required conditions to be sent to the network. From time to time you might acquire a [Transaction](/api/type-aliases/Transaction) from an untrusted network API or user input and you are not sure that it has all the required conditions to be sent to the network β€” such as being fully signed and within the size limit. This function can be used to assert that such a transaction is in fact sendable. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TTransaction` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> | ## Parameters | Parameter | Type | | ------------- | -------------- | | `transaction` | `TTransaction` | ## Returns `asserts transaction is FullySignedTransaction & TransactionWithinSizeLimit & TTransaction` ## Example ```ts import { assertIsSendableTransaction } from '@solana/transactions'; const transaction = getTransactionDecoder().decode(transactionBytes); try { // If this type assertion function doesn't throw, then Typescript will upcast `transaction` // to `SendableTransaction`. assertIsSendableTransaction(transaction); // At this point we know that the transaction can be sent to the network. await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); } catch(e) { if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) { setError(`Missing signatures for ${e.context.addresses.join(', ')}`); } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT)) { setError(`Transaction exceeds size limit of ${e.context.transactionSizeLimit} bytes`); } throw; } ``` # assertIsSequentialInstructionPlan (/api/functions/assertIsSequentialInstructionPlan) ```ts function assertIsSequentialInstructionPlan( plan, ): asserts plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: InstructionPlan[]; planType: 'instructionPlan'; }>; ``` Asserts that the given instruction plan is a [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------- | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to assert. | ## Returns `asserts plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: InstructionPlan[]; planType: "instructionPlan" }>` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a sequential instruction plan. ## Example ```ts const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]); assertIsSequentialInstructionPlan(plan); console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan. ``` ## See * [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) * [isSequentialInstructionPlan](/api/functions/isSequentialInstructionPlan) # assertIsSequentialTransactionPlan (/api/functions/assertIsSequentialTransactionPlan) ```ts function assertIsSequentialTransactionPlan( plan, ): asserts plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlan[]; planType: 'transactionPlan'; }>; ``` Asserts that the given transaction plan is a [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------- | | `plan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to assert. | ## Returns `asserts plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlan[]; planType: "transactionPlan" }>` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a sequential transaction plan. ## Example ```ts const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]); assertIsSequentialTransactionPlan(plan); console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan. ``` ## See * [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) * [isSequentialTransactionPlan](/api/functions/isSequentialTransactionPlan) # assertIsSequentialTransactionPlanResult (/api/functions/assertIsSequentialTransactionPlanResult) ```ts function assertIsSequentialTransactionPlanResult< TContext, TTransactionMessage, TSingle, >( plan, ): asserts plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlanResult< TContext, TTransactionMessage, TSingle >[]; planType: 'transactionPlanResult'; }>; ``` Asserts that the given transaction plan result is a [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result to assert. | ## Returns `asserts plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlanResult[]; planType: "transactionPlanResult" }>` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a sequential transaction plan result. ## Example ```ts const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]); assertIsSequentialTransactionPlanResult(result); console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult. ``` ## See * [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) * [isSequentialTransactionPlanResult](/api/functions/isSequentialTransactionPlanResult) # assertIsSignature (/api/functions/assertIsSignature) ```ts function assertIsSignature( putativeSignature, ): asserts putativeSignature is Signature; ``` Asserts that an arbitrary string is a base58-encoded Ed25519 signature. Useful when you receive a string from user input or an untrusted network API that you expect to represent an Ed25519 signature (eg. of a transaction). ## Parameters | Parameter | Type | | ------------------- | -------- | | `putativeSignature` | `string` | ## Returns `asserts putativeSignature is Signature` ## Example ```ts import { assertIsSignature } from '@solana/keys'; // Imagine a function that asserts whether a user-supplied signature is valid or not. function handleSubmit() { // We know only that what the user typed conforms to the `string` type. const signature: string = signatureInput.value; try { // If this type assertion function doesn't throw, then // Typescript will upcast `signature` to `Signature`. assertIsSignature(signature); // At this point, `signature` is a `Signature` that can be used with the RPC. const { value: [status], } = await rpc.getSignatureStatuses([signature]).send(); } catch (e) { // `signature` turned out not to be a base58-encoded signature } } ``` # assertIsSignatureBytes (/api/functions/assertIsSignatureBytes) ```ts function assertIsSignatureBytes( putativeSignatureBytes, ): asserts putativeSignatureBytes is SignatureBytes; ``` Asserts that an arbitrary `ReadonlyUint8Array` is an Ed25519 signature. Useful when you receive a `ReadonlyUint8Array` from an external interface (like the browser wallets' `signMessage` API) that you expect to represent an Ed25519 signature. ## Parameters | Parameter | Type | | ------------------------ | ---------------------------------------------------------- | | `putativeSignatureBytes` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ## Returns `asserts putativeSignatureBytes is SignatureBytes` ## Example ```ts import { assertIsSignatureBytes } from '@solana/keys'; // Imagine a function that verifies a signature. function verifySignature() { // We know only that the input conforms to the `ReadonlyUint8Array` type. const signatureBytes: ReadonlyUint8Array = signatureBytesInput; try { // If this type assertion function doesn't throw, then // Typescript will upcast `signatureBytes` to `SignatureBytes`. assertIsSignatureBytes(signatureBytes); // At this point, `signatureBytes` is a `SignatureBytes` that can be used with `verifySignature`. if (!(await verifySignature(publicKey, signatureBytes, data))) { throw new Error('The data were *not* signed by the private key associated with `publicKey`'); } } catch (e) { // `signatureBytes` turned out not to be a 64-byte Ed25519 signature } } ``` # assertIsSingleInstructionPlan (/api/functions/assertIsSingleInstructionPlan) ```ts function assertIsSingleInstructionPlan( plan, ): asserts plan is Readonly<{ instruction: Instruction; kind: 'single'; planType: 'instructionPlan'; }>; ``` Asserts that the given instruction plan is a [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------- | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to assert. | ## Returns `asserts plan is Readonly<{ instruction: Instruction; kind: "single"; planType: "instructionPlan" }>` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a single instruction plan. ## Example ```ts const plan: InstructionPlan = singleInstructionPlan(myInstruction); assertIsSingleInstructionPlan(plan); console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan. ``` ## See * [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan) * [isSingleInstructionPlan](/api/functions/isSingleInstructionPlan) # assertIsSingleTransactionPlan (/api/functions/assertIsSingleTransactionPlan) ```ts function assertIsSingleTransactionPlan( plan, ): asserts plan is Readonly<{ kind: 'single'; message: TransactionMessage & TransactionMessageWithFeePayer; planType: 'transactionPlan'; }>; ``` Asserts that the given transaction plan is a [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------- | | `plan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to assert. | ## Returns `asserts plan is Readonly<{ kind: "single"; message: TransactionMessage & TransactionMessageWithFeePayer; planType: "transactionPlan" }>` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a single transaction plan. ## Example ```ts const plan: TransactionPlan = singleTransactionPlan(transactionMessage); assertIsSingleTransactionPlan(plan); console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan. ``` ## See * [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan) * [isSingleTransactionPlan](/api/functions/isSingleTransactionPlan) # assertIsSingleTransactionPlanResult (/api/functions/assertIsSingleTransactionPlanResult) ```ts function assertIsSingleTransactionPlanResult< TContext, TTransactionMessage, TSingle, >(plan): asserts plan is TSingle; ``` Asserts that the given transaction plan result is a [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result to assert. | ## Returns `asserts plan is TSingle` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a single transaction plan result. ## Example ```ts const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, { signature }); assertIsSingleTransactionPlanResult(result); console.log(result.status); // TypeScript knows this is a SingleTransactionPlanResult. ``` ## See * [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) * [isSingleTransactionPlanResult](/api/functions/isSingleTransactionPlanResult) # assertIsStringifiedBigInt (/api/functions/assertIsStringifiedBigInt) ```ts function assertIsStringifiedBigInt( putativeBigInt, ): asserts putativeBigInt is StringifiedBigInt; ``` From time to time you might acquire a string, that you expect to parse as a `BigInt`, from an untrusted network API or user input. Use this function to assert that such an arbitrary string will in fact parse as a `BigInt`. ## Parameters | Parameter | Type | | ---------------- | -------- | | `putativeBigInt` | `string` | ## Returns `asserts putativeBigInt is StringifiedBigInt` ## Example ```ts import { assertIsStringifiedBigInt } from '@solana/rpc-types'; // Imagine having received a value that you presume represents the supply of some token. // At this point we know only that it conforms to the `string` type. try { // If this type assertion function doesn't throw, then // Typescript will upcast `supplyString` to `StringifiedBigInt`. assertIsStringifiedBigInt(supplyString); // At this point, `supplyString` is a `StringifiedBigInt`. supplyString satisfies StringifiedBigInt; } catch (e) { // `supplyString` turned out not to parse as a `BigInt` } ``` # assertIsStringifiedNumber (/api/functions/assertIsStringifiedNumber) ```ts function assertIsStringifiedNumber( putativeNumber, ): asserts putativeNumber is StringifiedNumber; ``` From time to time you might acquire a string, that you expect to parse as a `Number`, from an untrusted network API or user input. Use this function to assert that such an arbitrary string will in fact parse as a `Number`. ## Parameters | Parameter | Type | | ---------------- | -------- | | `putativeNumber` | `string` | ## Returns `asserts putativeNumber is StringifiedNumber` ## Example ```ts import { assertIsStringifiedNumber } from '@solana/rpc-types'; // Imagine having received a value that you presume represents some decimal number. // At this point we know only that it conforms to the `string` type. try { // If this type assertion function doesn't throw, then // Typescript will upcast `decimalNumberString` to `StringifiedNumber`. assertIsStringifiedNumber(decimalNumberString); // At this point, `decimalNumberString` is a `StringifiedNumber`. decimalNumberString satisfies StringifiedNumber; } catch (e) { // `decimalNumberString` turned out not to parse as a number. } ``` # assertIsSuccessfulSingleTransactionPlanResult (/api/functions/assertIsSuccessfulSingleTransactionPlanResult) ```ts function assertIsSuccessfulSingleTransactionPlanResult< TContext, TTransactionMessage, >( plan, ): asserts plan is SuccessfulSingleTransactionPlanResult< TContext, TTransactionMessage >; ``` Asserts that the given transaction plan result is a successful [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result to assert. | ## Returns `asserts plan is SuccessfulSingleTransactionPlanResult` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a successful single transaction plan result. ## Example ```ts const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, { signature }); assertIsSuccessfulSingleTransactionPlanResult(result); console.log(result.context.signature); // TypeScript knows this is a successful result. ``` ## See * [SuccessfulSingleTransactionPlanResult](/api/type-aliases/SuccessfulSingleTransactionPlanResult) * [isSuccessfulSingleTransactionPlanResult](/api/functions/isSuccessfulSingleTransactionPlanResult) # assertIsSuccessfulTransactionPlanResult (/api/functions/assertIsSuccessfulTransactionPlanResult) ```ts function assertIsSuccessfulTransactionPlanResult< TContext, TTransactionMessage, >( plan, ): asserts plan is SuccessfulTransactionPlanResult< TContext, TTransactionMessage >; ``` Asserts that the given transaction plan result is a [SuccessfulTransactionPlanResult](/api/type-aliases/SuccessfulTransactionPlanResult). This function verifies that the entire transaction plan result tree contains only successful single transaction results. It throws if any [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) in the tree has a 'failed' or 'canceled' status. Note: This is different from [assertIsSuccessfulSingleTransactionPlanResult](/api/functions/assertIsSuccessfulSingleTransactionPlanResult) which asserts that a single result is successful. This function asserts that the entire plan result tree (including all nested parallel/sequential structures) contains only successful transactions. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result to assert. | ## Returns `asserts plan is SuccessfulTransactionPlanResult` ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT` if any single transaction result in the tree is not successful. ## Example ```ts const result: TransactionPlanResult = parallelTransactionPlanResult([ successfulSingleTransactionPlanResult(messageA, { signature: signatureA }), successfulSingleTransactionPlanResult(messageB, { signature: signatureB }), ]); assertIsSuccessfulTransactionPlanResult(result); // All transactions were successful. result satisfies SuccessfulTransactionPlanResult; ``` ## See * [SuccessfulTransactionPlanResult](/api/type-aliases/SuccessfulTransactionPlanResult) * [isSuccessfulTransactionPlanResult](/api/functions/isSuccessfulTransactionPlanResult) * [assertIsSuccessfulSingleTransactionPlanResult](/api/functions/assertIsSuccessfulSingleTransactionPlanResult) # assertIsTransactionMessageWithBlockhashLifetime (/api/functions/assertIsTransactionMessageWithBlockhashLifetime) ```ts function assertIsTransactionMessageWithBlockhashLifetime( transactionMessage, ): asserts transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime; ``` From time to time you might acquire a transaction message, that you expect to have a blockhash-based lifetime, from an untrusted network API or user input. Use this function to assert that such a transaction message actually has a blockhash-based lifetime. ## Parameters | Parameter | Type | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `transactionMessage` | \| [`TransactionMessage`](/api/type-aliases/TransactionMessage) \| TransactionMessage & TransactionMessageWithBlockhashLifetime | ## Returns `asserts transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime` ## Example ```ts import { assertIsTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages'; try { // If this type assertion function doesn't throw, then // Typescript will upcast `message` to `TransactionMessageWithBlockhashLifetime`. assertIsTransactionMessageWithBlockhashLifetime(message); // At this point, `message` is a `TransactionMessageWithBlockhashLifetime` that can be used // with the RPC. const { blockhash } = message.lifetimeConstraint; const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send(); } catch (e) { // `message` turned out not to have a blockhash-based lifetime } ``` # assertIsTransactionMessageWithDurableNonceLifetime (/api/functions/assertIsTransactionMessageWithDurableNonceLifetime) ```ts function assertIsTransactionMessageWithDurableNonceLifetime( transactionMessage, ): asserts transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime; ``` From time to time you might acquire a transaction message, that you expect to have a nonce-based lifetime, from an untrusted network API or user input. Use this function to assert that such a transaction message actually has a nonce-based lifetime. ## Parameters | Parameter | Type | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `transactionMessage` | \| [`TransactionMessage`](/api/type-aliases/TransactionMessage) \| TransactionMessage & TransactionMessageWithDurableNonceLifetime\ | ## Returns `asserts transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime` ## Example ```ts import { assertIsTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages'; try { // If this type assertion function doesn't throw, then // Typescript will upcast `message` to `TransactionMessageWithDurableNonceLifetime`. assertIsTransactionMessageWithDurableNonceLifetime(message); // At this point, `message` is a `TransactionMessageWithDurableNonceLifetime` that can be used // with the RPC. const { nonce, nonceAccountAddress } = message.lifetimeConstraint; const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress); } catch (e) { // `message` turned out not to have a nonce-based lifetime } ``` # assertIsTransactionMessageWithSingleSendingSigner (/api/functions/assertIsTransactionMessageWithSingleSendingSigner) ```ts function assertIsTransactionMessageWithSingleSendingSigner< TTransactionMessage, >( transaction, ): asserts transaction is NominalType< 'brand', 'TransactionMessageWithSingleSendingSigner' > & Partial< Pick< | TransactionMessageWithFeePayerSigner< string, TransactionSigner > | Readonly<{ feePayer: Readonly<{ address: Address }> & Readonly<{ modifyAndSignTransactions?: undefined; signAndSendTransactions?: undefined; signTransactions?: undefined; }>; }>, 'feePayer' > > & Readonly<{ instructions: readonly (Instruction< string, readonly ( | AccountLookupMeta | AccountMeta )[] > & InstructionWithSigners< TransactionSigner, readonly AccountMetaWithSigner< TransactionSigner >[] >)[]; }> & TTransactionMessage; ``` Asserts that the provided transaction message has exactly one [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner). This can be useful when using the [signAndSendTransactionMessageWithSigners](/api/functions/signAndSendTransactionMessageWithSigners) function to ensure it will be able to select the correct signer to send the transaction. ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | | `TTransactionMessage` *extends* `TransactionMessage` & `TransactionMessageWithFeePayer`\<`string`> | The inferred type of the transaction message provided. | ## Parameters | Parameter | Type | | ------------- | --------------------- | | `transaction` | `TTransactionMessage` | ## Returns asserts transaction is NominalType\<"brand", "TransactionMessageWithSingleSendingSigner"> & Partial\> | Readonly\<\{ feePayer: Readonly\<\{ address: Address\ }> & Readonly\<\{ modifyAndSignTransactions?: undefined; signAndSendTransactions?: undefined; signTransactions?: undefined }> }>, "feePayer">> & Readonly\<\{ instructions: readonly (Instruction\ | AccountMeta\)\[]> & InstructionWithSigners\, readonly AccountMetaWithSigner\>\[]>)\[] }> & TTransactionMessage ## Example ```ts import { assertIsTransactionMessageWithSingleSendingSigner, signAndSendTransactionMessageWithSigners } from '@solana/signers'; assertIsTransactionMessageWithSingleSendingSigner(transactionMessage); const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage); ``` ## See * [signAndSendTransactionMessageWithSigners](/api/functions/signAndSendTransactionMessageWithSigners) * [isTransactionMessageWithSingleSendingSigner](/api/functions/isTransactionMessageWithSingleSendingSigner) # assertIsTransactionMessageWithinSizeLimit (/api/functions/assertIsTransactionMessageWithinSizeLimit) ```ts function assertIsTransactionMessageWithinSizeLimit( transactionMessage, ): asserts transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage; ``` Asserts that a given transaction message is within the size limit when compiled into a transaction. Throws a SolanaError of code SOLANA\_ERROR\_\_TRANSACTION\_\_EXCEEDS\_SIZE\_LIMIT if the transaction message exceeds the size limit. ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------------- | ------------------------------------------ | | `TTransactionMessage` *extends* `TransactionMessage` & `TransactionMessageWithFeePayer`\<`string`> | The type of the given transaction message. | ## Parameters | Parameter | Type | | -------------------- | --------------------- | | `transactionMessage` | `TTransactionMessage` | ## Returns `asserts transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage` ## Example ```ts assertIsTransactionMessageWithinSizeLimit(transactionMessage); transactionMessage satisfies TransactionMessageWithinSizeLimit; ``` # assertIsTransactionModifyingSigner (/api/functions/assertIsTransactionModifyingSigner) ```ts function assertIsTransactionModifyingSigner( value, ): asserts value is Readonly<{ address: Address; modifyAndSignTransactions: any; }> & TValue; ``` Asserts that the provided value implements the [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `asserts value is Readonly<{ address: Address; modifyAndSignTransactions: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { assertIsTransactionModifyingSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; assertIsTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // void assertIsTransactionModifyingSigner({ address }); // Throws an error. ``` ## See [isTransactionModifyingSigner](/api/functions/isTransactionModifyingSigner) # assertIsTransactionPartialSigner (/api/functions/assertIsTransactionPartialSigner) ```ts function assertIsTransactionPartialSigner( value, ): asserts value is Readonly<{ address: Address; signTransactions: any; }> & TValue; ``` Asserts that the provided value implements the [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `asserts value is Readonly<{ address: Address; signTransactions: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { assertIsTransactionPartialSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; assertIsTransactionPartialSigner({ address, signTransactions: async () => {} }); // void assertIsTransactionPartialSigner({ address }); // Throws an error. ``` ## See [isTransactionPartialSigner](/api/functions/isTransactionPartialSigner) # assertIsTransactionSendingSigner (/api/functions/assertIsTransactionSendingSigner) ```ts function assertIsTransactionSendingSigner( value, ): asserts value is Readonly<{ address: Address; signAndSendTransactions: any; }> & TValue; ``` Asserts that the provided value implements the [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `asserts value is Readonly<{ address: Address; signAndSendTransactions: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { assertIsTransactionSendingSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; assertIsTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // void assertIsTransactionSendingSigner({ address }); // Throws an error. ``` ## See [isTransactionSendingSigner](/api/functions/isTransactionSendingSigner) # assertIsTransactionSigner (/api/functions/assertIsTransactionSigner) ```ts function assertIsTransactionSigner( value, ): asserts value is TransactionSigner & TValue; ``` Asserts that the provided value implements the [TransactionSigner](/api/type-aliases/TransactionSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `asserts value is TransactionSigner & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { assertIsTransactionSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; assertIsTransactionSigner({ address, signTransactions: async () => {} }); // void assertIsTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // void assertIsTransactionSigner({ address, signAndSendTransactions: async () => {} }); // void assertIsTransactionSigner({ address }); // Throws an error. ``` ## See [isTransactionSigner](/api/functions/isTransactionSigner) # assertIsTransactionWithBlockhashLifetime (/api/functions/assertIsTransactionWithBlockhashLifetime) ```ts function assertIsTransactionWithBlockhashLifetime( transaction, ): asserts transaction is Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> & TransactionWithBlockhashLifetime; ``` From time to time you might acquire a transaction, that you expect to have a blockhash-based lifetime, from for example a wallet. Use this function to assert that such a transaction actually has a blockhash-based lifetime. ## Parameters | Parameter | Type | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `transaction` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> & [`TransactionWithLifetime`](/api/type-aliases/TransactionWithLifetime) | ## Returns `asserts transaction is Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap }> & TransactionWithBlockhashLifetime` ## Example ```ts import { assertIsTransactionWithBlockhashLifetime } from '@solana/transactions'; try { // If this type assertion function doesn't throw, then // Typescript will upcast `transaction` to `TransactionWithBlockhashLifetime`. assertIsTransactionWithBlockhashLifetime(transaction); // At this point, `transaction` is a `TransactionWithBlockhashLifetime` that can be used // with the RPC. const { blockhash } = transaction.lifetimeConstraint; const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send(); } catch (e) { // `transaction` turned out not to have a blockhash-based lifetime } ``` # assertIsTransactionWithDurableNonceLifetime (/api/functions/assertIsTransactionWithDurableNonceLifetime) ```ts function assertIsTransactionWithDurableNonceLifetime( transaction, ): asserts transaction is Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> & TransactionWithDurableNonceLifetime; ``` From time to time you might acquire a transaction, that you expect to have a nonce-based lifetime, from for example a wallet. Use this function to assert that such a transaction actually has a nonce-based lifetime. ## Parameters | Parameter | Type | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `transaction` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> & [`TransactionWithLifetime`](/api/type-aliases/TransactionWithLifetime) | ## Returns `asserts transaction is Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap }> & TransactionWithDurableNonceLifetime` ## Example ```ts import { assertIsTransactionWithDurableNonceLifetime } from '@solana/transactions'; try { // If this type assertion function doesn't throw, then // Typescript will upcast `transaction` to `TransactionWithDurableNonceLifetime`. assertIsTransactionWithDurableNonceLifetime(transaction); // At this point, `transaction` is a `TransactionWithDurableNonceLifetime` that can be used // with the RPC. const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint; const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress); } catch (e) { // `transaction` turned out not to have a nonce-based lifetime } ``` # assertIsTransactionWithinSizeLimit (/api/functions/assertIsTransactionWithinSizeLimit) ```ts function assertIsTransactionWithinSizeLimit( transaction, ): asserts transaction is TransactionWithinSizeLimit & TTransaction; ``` Asserts that a given transaction is within the size limit. Throws a SolanaError of code SOLANA\_ERROR\_\_TRANSACTION\_\_EXCEEDS\_SIZE\_LIMIT if the transaction exceeds the size limit. ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------- | | `TTransaction` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> | The type of the given transaction. | ## Parameters | Parameter | Type | | ------------- | -------------- | | `transaction` | `TTransaction` | ## Returns `asserts transaction is TransactionWithinSizeLimit & TTransaction` ## Example ```ts assertIsTransactionWithinSizeLimit(transaction); transaction satisfies TransactionWithinSizeLimit; ``` # assertIsUnixTimestamp (/api/functions/assertIsUnixTimestamp) ```ts function assertIsUnixTimestamp( putativeTimestamp, ): asserts putativeTimestamp is UnixTimestamp; ``` Timestamp values returned from the RPC API conform to the type [UnixTimestamp](/api/type-aliases/UnixTimestamp). You can use a value of that type wherever a timestamp is expected. ## Parameters | Parameter | Type | | ------------------- | -------- | | `putativeTimestamp` | `bigint` | ## Returns `asserts putativeTimestamp is UnixTimestamp` ## Example From time to time you might acquire a number that you expect to be a timestamp, from an untrusted network API or user input. To assert that such an arbitrary number is usable as a Unix timestamp, use this function. ```ts import { assertIsUnixTimestamp } from '@solana/rpc-types'; // Imagine having received a value that you presume represents a timestamp. // At this point we know only that it conforms to the `bigint` type. try { // If this type assertion function doesn't throw, then // Typescript will upcast `timestamp` to `UnixTimestamp`. assertIsUnixTimestamp(timestamp); // At this point, `timestamp` is a `UnixTimestamp`. timestamp satisfies UnixTimestamp; } catch (e) { // `timestamp` turned out not to be a valid Unix timestamp } ``` # assertIsVariableSize (/api/functions/assertIsVariableSize) ## Call Signature ```ts function assertIsVariableSize( encoder, ): asserts encoder is VariableSizeEncoder; ``` Asserts that the given codec, encoder, or decoder is variable-size. If the object is not variable-size (i.e., it has a `fixedSize` property), this function throws a [SolanaError](/api/classes/SolanaError) with the code `SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH`. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------ | | `encoder` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | ### Returns `asserts encoder is VariableSizeEncoder` ### Throws If the object is not variable-size. ### Examples Asserting a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); assertIsVariableSize(encoder); // Passes ``` Attempting to assert a fixed-size encoder. ```ts const encoder = getU32Encoder(); assertIsVariableSize(encoder); // Throws SolanaError ``` ### Remarks This function is the assertion-based counterpart of [isVariableSize](/api/functions/isVariableSize). If you only need to check whether an object is variable-size without throwing an error, use [isVariableSize](/api/functions/isVariableSize) instead. Also note that this function is the inverse of [assertIsFixedSize](/api/functions/assertIsFixedSize). ### See * [isVariableSize](/api/functions/isVariableSize) * [assertIsFixedSize](/api/functions/assertIsFixedSize) ## Call Signature ```ts function assertIsVariableSize( decoder, ): asserts decoder is VariableSizeDecoder; ``` Asserts that the given codec, encoder, or decoder is variable-size. If the object is not variable-size (i.e., it has a `fixedSize` property), this function throws a [SolanaError](/api/classes/SolanaError) with the code `SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH`. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | ### Returns `asserts decoder is VariableSizeDecoder` ### Throws If the object is not variable-size. ### Examples Asserting a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); assertIsVariableSize(encoder); // Passes ``` Attempting to assert a fixed-size encoder. ```ts const encoder = getU32Encoder(); assertIsVariableSize(encoder); // Throws SolanaError ``` ### Remarks This function is the assertion-based counterpart of [isVariableSize](/api/functions/isVariableSize). If you only need to check whether an object is variable-size without throwing an error, use [isVariableSize](/api/functions/isVariableSize) instead. Also note that this function is the inverse of [assertIsFixedSize](/api/functions/assertIsFixedSize). ### See * [isVariableSize](/api/functions/isVariableSize) * [assertIsFixedSize](/api/functions/assertIsFixedSize) ## Call Signature ```ts function assertIsVariableSize( codec, ): asserts codec is VariableSizeCodec; ``` Asserts that the given codec, encoder, or decoder is variable-size. If the object is not variable-size (i.e., it has a `fixedSize` property), this function throws a [SolanaError](/api/classes/SolanaError) with the code `SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH`. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | --------- | --------------------------------------------------- | | `codec` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | ### Returns `asserts codec is VariableSizeCodec` ### Throws If the object is not variable-size. ### Examples Asserting a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); assertIsVariableSize(encoder); // Passes ``` Attempting to assert a fixed-size encoder. ```ts const encoder = getU32Encoder(); assertIsVariableSize(encoder); // Throws SolanaError ``` ### Remarks This function is the assertion-based counterpart of [isVariableSize](/api/functions/isVariableSize). If you only need to check whether an object is variable-size without throwing an error, use [isVariableSize](/api/functions/isVariableSize) instead. Also note that this function is the inverse of [assertIsFixedSize](/api/functions/assertIsFixedSize). ### See * [isVariableSize](/api/functions/isVariableSize) * [assertIsFixedSize](/api/functions/assertIsFixedSize) ## Call Signature ```ts function assertIsVariableSize( codec, ): asserts codec is { maxSize?: number }; ``` Asserts that the given codec, encoder, or decoder is variable-size. If the object is not variable-size (i.e., it has a `fixedSize` property), this function throws a [SolanaError](/api/classes/SolanaError) with the code `SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH`. ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------ | | `codec` | \| \{ `fixedSize`: `number`; } \| \{ `maxSize?`: `number`; } | ### Returns `asserts codec is { maxSize?: number }` ### Throws If the object is not variable-size. ### Examples Asserting a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); assertIsVariableSize(encoder); // Passes ``` Attempting to assert a fixed-size encoder. ```ts const encoder = getU32Encoder(); assertIsVariableSize(encoder); // Throws SolanaError ``` ### Remarks This function is the assertion-based counterpart of [isVariableSize](/api/functions/isVariableSize). If you only need to check whether an object is variable-size without throwing an error, use [isVariableSize](/api/functions/isVariableSize) instead. Also note that this function is the inverse of [assertIsFixedSize](/api/functions/assertIsFixedSize). ### See * [isVariableSize](/api/functions/isVariableSize) * [assertIsFixedSize](/api/functions/assertIsFixedSize) # assertKeyExporterIsAvailable (/api/functions/assertKeyExporterIsAvailable) ```ts function assertKeyExporterIsAvailable(): void; ``` Throws an exception unless [\`crypto.subtle.exportKey()\`](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) is available in the current JavaScript environment. ## Returns `void` # assertKeyGenerationIsAvailable (/api/functions/assertKeyGenerationIsAvailable) ```ts function assertKeyGenerationIsAvailable(): Promise; ``` Throws an exception unless [\`crypto.subtle.generateKey()\`](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) is available in the current JavaScript environment and has support for the Ed25519 curve. ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`> # assertNumberIsBetweenForCodec (/api/functions/assertNumberIsBetweenForCodec) ```ts function assertNumberIsBetweenForCodec( codecDescription, min, max, value, ): void; ``` Ensures that a given number falls within a specified range. If the number is outside the allowed range, an error is thrown. This function is primarily used to validate values before encoding them in a codec. ## Parameters | Parameter | Type | Description | | ------------------ | -------------------- | ---------------------------------------------------------------- | | `codecDescription` | `string` | A string describing the codec that is performing the validation. | | `min` | `number` \| `bigint` | The minimum allowed value (inclusive). | | `max` | `number` \| `bigint` | The maximum allowed value (inclusive). | | `value` | `number` \| `bigint` | The number to validate. | ## Returns `void` ## Throws [SolanaError](/api/classes/SolanaError) if the value is out of range. ## Examples Validating a number within range. ```ts assertNumberIsBetweenForCodec('u8', 0, 255, 42); // Passes ``` Throwing an error for an out-of-range value. ```ts assertNumberIsBetweenForCodec('u8', 0, 255, 300); // Throws ``` # assertOffchainMessageV1Equal (/api/functions/assertOffchainMessageV1Equal) ```ts function assertOffchainMessageV1Equal( receivedMessage, expectedMessage, ): void; ``` Asserts that a version 1 offchain message you received from an untrusted source is the message that you expected it to be. A signer (eg. a wallet) returns the message bytes it signed alongside its signature. Verifying that signature proves only that the signer produced it over *those* bytes; it says nothing about whether those bytes represent the message you asked for. Use this function to establish that they do, then verify the signature separately with [verifyOffchainMessageEnvelope](/api/functions/verifyOffchainMessageEnvelope). Perform this assertion *before* verifying signatures. A signer that signed the wrong message will otherwise surface as a signature verification failure, which misattributes the problem to the cryptography rather than to the content. This function compares version 1 messages only. Decoding produces an [OffchainMessage](/api/type-aliases/OffchainMessage) of indeterminate version, so narrow it to a [OffchainMessageV1](/api/type-aliases/OffchainMessageV1) before calling this β€” see the example below. Deciding what to do about a message of some other version is a matter of policy that belongs to you rather than to this function. ## Parameters | Parameter | Type | Description | | ----------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------ | | `receivedMessage` | [`OffchainMessageV1`](/api/type-aliases/OffchainMessageV1) | The message you decoded from the bytes the signer reports having signed. | | `expectedMessage` | [`OffchainMessageV1`](/api/type-aliases/OffchainMessageV1) | The message you expected the signer to sign. | ## Returns `void` ## Throws A SolanaError with code SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_CONTENT\_DOES\_NOT\_MATCH\_EXPECTED if the two messages' contents differ. ## Throws A SolanaError with code SOLANA\_ERROR\_\_OFFCHAIN\_MESSAGE\_\_REQUIRED\_SIGNATORIES\_DO\_NOT\_MATCH\_EXPECTED if the two messages require signatures from different addresses. ## Example ```ts import { getOffchainMessageDecoder, assertOffchainMessageV1Equal } from '@solana/offchain-messages'; const receivedMessage = getOffchainMessageDecoder().decode(signedOffchainMessage); switch (receivedMessage.version) { case 1: assertOffchainMessageV1Equal(receivedMessage, expectedMessage); break; default: throw new Error(`Expected a version 1 message; got version ${receivedMessage.version}`); } ``` ## Remarks Required signatories are compared without regard to order. The offchain message specification mandates that they be serialized in lexicographic order, so a decoded message always lists them in that order while `expectedMessage` may list them in whatever order you built it with. Both lists are sorted before they are compared, and they are reported in sorted order in the error context so that they can be compared by eye. Order is the only thing ignored. The lists are otherwise compared element by element, so listing an address twice in `expectedMessage` is a mismatch rather than a no-op. A decoded message can never contain a duplicate β€” the codec rejects one β€” so this only arises from a malformed `expectedMessage`, and reporting it surfaces the mistake instead of hiding it. Message content is not included in the error context, because it can carry data you would rather not have written to logs or forwarded to an error reporting service. Its length in UTF-8 bytes β€” the encoding in which version 1 content is serialized β€” is reported instead. ## See [verifyOffchainMessageEnvelope](/api/functions/verifyOffchainMessageEnvelope) to verify the signatures themselves once you know the message is the one you expected. # assertPRNGIsAvailable (/api/functions/assertPRNGIsAvailable) ```ts function assertPRNGIsAvailable(): void; ``` Throws an exception unless [\`crypto.getRandomValues()\`](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) is available in the current JavaScript environment. ## Returns `void` # assertSigningCapabilityIsAvailable (/api/functions/assertSigningCapabilityIsAvailable) ```ts function assertSigningCapabilityIsAvailable(): void; ``` Throws an exception unless [\`crypto.subtle.sign()\`](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) is available in the current JavaScript environment. ## Returns `void` # assertValidBaseString (/api/functions/assertValidBaseString) ```ts function assertValidBaseString(alphabet, testValue, givenValue?): void; ``` Asserts that a given string contains only characters from the specified alphabet. This function validates whether a string consists exclusively of characters from the provided `alphabet`. If the validation fails, it throws an error indicating the invalid base string. ## Parameters | Parameter | Type | Description | | ------------- | -------- | ------------------------------------------------------------------- | | `alphabet` | `string` | The allowed set of characters for the base encoding. | | `testValue` | `string` | The string to validate against the given alphabet. | | `givenValue?` | `string` | The original string provided by the user (defaults to `testValue`). | ## Returns `void` ## Throws If `testValue` contains characters not present in `alphabet`. ## Example Validating a base-8 encoded string. ```ts assertValidBaseString('01234567', '123047'); // Passes assertValidBaseString('01234567', '128'); // Throws error ``` # assertValidNumberOfItemsForCodec (/api/functions/assertValidNumberOfItemsForCodec) ```ts function assertValidNumberOfItemsForCodec( codecDescription, expected, actual, ): void; ``` Checks the number of items in an array-like structure is expected. ## Parameters | Parameter | Type | | ------------------ | -------------------- | | `codecDescription` | `string` | | `expected` | `number` \| `bigint` | | `actual` | `number` \| `bigint` | ## Returns `void` # assertVerificationCapabilityIsAvailable (/api/functions/assertVerificationCapabilityIsAvailable) ```ts function assertVerificationCapabilityIsAvailable(): void; ``` Throws an exception unless [\`crypto.subtle.verify()\`](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) is available in the current JavaScript environment. ## Returns `void` # binaryFixedPoint (/api/functions/binaryFixedPoint) ```ts function binaryFixedPoint( signedness, totalBits, fractionalBits, ): ( input, rounding?, ) => BinaryFixedPoint; ``` Returns a factory that constructs [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) values from decimal strings. The outer call validates the shape parameters once and the returned factory can be called many times to construct values of that shape. The input string is parsed as a decimal number and scaled by `2 ** fractionalBits` to compute the raw bigint. Values that cannot be represented exactly in binary (such as `"0.1"`) trigger the rounding behaviour documented on [RoundingMode](/api/type-aliases/RoundingMode), with `'strict'` throwing `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` by default. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | ---------------- | ----------------- | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `fractionalBits` | `TFractionalBits` | ## Returns (`input`, `rounding?`) => [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> ## Example ```ts const audioSample = binaryFixedPoint('signed', 16, 15); audioSample('0.5'); // raw === 16384n (exact) audioSample('0.1'); // throws under the default 'strict' mode audioSample('0.1', 'round'); // raw === 3277n ``` ## See * [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) * [rawBinaryFixedPoint](/api/functions/rawBinaryFixedPoint) * [ratioBinaryFixedPoint](/api/functions/ratioBinaryFixedPoint) # binaryFixedPointToBase10 (/api/functions/binaryFixedPointToBase10) ```ts function binaryFixedPointToBase10(value): object; ``` Converts a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) to its exact base-10 representation as a `(raw, decimals)` pair such that the mathematical value equals `raw / 10 ** decimals`. Because `1 / 2 ** F` has a finite decimal expansion of exactly `F` digits, the conversion is always lossless: `raw / 2 ** F === (raw * 5 ** F) / 10 ** F`. The transformed raw therefore carries exactly `fractionalBits` decimal digits of precision. Useful when you want to feed a binary fixed-point into a tool that understands base-10 scaled integers (such as `Intl.NumberFormat`'s string scientific notation). ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------- | | `value` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `number`> | ## Returns `object` | Name | Type | | ---------- | -------- | | `decimals` | `number` | | `raw` | `bigint` | ## Example ```ts const q1_15 = binaryFixedPoint('signed', 16, 15); binaryFixedPointToBase10(q1_15('0.5')); // { raw: 500000000000000n, decimals: 15 } ``` ## See [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) # binaryFixedPointToNumber (/api/functions/binaryFixedPointToNumber) ```ts function binaryFixedPointToNumber(value): number; ``` Converts a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) to a JavaScript `number`. Precision loss occurs only when `|value.raw / 2 ** fractionalBits|` exceeds `Number.MAX_SAFE_INTEGER`, since JavaScript numbers have only \~53 bits of mantissa. For values whose magnitude fits that budget the result is exact, regardless of the raw value's magnitude. For exact representations prefer [binaryFixedPointToString](/api/functions/binaryFixedPointToString). ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------- | | `value` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `number`> | ## Returns `number` ## Example ```ts const q1_15 = binaryFixedPoint('signed', 16, 15); binaryFixedPointToNumber(q1_15('0.5')); // 0.5 ``` ## See [binaryFixedPointToString](/api/functions/binaryFixedPointToString) # binaryFixedPointToString (/api/functions/binaryFixedPointToString) ```ts function binaryFixedPointToString(value, options?): string; ``` Returns the canonical decimal string representation of a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint). Because `1 / 2 ** fractionalBits` has a finite decimal expansion, the default output is always exact. This means that values with many `fractionalBits` can produce long strings β€” pass `options.decimals` to cap the output at a desired precision, optionally with a [RoundingMode](/api/type-aliases/RoundingMode). Use `options.padTrailingZeros` to emit exactly as many fractional digits as requested; when `decimals` is omitted, this pads to `value.fractionalBits` (the full exact expansion length). Throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` when `options.decimals` forces a lossy rescale under the default `'strict'` rounding mode. ## Parameters | Parameter | Type | | ---------- | --------------------------------------------------------------------------------------------------------------------------- | | `value` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `number`> | | `options?` | [`FixedPointToStringOptions`](/api/type-aliases/FixedPointToStringOptions) | ## Returns `string` ## Example ```ts const q1_15 = binaryFixedPoint('signed', 16, 15); binaryFixedPointToString(q1_15('0.5')); // "0.5" binaryFixedPointToString(q1_15('0.5'), { padTrailingZeros: true }); // "0.500000000000000" binaryFixedPointToString(ugly, { decimals: 2, rounding: 'round' }); // "0.48" ``` ## See [binaryFixedPointToNumber](/api/functions/binaryFixedPointToNumber) # blockhash (/api/functions/blockhash) ```ts function blockhash(putativeBlockhash): Blockhash; ``` Combines *asserting* that a string is a blockhash with *coercing* it to the [Blockhash](/api/type-aliases/Blockhash) type. It's most useful with untrusted input. ## Parameters | Parameter | Type | | ------------------- | -------- | | `putativeBlockhash` | `string` | ## Returns [`Blockhash`](/api/type-aliases/Blockhash) ## Example ```ts import { blockhash } from '@solana/rpc-types'; const { value: isValid } = await rpc.isBlockhashValid(blockhash(blockhashFromUserInput)).send(); ``` > \[!TIP] > When starting from a known-good blockhash as a string, it's more efficient to typecast it > rather than to use the blockhash helper, because the helper unconditionally performs > validation on its input. > > ```ts > import { Blockhash } from '@solana/rpc-types'; > > const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash; > ``` # bridgeStoreToAsyncIterable (/api/functions/bridgeStoreToAsyncIterable) ```ts function bridgeStoreToAsyncIterable( store, signal, shouldYield?, ): AsyncIterable; ``` Adapts a [ReactiveStreamStore](/api/type-aliases/ReactiveStreamStore) into an `AsyncIterable`, so a *push*-based reactive store can be driven by *pull*-based code that consumes a stream by `for await`-ing it β€” for example TanStack Query's `experimental_streamedQuery`. The bridge only *observes* the store; it does not open or tear down the connection. Just like every other consumer in this ecosystem β€” a store does nothing until you `connect()` it β€” the caller owns the store's lifecycle: `connect()` the store yourself (typically binding the same `signal` via [\`withSignal()\`](/api/type-aliases/ReactiveStreamStore#withsignal)), and `reset()` it when you're done if you intend to reuse it. The bridge subscribes, yields the store's current and subsequent values, and unsubscribes when iteration ends. This is the store-backed counterpart to [createAsyncIterableFromDataPublisher](/api/functions/createAsyncIterableFromDataPublisher). That helper turns a raw [DataPublisher](/api/interfaces/DataPublisher) directly into an `AsyncIterable` and queues every message so none are dropped; use it when you have a publisher and no store. `bridgeStoreToAsyncIterable` instead sits on top of a `ReactiveStreamStore`, so it reflects the store's unified `idle`/`loading`/`loaded`/`error` lifecycle and its stale-while-revalidate behaviour β€” and, because a store only ever holds the *latest* snapshot, it is latest-wins rather than fully buffered. Note this is also distinct from an RPC subscription's own `AsyncIterable` (`await rpcSubscriptions.someNotifications().subscribe(...)`), which vends messages straight off the transport without a store in between. On iteration it seeds from the store's current snapshot, then yields its lifecycle: * `loaded` β†’ yields the value (the one already present when iteration begins, then each subsequent update), unless an optional `shouldYield` predicate rejects it. Latest-wins: if several notifications land between pulls, only the most recent unconsumed value is yielded (a subscription consumer wants the freshest state, not a backlog). * `error` β†’ throws, so the consuming `for await` rejects. Substitutes a SOLANA\_ERROR\_\_SUBSCRIBABLE\_\_STREAM\_CLOSED\_WITHOUT\_ERROR sentinel when the store reports an error with a nullish payload. An error takes precedence over a buffered value: if a `loaded` value is still pending when an `error` arrives, that value is dropped and the error propagates (once errored, stop yielding). * `signal` aborts β†’ ends the iterable cleanly (no error). A subscription never completes on its own, so `signal` is how the iterable terminates: aborting it unblocks a parked `for await` and ends the loop. Bind the same signal to the store's connection (`store.withSignal(signal).connect()`) so the abort tears the underlying stream down too. However iteration ends β€” value exhaustion, error, or abort β€” the bridge unsubscribes from the store. It does not `reset()` the store; that is the caller's decision. ## Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------- | | `T` | The notification type emitted by the store. | ## Parameters | Parameter | Type | Description | | -------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `store` | [`ReactiveStreamStore`](/api/type-aliases/ReactiveStreamStore)\<`T`> | A stream store to observe. Connect it yourself β€” the bridge does not. | | `signal` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | Terminates the iterable when aborted. Bind it to the store's connection too (`store.withSignal(signal).connect()`) so an abort also tears down the underlying stream. | | `shouldYield?` | (`value`) => `boolean` | Optional gate run against each `loaded` value before it is yielded. Return `false` to drop the value. When omitted, every loaded value is yielded. | ## Returns `AsyncIterable`\<`T`> An `AsyncIterable` that yields each store value until the store errors or `signal` aborts. ## Throws Rethrows the store's `error` payload when the store transitions to `status: 'error'`, or a SolanaError with code SOLANA\_ERROR\_\_SUBSCRIBABLE\_\_STREAM\_CLOSED\_WITHOUT\_ERROR when that payload is nullish. ## Example ```ts const store = rpcSubscriptions.slotNotifications().reactiveStore(); const controller = new AbortController(); // The caller owns the connection β€” bind it to the same signal so an abort tears it down. store.withSignal(controller.signal).connect(); try { for await (const notification of bridgeStoreToAsyncIterable(store, controller.signal)) { console.log('Latest slot:', notification.slot); } } catch (e) { console.error('The subscription errored', e); } finally { store.reset(); } // Elsewhere: controller.abort() ends the loop cleanly. ``` ## See * [ReactiveStreamStore](/api/type-aliases/ReactiveStreamStore) * [createAsyncIterableFromDataPublisher](/api/functions/createAsyncIterableFromDataPublisher) # bytesEqual (/api/functions/bytesEqual) ```ts function bytesEqual(bytes1, bytes2): boolean; ``` Returns true if and only if the provided `bytes1` and `bytes2` byte arrays are equal. ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | | `bytes1` | \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | The first byte array to compare. | | `bytes2` | \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | The second byte array to compare. | ## Returns `boolean` ## Example ```ts const bytes1 = new Uint8Array([0x01, 0x02, 0x03, 0x04]); const bytes2 = new Uint8Array([0x01, 0x02, 0x03, 0x04]); bytesEqual(bytes1, bytes2); // true ``` # canceledSingleTransactionPlanResult (/api/functions/canceledSingleTransactionPlanResult) ```ts function canceledSingleTransactionPlanResult< TContext, TTransactionMessage, >( plannedMessage, context?, ): CanceledSingleTransactionPlanResult; ``` Creates a canceled [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) from a transaction message. This function creates a single result with a 'canceled' status, indicating that the transaction execution was canceled. It includes the original transaction message. ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | The type of the transaction message | ## Parameters | Parameter | Type | Description | | ---------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------- | | `plannedMessage` | `TTransactionMessage` | The original transaction message | | `context?` | [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<`TContext`> | - | ## Returns [`CanceledSingleTransactionPlanResult`](/api/type-aliases/CanceledSingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> ## Example ```ts const result = canceledSingleTransactionPlanResult(transactionMessage); result satisfies SingleTransactionPlanResult; ``` ## See [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) # cmpBinaryFixedPoint (/api/functions/cmpBinaryFixedPoint) ```ts function cmpBinaryFixedPoint(a, b): -1 | 0 | 1; ``` Compares two [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) values and returns `-1`, `0`, or `1` depending on whether `a` is less than, equal to, or greater than `b`. Only the `kind` and `fractionalBits` of the two operands must match; `signedness` and `totalBits` are allowed to differ because they are storage concerns only and do not affect the mathematical value being compared. Mismatches on the constrained dimensions throw `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH`. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TFractionalBits`> | | `b` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TFractionalBits`>> | ## Returns `-1` | `0` | `1` ## Example ```ts const q1_15 = binaryFixedPoint('signed', 16, 15); cmpBinaryFixedPoint(q1_15('0.25'), q1_15('0.5')); // -1 cmpBinaryFixedPoint(q1_15('0.5'), q1_15('0.5')); // 0 cmpBinaryFixedPoint(q1_15('0.75'), q1_15('0.5')); // 1 ``` ## See * [eqBinaryFixedPoint](/api/functions/eqBinaryFixedPoint) * [ltBinaryFixedPoint](/api/functions/ltBinaryFixedPoint) * [lteBinaryFixedPoint](/api/functions/lteBinaryFixedPoint) * [gtBinaryFixedPoint](/api/functions/gtBinaryFixedPoint) * [gteBinaryFixedPoint](/api/functions/gteBinaryFixedPoint) # cmpDecimalFixedPoint (/api/functions/cmpDecimalFixedPoint) ```ts function cmpDecimalFixedPoint(a, b): -1 | 0 | 1; ``` Compares two [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) values and returns `-1`, `0`, or `1` depending on whether `a` is less than, equal to, or greater than `b`. Only the `kind` and `decimals` of the two operands must match; `signedness` and `totalBits` are allowed to differ because they are storage concerns only and do not affect the mathematical value being compared. Mismatches on the constrained dimensions throw `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH`. ## Type Parameters | Type Parameter | | ------------------------------ | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TDecimals`> | | `b` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TDecimals`>> | ## Returns `-1` | `0` | `1` ## Example ```ts const usd = decimalFixedPoint('unsigned', 64, 2); cmpDecimalFixedPoint(usd('1.25'), usd('2.50')); // -1 cmpDecimalFixedPoint(usd('2.50'), usd('2.50')); // 0 cmpDecimalFixedPoint(usd('3.75'), usd('2.50')); // 1 ``` ## See * [eqDecimalFixedPoint](/api/functions/eqDecimalFixedPoint) * [ltDecimalFixedPoint](/api/functions/ltDecimalFixedPoint) * [lteDecimalFixedPoint](/api/functions/lteDecimalFixedPoint) * [gtDecimalFixedPoint](/api/functions/gtDecimalFixedPoint) * [gteDecimalFixedPoint](/api/functions/gteDecimalFixedPoint) # combineCodec (/api/functions/combineCodec) ## Call Signature ```ts function combineCodec( encoder, decoder, ): FixedSizeCodec; ``` Combines an `Encoder` and a `Decoder` into a `Codec`. That is, given a `Encoder` and a `Decoder`, this function returns a `Codec`. This allows for modular composition by keeping encoding and decoding logic separate while still offering a convenient way to bundle them into a single `Codec`. This is particularly useful for library maintainers who want to expose `Encoders`, `Decoders`, and `Codecs` separately, enabling tree-shaking of unused logic. The provided `Encoder` and `Decoder` must be compatible in terms of: * **Fixed Size:** If both are fixed-size, they must have the same `fixedSize` value. * **Variable Size:** If either has a `maxSize` attribute, it must match the other. If these conditions are not met, a [SolanaError](/api/classes/SolanaError) will be thrown. ### Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes (for fixed-size codecs). | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------- | ------------------------- | | `encoder` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`> | The `Encoder` to combine. | | `decoder` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `TSize`> | The `Decoder` to combine. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`> A `Codec` that provides both `encode` and `decode` methods. ### Throws * `SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH` Thrown if the encoder and decoder have mismatched size types (fixed vs. variable). * `SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH` Thrown if both are fixed-size but have different `fixedSize` values. * `SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH` Thrown if the `maxSize` attributes do not match. ### Examples Creating a fixed-size `Codec` from an encoder and a decoder. ```ts const encoder = getU32Encoder(); const decoder = getU32Decoder(); const codec = combineCodec(encoder, decoder); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 ``` Creating a variable-size `Codec` from an encoder and a decoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()); const codec = combineCodec(encoder, decoder); const bytes = codec.encode("hello"); // 0x0500000068656c6c6f const value = codec.decode(bytes); // "hello" ``` ### Remarks The recommended pattern for defining codecs in libraries is to expose separate functions for the encoder, decoder, and codec. This allows users to import only what they need, improving tree-shaking efficiency. ```ts type MyType = /* ... */; const getMyTypeEncoder = (): Encoder => { /* ... */ }; const getMyTypeDecoder = (): Decoder => { /* ... */ }; const getMyTypeCodec = (): Codec => combineCodec(getMyTypeEncoder(), getMyTypeDecoder()); ``` ### See * [Codec](/api/type-aliases/Codec) * [Encoder](/api/type-aliases/Encoder) * [Decoder](/api/type-aliases/Decoder) ## Call Signature ```ts function combineCodec( encoder, decoder, ): VariableSizeCodec; ``` Combines an `Encoder` and a `Decoder` into a `Codec`. That is, given a `Encoder` and a `Decoder`, this function returns a `Codec`. This allows for modular composition by keeping encoding and decoding logic separate while still offering a convenient way to bundle them into a single `Codec`. This is particularly useful for library maintainers who want to expose `Encoders`, `Decoders`, and `Codecs` separately, enabling tree-shaking of unused logic. The provided `Encoder` and `Decoder` must be compatible in terms of: * **Fixed Size:** If both are fixed-size, they must have the same `fixedSize` value. * **Variable Size:** If either has a `maxSize` attribute, it must match the other. If these conditions are not met, a [SolanaError](/api/classes/SolanaError) will be thrown. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------- | ------------------------- | | `encoder` | [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`> | The `Encoder` to combine. | | `decoder` | [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`> | The `Decoder` to combine. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`> A `Codec` that provides both `encode` and `decode` methods. ### Throws * `SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH` Thrown if the encoder and decoder have mismatched size types (fixed vs. variable). * `SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH` Thrown if both are fixed-size but have different `fixedSize` values. * `SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH` Thrown if the `maxSize` attributes do not match. ### Examples Creating a fixed-size `Codec` from an encoder and a decoder. ```ts const encoder = getU32Encoder(); const decoder = getU32Decoder(); const codec = combineCodec(encoder, decoder); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 ``` Creating a variable-size `Codec` from an encoder and a decoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()); const codec = combineCodec(encoder, decoder); const bytes = codec.encode("hello"); // 0x0500000068656c6c6f const value = codec.decode(bytes); // "hello" ``` ### Remarks The recommended pattern for defining codecs in libraries is to expose separate functions for the encoder, decoder, and codec. This allows users to import only what they need, improving tree-shaking efficiency. ```ts type MyType = /* ... */; const getMyTypeEncoder = (): Encoder => { /* ... */ }; const getMyTypeDecoder = (): Decoder => { /* ... */ }; const getMyTypeCodec = (): Codec => combineCodec(getMyTypeEncoder(), getMyTypeDecoder()); ``` ### See * [Codec](/api/type-aliases/Codec) * [Encoder](/api/type-aliases/Encoder) * [Decoder](/api/type-aliases/Decoder) ## Call Signature ```ts function combineCodec(encoder, decoder): Codec; ``` Combines an `Encoder` and a `Decoder` into a `Codec`. That is, given a `Encoder` and a `Decoder`, this function returns a `Codec`. This allows for modular composition by keeping encoding and decoding logic separate while still offering a convenient way to bundle them into a single `Codec`. This is particularly useful for library maintainers who want to expose `Encoders`, `Decoders`, and `Codecs` separately, enabling tree-shaking of unused logic. The provided `Encoder` and `Decoder` must be compatible in terms of: * **Fixed Size:** If both are fixed-size, they must have the same `fixedSize` value. * **Variable Size:** If either has a `maxSize` attribute, it must match the other. If these conditions are not met, a [SolanaError](/api/classes/SolanaError) will be thrown. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------ | ------------------------- | | `encoder` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | The `Encoder` to combine. | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | The `Decoder` to combine. | ### Returns [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> A `Codec` that provides both `encode` and `decode` methods. ### Throws * `SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH` Thrown if the encoder and decoder have mismatched size types (fixed vs. variable). * `SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH` Thrown if both are fixed-size but have different `fixedSize` values. * `SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH` Thrown if the `maxSize` attributes do not match. ### Examples Creating a fixed-size `Codec` from an encoder and a decoder. ```ts const encoder = getU32Encoder(); const decoder = getU32Decoder(); const codec = combineCodec(encoder, decoder); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 ``` Creating a variable-size `Codec` from an encoder and a decoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()); const codec = combineCodec(encoder, decoder); const bytes = codec.encode("hello"); // 0x0500000068656c6c6f const value = codec.decode(bytes); // "hello" ``` ### Remarks The recommended pattern for defining codecs in libraries is to expose separate functions for the encoder, decoder, and codec. This allows users to import only what they need, improving tree-shaking efficiency. ```ts type MyType = /* ... */; const getMyTypeEncoder = (): Encoder => { /* ... */ }; const getMyTypeDecoder = (): Decoder => { /* ... */ }; const getMyTypeCodec = (): Codec => combineCodec(getMyTypeEncoder(), getMyTypeDecoder()); ``` ### See * [Codec](/api/type-aliases/Codec) * [Encoder](/api/type-aliases/Encoder) * [Decoder](/api/type-aliases/Decoder) # commitmentComparator (/api/functions/commitmentComparator) ```ts function commitmentComparator(a, b): -1 | 0 | 1; ``` ## Parameters | Parameter | Type | | --------- | -------------------------------------------- | | `a` | [`Commitment`](/api/type-aliases/Commitment) | | `b` | [`Commitment`](/api/type-aliases/Commitment) | ## Returns `-1` | `0` | `1` # compileOffchainMessageEnvelope (/api/functions/compileOffchainMessageEnvelope) ```ts function compileOffchainMessageEnvelope( offchainMessage, ): OffchainMessageEnvelope; ``` Returns an [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope) object for a given [OffchainMessage](/api/type-aliases/OffchainMessage). This includes the compiled bytes of the offchain message, and a map of signatures. This map will have a key for each address that is required to sign the message. The message envelope will not yet have signatures for any of these signatories. ## Parameters | Parameter | Type | | ----------------- | ------------------------------------------------------ | | `offchainMessage` | [`OffchainMessage`](/api/type-aliases/OffchainMessage) | ## Returns [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope) ## Remarks If the offchain message version is known ahead of time, use one of the compile functions specific to that version so as not to bundle more code than you need. # compileOffchainMessageV0Envelope (/api/functions/compileOffchainMessageV0Envelope) ```ts function compileOffchainMessageV0Envelope( offchainMessage, ): OffchainMessageEnvelope; ``` Returns an [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope) object for a given [OffchainMessageV0](/api/type-aliases/OffchainMessageV0). This includes the compiled bytes of the offchain message, and a map of signatures. This map will have a key for each address that is required to sign the message. The message envelope will not yet have signatures for any of these signatories. ## Parameters | Parameter | Type | | ----------------- | ---------------------------------------------------------- | | `offchainMessage` | [`OffchainMessageV0`](/api/type-aliases/OffchainMessageV0) | ## Returns [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope) # compileOffchainMessageV1Envelope (/api/functions/compileOffchainMessageV1Envelope) ```ts function compileOffchainMessageV1Envelope( offchainMessage, ): OffchainMessageEnvelope; ``` Returns an [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope) object for a given [OffchainMessageV1](/api/type-aliases/OffchainMessageV1). This includes the compiled bytes of the offchain message, and a map of signatures. This map will have a key for each address that is required to sign the message. The message envelope will not yet have signatures for any of these signatories. ## Parameters | Parameter | Type | | ----------------- | ---------------------------------------------------------- | | `offchainMessage` | [`OffchainMessageV1`](/api/type-aliases/OffchainMessageV1) | ## Returns [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope) # compileTransaction (/api/functions/compileTransaction) ```ts function compileTransaction( transactionMessage, ): Readonly>; ``` Returns a [Transaction](/api/type-aliases/Transaction) object for a given TransactionMessage. This includes the compiled bytes of the transaction message, and a map of signatures. This map will have a key for each address that is required to sign the transaction. The transaction will not yet have signatures for any of these addresses. Whether a transaction message is ready to be compiled or not is enforced for you at the type level. In order to be signable, a transaction message must: * have a version and a list of zero or more instructions (ie. conform to TransactionMessage) * have a fee payer set (ie. conform to TransactionMessageWithFeePayer) * have a lifetime specified (ie. conform to TransactionMessageWithBlockhashLifetime or TransactionMessageWithDurableNonceLifetime) ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* `TransactionMessage` & `TransactionMessageWithFeePayer`\<`string`> | ## Parameters | Parameter | Type | | -------------------- | --------------------- | | `transactionMessage` | `TTransactionMessage` | ## Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<[`TransactionFromTransactionMessage`](/api/type-aliases/TransactionFromTransactionMessage)\<`TTransactionMessage`>> # compileTransactionMessage (/api/functions/compileTransactionMessage) ## Call Signature ```ts function compileTransactionMessage( transactionMessage, ): ForwardTransactionMessageLifetime< Readonly<{ header: ReturnType; instructions: Readonly<{ accountIndices?: number[]; data?: ReadonlyUint8Array; programAddressIndex: number; }>[]; staticAccounts: Address[]; version: 'legacy'; }>, TTransactionMessage >; ``` Converts the type of transaction message data structure that you create in your application to the type of transaction message data structure that can be encoded for execution on the network. This is a lossy process; you can not fully reconstruct a source message from a compiled message without extra information. In particular, supporting details about the lifetime constraint and the concrete addresses of accounts sourced from account lookup tables will be lost to compilation. ### Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> & `object` | ### Parameters | Parameter | Type | | -------------------- | --------------------- | | `transactionMessage` | `TTransactionMessage` | ### Returns `ForwardTransactionMessageLifetime`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `header`: [`ReturnType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype)\<*typeof* `getCompiledMessageHeader`>; `instructions`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accountIndices?`: `number`\[]; `data?`: `ReadonlyUint8Array`\<`ArrayBufferLike`>; `programAddressIndex`: `number`; }>\[]; `staticAccounts`: `Address`\[]; `version`: `"legacy"`; }>, `TTransactionMessage`> ### See [decompileTransactionMessage](/api/functions/decompileTransactionMessage) ## Call Signature ```ts function compileTransactionMessage( transactionMessage, ): ForwardTransactionMessageLifetime< Readonly<{ addressTableLookups?: Readonly<{ lookupTableAddress: Address; readonlyIndexes: readonly number[]; writableIndexes: readonly number[]; }>[]; header: ReturnType; instructions: Readonly<{ accountIndices?: number[]; data?: ReadonlyUint8Array; programAddressIndex: number; }>[]; staticAccounts: Address[]; version: 0; }>, TTransactionMessage >; ``` Converts the type of transaction message data structure that you create in your application to the type of transaction message data structure that can be encoded for execution on the network. This is a lossy process; you can not fully reconstruct a source message from a compiled message without extra information. In particular, supporting details about the lifetime constraint and the concrete addresses of accounts sourced from account lookup tables will be lost to compilation. ### Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> & `object` | ### Parameters | Parameter | Type | | -------------------- | --------------------- | | `transactionMessage` | `TTransactionMessage` | ### Returns `ForwardTransactionMessageLifetime`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `addressTableLookups?`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lookupTableAddress`: `Address`; `readonlyIndexes`: readonly `number`\[]; `writableIndexes`: readonly `number`\[]; }>\[]; `header`: [`ReturnType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype)\<*typeof* `getCompiledMessageHeader`>; `instructions`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `accountIndices?`: `number`\[]; `data?`: `ReadonlyUint8Array`\<`ArrayBufferLike`>; `programAddressIndex`: `number`; }>\[]; `staticAccounts`: `Address`\[]; `version`: `0`; }>, `TTransactionMessage`> ### See [decompileTransactionMessage](/api/functions/decompileTransactionMessage) ## Call Signature ```ts function compileTransactionMessage( transactionMessage, ): ForwardTransactionMessageLifetime< Readonly<{ configMask: number; configValues: CompiledTransactionConfigValue[]; header: ReturnType; instructionHeaders: InstructionHeader[]; instructionPayloads: InstructionPayload[]; numInstructions: number; numStaticAccounts: number; staticAccounts: Address[]; version: 1; }>, TTransactionMessage >; ``` Converts the type of transaction message data structure that you create in your application to the type of transaction message data structure that can be encoded for execution on the network. This is a lossy process; you can not fully reconstruct a source message from a compiled message without extra information. In particular, supporting details about the lifetime constraint and the concrete addresses of accounts sourced from account lookup tables will be lost to compilation. ### Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> & `object` | ### Parameters | Parameter | Type | | -------------------- | --------------------- | | `transactionMessage` | `TTransactionMessage` | ### Returns `ForwardTransactionMessageLifetime`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `configMask`: `number`; `configValues`: `CompiledTransactionConfigValue`\[]; `header`: [`ReturnType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype)\<*typeof* `getCompiledMessageHeader`>; `instructionHeaders`: `InstructionHeader`\[]; `instructionPayloads`: `InstructionPayload`\[]; `numInstructions`: `number`; `numStaticAccounts`: `number`; `staticAccounts`: `Address`\[]; `version`: `1`; }>, `TTransactionMessage`> ### See [decompileTransactionMessage](/api/functions/decompileTransactionMessage) ## Call Signature ```ts function compileTransactionMessage( transactionMessage, ): ForwardTransactionMessageLifetime< CompiledTransactionMessage, TTransactionMessage >; ``` Converts the type of transaction message data structure that you create in your application to the type of transaction message data structure that can be encoded for execution on the network. This is a lossy process; you can not fully reconstruct a source message from a compiled message without extra information. In particular, supporting details about the lifetime constraint and the concrete addresses of accounts sourced from account lookup tables will be lost to compilation. ### Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ### Parameters | Parameter | Type | | -------------------- | --------------------- | | `transactionMessage` | `TTransactionMessage` | ### Returns `ForwardTransactionMessageLifetime`\<[`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage), `TTransactionMessage`> ### See [decompileTransactionMessage](/api/functions/decompileTransactionMessage) # compressTransactionMessageUsingAddressLookupTables (/api/functions/compressTransactionMessageUsingAddressLookupTables) ```ts function compressTransactionMessageUsingAddressLookupTables< TTransactionMessage, >( transactionMessage, addressesByLookupTableAddress, ): | TTransactionMessage | WidenTransactionMessageInstructions; ``` Given a transaction message and a mapping of lookup tables to the addresses stored in them, this function will return a new transaction message with the same instructions but with all non-signer accounts that are found in the given lookup tables represented by an AccountLookupMeta instead of an AccountMeta. This means that these accounts will take up less space in the compiled transaction message. This size reduction is most significant when the transaction includes many accounts from the same lookup table. ## Type Parameters | Type Parameter | Default type | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `instructions`: readonly `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]>\[]; `version`: `0`; }> | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `instructions`: readonly `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]>\[]; `version`: `0`; }> | ## Parameters | Parameter | Type | | ------------------------------- | ---------------------------------------------------------------------------------- | | `transactionMessage` | `TTransactionMessage` | | `addressesByLookupTableAddress` | [`AddressesByLookupTableAddress`](/api/type-aliases/AddressesByLookupTableAddress) | ## Returns \| `TTransactionMessage` \| `WidenTransactionMessageInstructions`\<`TTransactionMessage`> ## Example ```ts import { address } from '@solana/addresses'; import { AddressesByLookupTableAddress, compressTransactionMessageUsingAddressLookupTables, } from '@solana/transaction-messages'; import { fetchAddressLookupTable } from '@solana-program/address-lookup-table'; const lookupTableAddress = address('4QwSwNriKPrz8DLW4ju5uxC2TN5cksJx6tPUPj7DGLAW'); const { data: { addresses }, } = await fetchAddressLookupTable(rpc, lookupTableAddress); const addressesByAddressLookupTable: AddressesByLookupTableAddress = { [lookupTableAddress]: addresses, }; const compressedTransactionMessage = compressTransactionMessageUsingAddressLookupTables( transactionMessage, addressesByAddressLookupTable, ); ``` # containsBytes (/api/functions/containsBytes) ```ts function containsBytes(data, bytes, offset): boolean; ``` Returns true if and only if the provided `data` byte array contains the provided `bytes` byte array at the specified `offset`. ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | | `data` | \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | The byte array in which to search for `bytes`. | | `bytes` | \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | The byte sequence to search for. | | `offset` | `number` | The position in `data` where the search begins. | ## Returns `boolean` ## Example ```ts const data = new Uint8Array([0x01, 0x02, 0x03, 0x04]); const bytes = new Uint8Array([0x02, 0x03]); containsBytes(data, bytes, 1); // true containsBytes(data, bytes, 2); // false ``` # createAddressWithSeed (/api/functions/createAddressWithSeed) ```ts function createAddressWithSeed(__namedParameters): Promise
; ``` Returns a base58-encoded address derived from some base address, some program address, and a seed string or byte array. ## Parameters | Parameter | Type | | ------------------- | ----------- | | `__namedParameters` | `SeedInput` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Address`](/api/type-aliases/Address)> ## Example ```ts import { createAddressWithSeed } from '@solana/addresses'; const derivedAddress = await createAddressWithSeed({ // The private key associated with this address will be able to sign for `derivedAddress`. baseAddress: 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address, // Only this program will be able to write data to this account. programAddress: '445erYq578p2aERrGW9mn9KiYe3fuG6uHdcJ2LPPShGw' as Address, seed: 'data-account', }); ``` # createAsyncGeneratorWithInitialValueAndSlotTracking (/api/functions/createAsyncGeneratorWithInitialValueAndSlotTracking) ```ts function createAsyncGeneratorWithInitialValueAndSlotTracking< TRpcValue, TSubscriptionValue, TItem, >( config, ): AsyncGenerator< Readonly<{ context: Readonly<{ slot: Slot; }>; value: TItem; }> >; ``` Creates an async generator that combines an initial RPC fetch with an ongoing subscription, yielding values as they arrive from either source. The generator uses slot-based comparison to ensure that only the most recent values are yielded. Any value at a slot older than a previously yielded value is silently dropped. This prevents stale data from appearing when the RPC response and subscription notifications arrive out of order. Things to note: * The generator yields [SolanaRpcResponse](/api/type-aliases/SolanaRpcResponse) values from both the RPC response and subscription notifications, each containing the slot context and the mapped value. * Out-of-order values (by slot) are silently dropped β€” they are never yielded. * On error from either source, the generator throws the error. * Triggering the caller's abort signal causes the generator to return (complete without error). * The generator completes when the subscription ends, an error occurs, or the abort signal fires. ## Type Parameters | Type Parameter | | -------------------- | | `TRpcValue` | | `TSubscriptionValue` | | `TItem` | ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------- | ----------- | | `config` | `CreateAsyncGeneratorWithInitialValueAndSlotTrackingConfig`\<`TRpcValue`, `TSubscriptionValue`, `TItem`> | - | ## Returns [`AsyncGenerator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `context`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `slot`: [`Slot`](/api/type-aliases/Slot); }>; `value`: `TItem`; }>> ## Example ```ts import { address, createAsyncGeneratorWithInitialValueAndSlotTracking, createSolanaRpc, createSolanaRpcSubscriptions, } from '@solana/kit'; const rpc = createSolanaRpc('http://127.0.0.1:8899'); const rpcSubscriptions = createSolanaRpcSubscriptions('ws://127.0.0.1:8900'); const myAddress = address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'); const abortController = new AbortController(); for await (const balance of createAsyncGeneratorWithInitialValueAndSlotTracking({ abortSignal: abortController.signal, rpcRequest: rpc.getBalance(myAddress, { commitment: 'confirmed' }), rpcValueMapper: lamports => lamports, rpcSubscriptionRequest: rpcSubscriptions.accountNotifications(myAddress), rpcSubscriptionValueMapper: ({ lamports }) => lamports, })) { console.log(`Balance at slot ${balance.context.slot}:`, balance.value); } ``` # createAsyncIterableFromDataPublisher (/api/functions/createAsyncIterableFromDataPublisher) ```ts function createAsyncIterableFromDataPublisher( config, ): AsyncIterable; ``` Returns an `AsyncIterable` given a data publisher. The iterable will produce iterators that vend messages published to `dataChannelName` and will throw the first time a message is published to `errorChannelName`. Triggering the abort signal will cause all iterators spawned from this iterator to return once they have published all queued messages. Things to note: * If a message is published over a channel before the `AsyncIterator` attached to it has polled for the next result, the message will be queued in memory. * Messages only begin to be queued after the first time an iterator begins to poll. Channel messages published before that time will be dropped. * If there are messages in the queue and an error occurs, all queued messages will be vended to the iterator before the error is thrown. * If there are messages in the queue and the abort signal fires, all queued messages will be vended to the iterator after which it will return. * Any new iterators created after the first error is encountered will reject with that error when polled. ## Type Parameters | Type Parameter | | -------------- | | `TData` | ## Parameters | Parameter | Type | Description | | --------- | -------- | ----------- | | `config` | `Config` | - | ## Returns `AsyncIterable`\<`TData`> ## Example ```ts const iterable = createAsyncIterableFromDataPublisher({ abortSignal: AbortSignal.timeout(10_000), dataChannelName: 'message', dataPublisher, errorChannelName: 'error', }); try { for await (const message of iterable) { console.log('Got message', message); } } catch (e) { console.error('An error was published to the error channel', e); } finally { console.log("It's been 10 seconds; that's enough for now."); } ``` # createBlockHeightExceedencePromiseFactory (/api/functions/createBlockHeightExceedencePromiseFactory) ## Call Signature ```ts function createBlockHeightExceedencePromiseFactory( config, ): GetBlockHeightExceedencePromiseFn; ``` Creates a promise that throws when the network progresses past the block height after which the supplied blockhash is considered expired for use as a transaction lifetime specifier. When a transaction's lifetime is tied to a blockhash, that transaction can be landed on the network until that blockhash expires. All blockhashes have a block height after which they are considered to have expired. ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------- | ----------- | | `config` | `CreateBlockHeightExceedencePromiseFactoryConfig`\<`"devnet"`> | - | ### Returns `GetBlockHeightExceedencePromiseFn` ### Example ```ts import { isSolanaError, SolanaError } from '@solana/errors'; import { createBlockHeightExceedencePromiseFactory } from '@solana/transaction-confirmation'; const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({ rpc, rpcSubscriptions, }); try { await getBlockHeightExceedencePromise({ lastValidBlockHeight }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) { console.error( `The block height of the network has exceeded ${e.context.lastValidBlockHeight}. ` + `It is now ${e.context.currentBlockHeight}`, ); // Re-sign and retry the transaction. return; } throw e; } ``` ## Call Signature ```ts function createBlockHeightExceedencePromiseFactory( config, ): GetBlockHeightExceedencePromiseFn; ``` Creates a promise that throws when the network progresses past the block height after which the supplied blockhash is considered expired for use as a transaction lifetime specifier. When a transaction's lifetime is tied to a blockhash, that transaction can be landed on the network until that blockhash expires. All blockhashes have a block height after which they are considered to have expired. ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------- | ----------- | | `config` | `CreateBlockHeightExceedencePromiseFactoryConfig`\<`"testnet"`> | - | ### Returns `GetBlockHeightExceedencePromiseFn` ### Example ```ts import { isSolanaError, SolanaError } from '@solana/errors'; import { createBlockHeightExceedencePromiseFactory } from '@solana/transaction-confirmation'; const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({ rpc, rpcSubscriptions, }); try { await getBlockHeightExceedencePromise({ lastValidBlockHeight }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) { console.error( `The block height of the network has exceeded ${e.context.lastValidBlockHeight}. ` + `It is now ${e.context.currentBlockHeight}`, ); // Re-sign and retry the transaction. return; } throw e; } ``` ## Call Signature ```ts function createBlockHeightExceedencePromiseFactory( config, ): GetBlockHeightExceedencePromiseFn; ``` Creates a promise that throws when the network progresses past the block height after which the supplied blockhash is considered expired for use as a transaction lifetime specifier. When a transaction's lifetime is tied to a blockhash, that transaction can be landed on the network until that blockhash expires. All blockhashes have a block height after which they are considered to have expired. ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------- | ----------- | | `config` | `CreateBlockHeightExceedencePromiseFactoryConfig`\<`"mainnet"`> | - | ### Returns `GetBlockHeightExceedencePromiseFn` ### Example ```ts import { isSolanaError, SolanaError } from '@solana/errors'; import { createBlockHeightExceedencePromiseFactory } from '@solana/transaction-confirmation'; const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({ rpc, rpcSubscriptions, }); try { await getBlockHeightExceedencePromise({ lastValidBlockHeight }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) { console.error( `The block height of the network has exceeded ${e.context.lastValidBlockHeight}. ` + `It is now ${e.context.currentBlockHeight}`, ); // Re-sign and retry the transaction. return; } throw e; } ``` # createClient (/api/functions/createClient) ```ts function createClient(value?): Client; ``` Creates a new empty client that can be extended with plugins. This serves as an entry point for building Solana clients. Start with an empty client and chain the `.use()` method to apply plugins that add various functionalities such as RPC connectivity, wallet integration, transaction building, and more. See [ClientPlugin](/api/type-aliases/ClientPlugin) for detailed examples on creating and using plugins. ## Type Parameters | Type Parameter | Default type | | -------------------------- | ------------ | | `TSelf` *extends* `object` | `object` | ## Parameters | Parameter | Type | | --------- | ------- | | `value?` | `TSelf` | ## Returns [`Client`](/api/type-aliases/Client)\<`TSelf`> An empty client object with only the `use` method available. ## Example **Basic client setup** ```ts import { createClient } from '@solana/client'; import { generatedPayer } from '@solana/kit-plugin-payer'; import { rpc } from '@solana/kit-plugin-rpc'; const client = await createClient() .use(generatedPayer()) .use(rpc('https://api.mainnet-beta.solana.com')); ``` # createClientWithFetchAccountsFromRpc (/api/functions/createClientWithFetchAccountsFromRpc) ```ts function createClientWithFetchAccountsFromRpc( rpc, ): ClientWithFetchAccounts; ``` Creates a [ClientWithFetchAccounts](/api/type-aliases/ClientWithFetchAccounts) from a raw `Rpc` object. The returned client fetches the encoded content of accounts from their addresses, dispatching on the number of requested addresses: a single account is fetched via the [getAccountInfo](/api/type-aliases/GetAccountInfoApi#getaccountinfo) RPC method, whilst multiple accounts are fetched in a single round-trip via the [getMultipleAccounts](/api/type-aliases/GetMultipleAccountsApi#getmultipleaccounts) RPC method. Fetching an empty list short-circuits to an empty array without issuing any RPC call. The dispatch is based purely on the number of addresses because a raw `Rpc` object's capabilities cannot be detected at runtime. For this reason, the `Rpc` is required to support both methods. This is a convenience helper for consumers that only have a raw `Rpc` object rather than a Kit client. If you are building a full client, prefer composing it with a plugin such as `solanaRpc` (i.e. `createClient().use(solanaRpc(...))`), which provides account fetching amongst other capabilities. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `rpc` | [`Rpc`](/api/type-aliases/Rpc)\<[`GetAccountInfoApi`](/api/type-aliases/GetAccountInfoApi) & [`GetMultipleAccountsApi`](/api/type-aliases/GetMultipleAccountsApi)> | An object that supports both the [GetAccountInfoApi](/api/type-aliases/GetAccountInfoApi) and the [GetMultipleAccountsApi](/api/type-aliases/GetMultipleAccountsApi) of the Solana RPC API. | ## Returns [`ClientWithFetchAccounts`](/api/type-aliases/ClientWithFetchAccounts) ## Example ```ts const client = createClientWithFetchAccountsFromRpc(rpc); const accounts = await client.fetchAccounts([addressA, addressB]); ``` # createClientWithGetMinimumBalanceFromRpc (/api/functions/createClientWithGetMinimumBalanceFromRpc) ```ts function createClientWithGetMinimumBalanceFromRpc( rpc, ): ClientWithGetMinimumBalance; ``` Creates a [ClientWithGetMinimumBalance](/api/type-aliases/ClientWithGetMinimumBalance) from a raw `Rpc` object. The returned client computes the minimum balance for rent exemption using the [getMinimumBalanceForRentExemption](/api/type-aliases/GetMinimumBalanceForRentExemptionApi#getminimumbalanceforrentexemption) RPC method. By default, the 128-byte account header is included on top of the provided `space`; pass `{ withoutHeader: true }` to compute the minimum balance for the data portion only. This is a convenience helper for consumers that only have a raw `Rpc` object rather than a Kit client. If you are building a full client, prefer composing it with a plugin such as `solanaRpc` (i.e. `createClient().use(solanaRpc(...))`), which provides `getMinimumBalance` amongst other capabilities. ## Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `rpc` | [`Rpc`](/api/type-aliases/Rpc)\<[`GetMinimumBalanceForRentExemptionApi`](/api/type-aliases/GetMinimumBalanceForRentExemptionApi)> | An object that supports the [GetMinimumBalanceForRentExemptionApi](/api/type-aliases/GetMinimumBalanceForRentExemptionApi) of the Solana RPC API. | ## Returns [`ClientWithGetMinimumBalance`](/api/type-aliases/ClientWithGetMinimumBalance) ## Example ```ts const client = createClientWithGetMinimumBalanceFromRpc(rpc); const rentExemptBalance = await client.getMinimumBalance(100); ``` # createClientWithInterfacesFromRpc (/api/functions/createClientWithInterfacesFromRpc) ```ts function createClientWithInterfacesFromRpc( rpc, ): ClientInterfacesFromRpc; ``` Creates a client from a raw `Rpc` object, filling in whichever client interfaces the RPC supports. The returned object's type implements a [ClientWithGetMinimumBalance](/api/type-aliases/ClientWithGetMinimumBalance) when the RPC supports the [GetMinimumBalanceForRentExemptionApi](/api/type-aliases/GetMinimumBalanceForRentExemptionApi), and a [ClientWithFetchAccounts](/api/type-aliases/ClientWithFetchAccounts) when it supports both the [GetAccountInfoApi](/api/type-aliases/GetAccountInfoApi) and the [GetMultipleAccountsApi](/api/type-aliases/GetMultipleAccountsApi). The return type reflects the interfaces available on the provided RPC, so you only get the interfaces your RPC can actually back. Because a raw `Rpc` object's capabilities cannot be detected at runtime, the returned object always carries both `getMinimumBalance` and `fetchAccounts` at runtime; the return type is what narrows them to the interfaces your RPC declares. Invoking a method that your `Rpc` does not actually support will fail when the underlying RPC method is called. Note that this does not create a fully-fledged Kit client β€” it only wraps the RPC in the account interfaces above. To build a complete client, use `createClient().use(solanaRpc(...))` instead, which additionally exposes the underlying RPC and other capabilities. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TRpc` *extends* \| [`Rpc`](/api/type-aliases/Rpc)\<[`GetMinimumBalanceForRentExemptionApi`](/api/type-aliases/GetMinimumBalanceForRentExemptionApi)> \| [`Rpc`](/api/type-aliases/Rpc)\<[`GetAccountInfoApi`](/api/type-aliases/GetAccountInfoApi) & [`GetMultipleAccountsApi`](/api/type-aliases/GetMultipleAccountsApi)> | ## Parameters | Parameter | Type | Description | | --------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `rpc` | `TRpc` | A raw `Rpc` object that supports either the [GetMinimumBalanceForRentExemptionApi](/api/type-aliases/GetMinimumBalanceForRentExemptionApi), or both the [GetAccountInfoApi](/api/type-aliases/GetAccountInfoApi) and the [GetMultipleAccountsApi](/api/type-aliases/GetMultipleAccountsApi) (otherwise no interface can be produced). The interfaces exposed on the returned client's type depend on which RPC methods it supports. | ## Returns `ClientInterfacesFromRpc`\<`TRpc`> ## Example ```ts // With an RPC supporting both APIs, the client implements both interfaces. const client = createClientWithInterfacesFromRpc(rpc); const rentExemptBalance = await client.getMinimumBalance(100); const accounts = await client.fetchAccounts([addressA, addressB]); ``` # createCodec (/api/functions/createCodec) ## Call Signature ```ts function createCodec( codec, ): FixedSizeCodec; ``` Creates a `Codec` by filling in the missing `encode` and `decode` functions using the provided `write` and `read` functions. This utility combines the behavior of [createEncoder](/api/functions/createEncoder) and [createDecoder](/api/functions/createDecoder) to produce a fully functional `Codec`. The `encode` method is derived from the `write` function, while the `decode` method is derived from the `read` function. If the `fixedSize` property is provided, a [FixedSizeCodec](/api/interfaces/FixedSizeCodec) will be created, otherwise a [VariableSizeCodec](/api/interfaces/VariableSizeCodec) will be created. ### Type Parameters | Type Parameter | Default type | Description | | -------------------------- | ------------ | --------------------------------------------------------------------- | | `TFrom` | - | The type of the value to encode. | | `TTo` | `TFrom` | The type of the decoded value. | | `TSize` *extends* `number` | `number` | The fixed size of the encoded value in bytes (for fixed-size codecs). | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `codec` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`>, `"decode"` \| `"encode"`> | A codec object that implements `write` and `read`, but not `encode` or `decode`. - If the codec has a `fixedSize` property, it is treated as a [FixedSizeCodec](/api/interfaces/FixedSizeCodec). - Otherwise, it is treated as a [VariableSizeCodec](/api/interfaces/VariableSizeCodec). | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`> A fully functional `Codec` with `write`, `read`, `encode`, and `decode` methods. ### Examples Creating a custom fixed-size codec. ```ts const codec = createCodec({ fixedSize: 4, read: (bytes, offset) => { const value = bytes[offset]; return [value, offset + 4]; }, write: (value: number, bytes, offset) => { bytes.set(new Uint8Array([value]), offset); return offset + 4; }, }); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 ``` Creating a custom variable-size codec: ```ts const codec = createCodec({ getSizeFromValue: (value: string) => value.length, read: (bytes, offset) => { const decodedValue = new TextDecoder().decode(bytes.subarray(offset)); return [decodedValue, bytes.length]; }, write: (value: string, bytes, offset) => { const encodedValue = new TextEncoder().encode(value); bytes.set(encodedValue, offset); return offset + encodedValue.length; }, }); const bytes = codec.encode("hello"); // 0x68656c6c6f const value = codec.decode(bytes); // "hello" ``` ### Remarks This function effectively combines the behavior of [createEncoder](/api/functions/createEncoder) and [createDecoder](/api/functions/createDecoder). If you only need to encode or decode (but not both), consider using those functions instead. Here are some alternative examples using codec primitives instead of `createCodec`. ```ts // Fixed-size codec for unsigned 32-bit integers. const codec = getU32Codec(); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 // Variable-size codec for 32-bytes prefixed UTF-8 strings. const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const bytes = codec.encode("hello"); // 0x0500000068656c6c6f const value = codec.decode(bytes); // "hello" // Variable-size codec for custom objects. type Person = { name: string; age: number }; const codec: Codec = getStructCodec([ ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], ['age', getU32Codec()], ]); const bytes = codec.encode({ name: "Bob", age: 42 }); // 0x03000000426f622a000000 const value = codec.decode(bytes); // { name: "Bob", age: 42 } ``` ### See * [Codec](/api/type-aliases/Codec) * [FixedSizeCodec](/api/interfaces/FixedSizeCodec) * [VariableSizeCodec](/api/interfaces/VariableSizeCodec) * [createEncoder](/api/functions/createEncoder) * [createDecoder](/api/functions/createDecoder) * [getStructCodec](/api/functions/getStructCodec) * [getU32Codec](/api/variables/getU32Codec) * [getUtf8Codec](/api/variables/getUtf8Codec) * [addCodecSizePrefix](/api/functions/addCodecSizePrefix) ## Call Signature ```ts function createCodec(codec): VariableSizeCodec; ``` Creates a `Codec` by filling in the missing `encode` and `decode` functions using the provided `write` and `read` functions. This utility combines the behavior of [createEncoder](/api/functions/createEncoder) and [createDecoder](/api/functions/createDecoder) to produce a fully functional `Codec`. The `encode` method is derived from the `write` function, while the `decode` method is derived from the `read` function. If the `fixedSize` property is provided, a [FixedSizeCodec](/api/interfaces/FixedSizeCodec) will be created, otherwise a [VariableSizeCodec](/api/interfaces/VariableSizeCodec) will be created. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | -------------------------------- | | `TFrom` | - | The type of the value to encode. | | `TTo` | `TFrom` | The type of the decoded value. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `codec` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`>, `"decode"` \| `"encode"`> | A codec object that implements `write` and `read`, but not `encode` or `decode`. - If the codec has a `fixedSize` property, it is treated as a [FixedSizeCodec](/api/interfaces/FixedSizeCodec). - Otherwise, it is treated as a [VariableSizeCodec](/api/interfaces/VariableSizeCodec). | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`> A fully functional `Codec` with `write`, `read`, `encode`, and `decode` methods. ### Examples Creating a custom fixed-size codec. ```ts const codec = createCodec({ fixedSize: 4, read: (bytes, offset) => { const value = bytes[offset]; return [value, offset + 4]; }, write: (value: number, bytes, offset) => { bytes.set(new Uint8Array([value]), offset); return offset + 4; }, }); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 ``` Creating a custom variable-size codec: ```ts const codec = createCodec({ getSizeFromValue: (value: string) => value.length, read: (bytes, offset) => { const decodedValue = new TextDecoder().decode(bytes.subarray(offset)); return [decodedValue, bytes.length]; }, write: (value: string, bytes, offset) => { const encodedValue = new TextEncoder().encode(value); bytes.set(encodedValue, offset); return offset + encodedValue.length; }, }); const bytes = codec.encode("hello"); // 0x68656c6c6f const value = codec.decode(bytes); // "hello" ``` ### Remarks This function effectively combines the behavior of [createEncoder](/api/functions/createEncoder) and [createDecoder](/api/functions/createDecoder). If you only need to encode or decode (but not both), consider using those functions instead. Here are some alternative examples using codec primitives instead of `createCodec`. ```ts // Fixed-size codec for unsigned 32-bit integers. const codec = getU32Codec(); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 // Variable-size codec for 32-bytes prefixed UTF-8 strings. const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const bytes = codec.encode("hello"); // 0x0500000068656c6c6f const value = codec.decode(bytes); // "hello" // Variable-size codec for custom objects. type Person = { name: string; age: number }; const codec: Codec = getStructCodec([ ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], ['age', getU32Codec()], ]); const bytes = codec.encode({ name: "Bob", age: 42 }); // 0x03000000426f622a000000 const value = codec.decode(bytes); // { name: "Bob", age: 42 } ``` ### See * [Codec](/api/type-aliases/Codec) * [FixedSizeCodec](/api/interfaces/FixedSizeCodec) * [VariableSizeCodec](/api/interfaces/VariableSizeCodec) * [createEncoder](/api/functions/createEncoder) * [createDecoder](/api/functions/createDecoder) * [getStructCodec](/api/functions/getStructCodec) * [getU32Codec](/api/variables/getU32Codec) * [getUtf8Codec](/api/variables/getUtf8Codec) * [addCodecSizePrefix](/api/functions/addCodecSizePrefix) ## Call Signature ```ts function createCodec(codec): Codec; ``` Creates a `Codec` by filling in the missing `encode` and `decode` functions using the provided `write` and `read` functions. This utility combines the behavior of [createEncoder](/api/functions/createEncoder) and [createDecoder](/api/functions/createDecoder) to produce a fully functional `Codec`. The `encode` method is derived from the `write` function, while the `decode` method is derived from the `read` function. If the `fixedSize` property is provided, a [FixedSizeCodec](/api/interfaces/FixedSizeCodec) will be created, otherwise a [VariableSizeCodec](/api/interfaces/VariableSizeCodec) will be created. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | -------------------------------- | | `TFrom` | - | The type of the value to encode. | | `TTo` | `TFrom` | The type of the decoded value. | ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `codec` | \| [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `number`>, `"encode"` \| `"decode"`> \| [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`>, `"encode"` \| `"decode"`> | A codec object that implements `write` and `read`, but not `encode` or `decode`. - If the codec has a `fixedSize` property, it is treated as a [FixedSizeCodec](/api/interfaces/FixedSizeCodec). - Otherwise, it is treated as a [VariableSizeCodec](/api/interfaces/VariableSizeCodec). | ### Returns [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> A fully functional `Codec` with `write`, `read`, `encode`, and `decode` methods. ### Examples Creating a custom fixed-size codec. ```ts const codec = createCodec({ fixedSize: 4, read: (bytes, offset) => { const value = bytes[offset]; return [value, offset + 4]; }, write: (value: number, bytes, offset) => { bytes.set(new Uint8Array([value]), offset); return offset + 4; }, }); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 ``` Creating a custom variable-size codec: ```ts const codec = createCodec({ getSizeFromValue: (value: string) => value.length, read: (bytes, offset) => { const decodedValue = new TextDecoder().decode(bytes.subarray(offset)); return [decodedValue, bytes.length]; }, write: (value: string, bytes, offset) => { const encodedValue = new TextEncoder().encode(value); bytes.set(encodedValue, offset); return offset + encodedValue.length; }, }); const bytes = codec.encode("hello"); // 0x68656c6c6f const value = codec.decode(bytes); // "hello" ``` ### Remarks This function effectively combines the behavior of [createEncoder](/api/functions/createEncoder) and [createDecoder](/api/functions/createDecoder). If you only need to encode or decode (but not both), consider using those functions instead. Here are some alternative examples using codec primitives instead of `createCodec`. ```ts // Fixed-size codec for unsigned 32-bit integers. const codec = getU32Codec(); const bytes = codec.encode(42); // 0x2a000000 const value = codec.decode(bytes); // 42 // Variable-size codec for 32-bytes prefixed UTF-8 strings. const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const bytes = codec.encode("hello"); // 0x0500000068656c6c6f const value = codec.decode(bytes); // "hello" // Variable-size codec for custom objects. type Person = { name: string; age: number }; const codec: Codec = getStructCodec([ ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())], ['age', getU32Codec()], ]); const bytes = codec.encode({ name: "Bob", age: 42 }); // 0x03000000426f622a000000 const value = codec.decode(bytes); // { name: "Bob", age: 42 } ``` ### See * [Codec](/api/type-aliases/Codec) * [FixedSizeCodec](/api/interfaces/FixedSizeCodec) * [VariableSizeCodec](/api/interfaces/VariableSizeCodec) * [createEncoder](/api/functions/createEncoder) * [createDecoder](/api/functions/createDecoder) * [getStructCodec](/api/functions/getStructCodec) * [getU32Codec](/api/variables/getU32Codec) * [getUtf8Codec](/api/variables/getUtf8Codec) * [addCodecSizePrefix](/api/functions/addCodecSizePrefix) # createDecoder (/api/functions/createDecoder) ## Call Signature ```ts function createDecoder( decoder, ): FixedSizeDecoder; ``` Creates a `Decoder` by filling in the missing `decode` function using the provided `read` function. Instead of manually implementing `decode`, this utility leverages the existing `read` function and the size properties to generate a complete decoder. The provided `decode` method will read from a `Uint8Array` at the given offset and return the decoded value. If the `fixedSize` property is provided, a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) will be created, otherwise a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) will be created. ### Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------------------------------------- | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes (for fixed-size decoders). | ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `decoder` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `TSize`>, `"decode"`> | A decoder object that implements `read`, but not `decode`. - If the decoder has a `fixedSize` property, it is treated as a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder). - Otherwise, it is treated as a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `TSize`> A fully functional `Decoder` with both `read` and `decode` methods. ### Examples Creating a custom fixed-size decoder. ```ts const decoder = createDecoder({ fixedSize: 4, read: (bytes, offset) => { const value = bytes[offset]; return [value, offset + 4]; }, }); const value = decoder.decode(new Uint8Array([42, 0, 0, 0])); // 42 ``` Creating a custom variable-size decoder: ```ts const decoder = createDecoder({ read: (bytes, offset) => { const decodedValue = new TextDecoder().decode(bytes.subarray(offset)); return [decodedValue, bytes.length]; }, }); const value = decoder.decode(new Uint8Array([104, 101, 108, 108, 111])); // "hello" ``` ### Remarks Note that, while `createDecoder` is useful for defining more complex decoders, it is more common to compose decoders together using the various helpers and primitives of the `@solana/codecs` package. Here are some alternative examples using codec primitives instead of `createDecoder`. ```ts // Fixed-size decoder for unsigned 32-bit integers. const decoder = getU32Decoder(); const value = decoder.decode(new Uint8Array([42, 0, 0, 0])); // 42 // Variable-size decoder for 32-bytes prefixed UTF-8 strings. const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()); const value = decoder.decode(new Uint8Array([5, 0, 0, 0, 104, 101, 108, 108, 111])); // "hello" // Variable-size decoder for custom objects. type Person = { name: string; age: number }; const decoder: Decoder = getStructDecoder([ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())], ['age', getU32Decoder()], ]); const value = decoder.decode(new Uint8Array([3, 0, 0, 0, 66, 111, 98, 42, 0, 0, 0])); // { name: "Bob", age: 42 } ``` ### See * [Decoder](/api/type-aliases/Decoder) * [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) * [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) * [getStructDecoder](/api/functions/getStructDecoder) * [getU32Decoder](/api/variables/getU32Decoder) * [getUtf8Decoder](/api/variables/getUtf8Decoder) * [addDecoderSizePrefix](/api/functions/addDecoderSizePrefix) ## Call Signature ```ts function createDecoder(decoder): VariableSizeDecoder; ``` Creates a `Decoder` by filling in the missing `decode` function using the provided `read` function. Instead of manually implementing `decode`, this utility leverages the existing `read` function and the size properties to generate a complete decoder. The provided `decode` method will read from a `Uint8Array` at the given offset and return the decoded value. If the `fixedSize` property is provided, a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) will be created, otherwise a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) will be created. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `decoder` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`>, `"decode"`> | A decoder object that implements `read`, but not `decode`. - If the decoder has a `fixedSize` property, it is treated as a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder). - Otherwise, it is treated as a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`> A fully functional `Decoder` with both `read` and `decode` methods. ### Examples Creating a custom fixed-size decoder. ```ts const decoder = createDecoder({ fixedSize: 4, read: (bytes, offset) => { const value = bytes[offset]; return [value, offset + 4]; }, }); const value = decoder.decode(new Uint8Array([42, 0, 0, 0])); // 42 ``` Creating a custom variable-size decoder: ```ts const decoder = createDecoder({ read: (bytes, offset) => { const decodedValue = new TextDecoder().decode(bytes.subarray(offset)); return [decodedValue, bytes.length]; }, }); const value = decoder.decode(new Uint8Array([104, 101, 108, 108, 111])); // "hello" ``` ### Remarks Note that, while `createDecoder` is useful for defining more complex decoders, it is more common to compose decoders together using the various helpers and primitives of the `@solana/codecs` package. Here are some alternative examples using codec primitives instead of `createDecoder`. ```ts // Fixed-size decoder for unsigned 32-bit integers. const decoder = getU32Decoder(); const value = decoder.decode(new Uint8Array([42, 0, 0, 0])); // 42 // Variable-size decoder for 32-bytes prefixed UTF-8 strings. const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()); const value = decoder.decode(new Uint8Array([5, 0, 0, 0, 104, 101, 108, 108, 111])); // "hello" // Variable-size decoder for custom objects. type Person = { name: string; age: number }; const decoder: Decoder = getStructDecoder([ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())], ['age', getU32Decoder()], ]); const value = decoder.decode(new Uint8Array([3, 0, 0, 0, 66, 111, 98, 42, 0, 0, 0])); // { name: "Bob", age: 42 } ``` ### See * [Decoder](/api/type-aliases/Decoder) * [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) * [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) * [getStructDecoder](/api/functions/getStructDecoder) * [getU32Decoder](/api/variables/getU32Decoder) * [getUtf8Decoder](/api/variables/getUtf8Decoder) * [addDecoderSizePrefix](/api/functions/addDecoderSizePrefix) ## Call Signature ```ts function createDecoder(decoder): Decoder; ``` Creates a `Decoder` by filling in the missing `decode` function using the provided `read` function. Instead of manually implementing `decode`, this utility leverages the existing `read` function and the size properties to generate a complete decoder. The provided `decode` method will read from a `Uint8Array` at the given offset and return the decoded value. If the `fixedSize` property is provided, a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) will be created, otherwise a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) will be created. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `decoder` | \| [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `number`>, `"decode"`> \| [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`>, `"decode"`> | A decoder object that implements `read`, but not `decode`. - If the decoder has a `fixedSize` property, it is treated as a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder). - Otherwise, it is treated as a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). | ### Returns [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> A fully functional `Decoder` with both `read` and `decode` methods. ### Examples Creating a custom fixed-size decoder. ```ts const decoder = createDecoder({ fixedSize: 4, read: (bytes, offset) => { const value = bytes[offset]; return [value, offset + 4]; }, }); const value = decoder.decode(new Uint8Array([42, 0, 0, 0])); // 42 ``` Creating a custom variable-size decoder: ```ts const decoder = createDecoder({ read: (bytes, offset) => { const decodedValue = new TextDecoder().decode(bytes.subarray(offset)); return [decodedValue, bytes.length]; }, }); const value = decoder.decode(new Uint8Array([104, 101, 108, 108, 111])); // "hello" ``` ### Remarks Note that, while `createDecoder` is useful for defining more complex decoders, it is more common to compose decoders together using the various helpers and primitives of the `@solana/codecs` package. Here are some alternative examples using codec primitives instead of `createDecoder`. ```ts // Fixed-size decoder for unsigned 32-bit integers. const decoder = getU32Decoder(); const value = decoder.decode(new Uint8Array([42, 0, 0, 0])); // 42 // Variable-size decoder for 32-bytes prefixed UTF-8 strings. const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()); const value = decoder.decode(new Uint8Array([5, 0, 0, 0, 104, 101, 108, 108, 111])); // "hello" // Variable-size decoder for custom objects. type Person = { name: string; age: number }; const decoder: Decoder = getStructDecoder([ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())], ['age', getU32Decoder()], ]); const value = decoder.decode(new Uint8Array([3, 0, 0, 0, 66, 111, 98, 42, 0, 0, 0])); // { name: "Bob", age: 42 } ``` ### See * [Decoder](/api/type-aliases/Decoder) * [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) * [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) * [getStructDecoder](/api/functions/getStructDecoder) * [getU32Decoder](/api/variables/getU32Decoder) * [getUtf8Decoder](/api/variables/getUtf8Decoder) * [addDecoderSizePrefix](/api/functions/addDecoderSizePrefix) # createDecoderThatConsumesEntireByteArray (/api/functions/createDecoderThatConsumesEntireByteArray) ```ts function createDecoderThatConsumesEntireByteArray( decoder, ): Decoder; ``` Create a [Decoder](/api/type-aliases/Decoder) that asserts that the bytes provided to `decode` or `read` are fully consumed by the inner decoder ## Type Parameters | Type Parameter | Description | | -------------- | ----------------------- | | `T` | The type of the decoder | ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------- | ----------------- | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`T`> | A decoder to wrap | ## Returns [`Decoder`](/api/type-aliases/Decoder)\<`T`> A new decoder that will throw if provided with a byte array that it does not fully consume ## Remarks Note that this compares the offset after encoding to the length of the input byte array The `offset` parameter to `decode` and `read` is still considered, and will affect the new offset that is compared to the byte array length The error that is thrown by the returned decoder is a [SolanaError](/api/classes/SolanaError) with the code `SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY` ## Example Create a decoder that decodes a `u32` (4 bytes) and ensures the entire byte array is consumed ```ts const decoder = createDecoderThatUsesExactByteArray(getU32Decoder()); decoder.decode(new Uint8Array([0, 0, 0, 0])); // 0 decoder.decode(new Uint8Array([0, 0, 0, 0, 0])); // throws // with an offset decoder.decode(new Uint8Array([0, 0, 0, 0, 0]), 1); // 0 decoder.decode(new Uint8Array([0, 0, 0, 0, 0, 0]), 1); // throws ``` # createDefaultRpcSubscriptionsChannelCreator (/api/functions/createDefaultRpcSubscriptionsChannelCreator) ```ts function createDefaultRpcSubscriptionsChannelCreator( config, ): RpcSubscriptionsChannelCreatorFromClusterUrl< TClusterUrl, unknown, unknown >; ``` Creates a function that returns new subscription channels when called. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------- | | `config` | [`DefaultRpcSubscriptionsChannelConfig`](/api/type-aliases/DefaultRpcSubscriptionsChannelConfig)\<`TClusterUrl`> | ## Returns [`RpcSubscriptionsChannelCreatorFromClusterUrl`](/api/type-aliases/RpcSubscriptionsChannelCreatorFromClusterUrl)\<`TClusterUrl`, `unknown`, `unknown`> # createDefaultRpcSubscriptionsTransport (/api/functions/createDefaultRpcSubscriptionsTransport) ```ts function createDefaultRpcSubscriptionsTransport( config, ): RpcSubscriptionsTransportFromClusterUrl; ``` Creates a [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport) with some default behaviours. The default behaviours include: * Logic that coalesces multiple subscriptions for the same notifications with the same arguments into a single subscription. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ----------- | | `config` | [`DefaultRpcSubscriptionsTransportConfig`](/api/type-aliases/DefaultRpcSubscriptionsTransportConfig)\<`TClusterUrl`> | - | ## Returns [`RpcSubscriptionsTransportFromClusterUrl`](/api/type-aliases/RpcSubscriptionsTransportFromClusterUrl)\<`TClusterUrl`> # createDefaultRpcTransport (/api/functions/createDefaultRpcTransport) ```ts function createDefaultRpcTransport( config, ): RpcTransportFromClusterUrl; ``` Creates a [RpcTransport](/api/type-aliases/RpcTransport) with some default behaviours. The default behaviours include: * An automatically-set `Solana-Client` request header, containing the version of `@solana/kit` * Logic that coalesces multiple calls in the same runloop, for the same methods with the same arguments, into a single network request. * \[node-only] An automatically-set `Accept-Encoding` request header asking the server to compress responses ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------- | ----------- | | `config` | `DefaultRpcTransportConfig`\<`TClusterUrl`> | - | ## Returns [`RpcTransportFromClusterUrl`](/api/type-aliases/RpcTransportFromClusterUrl)\<`TClusterUrl`> # createDefaultSolanaRpcSubscriptionsChannelCreator (/api/functions/createDefaultSolanaRpcSubscriptionsChannelCreator) ```ts function createDefaultSolanaRpcSubscriptionsChannelCreator( config, ): RpcSubscriptionsChannelCreatorFromClusterUrl< TClusterUrl, unknown, unknown >; ``` Similar to [createDefaultRpcSubscriptionsChannelCreator](/api/functions/createDefaultRpcSubscriptionsChannelCreator) with some Solana-specific defaults. For instance, it safely handles `BigInt` values in JSON messages since Solana RPC servers accept and return integers larger than [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------- | | `config` | [`DefaultRpcSubscriptionsChannelConfig`](/api/type-aliases/DefaultRpcSubscriptionsChannelConfig)\<`TClusterUrl`> | ## Returns [`RpcSubscriptionsChannelCreatorFromClusterUrl`](/api/type-aliases/RpcSubscriptionsChannelCreatorFromClusterUrl)\<`TClusterUrl`, `unknown`, `unknown`> # createDependentStructDecoder (/api/functions/createDependentStructDecoder) ```ts function createDependentStructDecoder(): DependentStructDecoderBuilder< Record, true >; ``` Creates a fluent builder for a struct decoder whose later fields may depend on the decoded values of earlier ones. Unlike [getStructDecoder](/api/functions/getStructDecoder), which accepts a fixed array of named decoders, this builder lets each field provide a factory that receives the values that have already been decoded. This is useful for binary formats where a count, version, or discriminator decoded near the start of the struct controls how a later field must be parsed. The builder mirrors the fixed vs variable size behaviour of [getStructDecoder](/api/functions/getStructDecoder). The empty builder finishes to a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) of size zero. Adding a [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder) preserves the fixed size property and the sizes accumulate. Adding a [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder) or a [field factory](/api/type-aliases/DependentStructDecoderFieldFactory) drops the builder to variable size, which is then preserved by every subsequent [\`field\`](/api/type-aliases/DependentStructDecoderBuilder#field) call. The returned builder is immutable; each [\`field\`](/api/type-aliases/DependentStructDecoderBuilder#field) call returns a new builder whose accumulated field type is widened by the newly added field. Call [\`build\`](/api/type-aliases/DependentStructDecoderBuilder#build) to produce the final decoder. ## Returns [`DependentStructDecoderBuilder`](/api/type-aliases/DependentStructDecoderBuilder)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`never`, `never`>, `true`> ## Remarks Prefer [getStructDecoder](/api/functions/getStructDecoder) when every field's decoder is independent of the values that precede it. Reach for this builder only when at least one field needs to be parameterised by another. The encoder direction does not need a dependent variant. An encoder already has access to the entire value when serialising, so the existing [getStructEncoder](/api/functions/getStructEncoder) can be paired with the decoder returned by this builder and combined with `combineCodec` to obtain a full codec. ## Examples Decoding a struct whose array length is read from an earlier field. ```ts import { getArrayDecoder } from '@solana/codecs-data-structures'; import { getU8Decoder, getU32Decoder } from '@solana/codecs-numbers'; const decoder = createDependentStructDecoder() .field('count', getU8Decoder()) .field('values', fields => getArrayDecoder(getU32Decoder(), { size: fields.count })) .build(); decoder.decode(new Uint8Array([0x02, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00])); // { count: 2, values: [1, 2] } ``` Mixing static and dependent fields, with a discriminator selecting the payload decoder. ```ts const decoder = createDependentStructDecoder() .field('version', getU8Decoder()) .field('header', fields => fields.version === 0 ? getU16Decoder() : getU32Decoder()) .build(); ``` Combining the dependent decoder with a static encoder to obtain a full codec. ```ts import { combineCodec } from '@solana/codecs-core'; const encoder = getStructEncoder([ ['count', getU8Encoder()], ['values', getArrayEncoder(getU32Encoder())], ]); const decoder = createDependentStructDecoder() .field('count', getU8Decoder()) .field('values', fields => getArrayDecoder(getU32Decoder(), { size: fields.count })) .build(); const codec = combineCodec(encoder, decoder); ``` ## See * [getStructDecoder](/api/functions/getStructDecoder) * [getStructEncoder](/api/functions/getStructEncoder) # createEncoder (/api/functions/createEncoder) ## Call Signature ```ts function createEncoder( encoder, ): FixedSizeEncoder; ``` Creates an `Encoder` by filling in the missing `encode` function using the provided `write` function and either the `fixedSize` property (for [FixedSizeEncoders](/api/interfaces/FixedSizeEncoder)) or the `getSizeFromValue` function (for [VariableSizeEncoders](/api/interfaces/VariableSizeEncoder)). Instead of manually implementing `encode`, this utility leverages the existing `write` function and the size helpers to generate a complete encoder. The provided `encode` method will allocate a new `Uint8Array` of the correct size and use `write` to populate it. ### Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes (for fixed-size encoders). | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `encoder` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`>, `"encode"`> | An encoder object that implements `write`, but not `encode`. - If the encoder has a `fixedSize` property, it is treated as a [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder). - Otherwise, it is treated as a [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder). | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`> A fully functional `Encoder` with both `write` and `encode` methods. ### Examples Creating a custom fixed-size encoder. ```ts const encoder = createEncoder({ fixedSize: 4, write: (value: number, bytes, offset) => { bytes.set(new Uint8Array([value]), offset); return offset + 4; }, }); const bytes = encoder.encode(42); // 0x2a000000 ``` Creating a custom variable-size encoder: ```ts const encoder = createEncoder({ getSizeFromValue: (value: string) => value.length, write: (value: string, bytes, offset) => { const encodedValue = new TextEncoder().encode(value); bytes.set(encodedValue, offset); return offset + encodedValue.length; }, }); const bytes = encoder.encode("hello"); // 0x68656c6c6f ``` ### Remarks Note that, while `createEncoder` is useful for defining more complex encoders, it is more common to compose encoders together using the various helpers and primitives of the `@solana/codecs` package. Here are some alternative examples using codec primitives instead of `createEncoder`. ```ts // Fixed-size encoder for unsigned 32-bit integers. const encoder = getU32Encoder(); const bytes = encoder.encode(42); // 0x2a000000 // Variable-size encoder for 32-bytes prefixed UTF-8 strings. const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); const bytes = encoder.encode("hello"); // 0x0500000068656c6c6f // Variable-size encoder for custom objects. type Person = { name: string; age: number }; const encoder: Encoder = getStructEncoder([ ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())], ['age', getU32Encoder()], ]); const bytes = encoder.encode({ name: "Bob", age: 42 }); // 0x03000000426f622a000000 ``` ### See * [Encoder](/api/type-aliases/Encoder) * [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder) * [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder) * [getStructEncoder](/api/functions/getStructEncoder) * [getU32Encoder](/api/variables/getU32Encoder) * [getUtf8Encoder](/api/variables/getUtf8Encoder) * [addEncoderSizePrefix](/api/functions/addEncoderSizePrefix) ## Call Signature ```ts function createEncoder(encoder): VariableSizeEncoder; ``` Creates an `Encoder` by filling in the missing `encode` function using the provided `write` function and either the `fixedSize` property (for [FixedSizeEncoders](/api/interfaces/FixedSizeEncoder)) or the `getSizeFromValue` function (for [VariableSizeEncoders](/api/interfaces/VariableSizeEncoder)). Instead of manually implementing `encode`, this utility leverages the existing `write` function and the size helpers to generate a complete encoder. The provided `encode` method will allocate a new `Uint8Array` of the correct size and use `write` to populate it. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `encoder` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`>, `"encode"`> | An encoder object that implements `write`, but not `encode`. - If the encoder has a `fixedSize` property, it is treated as a [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder). - Otherwise, it is treated as a [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder). | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`> A fully functional `Encoder` with both `write` and `encode` methods. ### Examples Creating a custom fixed-size encoder. ```ts const encoder = createEncoder({ fixedSize: 4, write: (value: number, bytes, offset) => { bytes.set(new Uint8Array([value]), offset); return offset + 4; }, }); const bytes = encoder.encode(42); // 0x2a000000 ``` Creating a custom variable-size encoder: ```ts const encoder = createEncoder({ getSizeFromValue: (value: string) => value.length, write: (value: string, bytes, offset) => { const encodedValue = new TextEncoder().encode(value); bytes.set(encodedValue, offset); return offset + encodedValue.length; }, }); const bytes = encoder.encode("hello"); // 0x68656c6c6f ``` ### Remarks Note that, while `createEncoder` is useful for defining more complex encoders, it is more common to compose encoders together using the various helpers and primitives of the `@solana/codecs` package. Here are some alternative examples using codec primitives instead of `createEncoder`. ```ts // Fixed-size encoder for unsigned 32-bit integers. const encoder = getU32Encoder(); const bytes = encoder.encode(42); // 0x2a000000 // Variable-size encoder for 32-bytes prefixed UTF-8 strings. const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); const bytes = encoder.encode("hello"); // 0x0500000068656c6c6f // Variable-size encoder for custom objects. type Person = { name: string; age: number }; const encoder: Encoder = getStructEncoder([ ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())], ['age', getU32Encoder()], ]); const bytes = encoder.encode({ name: "Bob", age: 42 }); // 0x03000000426f622a000000 ``` ### See * [Encoder](/api/type-aliases/Encoder) * [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder) * [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder) * [getStructEncoder](/api/functions/getStructEncoder) * [getU32Encoder](/api/variables/getU32Encoder) * [getUtf8Encoder](/api/variables/getUtf8Encoder) * [addEncoderSizePrefix](/api/functions/addEncoderSizePrefix) ## Call Signature ```ts function createEncoder(encoder): Encoder; ``` Creates an `Encoder` by filling in the missing `encode` function using the provided `write` function and either the `fixedSize` property (for [FixedSizeEncoders](/api/interfaces/FixedSizeEncoder)) or the `getSizeFromValue` function (for [VariableSizeEncoders](/api/interfaces/VariableSizeEncoder)). Instead of manually implementing `encode`, this utility leverages the existing `write` function and the size helpers to generate a complete encoder. The provided `encode` method will allocate a new `Uint8Array` of the correct size and use `write` to populate it. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `encoder` | \| [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `number`>, `"encode"`> \| [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`>, `"encode"`> | An encoder object that implements `write`, but not `encode`. - If the encoder has a `fixedSize` property, it is treated as a [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder). - Otherwise, it is treated as a [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder). | ### Returns [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> A fully functional `Encoder` with both `write` and `encode` methods. ### Examples Creating a custom fixed-size encoder. ```ts const encoder = createEncoder({ fixedSize: 4, write: (value: number, bytes, offset) => { bytes.set(new Uint8Array([value]), offset); return offset + 4; }, }); const bytes = encoder.encode(42); // 0x2a000000 ``` Creating a custom variable-size encoder: ```ts const encoder = createEncoder({ getSizeFromValue: (value: string) => value.length, write: (value: string, bytes, offset) => { const encodedValue = new TextEncoder().encode(value); bytes.set(encodedValue, offset); return offset + encodedValue.length; }, }); const bytes = encoder.encode("hello"); // 0x68656c6c6f ``` ### Remarks Note that, while `createEncoder` is useful for defining more complex encoders, it is more common to compose encoders together using the various helpers and primitives of the `@solana/codecs` package. Here are some alternative examples using codec primitives instead of `createEncoder`. ```ts // Fixed-size encoder for unsigned 32-bit integers. const encoder = getU32Encoder(); const bytes = encoder.encode(42); // 0x2a000000 // Variable-size encoder for 32-bytes prefixed UTF-8 strings. const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); const bytes = encoder.encode("hello"); // 0x0500000068656c6c6f // Variable-size encoder for custom objects. type Person = { name: string; age: number }; const encoder: Encoder = getStructEncoder([ ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())], ['age', getU32Encoder()], ]); const bytes = encoder.encode({ name: "Bob", age: 42 }); // 0x03000000426f622a000000 ``` ### See * [Encoder](/api/type-aliases/Encoder) * [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder) * [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder) * [getStructEncoder](/api/functions/getStructEncoder) * [getU32Encoder](/api/variables/getU32Encoder) * [getUtf8Encoder](/api/variables/getUtf8Encoder) * [addEncoderSizePrefix](/api/functions/addEncoderSizePrefix) # createFailedToExecuteTransactionPlanError (/api/functions/createFailedToExecuteTransactionPlanError) ```ts function createFailedToExecuteTransactionPlanError( result, abortReason?, ): SolanaError<7618003>; ``` Creates a [SolanaError](/api/classes/SolanaError) with the [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_FAILED\_TO\_EXECUTE\_TRANSACTION\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN) error code from a [TransactionPlanResult](/api/type-aliases/TransactionPlanResult). This is a low-level error intended for custom transaction plan executor authors. It attaches the full `transactionPlanResult` as a non-enumerable property so that callers can inspect execution details without the result being serialized with the error. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object attached to the results. Any context is accepted, since this helper never reads from it. | ## Parameters | Parameter | Type | Description | | -------------- | ------------------------------------------------------------------------------- | ------------------------------------------------- | | `result` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`> | The full transaction plan result tree. | | `abortReason?` | `unknown` | An optional abort reason if the plan was aborted. | ## Returns [`SolanaError`](/api/classes/SolanaError)\<`7618003`> A [SolanaError](/api/classes/SolanaError) with the appropriate error code and context. ## Example Throwing a failed-to-execute error from a custom executor. ```ts import { createFailedToExecuteTransactionPlanError } from '@solana/instruction-plans'; throw createFailedToExecuteTransactionPlanError(transactionPlanResult, abortSignal?.reason); ``` ## See * [createFailedToSendTransactionError](/api/functions/createFailedToSendTransactionError) * [createFailedToSendTransactionsError](/api/functions/createFailedToSendTransactionsError) # createFailedToSendTransactionError (/api/functions/createFailedToSendTransactionError) ```ts function createFailedToSendTransactionError( result, abortReason?, ): SolanaError<11>; ``` Creates a [SolanaError](/api/classes/SolanaError) with the [SOLANA\_ERROR\_\_FAILED\_TO\_SEND\_TRANSACTION](/api/variables/SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION) error code from a failed or canceled [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). This is a high-level error designed for user-facing transaction send failures. It unwraps simulation errors (such as preflight failures) to expose the underlying transaction error as the `cause`, and extracts preflight data and logs into the error context for easy access. The error message includes an indicator showing whether the failure was a preflight error or includes the on-chain transaction signature for easy copy-pasting into block explorers. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object attached to the result. Any context is accepted; the signature is read from it only if one happens to be there. | ## Parameters | Parameter | Type | Description | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | `result` | \| [`CanceledSingleTransactionPlanResult`](/api/type-aliases/CanceledSingleTransactionPlanResult)\<`TContext`> \| [`FailedSingleTransactionPlanResult`](/api/type-aliases/FailedSingleTransactionPlanResult)\<`TContext`> | A failed or canceled single transaction plan result. | | `abortReason?` | `unknown` | An optional abort reason if the transaction was canceled. | ## Returns [`SolanaError`](/api/classes/SolanaError)\<`11`> A [SolanaError](/api/classes/SolanaError) with the appropriate error code, context, and cause. ## Example Creating an error from a failed transaction plan result. ```ts import { createFailedToSendTransactionError } from '@solana/instruction-plans'; const error = createFailedToSendTransactionError(failedResult); console.log(error.message); // "Failed to send transaction (preflight): Insufficient funds for fee" console.log(error.cause); // The unwrapped transaction error console.log(error.context.logs); // Transaction logs from the preflight simulation ``` ## See * [createFailedToSendTransactionsError](/api/functions/createFailedToSendTransactionsError) * [createFailedToSignTransactionError](/api/functions/createFailedToSignTransactionError) # createFailedToSendTransactionsError (/api/functions/createFailedToSendTransactionsError) ```ts function createFailedToSendTransactionsError( result, abortReason?, ): SolanaError<12>; ``` Creates a [SolanaError](/api/classes/SolanaError) with the [SOLANA\_ERROR\_\_FAILED\_TO\_SEND\_TRANSACTIONS](/api/variables/SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS) error code from a [TransactionPlanResult](/api/type-aliases/TransactionPlanResult). This is a high-level error designed for user-facing transaction send failures involving multiple transactions. It walks the result tree, unwraps simulation errors from each failure, and builds a `failedTransactions` array pairing each failure with its unwrapped error, logs, and preflight data. The error message lists each failure with its position in the plan and an indicator showing whether it was a preflight error or includes the transaction signature. When all transactions were canceled, the message is a single line. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object attached to the results. Any context is accepted; each signature is read from it only if one happens to be there. | ## Parameters | Parameter | Type | Description | | -------------- | ------------------------------------------------------------------------------- | ------------------------------------------------- | | `result` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`> | The full transaction plan result tree. | | `abortReason?` | `unknown` | An optional abort reason if the plan was aborted. | ## Returns [`SolanaError`](/api/classes/SolanaError)\<`12`> A [SolanaError](/api/classes/SolanaError) with the appropriate error code, context, and cause. ## Example Creating an error from a failed transaction plan result. ```ts import { createFailedToSendTransactionsError } from '@solana/instruction-plans'; const error = createFailedToSendTransactionsError(planResult); console.log(error.message); // "Failed to send transactions. // [Tx #1 (preflight)] Insufficient funds for fee // [Tx #3 (5abc...)] Custom program error: 0x1" console.log(error.context.failedTransactions); // [{ index: 0, error: ..., logs: [...], preflightData: {...} }, ...] ``` ## See * [createFailedToSendTransactionError](/api/functions/createFailedToSendTransactionError) * [createFailedToSignTransactionsError](/api/functions/createFailedToSignTransactionsError) # createFailedToSignTransactionError (/api/functions/createFailedToSignTransactionError) ```ts function createFailedToSignTransactionError( result, abortReason?, ): SolanaError<13>; ``` Creates a [SolanaError](/api/classes/SolanaError) with the [SOLANA\_ERROR\_\_FAILED\_TO\_SIGN\_TRANSACTION](/api/variables/SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION) error code from a failed or canceled [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). This is the signing counterpart to [createFailedToSendTransactionError](/api/functions/createFailedToSendTransactionError), designed for user-facing failures raised by executors that sign a transaction without submitting it. It behaves identically β€” unwrapping simulation errors to expose the underlying transaction error as the `cause`, and extracting preflight data and logs into the error context β€” because signing executors typically estimate resource limits by simulating before they sign. Unlike the sending variant, the message carries no indicator of where the failure happened. That indicator locates a failure relative to network submission β€” `(preflight)` before it, or the transaction signature after it β€” and signing never submits, so neither applies. The `logs` and `preflightData` context properties are still populated whenever a simulation was responsible, and those logs still appear in the message, so nothing is lost beyond the prefix. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | The type of the context object attached to the result. Any context is accepted, since this helper never reads from it. | ## Parameters | Parameter | Type | Description | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | `result` | \| [`CanceledSingleTransactionPlanResult`](/api/type-aliases/CanceledSingleTransactionPlanResult)\<`TContext`> \| [`FailedSingleTransactionPlanResult`](/api/type-aliases/FailedSingleTransactionPlanResult)\<`TContext`> | A failed or canceled single transaction plan result. | | `abortReason?` | `unknown` | An optional abort reason if the transaction was canceled. | ## Returns [`SolanaError`](/api/classes/SolanaError)\<`13`> A [SolanaError](/api/classes/SolanaError) with the appropriate error code, context, and cause. ## Example Creating an error from a failed transaction plan result. ```ts import { createFailedToSignTransactionError } from '@solana/instruction-plans'; const error = createFailedToSignTransactionError(failedResult); console.log(error.message); // "Failed to sign transaction: The user rejected the signing request" console.log(error.cause); // The unwrapped signing error ``` ## See * [createFailedToSignTransactionsError](/api/functions/createFailedToSignTransactionsError) * [createFailedToSendTransactionError](/api/functions/createFailedToSendTransactionError) # createFailedToSignTransactionsError (/api/functions/createFailedToSignTransactionsError) ```ts function createFailedToSignTransactionsError( result, abortReason?, ): SolanaError<14>; ``` Creates a [SolanaError](/api/classes/SolanaError) with the [SOLANA\_ERROR\_\_FAILED\_TO\_SIGN\_TRANSACTIONS](/api/variables/SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS) error code from a [TransactionPlanResult](/api/type-aliases/TransactionPlanResult). This is the signing counterpart to [createFailedToSendTransactionsError](/api/functions/createFailedToSendTransactionsError), designed for user-facing failures raised by executors that sign several transactions without submitting them. It walks the result tree, unwraps simulation errors from each failure, and builds the same `failedTransactions` array pairing each failure with its unwrapped error, logs, and preflight data. As with [createFailedToSignTransactionError](/api/functions/createFailedToSignTransactionError), each line names only the position of the failure in the plan. Nothing was submitted, so there is no preflight to flag and no transaction signature worth quoting. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | The type of the context object attached to the results. Any context is accepted, since this helper never reads from it. | ## Parameters | Parameter | Type | Description | | -------------- | ------------------------------------------------------------------------------- | ------------------------------------------------- | | `result` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`> | The full transaction plan result tree. | | `abortReason?` | `unknown` | An optional abort reason if the plan was aborted. | ## Returns [`SolanaError`](/api/classes/SolanaError)\<`14`> A [SolanaError](/api/classes/SolanaError) with the appropriate error code, context, and cause. ## Example Creating an error from a failed transaction plan result. ```ts import { createFailedToSignTransactionsError } from '@solana/instruction-plans'; const error = createFailedToSignTransactionsError(planResult); console.log(error.message); // "Failed to sign transactions. // [Tx #1] Insufficient funds for fee // [Tx #3] The user rejected the signing request" console.log(error.context.failedTransactions); // [{ index: 0, error: ..., logs: [...], preflightData: {...} }, ...] ``` ## See * [createFailedToSignTransactionError](/api/functions/createFailedToSignTransactionError) * [createFailedToSendTransactionsError](/api/functions/createFailedToSendTransactionsError) # createHttpTransport (/api/functions/createHttpTransport) ```ts function createHttpTransport(config): RpcTransport; ``` Creates a function you can use to make `POST` requests with headers suitable for sending JSON data to a server. ## Parameters | Parameter | Type | | --------- | -------- | | `config` | `Config` | ## Returns `RpcTransport` ## Example ```ts import { createHttpTransport } from '@solana/rpc-transport-http'; const transport = createHttpTransport({ url: 'https://api.mainnet-beta.solana.com' }); const response = await transport({ payload: { id: 1, jsonrpc: '2.0', method: 'getSlot' }, }); const data = await response.json(); ``` # createHttpTransportForSolanaRpc (/api/functions/createHttpTransportForSolanaRpc) ```ts function createHttpTransportForSolanaRpc(config): RpcTransport; ``` Creates a RpcTransport that uses JSON HTTP requests β€” much like the [createHttpTransport](/api/functions/createHttpTransport) function - except that it also uses custom `toJson` and `fromJson` functions in order to allow `bigint` values to be serialized and deserialized correctly over the wire. Since this is something specific to the Solana RPC API, these custom JSON functions are only triggered when the request is recognized as a Solana RPC request. Normal RPC APIs should aim to wrap their `bigint` values β€” e.g. `u64` or `i64` β€” in special value objects that represent the number as a string to avoid numerical values going above `Number.MAX_SAFE_INTEGER`. It has the same configuration options as [createHttpTransport](/api/functions/createHttpTransport), but without the `fromJson` and `toJson` options. ## Parameters | Parameter | Type | | --------- | -------- | | `config` | `Config` | ## Returns `RpcTransport` # createJsonRpcApi (/api/functions/createJsonRpcApi) ```ts function createJsonRpcApi(config?): RpcApi; ``` Creates a JavaScript proxy that converts *any* function call called on it to a [RpcPlan](/api/type-aliases/RpcPlan) by creating an `execute` function that: * sets the transport payload to a JSON RPC v2 payload object with the requested `methodName` and `params` properties, optionally transformed by RpcApiConfig.requestTransformer. * transforms the transport's response using the RpcApiConfig.responseTransformer function, if provided. ## Type Parameters | Type Parameter | | --------------------------------------- | | `TRpcMethods` *extends* `RpcApiMethods` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `requestTransformer?`: `RpcRequestTransformer`; `responseTransformer?`: `RpcResponseTransformer`; }> | ## Returns [`RpcApi`](/api/type-aliases/RpcApi)\<`TRpcMethods`> ## Example ```ts // For example, given this `RpcApi`: const rpcApi = createJsonRpcApi({ requestTransformer: (...rawParams) => rawParams.reverse(), responseTransformer: response => response.result, }); // ...the following function call: rpcApi.foo('bar', { baz: 'bat' }); // ...will produce a `RpcPlan` that: // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }. // - Returns the "result" property of the RPC response. ``` # createKeyPairFromBytes (/api/functions/createKeyPairFromBytes) ```ts function createKeyPairFromBytes( bytes, extractable?, ): Promise; ``` Given a 64-byte `Uint8Array` secret key, creates an Ed25519 public/private key pair for use with other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects. ## Parameters | Parameter | Type | Description | | -------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `bytes` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | 64 bytes, the first 32 of which represent the private key and the last 32 of which represent its associated public key | | `extractable?` | `boolean` | Setting this to `true` makes it possible to extract the bytes of the private key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey) API. Defaults to `false`. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`CryptoKeyPair`> ## Example ```ts import fs from 'fs'; import { createKeyPairFromBytes } from '@solana/keys'; // Get bytes from local keypair file. const keypairFile = fs.readFileSync('~/.config/solana/id.json'); const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString())); // Create a CryptoKeyPair from the bytes. const { privateKey, publicKey } = await createKeyPairFromBytes(keypairBytes); ``` ## See [writeKeyPair](/api/functions/writeKeyPair) β€” the inverse helper that persists a key pair to disk in the same format. # createKeyPairFromPrivateKeyBytes (/api/functions/createKeyPairFromPrivateKeyBytes) ```ts function createKeyPairFromPrivateKeyBytes( bytes, extractable?, ): Promise; ``` Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 public/private key pair for use with other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects. ## Parameters | Parameter | Type | Description | | -------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `bytes` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | 32 bytes that represent the private key | | `extractable?` | `boolean` | Setting this to `true` makes it possible to extract the bytes of the private key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey) API. Defaults to `false`. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`CryptoKeyPair`> ## Example ```ts import { createKeyPairFromPrivateKeyBytes } from '@solana/keys'; const { privateKey, publicKey } = await createKeyPairFromPrivateKeyBytes(new Uint8Array([...])); ``` This can be useful when you have a private key but not the corresponding public key or when you need to derive key pairs from seeds. For instance, the following code snippet derives a key pair from the hash of a message. ```ts import { getUtf8Encoder } from '@solana/codecs-strings'; import { createKeyPairFromPrivateKeyBytes } from '@solana/keys'; const message = getUtf8Encoder().encode('Hello, World!'); const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message)); const derivedKeypair = await createKeyPairFromPrivateKeyBytes(seed); ``` # createKeyPairSignerFromBytes (/api/functions/createKeyPairSignerFromBytes) ```ts function createKeyPairSignerFromBytes( bytes, extractable?, ): Promise>; ``` Creates a new [KeyPairSigner](/api/type-aliases/KeyPairSigner) from a 64-bytes `Uint8Array` secret key (private key and public key). ## Parameters | Parameter | Type | | -------------- | -------------------- | | `bytes` | `ReadonlyUint8Array` | | `extractable?` | `boolean` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`KeyPairSigner`](/api/type-aliases/KeyPairSigner)\<`string`>> ## Example ```ts import fs from 'fs'; import { createKeyPairSignerFromBytes } from '@solana/signers'; // Get bytes from local keypair file. const keypairFile = fs.readFileSync('~/.config/solana/id.json'); const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString())); // Create a KeyPairSigner from the bytes. const signer = await createKeyPairSignerFromBytes(keypairBytes); ``` ## See * [createKeyPairSignerFromPrivateKeyBytes](/api/functions/createKeyPairSignerFromPrivateKeyBytes) if you only have the 32-bytes private key instead. * [writeKeyPairSigner](/api/functions/writeKeyPairSigner) β€” the inverse helper that persists a signer's key pair to disk in the same format. # createKeyPairSignerFromPrivateKeyBytes (/api/functions/createKeyPairSignerFromPrivateKeyBytes) ```ts function createKeyPairSignerFromPrivateKeyBytes( bytes, extractable?, ): Promise>; ``` Creates a new [KeyPairSigner](/api/type-aliases/KeyPairSigner) from a 32-bytes `Uint8Array` private key. ## Parameters | Parameter | Type | | -------------- | -------------------- | | `bytes` | `ReadonlyUint8Array` | | `extractable?` | `boolean` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`KeyPairSigner`](/api/type-aliases/KeyPairSigner)\<`string`>> ## Example ```ts import { getUtf8Encoder } from '@solana/codecs-strings'; import { createKeyPairSignerFromPrivateKeyBytes } from '@solana/signers'; const message = getUtf8Encoder().encode('Hello, World!'); const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message)); const derivedSigner = await createKeyPairSignerFromPrivateKeyBytes(seed); ``` ## See [createKeyPairSignerFromBytes](/api/functions/createKeyPairSignerFromBytes) if you have the 64-bytes secret key instead (private key and public key). # createMessageSignerFromWalletAccount (/api/functions/createMessageSignerFromWalletAccount) ```ts function createMessageSignerFromWalletAccount( uiWalletAccount, ): MessageModifyingSigner; ``` Creates a MessageModifyingSigner from a UiWalletAccount. This function provides a bridge between wallet-standard UiWalletAccount and the MessageModifyingSigner interface, allowing any wallet that implements the `solana:signMessage` feature to be used as a message signer. ## Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ## Parameters | Parameter | Type | Description | | ----------------- | ---------------- | ------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | The wallet account to create a signer from. | ## Returns `MessageModifyingSigner`\<`TWalletAccount`\[`"address"`]> A MessageModifyingSigner that signs messages using the wallet. ## Example ```ts import { createMessageSignerFromWalletAccount } from '@solana/wallet-account-signer'; import { createSignableMessage } from '@solana/signers'; const signer = createMessageSignerFromWalletAccount(walletAccount); const message = createSignableMessage(new Uint8Array([1, 2, 3])); const [signedMessage] = await signer.modifyAndSignMessages([message]); const signature = signedMessage.signatures[signer.address]; ``` ## See * MessageModifyingSigner * SignableMessage # createNonceInvalidationPromiseFactory (/api/functions/createNonceInvalidationPromiseFactory) ## Call Signature ```ts function createNonceInvalidationPromiseFactory( config, ): GetNonceInvalidationPromiseFn; ``` Creates a promise that throws when the value stored in a nonce account is not the expected one. When a transaction's lifetime is tied to the value stored in a nonce account, that transaction can be landed on the network until the nonce is advanced to a new value. ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------- | | `config` | `CreateNonceInvalidationPromiseFactoryConfig`\<`"devnet"`> | - | ### Returns `GetNonceInvalidationPromiseFn` ### Example ```ts import { isSolanaError, SolanaError } from '@solana/errors'; import { createNonceInvalidationPromiseFactory } from '@solana/transaction-confirmation'; const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({ rpc, rpcSubscriptions, }); try { await getNonceInvalidationPromise({ currentNonceValue, nonceAccountAddress, }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__NONCE_INVALID)) { console.error(`The nonce has advanced to ${e.context.actualNonceValue}`); // Re-sign and retry the transaction. return; } else if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) { console.error(`No nonce account was found at ${nonceAccountAddress}`); } throw e; } ``` ## Call Signature ```ts function createNonceInvalidationPromiseFactory( config, ): GetNonceInvalidationPromiseFn; ``` Creates a promise that throws when the value stored in a nonce account is not the expected one. When a transaction's lifetime is tied to the value stored in a nonce account, that transaction can be landed on the network until the nonce is advanced to a new value. ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------- | ----------- | | `config` | `CreateNonceInvalidationPromiseFactoryConfig`\<`"testnet"`> | - | ### Returns `GetNonceInvalidationPromiseFn` ### Example ```ts import { isSolanaError, SolanaError } from '@solana/errors'; import { createNonceInvalidationPromiseFactory } from '@solana/transaction-confirmation'; const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({ rpc, rpcSubscriptions, }); try { await getNonceInvalidationPromise({ currentNonceValue, nonceAccountAddress, }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__NONCE_INVALID)) { console.error(`The nonce has advanced to ${e.context.actualNonceValue}`); // Re-sign and retry the transaction. return; } else if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) { console.error(`No nonce account was found at ${nonceAccountAddress}`); } throw e; } ``` ## Call Signature ```ts function createNonceInvalidationPromiseFactory( config, ): GetNonceInvalidationPromiseFn; ``` Creates a promise that throws when the value stored in a nonce account is not the expected one. When a transaction's lifetime is tied to the value stored in a nonce account, that transaction can be landed on the network until the nonce is advanced to a new value. ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------- | ----------- | | `config` | `CreateNonceInvalidationPromiseFactoryConfig`\<`"mainnet"`> | - | ### Returns `GetNonceInvalidationPromiseFn` ### Example ```ts import { isSolanaError, SolanaError } from '@solana/errors'; import { createNonceInvalidationPromiseFactory } from '@solana/transaction-confirmation'; const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({ rpc, rpcSubscriptions, }); try { await getNonceInvalidationPromise({ currentNonceValue, nonceAccountAddress, }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__NONCE_INVALID)) { console.error(`The nonce has advanced to ${e.context.actualNonceValue}`); // Re-sign and retry the transaction. return; } else if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) { console.error(`No nonce account was found at ${nonceAccountAddress}`); } throw e; } ``` # createNoopSigner (/api/functions/createNoopSigner) ```ts function createNoopSigner(address): NoopSigner; ``` Creates a [NoopSigner](/api/type-aliases/NoopSigner) from the provided Address. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------ | | `TAddress` *extends* `string` | `string` | The inferred type of the address provided. | ## Parameters | Parameter | Type | | --------- | ---------------------- | | `address` | `Address`\<`TAddress`> | ## Returns [`NoopSigner`](/api/type-aliases/NoopSigner)\<`TAddress`> ## Example ```ts import { address } from '@solana/addresses'; import { createNoopSigner } from '@solana/signers'; const signer = createNoopSigner(address('1234..5678')); ``` # createPrivateKeyFromBytes (/api/functions/createPrivateKeyFromBytes) ```ts function createPrivateKeyFromBytes( bytes, extractable?, ): Promise; ``` Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 private key for use with other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects. ## Parameters | Parameter | Type | Description | | -------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `bytes` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | 32 bytes that represent the private key | | `extractable?` | `boolean` | Setting this to `true` makes it possible to extract the bytes of the private key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey) API. Defaults to `false`. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`CryptoKey`](https://developer.mozilla.org/docs/Web/API/CryptoKey)> ## Example ```ts import { createPrivateKeyFromBytes } from '@solana/keys'; const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...])); const extractablePrivateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true); ``` # createReactiveActionStore (/api/functions/createReactiveActionStore) ```ts function createReactiveActionStore( fn, ): ReactiveActionStore; ``` Wraps an async function in a [ReactiveActionStore](/api/type-aliases/ReactiveActionStore). Each `dispatch` creates a fresh AbortController and aborts the previous one; the superseded call's outcome is dropped, so only the most recent dispatch can mutate state. The wrapped function receives the `AbortSignal` as its first argument, followed by whatever arguments were passed to `dispatch`. Callers attach their own cancellation source per-call via [ReactiveActionStore.withSignal](/api/type-aliases/ReactiveActionStore#withsignal) β€” `store.withSignal(signal).dispatch(...)`. The caller's signal is composed with the per-dispatch controller via `AbortSignal.any`, so aborting it cancels the in-flight call and surfaces the abort reason on state. ## Type Parameters | Type Parameter | Description | | --------------------------------------- | ------------------------------------------------- | | `TArgs` *extends* readonly `unknown`\[] | Argument tuple forwarded from `dispatch` to `fn`. | | `TResult` | Resolved value type of `fn`. | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | | `fn` | (`signal`, ...`args`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TResult`> | Async function to wrap. Receives an [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal) plus the dispatch arguments. | ## Returns [`ReactiveActionStore`](/api/type-aliases/ReactiveActionStore)\<`TArgs`, `TResult`> A [ReactiveActionStore](/api/type-aliases/ReactiveActionStore) exposing `dispatch`, `dispatchAsync`, `getState`, `subscribe`, `reset`, and `withSignal`. ## Example ```ts const store = createReactiveActionStore(async (signal, accountId: Address) => { const response = await fetch(`/api/accounts/${accountId}`, { signal }); return response.json(); }); store.subscribe(() => console.log(store.getState())); store.dispatch(someAccountId); // fire-and-forget; state is the source of truth // Per-attempt timeout β€” fresh signal per call: store.withSignal(AbortSignal.timeout(30_000)).dispatch(someAccountId); // Imperative call with the resolved value: const account = await store.dispatchAsync(someAccountId); ``` ## See [ReactiveActionStore](/api/type-aliases/ReactiveActionStore) # createReactiveStoreFromDataPublisherFactory (/api/functions/createReactiveStoreFromDataPublisherFactory) ```ts function createReactiveStoreFromDataPublisherFactory( config, ): ReactiveStreamStore; ``` Returns a [ReactiveStreamStore](/api/type-aliases/ReactiveStreamStore) that wires itself to a fresh [DataPublisher](/api/interfaces/DataPublisher) on every [\`connect()\`](/api/type-aliases/ReactiveStreamStore#connect). The store accepts a `createDataPublisher` factory rather than a ready-made publisher β€” that lets the store tear down a broken stream and open a new one without losing subscribers or the last known value. The factory receives the per-connection signal so the underlying transport can stop on per-connection abort, not just the stream-store's listeners. Things to note: * The returned store starts in `status: 'idle'`. Call `connect()` to open the first stream. * `createDataPublisher` is invoked on every `connect()`. The store transitions through `loading`, preserving the last known `data` and `error` (stale-while-revalidate). * If `createDataPublisher` rejects, the store transitions to `status: 'error'` with the rejection as the error. Call `connect()` to try again. * `reset()` aborts the current connection and returns the store to `idle`, clearing `data` and `error`. A follow-up `connect()` opens a fresh stream. * Attach a caller-provided cancellation source via [\`withSignal()\`](/api/type-aliases/ReactiveStreamStore#withsignal) β€” `store.withSignal(signal).connect()` composes the signal with the per-connection controller. Aborting the caller's signal transitions the store to `error` with that abort reason. ## Type Parameters | Type Parameter | | -------------- | | `TData` | ## Parameters | Parameter | Type | Description | | --------- | --------------- | ----------- | | `config` | `FactoryConfig` | - | ## Returns [`ReactiveStreamStore`](/api/type-aliases/ReactiveStreamStore)\<`TData`> ## Example ```ts const store = createReactiveStoreFromDataPublisherFactory({ createDataPublisher: signal => getDataPublisherFromEventEmitter(new WebSocket(url, { signal })), dataChannelName: 'message', errorChannelName: 'error', }); const unsubscribe = store.subscribe(() => { const snapshot = store.getState(); if (snapshot.status === 'error') console.error('Connection failed:', snapshot.error); else if (snapshot.status === 'loaded') console.log('Latest:', snapshot.data); }); // Fresh 30-second clock per connection attempt: store.withSignal(AbortSignal.timeout(30_000)).connect(); ``` # createReactiveStoreWithInitialValueAndSlotTracking (/api/functions/createReactiveStoreWithInitialValueAndSlotTracking) ```ts function createReactiveStoreWithInitialValueAndSlotTracking< TInitialValue, TStreamValue, TItem, >( config, ): ReactiveStreamStore< Readonly<{ context: Readonly<{ slot: Slot; }>; value: TItem; }> >; ``` Creates a [ReactiveStreamStore](/api/type-aliases/ReactiveStreamStore) that combines an initial one-shot fetch with an ongoing stream to keep its state up to date. The store uses slot-based comparison to ensure that only the most recent value is kept, regardless of whether it came from the initial value source or a stream notification. This prevents stale data from overwriting newer data when the two sources arrive out of order. The two sources are consumed via their [\`reactiveStore()\`](/api/type-aliases/ReactiveActionSource#reactivestore) methods rather than by calling `send()` / `subscribe()` directly, so any object satisfying the [ReactiveActionSource](/api/type-aliases/ReactiveActionSource) / [ReactiveStreamSource](/api/type-aliases/ReactiveStreamSource) duck-types works β€” including `PendingRpcRequest` / `PendingRpcSubscriptionsRequest` and plugin-authored wrappers. Things to note: * The returned store starts in `status: 'idle'`. Call [\`connect()\`](/api/type-aliases/ReactiveStreamStore#connect) to dispatch the initial-value source and open the stream. * The store transitions through `loading` until the first value or notification arrives, then to `loaded` with a [SolanaRpcResponse](/api/type-aliases/SolanaRpcResponse) containing the value and the slot context at which it was observed. * On error from either source, the store transitions to `status: 'error'` preserving the last known value. Only the first error per connection window is captured. * A subsequent `connect()` aborts the current connection, transitions back to `status: 'loading'` (preserving the last known `data` and `error` for stale-while-revalidate), and re-builds both inner stores with a fresh inner abort signal. * [\`reset()\`](/api/type-aliases/ReactiveStreamStore#reset) aborts the current connection and returns the store to `idle`, clearing `data` and `error`. * Attach a caller-provided cancellation source via [\`withSignal()\`](/api/type-aliases/ReactiveStreamStore#withsignal) β€” `store.withSignal(signal).connect()` composes the signal with the per-connection controller. Aborting the caller's signal transitions the store to `error` with that abort reason. ## Type Parameters | Type Parameter | | --------------- | | `TInitialValue` | | `TStreamValue` | | `TItem` | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | `config` | [`CreateReactiveStoreWithInitialValueAndSlotTrackingConfig`](/api/type-aliases/CreateReactiveStoreWithInitialValueAndSlotTrackingConfig)\<`TInitialValue`, `TStreamValue`, `TItem`> | - | ## Returns [`ReactiveStreamStore`](/api/type-aliases/ReactiveStreamStore)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `context`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `slot`: [`Slot`](/api/type-aliases/Slot); }>; `value`: `TItem`; }>> ## Example ```ts import { address, createReactiveStoreWithInitialValueAndSlotTracking, createSolanaRpc, createSolanaRpcSubscriptions, } from '@solana/kit'; const rpc = createSolanaRpc('http://127.0.0.1:8899'); const rpcSubscriptions = createSolanaRpcSubscriptions('ws://127.0.0.1:8900'); const myAddress = address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'); const balanceStore = createReactiveStoreWithInitialValueAndSlotTracking({ initialValueSource: rpc.getBalance(myAddress, { commitment: 'confirmed' }), initialValueMapper: lamports => lamports, streamSource: rpcSubscriptions.accountNotifications(myAddress), streamValueMapper: ({ lamports }) => lamports, }); const unsubscribe = balanceStore.subscribe(() => { const state = balanceStore.getState(); if (state.status === 'error') { console.error('Error:', state.error); balanceStore.connect(); } else if (state.status === 'loaded') { console.log(`Balance at slot ${state.data.context.slot}:`, state.data.value); } }); balanceStore.withSignal(AbortSignal.timeout(60_000)).connect(); ``` ## See [ReactiveStreamStore](/api/type-aliases/ReactiveStreamStore) # createRecentSignatureConfirmationPromiseFactory (/api/functions/createRecentSignatureConfirmationPromiseFactory) ## Call Signature ```ts function createRecentSignatureConfirmationPromiseFactory( config, ): GetRecentSignatureConfirmationPromiseFn; ``` Creates a promise that resolves when a recently-landed transaction achieves the target confirmation commitment, and throws when the transaction fails with an error. The status of recently-landed transactions is available in the network's status cache. This confirmation strategy will only yield a result if the signature is still in the status cache. To fetch the status of transactions older than those available in the status cache, use the GetSignatureStatusesApi.getSignatureStatuses method setting the `searchTransactionHistory` configuration param to `true`. ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------- | ----------- | | `config` | `CreateRecentSignatureConfirmationPromiseFactoryConfig`\<`"devnet"`> | - | ### Returns `GetRecentSignatureConfirmationPromiseFn` ### Example ```ts import { createRecentSignatureConfirmationPromiseFactory } from '@solana/transaction-confirmation'; const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({ rpc, rpcSubscriptions, }); try { await getRecentSignatureConfirmationPromise({ commitment, signature, }); console.log(`The transaction with signature \`${signature}\` has achieved a commitment level of \`${commitment}\``); } catch (e) { console.error(`The transaction with signature \`${signature}\` failed`, e.cause); throw e; } ``` ## Call Signature ```ts function createRecentSignatureConfirmationPromiseFactory( config, ): GetRecentSignatureConfirmationPromiseFn; ``` Creates a promise that resolves when a recently-landed transaction achieves the target confirmation commitment, and throws when the transaction fails with an error. The status of recently-landed transactions is available in the network's status cache. This confirmation strategy will only yield a result if the signature is still in the status cache. To fetch the status of transactions older than those available in the status cache, use the GetSignatureStatusesApi.getSignatureStatuses method setting the `searchTransactionHistory` configuration param to `true`. ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------- | ----------- | | `config` | `CreateRecentSignatureConfirmationPromiseFactoryConfig`\<`"testnet"`> | - | ### Returns `GetRecentSignatureConfirmationPromiseFn` ### Example ```ts import { createRecentSignatureConfirmationPromiseFactory } from '@solana/transaction-confirmation'; const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({ rpc, rpcSubscriptions, }); try { await getRecentSignatureConfirmationPromise({ commitment, signature, }); console.log(`The transaction with signature \`${signature}\` has achieved a commitment level of \`${commitment}\``); } catch (e) { console.error(`The transaction with signature \`${signature}\` failed`, e.cause); throw e; } ``` ## Call Signature ```ts function createRecentSignatureConfirmationPromiseFactory( config, ): GetRecentSignatureConfirmationPromiseFn; ``` Creates a promise that resolves when a recently-landed transaction achieves the target confirmation commitment, and throws when the transaction fails with an error. The status of recently-landed transactions is available in the network's status cache. This confirmation strategy will only yield a result if the signature is still in the status cache. To fetch the status of transactions older than those available in the status cache, use the GetSignatureStatusesApi.getSignatureStatuses method setting the `searchTransactionHistory` configuration param to `true`. ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------- | ----------- | | `config` | `CreateRecentSignatureConfirmationPromiseFactoryConfig`\<`"mainnet"`> | - | ### Returns `GetRecentSignatureConfirmationPromiseFn` ### Example ```ts import { createRecentSignatureConfirmationPromiseFactory } from '@solana/transaction-confirmation'; const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({ rpc, rpcSubscriptions, }); try { await getRecentSignatureConfirmationPromise({ commitment, signature, }); console.log(`The transaction with signature \`${signature}\` has achieved a commitment level of \`${commitment}\``); } catch (e) { console.error(`The transaction with signature \`${signature}\` failed`, e.cause); throw e; } ``` # createRpc (/api/functions/createRpc) ```ts function createRpc( rpcConfig, ): Rpc; ``` Creates a [Rpc](/api/type-aliases/Rpc) instance given a [RpcApi\](/api/type-aliases/RpcApi) and a [RpcTransport](/api/type-aliases/RpcTransport) capable of fulfilling them. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------- | | `TRpcMethods` | | `TRpcTransport` *extends* [`RpcTransport`](/api/type-aliases/RpcTransport) | ## Parameters | Parameter | Type | | ----------- | --------------------------------------------------------------------------- | | `rpcConfig` | [`RpcConfig`](/api/type-aliases/RpcConfig)\<`TRpcMethods`, `TRpcTransport`> | ## Returns [`Rpc`](/api/type-aliases/Rpc)\<`TRpcMethods`> # createRpcMessage (/api/functions/createRpcMessage) ```ts function createRpcMessage(request): object; ``` Returns a spec-compliant JSON RPC 2.0 message, given a method name and some params. Generates a new `id` on each call by incrementing a `bigint` and casting it to a string. ## Type Parameters | Type Parameter | | -------------- | | `TParams` | ## Parameters | Parameter | Type | | --------- | -------------------------------------------------------- | | `request` | [`RpcRequest`](/api/type-aliases/RpcRequest)\<`TParams`> | ## Returns `object` | Name | Type | Default value | | --------- | --------- | -------------------- | | `id` | `string` | - | | `jsonrpc` | `string` | `'2.0'` | | `method` | `string` | `request.methodName` | | `params` | `TParams` | `request.params` | # createRpcSubscriptionsApi (/api/functions/createRpcSubscriptionsApi) ```ts function createRpcSubscriptionsApi( config, ): RpcSubscriptionsApi; ``` Creates a JavaScript proxy that converts *any* function call called on it to a [RpcSubscriptionsPlan](/api/type-aliases/RpcSubscriptionsPlan) by creating an `execute` function that: * calls the supplied RpcSubscriptionsApiConfig.planExecutor with a JSON RPC v2 payload object with the requested `methodName` and `params` properties, optionally transformed by RpcSubscriptionsApiConfig.requestTransformer. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------ | | `TRpcSubscriptionsApiMethods` *extends* [`RpcSubscriptionsApiMethods`](/api/interfaces/RpcSubscriptionsApiMethods) | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------- | | `config` | [`RpcSubscriptionsApiConfig`](/api/type-aliases/RpcSubscriptionsApiConfig)\<`TRpcSubscriptionsApiMethods`> | ## Returns [`RpcSubscriptionsApi`](/api/type-aliases/RpcSubscriptionsApi)\<`TRpcSubscriptionsApiMethods`> ## Example ```ts // For example, given this `RpcSubscriptionsApi`: const rpcSubscriptionsApi = createJsonRpcSubscriptionsApi({ async planExecutor({ channel, request }) { await channel.send(request); return { ...channel, on(type, listener, options) { if (type !== 'message') { return channel.on(type, listener, options); } return channel.on( 'message', function resultGettingListener(message) { listener(message.result); }, options, ); } } }, requestTransformer: (...rawParams) => rawParams.reverse(), }); // ...the following function call: rpcSubscriptionsApi.foo('bar', { baz: 'bat' }); // ...will produce a `RpcSubscriptionsPlan` that: // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }. // - Emits the "result" property of each RPC Subscriptions message. ``` # createRpcSubscriptionsTransportFromChannelCreator (/api/functions/createRpcSubscriptionsTransportFromChannelCreator) ```ts function createRpcSubscriptionsTransportFromChannelCreator< TChannelCreator, TInboundMessage, TOutboundMessage, >( createChannel, ): TChannelCreator extends RpcSubscriptionsChannelCreatorDevnet< TOutboundMessage, TInboundMessage > ? RpcSubscriptionsTransportDevnet : TChannelCreator extends RpcSubscriptionsChannelCreatorTestnet< TOutboundMessage, TInboundMessage > ? RpcSubscriptionsTransportTestnet : TChannelCreator extends RpcSubscriptionsChannelCreatorMainnet< TOutboundMessage, TInboundMessage > ? RpcSubscriptionsTransportMainnet : RpcSubscriptionsTransport; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TChannelCreator` *extends* [`RpcSubscriptionsChannelCreator`](/api/type-aliases/RpcSubscriptionsChannelCreator)\<`TOutboundMessage`, `TInboundMessage`> | | `TInboundMessage` | | `TOutboundMessage` | ## Parameters | Parameter | Type | | --------------- | ----------------- | | `createChannel` | `TChannelCreator` | ## Returns `TChannelCreator` *extends* [`RpcSubscriptionsChannelCreatorDevnet`](/api/type-aliases/RpcSubscriptionsChannelCreatorDevnet)\<`TOutboundMessage`, `TInboundMessage`> ? [`RpcSubscriptionsTransportDevnet`](/api/type-aliases/RpcSubscriptionsTransportDevnet) : `TChannelCreator` *extends* [`RpcSubscriptionsChannelCreatorTestnet`](/api/type-aliases/RpcSubscriptionsChannelCreatorTestnet)\<`TOutboundMessage`, `TInboundMessage`> ? [`RpcSubscriptionsTransportTestnet`](/api/type-aliases/RpcSubscriptionsTransportTestnet) : `TChannelCreator` *extends* [`RpcSubscriptionsChannelCreatorMainnet`](/api/type-aliases/RpcSubscriptionsChannelCreatorMainnet)\<`TOutboundMessage`, `TInboundMessage`> ? [`RpcSubscriptionsTransportMainnet`](/api/type-aliases/RpcSubscriptionsTransportMainnet) : [`RpcSubscriptionsTransport`](/api/interfaces/RpcSubscriptionsTransport) # createSignableMessage (/api/functions/createSignableMessage) ```ts function createSignableMessage(content, signatures?): SignableMessage; ``` Creates a [SignableMessage](/api/type-aliases/SignableMessage) from a `Uint8Array` or a UTF-8 string. It optionally accepts a signature dictionary if the message already contains signatures. ## Parameters | Parameter | Type | | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | | `content` | \| `string` \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | | `signatures` | [`SignatureDictionary`](/api/type-aliases/SignatureDictionary) | ## Returns [`SignableMessage`](/api/type-aliases/SignableMessage) ## Example ```ts const message = createSignableMessage(new Uint8Array([1, 2, 3])); const messageFromText = createSignableMessage('Hello world!'); const messageWithSignatures = createSignableMessage('Hello world!', { [address('1234..5678')]: new Uint8Array([1, 2, 3]) as SignatureBytes, }); ``` # createSignerFromKeyPair (/api/functions/createSignerFromKeyPair) ```ts function createSignerFromKeyPair( keyPair, ): Promise>; ``` Creates a [KeyPairSigner](/api/type-aliases/KeyPairSigner) from a provided CryptoKeyPair. The MessagePartialSigner#signMessages | signMessages and TransactionPartialSigner#signTransactions | signTransactions functions of the returned signer will use the private key of the provided key pair to sign messages and transactions. Note that both the MessagePartialSigner#signMessages | signMessages and TransactionPartialSigner#signTransactions | signTransactions implementations are parallelized, meaning that they will sign all provided messages and transactions in parallel. ## Parameters | Parameter | Type | | --------- | --------------- | | `keyPair` | `CryptoKeyPair` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`KeyPairSigner`](/api/type-aliases/KeyPairSigner)\<`string`>> ## Example ```ts import { generateKeyPair } from '@solana/keys'; import { createSignerFromKeyPair, KeyPairSigner } from '@solana/signers'; const keyPair: CryptoKeyPair = await generateKeyPair(); const signer: KeyPairSigner = await createSignerFromKeyPair(keyPair); ``` # createSignerFromWalletAccount (/api/functions/createSignerFromWalletAccount) ```ts function createSignerFromWalletAccount( uiWalletAccount, chain, ): | TransactionSigner | (MessageSigner & TransactionSigner); ``` Creates a combined signer from a UiWalletAccount that exposes all signing capabilities the wallet account supports. Unlike the more specific helpers ([createTransactionSignerFromWalletAccount](/api/functions/createTransactionSignerFromWalletAccount), [createTransactionSendingSignerFromWalletAccount](/api/functions/createTransactionSendingSignerFromWalletAccount), [createMessageSignerFromWalletAccount](/api/functions/createMessageSignerFromWalletAccount)), this function inspects the wallet account's features at call time and returns a single signer object with whichever of the following methods are available: * `modifyAndSignTransactions` β€” present when the `solana:signTransaction` feature is available. * `signAndSendTransactions` β€” present when the `solana:signAndSendTransaction` feature is available. * `modifyAndSignMessages` β€” present when the `solana:signMessage` feature is available. At least one of `solana:signTransaction` or `solana:signAndSendTransaction` must be present, otherwise an error is thrown. `solana:signMessage` is optional. ## Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ## Parameters | Parameter | Type | Description | | ----------------- | --------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | The wallet account to create a signer from. | | `chain` | \| `"solana:mainnet"` \| `"solana:devnet"` \| `"solana:testnet"` \| `"solana:localnet"` \| `` `${string}:${string}` `` & `object` | The Solana chain identifier (e.g., `'solana:devnet'`, `'solana:mainnet'`). | ## Returns \| `TransactionSigner`\<`TWalletAccount`\[`"address"`]> \| MessageSigner\ & TransactionSigner\ A TransactionSigner, optionally combined with a MessageSigner, depending on the features available on the wallet account. ## Throws If the wallet account does not support the specified chain. ## Throws If the wallet account supports neither `solana:signTransaction` nor `solana:signAndSendTransaction`. ## Example ```ts import { createSignerFromWalletAccount } from '@solana/wallet-account-signer'; import { isMessageSigner } from '@solana/signers'; const signer = createSignerFromWalletAccount(walletAccount, 'solana:devnet'); // Sign a transaction (always available β€” at least one tx feature must exist) if ('modifyAndSignTransactions' in signer) { const [signedTransaction] = await signer.modifyAndSignTransactions([transaction]); } // Also sign messages if the wallet supports it if (isMessageSigner(signer)) { const [signedMessage] = await signer.modifyAndSignMessages([message]); } ``` ## See * [createTransactionSignerFromWalletAccount](/api/functions/createTransactionSignerFromWalletAccount) * [createTransactionSendingSignerFromWalletAccount](/api/functions/createTransactionSendingSignerFromWalletAccount) * [createMessageSignerFromWalletAccount](/api/functions/createMessageSignerFromWalletAccount) # createSolanaRpc (/api/functions/createSolanaRpc) ```ts function createSolanaRpc( clusterUrl, config?, ): RpcFromTransport< SolanaRpcApiFromTransport>, RpcTransportFromClusterUrl >; ``` Creates a [Rpc](/api/type-aliases/Rpc) instance that exposes the Solana JSON RPC API given a cluster URL and some optional transport config. See [createDefaultRpcTransport](/api/functions/createDefaultRpcTransport) for the shape of the transport config. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Parameters | Parameter | Type | | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `clusterUrl` | `TClusterUrl` | | `config?` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`DefaultRpcTransportConfig`\<`TClusterUrl`>, `"url"`> | ## Returns [`RpcFromTransport`](/api/type-aliases/RpcFromTransport)\<[`SolanaRpcApiFromTransport`](/api/type-aliases/SolanaRpcApiFromTransport)\<[`RpcTransportFromClusterUrl`](/api/type-aliases/RpcTransportFromClusterUrl)\<`TClusterUrl`>>, [`RpcTransportFromClusterUrl`](/api/type-aliases/RpcTransportFromClusterUrl)\<`TClusterUrl`>> # createSolanaRpcApi (/api/functions/createSolanaRpcApi) ```ts function createSolanaRpcApi(config?): RpcApi; ``` Creates a [RpcApi](/api/type-aliases/RpcApi) implementation of the Solana JSON RPC API with some default behaviours. The default behaviours include: * A transform that calls the config's Config.onIntegerOverflow | onIntegerOverflow handler whenever a `bigint` input would overflow a JavaScript IEEE 754 number. See [this](https://github.com/solana-labs/solana-web3.js/issues/1116) GitHub issue for more information. * A transform that applies a default commitment wherever not specified ## Type Parameters | Type Parameter | Default type | | ------------------------------------------------------------------------------------- | ----------------------------- | | `TRpcMethods` *extends* `SolanaRpcApiForAllClusters` \| `SolanaRpcApiForTestClusters` | `SolanaRpcApiForTestClusters` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `defaultCommitment?`: `Commitment`; `onIntegerOverflow?`: `IntegerOverflowHandler`; }> | ## Returns [`RpcApi`](/api/type-aliases/RpcApi)\<`TRpcMethods`> # createSolanaRpcFromTransport (/api/functions/createSolanaRpcFromTransport) ```ts function createSolanaRpcFromTransport( transport, ): RpcFromTransport, TTransport>; ``` Creates a [Rpc](/api/type-aliases/Rpc) instance that exposes the Solana JSON RPC API given the supplied [RpcTransport](/api/type-aliases/RpcTransport). ## Type Parameters | Type Parameter | | ----------------------------------------------------------------------- | | `TTransport` *extends* [`RpcTransport`](/api/type-aliases/RpcTransport) | ## Parameters | Parameter | Type | | ----------- | ------------ | | `transport` | `TTransport` | ## Returns [`RpcFromTransport`](/api/type-aliases/RpcFromTransport)\<[`SolanaRpcApiFromTransport`](/api/type-aliases/SolanaRpcApiFromTransport)\<`TTransport`>, `TTransport`> # createSolanaRpcSubscriptions (/api/functions/createSolanaRpcSubscriptions) ```ts function createSolanaRpcSubscriptions( clusterUrl, config?, ): RpcSubscriptionsFromTransport< SolanaRpcSubscriptionsApi, RpcSubscriptionsTransportFromClusterUrl >; ``` Creates a [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) instance that exposes the Solana JSON RPC WebSocket API given a cluster URL and some optional channel config. See [createDefaultRpcSubscriptionsChannelCreator](/api/functions/createDefaultRpcSubscriptionsChannelCreator) for the shape of the channel config. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Parameters | Parameter | Type | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `clusterUrl` | `TClusterUrl` | | `config?` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `intervalMs?`: `number`; `maxSubscriptionsPerChannel?`: `number`; `minChannels?`: `number`; `sendBufferHighWatermark?`: `number`; `url`: `TClusterUrl`; }>, `"url"`> | ## Returns [`RpcSubscriptionsFromTransport`](/api/type-aliases/RpcSubscriptionsFromTransport)\<[`SolanaRpcSubscriptionsApi`](/api/type-aliases/SolanaRpcSubscriptionsApi), [`RpcSubscriptionsTransportFromClusterUrl`](/api/type-aliases/RpcSubscriptionsTransportFromClusterUrl)\<`TClusterUrl`>> # createSolanaRpcSubscriptionsApi (/api/functions/createSolanaRpcSubscriptionsApi) ```ts function createSolanaRpcSubscriptionsApi( config?, ): RpcSubscriptionsApi; ``` ## Type Parameters | Type Parameter | Default type | | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | `TApi` *extends* [`RpcSubscriptionsApiMethods`](/api/interfaces/RpcSubscriptionsApiMethods) | [`SolanaRpcSubscriptionsApi`](/api/type-aliases/SolanaRpcSubscriptionsApi) | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `defaultCommitment?`: `Commitment`; `onIntegerOverflow?`: `IntegerOverflowHandler`; }> | ## Returns [`RpcSubscriptionsApi`](/api/type-aliases/RpcSubscriptionsApi)\<`TApi`> # createSolanaRpcSubscriptionsApi_UNSTABLE (/api/functions/createSolanaRpcSubscriptionsApi_UNSTABLE) ```ts function createSolanaRpcSubscriptionsApi_UNSTABLE( config?, ): RpcSubscriptionsApi< AccountNotificationsApi & LogsNotificationsApi & ProgramNotificationsApi & RootNotificationsApi & SignatureNotificationsApi & SlotNotificationsApi & BlockNotificationsApi & SlotsUpdatesNotificationsApi & VoteNotificationsApi >; ``` ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `defaultCommitment?`: `Commitment`; `onIntegerOverflow?`: `IntegerOverflowHandler`; }> | ## Returns [`RpcSubscriptionsApi`](/api/type-aliases/RpcSubscriptionsApi)\<[`AccountNotificationsApi`](/api/type-aliases/AccountNotificationsApi) & [`LogsNotificationsApi`](/api/type-aliases/LogsNotificationsApi) & [`ProgramNotificationsApi`](/api/type-aliases/ProgramNotificationsApi) & [`RootNotificationsApi`](/api/type-aliases/RootNotificationsApi) & [`SignatureNotificationsApi`](/api/type-aliases/SignatureNotificationsApi) & [`SlotNotificationsApi`](/api/type-aliases/SlotNotificationsApi) & [`BlockNotificationsApi`](/api/type-aliases/BlockNotificationsApi) & [`SlotsUpdatesNotificationsApi`](/api/type-aliases/SlotsUpdatesNotificationsApi) & [`VoteNotificationsApi`](/api/type-aliases/VoteNotificationsApi)> # createSolanaRpcSubscriptionsFromTransport (/api/functions/createSolanaRpcSubscriptionsFromTransport) ```ts function createSolanaRpcSubscriptionsFromTransport( transport, ): RpcSubscriptionsFromTransport; ``` Creates a [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) instance that exposes the Solana JSON RPC WebSocket API given the supplied [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport). ## Type Parameters | Type Parameter | Default type | | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | `TTransport` *extends* [`RpcSubscriptionsTransport`](/api/interfaces/RpcSubscriptionsTransport) | - | | `TApi` *extends* [`RpcSubscriptionsApiMethods`](/api/interfaces/RpcSubscriptionsApiMethods) | [`SolanaRpcSubscriptionsApi`](/api/type-aliases/SolanaRpcSubscriptionsApi) | ## Parameters | Parameter | Type | | ----------- | ------------ | | `transport` | `TTransport` | ## Returns [`RpcSubscriptionsFromTransport`](/api/type-aliases/RpcSubscriptionsFromTransport)\<`TApi`, `TTransport`> # createSolanaRpcSubscriptions_UNSTABLE (/api/functions/createSolanaRpcSubscriptions_UNSTABLE) ```ts function createSolanaRpcSubscriptions_UNSTABLE( clusterUrl, config?, ): RpcSubscriptionsFromTransport< AccountNotificationsApi & LogsNotificationsApi & ProgramNotificationsApi & RootNotificationsApi & SignatureNotificationsApi & SlotNotificationsApi & BlockNotificationsApi & SlotsUpdatesNotificationsApi & VoteNotificationsApi, RpcSubscriptionsTransportFromClusterUrl >; ``` Creates a [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) instance that exposes the Solana JSON RPC WebSocket API, including its unstable methods, given a cluster URL and some optional channel config. See [createDefaultRpcSubscriptionsChannelCreator](/api/functions/createDefaultRpcSubscriptionsChannelCreator) for the shape of the channel config. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TClusterUrl` *extends* `ClusterUrl` | ## Parameters | Parameter | Type | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `clusterUrl` | `TClusterUrl` | | `config?` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `intervalMs?`: `number`; `maxSubscriptionsPerChannel?`: `number`; `minChannels?`: `number`; `sendBufferHighWatermark?`: `number`; `url`: `TClusterUrl`; }>, `"url"`> | ## Returns [`RpcSubscriptionsFromTransport`](/api/type-aliases/RpcSubscriptionsFromTransport)\<[`AccountNotificationsApi`](/api/type-aliases/AccountNotificationsApi) & [`LogsNotificationsApi`](/api/type-aliases/LogsNotificationsApi) & [`ProgramNotificationsApi`](/api/type-aliases/ProgramNotificationsApi) & [`RootNotificationsApi`](/api/type-aliases/RootNotificationsApi) & [`SignatureNotificationsApi`](/api/type-aliases/SignatureNotificationsApi) & [`SlotNotificationsApi`](/api/type-aliases/SlotNotificationsApi) & [`BlockNotificationsApi`](/api/type-aliases/BlockNotificationsApi) & [`SlotsUpdatesNotificationsApi`](/api/type-aliases/SlotsUpdatesNotificationsApi) & [`VoteNotificationsApi`](/api/type-aliases/VoteNotificationsApi), [`RpcSubscriptionsTransportFromClusterUrl`](/api/type-aliases/RpcSubscriptionsTransportFromClusterUrl)\<`TClusterUrl`>> # createSubscriptionRpc (/api/functions/createSubscriptionRpc) ```ts function createSubscriptionRpc( rpcConfig, ): RpcSubscriptions; ``` Creates a [RpcSubscriptions](/api/type-aliases/RpcSubscriptions) instance given a [RpcSubscriptionsApi\](/api/type-aliases/RpcSubscriptionsApi) and a [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport) capable of fulfilling them. ## Type Parameters | Type Parameter | | ----------------------------- | | `TRpcSubscriptionsApiMethods` | ## Parameters | Parameter | Type | | ----------- | ---------------------------------------------------------------------------------------------------- | | `rpcConfig` | [`RpcSubscriptionsConfig`](/api/type-aliases/RpcSubscriptionsConfig)\<`TRpcSubscriptionsApiMethods`> | ## Returns [`RpcSubscriptions`](/api/type-aliases/RpcSubscriptions)\<`TRpcSubscriptionsApiMethods`> # createTransactionMessage (/api/functions/createTransactionMessage) ```ts function createTransactionMessage( config, ): EmptyTransactionMessage; ``` Given a [TransactionVersion](/api/type-aliases/TransactionVersion) this method will return an empty transaction having the capabilities of that version. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------- | | `TVersion` *extends* [`TransactionVersion`](/api/type-aliases/TransactionVersion) | ## Parameters | Parameter | Type | | --------- | -------------------------------- | | `config` | `TransactionConfig`\<`TVersion`> | ## Returns `EmptyTransactionMessage`\<`TVersion`> ## Example ```ts import { createTransactionMessage } from '@solana/transaction-messages'; const message = createTransactionMessage({ version: 0 }); ``` # createTransactionPlanExecutor (/api/functions/createTransactionPlanExecutor) ```ts function createTransactionPlanExecutor( config, ): TransactionPlanExecutor; ``` Creates a new transaction plan executor based on the provided configuration. The executor will traverse the provided `TransactionPlan` sequentially or in parallel, executing each transaction message using the `executeTransactionMessage` function. The `executeTransactionMessage` callback receives a mutable context object as its first argument, which can be used to incrementally store useful data as execution progresses (e.g. the latest version of the transaction message after setting its lifetime, the compiled and signed transaction, the transaction signature, or any custom properties). This context is included in the resulting [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) regardless of the outcome. This means that if an error is thrown at any point in the callback, any attributes already saved to the context will still be available in the plan result, which can be useful for debugging failures or building recovery plans. The callback then returns the context a successful result should carry, as a complete `TContext`. The executor writes nothing to it on the callback's behalf β€” notably, it does not derive a `signature` from a stored transaction. Producing `signature` is therefore the callback's job, and an executor that produces transactions its fee payer has not signed can simply leave the property out and declare a `TContext` that does not require it. Requiring that return value is what keeps `TContext` honest: a callback that declares a context with a required `signature` and never produces one fails to compile, rather than yielding a result whose `context.signature` is typed but `undefined` at runtime. Note that the mutable context cannot itself be returned β€” every property on it is optional, so it does not satisfy `TContext`. Return an object built from the values you have instead: ```ts executeTransactionMessage: async (context, message) => { const transaction = await signTransactionMessageWithSigners(message); context.transaction = transaction; // Recorded now, in case the next step throws. const signature = getSignatureFromTransaction(transaction); await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); return { signature, transaction }; } ``` The two channels serve different outcomes. Mutating the context makes a value available to a *failed* result; returning it makes a value available to a *successful* one. On success the two are merged, with the returned value taking precedence, so a property stored on the context but omitted from the return value is still reported. `TContext` is the only thing that says what a context contains β€” the executor adds nothing of its own on top, in either direction. It defaults to [TransactionPlanResultContextWithSignature](/api/type-aliases/TransactionPlanResultContextWithSignature), which is why the zero-type-argument spelling hands the callback the familiar `message`, `transaction` and `signature` properties and guarantees a `context.signature` on every successful result. Supply a different `TContext` and you get exactly that instead, so intersect one of the base context types in if you want those properties alongside your own: ```ts createTransactionPlanExecutor(config); ``` Note the asymmetry between the callback's two context types. A fresh context is created for every single transaction plan, so on entry it is empty and *every* property of `TContext` is optional on the parameter β€” populating them is the callback's job, not a guarantee the executor makes. The value it returns is a complete `TContext`, which is what lets the `TransactionPlanExecutor` this factory returns report a successful result's context as fully populated. Declare the properties you intend to produce as an explicit type argument to this function; a callback cannot annotate its own context parameter with required properties, because none of them are present when it is called. * If that function is successful, the executor will return a successful `TransactionPlanResult` for that message, carrying the context the callback returned merged over the one it mutated. * If that function throws an error, the executor will stop processing and cancel all remaining transaction messages in the plan. The context accumulated up to the point of failure is preserved in the resulting [FailedSingleTransactionPlanResult](/api/type-aliases/FailedSingleTransactionPlanResult). * If the `abortSignal` is triggered, the executor will immediately stop processing the plan and return a `TransactionPlanResult` with the status set to `canceled`. ## Type Parameters | Type Parameter | Default type | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | `config` | [`TransactionPlanExecutorConfig`](/api/type-aliases/TransactionPlanExecutorConfig)\<`TContext`> | Configuration object containing the transaction message executor function. | ## Returns [`TransactionPlanExecutor`](/api/type-aliases/TransactionPlanExecutor)\<`TContext`> A [TransactionPlanExecutor](/api/type-aliases/TransactionPlanExecutor) function that can execute transaction plans. ## Throws [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_FAILED\_TO\_EXECUTE\_TRANSACTION\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN) if any transaction in the plan fails to execute. The error context contains a `transactionPlanResult` property with the partial results up to the point of failure. ## Throws [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_NON\_DIVISIBLE\_TRANSACTION\_PLANS\_NOT\_SUPPORTED](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED) if the transaction plan contains non-divisible sequential plans, which are not supported by this executor. ## Example ```ts const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); const transactionPlanExecutor = createTransactionPlanExecutor({ executeTransactionMessage: async (context, message) => { const transaction = await signTransactionMessageWithSigners(message); context.transaction = transaction; const signature = getSignatureFromTransaction(transaction); await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); return { signature, transaction }; } }); ``` ## See [TransactionPlanExecutorConfig](/api/type-aliases/TransactionPlanExecutorConfig) # createTransactionPlanExecutorWithConcurrentLeaves (/api/functions/createTransactionPlanExecutorWithConcurrentLeaves) ```ts function createTransactionPlanExecutorWithConcurrentLeaves( config, ): TransactionPlanExecutor; ``` Creates a transaction plan executor that processes every leaf concurrently. It takes the same configuration as [createTransactionPlanExecutor](/api/functions/createTransactionPlanExecutor) and its `executeTransactionMessage` callback follows the same contract: it receives a fresh mutable context object for every leaf and returns the complete `TContext` a successful result must carry. On success the two are merged with the returned value taking precedence; on a throw the context accumulated so far is preserved in the failed result. The difference is the traversal. This executor preserves the input plan's nesting, order, and divisibility in the returned result, but it does not enforce the execution dependencies expressed by sequential plans: every leaf callback is started immediately, without a concurrency limit. This makes it suitable for operations such as signing or serializing transactions that can be performed independently. For the same reason, a callback that throws does not cancel the other leaves β€” each one runs to completion β€” and non-divisible sequential plans are supported. The optional abort signal is forwarded to every leaf callback and enforced by the executor. When the signal is already aborted, leaves are canceled without invoking their callbacks. When it is aborted during execution, the executor stops waiting for active callbacks and records failed results carrying the abort reason and the context accumulated so far β€” a value the callback resolves with afterwards is discarded. After all leaves settle, a plan containing failed or canceled results throws a failed execution error containing the complete result tree. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The context carried by each single transaction plan result. | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | `config` | [`TransactionPlanExecutorConfig`](/api/type-aliases/TransactionPlanExecutorConfig)\<`TContext`> | Configuration object containing the transaction message executor function. | ## Returns [`TransactionPlanExecutor`](/api/type-aliases/TransactionPlanExecutor)\<`TContext`> A [TransactionPlanExecutor](/api/type-aliases/TransactionPlanExecutor) that processes all transaction plan leaves concurrently. ## Throws [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_FAILED\_TO\_EXECUTE\_TRANSACTION\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN) if any leaf callback throws, any leaf is canceled, or the abort signal fires. The error context contains a `transactionPlanResult` property with the complete result tree. ## Throws [SOLANA\_ERROR\_\_INVARIANT\_VIOLATION\_\_INVALID\_TRANSACTION\_PLAN\_KIND](/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND) if the plan has an unknown kind. ## Example Signing every transaction in a plan concurrently. ```ts const executor = createTransactionPlanExecutorWithConcurrentLeaves<{ transaction: Transaction }>({ executeTransactionMessage: async (_context, message) => { const transaction = await signTransactionMessageWithSigners(message); return { transaction }; }, }); const result = await executor(transactionPlan); ``` ## See * [TransactionPlanExecutorConfig](/api/type-aliases/TransactionPlanExecutorConfig) * [createTransactionPlanExecutor](/api/functions/createTransactionPlanExecutor) # createTransactionPlanner (/api/functions/createTransactionPlanner) ```ts function createTransactionPlanner(config): TransactionPlanner; ``` Creates a new transaction planner based on the provided configuration. At the very least, the `createTransactionMessage` function must be provided. This function is used to create new transaction messages whenever needed. Additionally, the `onTransactionMessageUpdated` function can be provided to update transaction messages during the planning process. This function will be called whenever a transaction message is updated, e.g. when new instructions are added to a transaction message. It accepts the updated transaction message and must return a transaction message back, even if no changes were made. You may also provide `maxInstructionsPerTransaction` to limit the number of instructions in each planned transaction message. This limit includes any instructions already present in messages returned by `createTransactionMessage` and any instructions added by `onTransactionMessageUpdated`. It must be a positive integer no greater than the hard limit of `64` instructions per transaction; larger values throw. Defaults to 16. ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------ | | `config` | [`TransactionPlannerConfig`](/api/type-aliases/TransactionPlannerConfig) | ## Returns [`TransactionPlanner`](/api/type-aliases/TransactionPlanner) ## Example ```ts const transactionPlanner = createTransactionPlanner({ createTransactionMessage: () => pipe( createTransactionMessage({ version: 0 }), message => setTransactionMessageFeePayerSigner(mySigner, message), ) }); ``` ## See [TransactionPlannerConfig](/api/type-aliases/TransactionPlannerConfig) # createTransactionSendingSignerFromWalletAccount (/api/functions/createTransactionSendingSignerFromWalletAccount) ```ts function createTransactionSendingSignerFromWalletAccount< TWalletAccount, >( uiWalletAccount, chain, ): TransactionSendingSigner; ``` Creates a TransactionSendingSigner from a UiWalletAccount. This function provides a bridge between wallet-standard UiWalletAccount and the TransactionSendingSigner interface, allowing any wallet that implements the `solana:signAndSendTransaction` feature to sign and send transactions. ## Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ## Parameters | Parameter | Type | Description | | ----------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | The wallet account to create a signer from. | | `chain` | \| `"solana:mainnet"` \| `"solana:devnet"` \| `"solana:testnet"` \| `"solana:localnet"` \| `` `${string}:${string}` `` & `object` | The Solana chain identifier (e.g., 'solana:devnet', 'solana:mainnet'). | ## Returns `TransactionSendingSigner`\<`TWalletAccount`\[`"address"`]> A TransactionSendingSigner that signs and sends transactions using the wallet. ## Throws If the wallet account does not support the specified chain. ## Example ```ts import { createTransactionSendingSignerFromWalletAccount } from '@solana/wallet-account-signer'; const signer = createTransactionSendingSignerFromWalletAccount(walletAccount, 'solana:devnet'); const [signature] = await signer.signAndSendTransactions([transaction]); ``` ## See * TransactionSendingSigner * [createTransactionSignerFromWalletAccount](/api/functions/createTransactionSignerFromWalletAccount) # createTransactionSignerFromWalletAccount (/api/functions/createTransactionSignerFromWalletAccount) ```ts function createTransactionSignerFromWalletAccount( uiWalletAccount, chain, ): TransactionModifyingSigner; ``` Creates a TransactionModifyingSigner from a UiWalletAccount. This function provides a bridge between wallet-standard UiWalletAccount and the TransactionModifyingSigner interface, allowing any wallet that implements the `solana:signTransaction` feature to be used as a transaction signer. ## Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ## Parameters | Parameter | Type | Description | | ----------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | The wallet account to create a signer from. | | `chain` | \| `"solana:mainnet"` \| `"solana:devnet"` \| `"solana:testnet"` \| `"solana:localnet"` \| `` `${string}:${string}` `` & `object` | The Solana chain identifier (e.g., 'solana:devnet', 'solana:mainnet'). | ## Returns `TransactionModifyingSigner`\<`TWalletAccount`\[`"address"`]> A TransactionModifyingSigner that signs transactions using the wallet. ## Throws If the wallet account does not support the specified chain. ## Example ```ts import { createTransactionSignerFromWalletAccount } from '@solana/wallet-account-signer'; const signer = createTransactionSignerFromWalletAccount(walletAccount, 'solana:devnet'); const [signedTransaction] = await signer.modifyAndSignTransactions([transaction]); ``` ## See * TransactionModifyingSigner * [createTransactionSendingSignerFromWalletAccount](/api/functions/createTransactionSendingSignerFromWalletAccount) # createWebSocketChannel (/api/functions/createWebSocketChannel) ```ts function createWebSocketChannel( __namedParameters, ): Promise>; ``` Creates an object that represents an open channel to a `WebSocket` server. You can use it to send messages by calling its RpcSubscriptionsChannel.send | \`send()\` function and you can receive them by subscribing to the RpcSubscriptionChannelEvents it emits. ## Parameters | Parameter | Type | | ------------------- | ------------------------------------ | | `__namedParameters` | [`Config`](/api/type-aliases/Config) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`RpcSubscriptionsChannel`\<`WebSocketMessage`, `string`>> # decimalFixedPoint (/api/functions/decimalFixedPoint) ```ts function decimalFixedPoint( signedness, totalBits, decimals, ): ( input, rounding?, ) => DecimalFixedPoint; ``` Returns a factory that constructs [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) values from decimal strings. The outer call validates the shape parameters once and the returned factory can be called many times to construct values of that shape. If the string carries more precision than the target `decimals` can represent exactly, the returned factory throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` under the default `'strict'` rounding mode. Pass a different [RoundingMode](/api/type-aliases/RoundingMode) to allow a rounded result. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | ------------ | ------------- | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `decimals` | `TDecimals` | ## Returns (`input`, `rounding?`) => [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> ## Example ```ts const usdc = decimalFixedPoint('unsigned', 64, 6); usdc('42.5'); // raw === 42500000n usdc('0.0000001'); // throws under the default 'strict' mode usdc('0.0000001', 'round'); // raw === 0n ``` ## See * [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) * [rawDecimalFixedPoint](/api/functions/rawDecimalFixedPoint) * [ratioDecimalFixedPoint](/api/functions/ratioDecimalFixedPoint) # decimalFixedPointToNumber (/api/functions/decimalFixedPointToNumber) ```ts function decimalFixedPointToNumber(value): number; ``` Converts a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) to a JavaScript `number`. This conversion is inherently lossy: `1 / 10 ** decimals` is not representable exactly in IEEE 754 for any positive `decimals`, and additional precision is lost when `|value.raw|` exceeds `Number.MAX_SAFE_INTEGER`, since JavaScript numbers have only \~53 bits of mantissa. For exact representations prefer [decimalFixedPointToString](/api/functions/decimalFixedPointToString). ## Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------------------------------------------- | | `value` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `number`> | ## Returns `number` ## Example ```ts const usdc = decimalFixedPoint('unsigned', 64, 6); decimalFixedPointToNumber(usdc('42.5')); // 42.5 ``` ## See [decimalFixedPointToString](/api/functions/decimalFixedPointToString) # decimalFixedPointToString (/api/functions/decimalFixedPointToString) ```ts function decimalFixedPointToString(value, options?): string; ``` Returns the canonical decimal string representation of a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint). By default, trailing zeros are trimmed and the decimal point is dropped for whole numbers. Pass `options.decimals` to emit a different number of fractional digits (with [RoundingMode](/api/type-aliases/RoundingMode) control when scale-down is lossy), and `options.padTrailingZeros` to emit exactly that many digits. When `padTrailingZeros` is set without `decimals`, the output is padded to `value.decimals`. Throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` when `options.decimals` forces a lossy rescale under the default `'strict'` rounding mode. ## Parameters | Parameter | Type | | ---------- | ----------------------------------------------------------------------------------------------------------------------------- | | `value` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `number`> | | `options?` | [`FixedPointToStringOptions`](/api/type-aliases/FixedPointToStringOptions) | ## Returns `string` ## Example ```ts const usdc = decimalFixedPoint('unsigned', 64, 6); decimalFixedPointToString(usdc('42.5')); // "42.5" decimalFixedPointToString(usdc('42.5'), { padTrailingZeros: true }); // "42.500000" decimalFixedPointToString(usdc('42.678'), { decimals: 2, rounding: 'floor' }); // "42.67" ``` ## See [decimalFixedPointToNumber](/api/functions/decimalFixedPointToNumber) # decodeAccount (/api/functions/decodeAccount) ## Call Signature ```ts function decodeAccount( encodedAccount, decoder, ): Account; ``` Transforms an [EncodedAccount](/api/interfaces/EncodedAccount) into an [Account](/api/interfaces/Account) (or a [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount) into a [MaybeAccount](/api/type-aliases/MaybeAccount)) by decoding the account data using the provided [Decoder](/api/type-aliases/Decoder) instance. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TData` *extends* `object` | - | The type of this account's data. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | ---------------- | --------------------------------------------------------------- | | `encodedAccount` | [`EncodedAccount`](/api/interfaces/EncodedAccount)\<`TAddress`> | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TData`> | ### Returns [`Account`](/api/interfaces/Account)\<`TData`, `TAddress`> ### Example ```ts type MyAccountData = { name: string; age: number }; const myAccount: EncodedAccount<'1234..5678'>; const myDecoder: Decoder = getStructDecoder([ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())], ['age', getU32Decoder()], ]); const myDecodedAccount = decodeAccount(myAccount, myDecoder); myDecodedAccount satisfies Account; ``` ## Call Signature ```ts function decodeAccount( encodedAccount, decoder, ): MaybeAccount; ``` Transforms an [EncodedAccount](/api/interfaces/EncodedAccount) into an [Account](/api/interfaces/Account) (or a [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount) into a [MaybeAccount](/api/type-aliases/MaybeAccount)) by decoding the account data using the provided [Decoder](/api/type-aliases/Decoder) instance. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TData` *extends* `object` | - | The type of this account's data. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | ---------------- | --------------------------------------------------------------------------- | | `encodedAccount` | [`MaybeEncodedAccount`](/api/type-aliases/MaybeEncodedAccount)\<`TAddress`> | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TData`> | ### Returns [`MaybeAccount`](/api/type-aliases/MaybeAccount)\<`TData`, `TAddress`> ### Example ```ts type MyAccountData = { name: string; age: number }; const myAccount: EncodedAccount<'1234..5678'>; const myDecoder: Decoder = getStructDecoder([ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())], ['age', getU32Decoder()], ]); const myDecodedAccount = decodeAccount(myAccount, myDecoder); myDecodedAccount satisfies Account; ``` # decodeTransactionFromRpcResponse (/api/functions/decodeTransactionFromRpcResponse) ## Call Signature ```ts function decodeTransactionFromRpcResponse(rpcTx): Readonly<{ compiledMessage: CompiledTransactionMessage & Readonly<{ lifetimeToken: string; }>; loadedAddresses: LoadedAddresses; transaction?: Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }>; }> & object; ``` Decodes a confirmed-transaction RPC response (any of `encoding: 'base64'`, `'base58'`, or `'json'`) into a CompiledTransactionMessage plus, for `'base64'` and `'base58'`, a re-encodable Transaction. The JSON path does not produce a `Transaction`: the server has already decompiled the wire format, so there are no message bytes to carry. Because it reads only the `transaction` / `meta` / `version` envelope β€” not a method-specific response shape β€” it accepts results from any method that returns confirmed transactions in these encodings: `getTransaction`, `getTransactionsForAddress`, and `getBlock` (the latter two with `transactionDetails: 'full'`). The array-returning methods just need a map: ```ts const { data } = await rpc.getTransactionsForAddress(address, { encoding: 'base64', maxSupportedTransactionVersion: 0, transactionDetails: 'full', }).send(); const decoded = data.map(tx => decodeTransactionFromRpcResponse(tx)); const block = await rpc.getBlock(slot, { encoding: 'base64', maxSupportedTransactionVersion: 0, transactionDetails: 'full', }).send(); const decodedBlockTxs = block?.transactions.map(tx => decodeTransactionFromRpcResponse(tx)) ?? []; ``` `'jsonParsed'` is **not** supported β€” its instructions arrive pre-parsed by the server and lack raw bytes, so they cannot be round-tripped through the auto-generated `parseXInstruction` clients. Passing a `'jsonParsed'` response throws SOLANA\_ERROR\_\_TRANSACTION\_INTROSPECTION\_\_CANNOT\_DECODE\_JSON\_PARSED\_TRANSACTION; any other unrecognized input throws SOLANA\_ERROR\_\_TRANSACTION\_INTROSPECTION\_\_UNRECOGNIZED\_GET\_TRANSACTION\_RESPONSE. A response carrying a transaction version this package cannot decode throws SOLANA\_ERROR\_\_TRANSACTION\_\_VERSION\_NUMBER\_NOT\_SUPPORTED β€” raised by the JSON path for an unrecognized `version`, and by the wire decoders for malformed binary input. Use this together with [getInstructionsFromCompiledTransactionMessage](/api/functions/getInstructionsFromCompiledTransactionMessage) (or [walkInstructions](/api/functions/walkInstructions)) to inspect a confirmed transaction's instructions in a form the auto-generated `@solana-program/*` clients can `parse` directly. Prefer `encoding: 'base64'` when bandwidth allows β€” it is the most compact, the wire bytes round-trip cleanly through the kit codecs, and the return type statically guarantees a re-encodable `transaction`. ### Parameters | Parameter | Type | | --------- | ---------------------------------- | | `rpcTx` | `DecodableWireTransactionResponse` | ### Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `compiledMessage`: `CompiledTransactionMessage` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }>; `loadedAddresses`: [`LoadedAddresses`](/api/type-aliases/LoadedAddresses); `transaction?`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: `TransactionMessageBytes`; `signatures`: `SignaturesMap`; }>; }> & `object` ### Example ```ts const rpcResponse = await rpc.getTransaction(signature(txid), { commitment: 'confirmed', encoding: 'base64', maxSupportedTransactionVersion: 0, }).send(); if (!rpcResponse) throw new Error('not found'); const { compiledMessage, loadedAddresses } = decodeTransactionFromRpcResponse(rpcResponse); const instructions = getInstructionsFromCompiledTransactionMessage(compiledMessage, loadedAddresses); ``` ## Call Signature ```ts function decodeTransactionFromRpcResponse(rpcTx): Readonly<{ compiledMessage: CompiledTransactionMessage & Readonly<{ lifetimeToken: string; }>; loadedAddresses: LoadedAddresses; transaction?: Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }>; }> & object; ``` Decodes a confirmed-transaction RPC response (any of `encoding: 'base64'`, `'base58'`, or `'json'`) into a CompiledTransactionMessage plus, for `'base64'` and `'base58'`, a re-encodable Transaction. The JSON path does not produce a `Transaction`: the server has already decompiled the wire format, so there are no message bytes to carry. Because it reads only the `transaction` / `meta` / `version` envelope β€” not a method-specific response shape β€” it accepts results from any method that returns confirmed transactions in these encodings: `getTransaction`, `getTransactionsForAddress`, and `getBlock` (the latter two with `transactionDetails: 'full'`). The array-returning methods just need a map: ```ts const { data } = await rpc.getTransactionsForAddress(address, { encoding: 'base64', maxSupportedTransactionVersion: 0, transactionDetails: 'full', }).send(); const decoded = data.map(tx => decodeTransactionFromRpcResponse(tx)); const block = await rpc.getBlock(slot, { encoding: 'base64', maxSupportedTransactionVersion: 0, transactionDetails: 'full', }).send(); const decodedBlockTxs = block?.transactions.map(tx => decodeTransactionFromRpcResponse(tx)) ?? []; ``` `'jsonParsed'` is **not** supported β€” its instructions arrive pre-parsed by the server and lack raw bytes, so they cannot be round-tripped through the auto-generated `parseXInstruction` clients. Passing a `'jsonParsed'` response throws SOLANA\_ERROR\_\_TRANSACTION\_INTROSPECTION\_\_CANNOT\_DECODE\_JSON\_PARSED\_TRANSACTION; any other unrecognized input throws SOLANA\_ERROR\_\_TRANSACTION\_INTROSPECTION\_\_UNRECOGNIZED\_GET\_TRANSACTION\_RESPONSE. A response carrying a transaction version this package cannot decode throws SOLANA\_ERROR\_\_TRANSACTION\_\_VERSION\_NUMBER\_NOT\_SUPPORTED β€” raised by the JSON path for an unrecognized `version`, and by the wire decoders for malformed binary input. Use this together with [getInstructionsFromCompiledTransactionMessage](/api/functions/getInstructionsFromCompiledTransactionMessage) (or [walkInstructions](/api/functions/walkInstructions)) to inspect a confirmed transaction's instructions in a form the auto-generated `@solana-program/*` clients can `parse` directly. Prefer `encoding: 'base64'` when bandwidth allows β€” it is the most compact, the wire bytes round-trip cleanly through the kit codecs, and the return type statically guarantees a re-encodable `transaction`. ### Parameters | Parameter | Type | | --------- | ---------------------------------- | | `rpcTx` | `DecodableJsonTransactionResponse` | ### Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `compiledMessage`: `CompiledTransactionMessage` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }>; `loadedAddresses`: [`LoadedAddresses`](/api/type-aliases/LoadedAddresses); `transaction?`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: `TransactionMessageBytes`; `signatures`: `SignaturesMap`; }>; }> & `object` ### Example ```ts const rpcResponse = await rpc.getTransaction(signature(txid), { commitment: 'confirmed', encoding: 'base64', maxSupportedTransactionVersion: 0, }).send(); if (!rpcResponse) throw new Error('not found'); const { compiledMessage, loadedAddresses } = decodeTransactionFromRpcResponse(rpcResponse); const instructions = getInstructionsFromCompiledTransactionMessage(compiledMessage, loadedAddresses); ``` # decompileTransactionMessage (/api/functions/decompileTransactionMessage) ## Call Signature ```ts function decompileTransactionMessage( compiledTransactionMessage, config?, ): TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime & { version: 'legacy' }; ``` Converts the type of transaction message data structure appropriate for execution on the network to the type of transaction message data structure designed for use in your application. Because compilation is a lossy process, you can not fully reconstruct a source message from a compiled message without extra information. In order to faithfully reconstruct the original source message you will need to supply supporting details about the lifetime constraint and the concrete addresses of any accounts sourced from account lookup tables (for v0 transactions). ### Parameters | Parameter | Type | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `compiledTransactionMessage` | [`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }> & `object` | | `config?` | [`DecompileTransactionMessageConfig`](/api/type-aliases/DecompileTransactionMessageConfig) | ### Returns TransactionMessage & TransactionMessageWithFeePayer\ & TransactionMessageWithLifetime & \{ version: "legacy"; } ### See [compileTransactionMessage](/api/functions/compileTransactionMessage) ## Call Signature ```ts function decompileTransactionMessage( compiledTransactionMessage, config?, ): TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime & { version: 0 }; ``` Converts the type of transaction message data structure appropriate for execution on the network to the type of transaction message data structure designed for use in your application. Because compilation is a lossy process, you can not fully reconstruct a source message from a compiled message without extra information. In order to faithfully reconstruct the original source message you will need to supply supporting details about the lifetime constraint and the concrete addresses of any accounts sourced from account lookup tables (for v0 transactions). ### Parameters | Parameter | Type | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `compiledTransactionMessage` | [`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }> & `object` | | `config?` | [`DecompileTransactionMessageConfig`](/api/type-aliases/DecompileTransactionMessageConfig) | ### Returns TransactionMessage & TransactionMessageWithFeePayer\ & TransactionMessageWithLifetime & \{ version: 0; } ### See [compileTransactionMessage](/api/functions/compileTransactionMessage) ## Call Signature ```ts function decompileTransactionMessage( compiledTransactionMessage, config?, ): TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime & { version: 1 }; ``` Converts the type of transaction message data structure appropriate for execution on the network to the type of transaction message data structure designed for use in your application. Because compilation is a lossy process, you can not fully reconstruct a source message from a compiled message without extra information. In order to faithfully reconstruct the original source message you will need to supply supporting details about the lifetime constraint and the concrete addresses of any accounts sourced from account lookup tables (for v0 transactions). ### Parameters | Parameter | Type | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `compiledTransactionMessage` | [`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }> & `object` | | `config?` | [`DecompileTransactionMessageConfig`](/api/type-aliases/DecompileTransactionMessageConfig) | ### Returns TransactionMessage & TransactionMessageWithFeePayer\ & TransactionMessageWithLifetime & \{ version: 1; } ### See [compileTransactionMessage](/api/functions/compileTransactionMessage) ## Call Signature ```ts function decompileTransactionMessage( compiledTransactionMessage, config?, ): TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime; ``` Converts the type of transaction message data structure appropriate for execution on the network to the type of transaction message data structure designed for use in your application. Because compilation is a lossy process, you can not fully reconstruct a source message from a compiled message without extra information. In order to faithfully reconstruct the original source message you will need to supply supporting details about the lifetime constraint and the concrete addresses of any accounts sourced from account lookup tables (for v0 transactions). ### Parameters | Parameter | Type | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `compiledTransactionMessage` | [`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }> | | `config?` | [`DecompileTransactionMessageConfig`](/api/type-aliases/DecompileTransactionMessageConfig) | ### Returns [`TransactionMessage`](/api/type-aliases/TransactionMessage) & TransactionMessageWithFeePayer\ & TransactionMessageWithLifetime ### See [compileTransactionMessage](/api/functions/compileTransactionMessage) # decompileTransactionMessageFetchingLookupTables (/api/functions/decompileTransactionMessageFetchingLookupTables) ```ts function decompileTransactionMessageFetchingLookupTables( compiledTransactionMessage, rpc, config?, ): Promise< TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime >; ``` Returns a [TransactionMessage](/api/type-aliases/TransactionMessage) from a [CompiledTransactionMessage](/api/type-aliases/CompiledTransactionMessage). If any of the accounts in the compiled message require an address lookup table to find their address, this function will use the supplied RPC instance to fetch the contents of the address lookup table from the network. ## Parameters | Parameter | Type | Description | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `compiledTransactionMessage` | [`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }> | - | | `rpc` | [`Rpc`](/api/type-aliases/Rpc)\<[`GetMultipleAccountsApi`](/api/type-aliases/GetMultipleAccountsApi)> | An object that supports the [GetMultipleAccountsApi](/api/type-aliases/GetMultipleAccountsApi) of the Solana RPC API | | `config?` | `DecompileTransactionMessageFetchingLookupTablesConfig` | - | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`TransactionMessage`](/api/type-aliases/TransactionMessage) & TransactionMessageWithFeePayer\ & TransactionMessageWithLifetime> # demultiplexDataPublisher (/api/functions/demultiplexDataPublisher) ```ts function demultiplexDataPublisher( publisher, sourceChannelName, messageTransformer, ): DataPublisher; ``` Given a channel that carries messages for multiple subscribers on a single channel name, this function returns a new [DataPublisher](/api/interfaces/DataPublisher) that splits them into multiple channel names. ## Type Parameters | Type Parameter | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TDataPublisher` *extends* [`DataPublisher`](/api/interfaces/DataPublisher)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `unknown`>> | | `TChannelName` *extends* `string` | ## Parameters | Parameter | Type | Description | | -------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `publisher` | `TDataPublisher` | - | | `sourceChannelName` | `TChannelName` | - | | `messageTransformer` | (`message`) => `void` \| \[`string`, `unknown`] | A function that receives the message as the first argument, and returns a tuple of the derived channel name and the message. | ## Returns [`DataPublisher`](/api/interfaces/DataPublisher) ## Example Imagine a channel that carries multiple notifications whose destination is contained within the message itself. ```ts const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => { const destinationChannelName = `notification-for:${message.subscriberId}`; return [destinationChannelName, message]; }); ``` Now you can subscribe to *only* the messages you are interested in, without having to subscribe to the entire `'message'` channel and filter out the messages that are not for you. ```ts demuxedDataPublisher.on( 'notification-for:123', message => { console.log('Got a message for subscriber 123', message); }, { signal: AbortSignal.timeout(5_000) }, ); ``` # devnet (/api/functions/devnet) ```ts function devnet(putativeString): DevnetUrl; ``` Given a URL casts it to a type that is only accepted where devnet URLs are expected. ## Parameters | Parameter | Type | | ---------------- | -------- | | `putativeString` | `string` | ## Returns [`DevnetUrl`](/api/type-aliases/DevnetUrl) # divideBinaryFixedPoint (/api/functions/divideBinaryFixedPoint) ```ts function divideBinaryFixedPoint< TSignedness, TTotalBits, TFractionalBits, >( a, b, rounding?, ): BinaryFixedPoint; ``` Divides a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) by a scalar. The second operand may be another [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) with the same signedness (any total bits or fractional bits) or a bare `bigint`. The result always has `a`'s shape. The optional [RoundingMode](/api/type-aliases/RoundingMode) is consulted whenever the division is inexact; it defaults to `'strict'` and throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` in that case. A zero divisor always throws `SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO`. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> | | `b` | \| `bigint` \| [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TSignedness`>, `number`, `number`> | | `rounding?` | [`RoundingMode`](/api/type-aliases/RoundingMode) | ## Returns [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> ## Example ```ts const q1_15 = binaryFixedPoint('signed', 16, 15); divideBinaryFixedPoint(q1_15('0.5'), q1_15('0.25')); // represents 2.0 (overflows) divideBinaryFixedPoint(q1_15('0.5'), 2n); // represents 0.25 ``` ## See [multiplyBinaryFixedPoint](/api/functions/multiplyBinaryFixedPoint) # divideDecimalFixedPoint (/api/functions/divideDecimalFixedPoint) ```ts function divideDecimalFixedPoint( a, b, rounding?, ): DecimalFixedPoint; ``` Divides a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) by a scalar. The second operand may be another [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) with the same signedness (any total bits or decimals) or a bare `bigint`. The result always has `a`'s shape. The optional [RoundingMode](/api/type-aliases/RoundingMode) is consulted whenever the division is inexact; it defaults to `'strict'` and throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` in that case. A zero divisor always throws `SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO`. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> | | `b` | \| `bigint` \| [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TSignedness`>, `number`, `number`> | | `rounding?` | [`RoundingMode`](/api/type-aliases/RoundingMode) | ## Returns [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> ## Example ```ts const usd = decimalFixedPoint('unsigned', 64, 2); const rate = decimalFixedPoint('unsigned', 64, 4); divideDecimalFixedPoint(usd('10'), rate('0.05')); // represents 200.00 divideDecimalFixedPoint(usd('10.50'), 3n, 'round'); // represents 3.50 ``` ## See [multiplyDecimalFixedPoint](/api/functions/multiplyDecimalFixedPoint) # downgradeRoleToNonSigner (/api/functions/downgradeRoleToNonSigner) ## Call Signature ```ts function downgradeRoleToNonSigner(role): READONLY; ``` ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `role` | [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) | ### Returns [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) An [AccountRole](/api/enumerations/AccountRole) representing the non-signer variant of the supplied role. ## Call Signature ```ts function downgradeRoleToNonSigner(role): WRITABLE; ``` ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `role` | [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) | ### Returns [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) An [AccountRole](/api/enumerations/AccountRole) representing the non-signer variant of the supplied role. ## Call Signature ```ts function downgradeRoleToNonSigner(role): AccountRole; ``` ### Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `role` | [`AccountRole`](/api/enumerations/AccountRole) | ### Returns [`AccountRole`](/api/enumerations/AccountRole) An [AccountRole](/api/enumerations/AccountRole) representing the non-signer variant of the supplied role. # downgradeRoleToReadonly (/api/functions/downgradeRoleToReadonly) ## Call Signature ```ts function downgradeRoleToReadonly(role): READONLY; ``` ### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `role` | [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) | ### Returns [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) An [AccountRole](/api/enumerations/AccountRole) representing the read-only variant of the supplied role. ## Call Signature ```ts function downgradeRoleToReadonly(role): READONLY_SIGNER; ``` ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `role` | [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) | ### Returns [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) An [AccountRole](/api/enumerations/AccountRole) representing the read-only variant of the supplied role. ## Call Signature ```ts function downgradeRoleToReadonly(role): AccountRole; ``` ### Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `role` | [`AccountRole`](/api/enumerations/AccountRole) | ### Returns [`AccountRole`](/api/enumerations/AccountRole) An [AccountRole](/api/enumerations/AccountRole) representing the read-only variant of the supplied role. # eqBinaryFixedPoint (/api/functions/eqBinaryFixedPoint) ```ts function eqBinaryFixedPoint(a, b): boolean; ``` Returns `true` when `a` and `b` represent the same value. See [cmpBinaryFixedPoint](/api/functions/cmpBinaryFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TFractionalBits`> | | `b` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TFractionalBits`>> | ## Returns `boolean` # eqDecimalFixedPoint (/api/functions/eqDecimalFixedPoint) ```ts function eqDecimalFixedPoint(a, b): boolean; ``` Returns `true` when `a` and `b` represent the same value. See [cmpDecimalFixedPoint](/api/functions/cmpDecimalFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------ | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TDecimals`> | | `b` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TDecimals`>> | ## Returns `boolean` # estimateAndSetResourceLimitsFactory (/api/functions/estimateAndSetResourceLimitsFactory) ```ts function estimateAndSetResourceLimitsFactory( estimateResourceLimits, ): ( transactionMessage, config?, ) => Promise; ``` Returns a function that estimates the resource limits for a transaction message and sets them on the message. For all versions, the compute unit limit is updated to the estimated value if it is not already set to an explicit, non-provisory value. The compute unit limit also treats the maximum (1,400,000) as non-explicit, so messages that pre-set the max for simulation get re-estimated. For version 1 messages, the loaded accounts data size limit is updated only if it is unset or set to the provisory value of 0. An explicit value β€” including the runtime maximum β€” is left untouched, since callers who set it explicitly are signaling a deliberate choice. This is designed to work with [fillTransactionMessageProvisoryResourceLimits](/api/functions/fillTransactionMessageProvisoryResourceLimits): first add provisory limits during transaction construction, then later estimate and replace them before sending. ## Parameters | Parameter | Type | Description | | ------------------------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `estimateResourceLimits` | `EstimateResourceLimitsFunction` | The estimator function, typically created by [estimateResourceLimitsFactory](/api/functions/estimateResourceLimitsFactory). You can also pass a custom wrapper that applies a buffer to the returned values. | ## Returns A function that accepts a transaction message and returns it with resource limits set to the estimated values. \<`TTransactionMessage`>(`transactionMessage`, `config?`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TTransactionMessage`> ## Example ```ts import { estimateAndSetResourceLimitsFactory, estimateResourceLimitsFactory } from '@solana/kit'; const estimator = estimateResourceLimitsFactory({ rpc }); const estimateAndSet = estimateAndSetResourceLimitsFactory(estimator); const updatedMessage = await estimateAndSet(transactionMessage); ``` # estimateResourceLimitsFactory (/api/functions/estimateResourceLimitsFactory) ```ts function estimateResourceLimitsFactory( factoryConfig, ): EstimateResourceLimitsFunction; ``` Returns a function that estimates the resource limits required by a transaction message by simulating it. The estimator sets the compute unit limit to the maximum (1,400,000) and the loaded accounts data size limit to the maximum (64 MiB) before simulating, so the simulation does not fail due to resource exhaustion. For blockhash-lifetime transactions, the RPC is asked to replace the blockhash during simulation, so any blockhash value will work. For durable nonce transactions, the actual nonce value is used. For version 1 transaction messages, both `computeUnitLimit` and `loadedAccountsDataSizeLimit` are returned. The function throws if the RPC does not return a `loadedAccountsDataSize` value, since this value is required for version 1 transactions. For legacy and version 0 messages, only `computeUnitLimit` is returned. ## Parameters | Parameter | Type | Description | | --------------- | ------------------------------------- | ------------------------------------------------------------ | | `factoryConfig` | `EstimateResourceLimitsFactoryConfig` | An object containing the RPC instance to use for simulation. | ## Returns `EstimateResourceLimitsFunction` A function that accepts a transaction message and returns the estimated resource limits. ## Example ```ts import { estimateResourceLimitsFactory } from '@solana/kit'; const estimateResourceLimits = estimateResourceLimitsFactory({ rpc }); const { computeUnitLimit, loadedAccountsDataSizeLimit } = await estimateResourceLimits(transactionMessage); ``` # everyInstructionPlan (/api/functions/everyInstructionPlan) ```ts function everyInstructionPlan(instructionPlan, predicate): boolean; ``` Checks if every instruction plan in the tree satisfies the given predicate. This function performs a depth-first traversal through the instruction plan tree, returning `true` only if the predicate returns `true` for every plan in the tree (including the root plan and all nested plans). ## Parameters | Parameter | Type | Description | | ----------------- | ------------------------------------------------------ | ------------------------------------------------------------------- | | `instructionPlan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan tree to check. | | `predicate` | (`plan`) => `boolean` | A function that returns `true` if the plan satisfies the condition. | ## Returns `boolean` `true` if every plan in the tree satisfies the predicate, `false` otherwise. ## Examples Checking if all plans are divisible. ```ts const plan = sequentialInstructionPlan([ parallelInstructionPlan([instructionA, instructionB]), sequentialInstructionPlan([instructionC, instructionD]), ]); const allDivisible = everyInstructionPlan( plan, (p) => p.kind !== 'sequential' || p.divisible, ); // Returns true because all sequential plans are divisible. ``` Checking if all single instructions use a specific program. ```ts const plan = parallelInstructionPlan([instructionA, instructionB, instructionC]); const allUseSameProgram = everyInstructionPlan( plan, (p) => p.kind !== 'single' || p.instruction.programAddress === myProgramAddress, ); ``` ## See * [InstructionPlan](/api/type-aliases/InstructionPlan) * [findInstructionPlan](/api/functions/findInstructionPlan) * [transformInstructionPlan](/api/functions/transformInstructionPlan) * [flattenInstructionPlan](/api/functions/flattenInstructionPlan) # everyTransactionPlan (/api/functions/everyTransactionPlan) ```ts function everyTransactionPlan(transactionPlan, predicate): boolean; ``` Checks if every transaction plan in the tree satisfies the given predicate. This function performs a depth-first traversal through the transaction plan tree, returning `true` only if the predicate returns `true` for every plan in the tree (including the root plan and all nested plans). ## Parameters | Parameter | Type | Description | | ----------------- | ------------------------------------------------------ | ------------------------------------------------------------------- | | `transactionPlan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan tree to check. | | `predicate` | (`plan`) => `boolean` | A function that returns `true` if the plan satisfies the condition. | ## Returns `boolean` `true` if every plan in the tree satisfies the predicate, `false` otherwise. ## Examples Checking if all plans are divisible. ```ts const plan = sequentialTransactionPlan([ parallelTransactionPlan([messageA, messageB]), sequentialTransactionPlan([messageC, messageD]), ]); const allDivisible = everyTransactionPlan( plan, (p) => p.kind !== 'sequential' || p.divisible, ); // Returns true because all sequential plans are divisible. ``` Checking if all single plans have a specific fee payer. ```ts const plan = parallelTransactionPlan([messageA, messageB, messageC]); const allUseSameFeePayer = everyTransactionPlan( plan, (p) => p.kind !== 'single' || p.message.feePayer.address === myFeePayer, ); ``` ## See * [TransactionPlan](/api/type-aliases/TransactionPlan) * [findTransactionPlan](/api/functions/findTransactionPlan) * [transformTransactionPlan](/api/functions/transformTransactionPlan) * [flattenTransactionPlan](/api/functions/flattenTransactionPlan) # everyTransactionPlanResult (/api/functions/everyTransactionPlanResult) ```ts function everyTransactionPlanResult< TContext, TTransactionMessage, TSingle, >(transactionPlanResult, predicate): boolean; ``` Checks if every transaction plan result in the tree satisfies the given predicate. This function performs a depth-first traversal through the transaction plan result tree, returning `true` only if the predicate returns `true` for every result in the tree (including the root result and all nested results). ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | The type of the transaction message | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The type of single transaction plan results in this tree | ## Parameters | Parameter | Type | Description | | ----------------------- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | `transactionPlanResult` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result tree to check. | | `predicate` | (`plan`) => `boolean` | A function that returns `true` if the result satisfies the condition. | ## Returns `boolean` `true` if every result in the tree satisfies the predicate, `false` otherwise. ## Examples Checking if all transactions were successful. ```ts const result = parallelTransactionPlanResult([ successfulSingleTransactionPlanResult(messageA, { signature: signatureA }), successfulSingleTransactionPlanResult(messageB, { signature: signatureB }), ]); const allSuccessful = everyTransactionPlanResult( result, (r) => r.kind !== 'single' || r.status === 'successful', ); // Returns true because all single results are successful. ``` Checking if no transactions were canceled. ```ts const result = sequentialTransactionPlanResult([resultA, resultB, resultC]); const noCanceled = everyTransactionPlanResult( result, (r) => r.kind !== 'single' || r.status !== 'canceled', ); ``` ## See * [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) * [findTransactionPlanResult](/api/functions/findTransactionPlanResult) * [transformTransactionPlanResult](/api/functions/transformTransactionPlanResult) * [flattenTransactionPlanResult](/api/functions/flattenTransactionPlanResult) # executeRpcPubSubSubscriptionPlan (/api/functions/executeRpcPubSubSubscriptionPlan) ```ts function executeRpcPubSubSubscriptionPlan( config, ): Promise< DataPublisher> >; ``` Given a channel, this function executes the particular subscription plan required by the Solana JSON RPC Subscriptions API. ## Type Parameters | Type Parameter | | --------------- | | `TNotification` | ## Parameters | Parameter | Type | Description | | --------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `config` | `Config`\<`TNotification`> | 1. Calls the `subscribeRequest` on the remote RPC 2. Waits for a response containing the subscription id 3. Returns a DataPublisher that publishes notifications related to that subscriptions id, filtering out all others 4. Calls the `unsubscribeMethodName` on the remote RPC when the abort signal is fired. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`DataPublisher`\<`RpcSubscriptionNotificationEvents`\<`TNotification`>>> # extendClient (/api/functions/extendClient) ```ts function extendClient( client, additions, ): { [K in string | number | symbol]: (Omit & TAdditions)[K]; }; ``` Extends a client object with additional properties, preserving property descriptors (getters, symbol-keyed properties, and non-enumerable properties) from both objects. Use this inside plugins instead of plain object spread (`{...client, ...additions}`) when the client may carry getters or symbol-keyed properties that spread would flatten or lose. When the same key exists on both, `additions` wins. The return type is an [ExtendedClient](/api/type-aliases/ExtendedClient), which flattens the merged shape into a single object literal so chained `extendClient` calls do not accumulate nested `Omit<...>` wrappers in editor tooltips and error messages. ## Type Parameters | Type Parameter | Description | | ------------------------------- | --------------------------------------- | | `TClient` *extends* `object` | The type of the original client. | | `TAdditions` *extends* `object` | The type of the properties being added. | ## Parameters | Parameter | Type | Description | | ----------- | ------------ | ------------------------------------------------ | | `client` | `TClient` | The original client object to extend. | | `additions` | `TAdditions` | The properties to add or override on the client. | ## Returns \{ \[K in string | number | symbol]: (Omit\ & TAdditions)\[K] } A new object combining both, with `additions` taking precedence on conflicts. ## Example ```ts function rpcPlugin(endpoint: string) { return (client: T) => extendClient(client, { rpc: createSolanaRpc(endpoint) }); } ``` ## See * [ClientPlugin](/api/type-aliases/ClientPlugin) * [ExtendedClient](/api/type-aliases/ExtendedClient) # failedSingleTransactionPlanResult (/api/functions/failedSingleTransactionPlanResult) ```ts function failedSingleTransactionPlanResult< TContext, TTransactionMessage, >( plannedMessage, error, context?, ): FailedSingleTransactionPlanResult; ``` Creates a failed [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) from a transaction message and error. This function creates a single result with a 'failed' status, indicating that the transaction execution failed. It includes the original transaction message and the error that caused the failure. ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | The type of the transaction message | ## Parameters | Parameter | Type | Description | | ---------------- | ----------------------------------------------------------------------------------------------------- | --------------------------------------------- | | `plannedMessage` | `TTransactionMessage` | The original transaction message | | `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error that caused the transaction to fail | | `context?` | [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<`TContext`> | - | ## Returns [`FailedSingleTransactionPlanResult`](/api/type-aliases/FailedSingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> ## Example ```ts const result = failedSingleTransactionPlanResult( transactionMessage, new SolanaError({ code: 123, message: 'Transaction simulation failed', }), ); result satisfies SingleTransactionPlanResult; ``` ## See [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) # fetchAddressesForLookupTables (/api/functions/fetchAddressesForLookupTables) ```ts function fetchAddressesForLookupTables( lookupTableAddresses, rpc, config?, ): Promise; ``` Given a list of addresses belonging to address lookup tables, returns a map of lookup table addresses to an ordered array of the addresses they contain. ## Parameters | Parameter | Type | Description | | ---------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `lookupTableAddresses` | [`Address`](/api/type-aliases/Address)\[] | - | | `rpc` | [`Rpc`](/api/type-aliases/Rpc)\<[`GetMultipleAccountsApi`](/api/type-aliases/GetMultipleAccountsApi)> | An object that supports the [GetMultipleAccountsApi](/api/type-aliases/GetMultipleAccountsApi) of the Solana RPC API | | `config?` | [`FetchAccountsConfig`](/api/interfaces/FetchAccountsConfig) | - | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`AddressesByLookupTableAddress`](/api/type-aliases/AddressesByLookupTableAddress)> # fetchEncodedAccount (/api/functions/fetchEncodedAccount) ```ts function fetchEncodedAccount( rpc, address, config?, ): Promise>; ``` Fetches a [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount) from the provided RPC client and address. It uses the [getAccountInfo](/api/type-aliases/GetAccountInfoApi#getaccountinfo) RPC method under the hood with base64 encoding and an additional configuration object can be provided to customize the behavior of the RPC call. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------- | | `rpc` | [`Rpc`](/api/type-aliases/Rpc)\<`GetAccountInfoApi`> | | `address` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `config?` | [`FetchAccountConfig`](/api/interfaces/FetchAccountConfig) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`MaybeEncodedAccount`](/api/type-aliases/MaybeEncodedAccount)\<`TAddress`>> ## Example ```ts const myAddress = address('1234..5678'); const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress); // With custom configuration. const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress, { abortSignal: myAbortController.signal, commitment: 'confirmed', }); ``` # fetchEncodedAccounts (/api/functions/fetchEncodedAccounts) ```ts function fetchEncodedAccounts( rpc, addresses, config?, ): Promise<{ [P in string | number | symbol]: MaybeEncodedAccount; }>; ``` Fetches an array of [MaybeEncodedAccounts](/api/type-aliases/MaybeEncodedAccount) from the provided RPC client and an array of addresses. It uses the [getMultipleAccounts](/api/type-aliases/GetMultipleAccountsApi#getmultipleaccounts) RPC method under the hood with base64 encodings and an additional configuration object can be provided to customize the behavior of the RPC call. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `TAddresses` *extends* `string`\[] | `string`\[] | Supply an array of string literals to define accounts having particular addresses. | | `TWrappedAddresses` *extends* \{ \[P in string \| number \| symbol]: Address\ } | \{ \[P in string \| number \| symbol]: Address\ } | - | ## Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------ | | `rpc` | [`Rpc`](/api/type-aliases/Rpc)\<`GetMultipleAccountsApi`> | | `addresses` | `TWrappedAddresses` | | `config?` | [`FetchAccountsConfig`](/api/interfaces/FetchAccountsConfig) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ \[P in string | number | symbol]: MaybeEncodedAccount\ }> ## Example ```ts const myAddressA = address('1234..5678'); const myAddressB = address('8765..4321'); const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB]); myAccountA satisfies MaybeEncodedAccount<'1234..5678'>; myAccountB satisfies MaybeEncodedAccount<'8765..4321'>; // With custom configuration. const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB], { abortSignal: myAbortController.signal, commitment: 'confirmed', }); ``` # fetchEncodedSysvarAccount (/api/functions/fetchEncodedSysvarAccount) ```ts function fetchEncodedSysvarAccount( rpc, address, config?, ): Promise>; ``` Fetch an encoded sysvar account. Sysvars are special accounts that contain dynamically-updated data about the network cluster, the blockchain history, and the executing transaction. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TAddress` *extends* `SysvarAddress` | ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `address` | `TAddress` | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`MaybeEncodedAccount`\<`TAddress`>> # fetchJsonParsedAccount (/api/functions/fetchJsonParsedAccount) ```ts function fetchJsonParsedAccount( rpc, address, config?, ): Promise< | { address: Address; exists: false; } | (BaseAccount & object & object) | (BaseAccount & object & object) >; ``` Fetches a [MaybeAccount](/api/type-aliases/MaybeAccount) from the provided RPC client and address by using [getAccountInfo](/api/type-aliases/GetAccountInfoApi#getaccountinfo) under the hood with the `jsonParsed` encoding. It may also return a [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount) if the RPC client does not know how to parse the account at the requested address. In any case, the expected data type should be explicitly provided as the first type parameter. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TData` *extends* `object` | - | The expected type of this account's data. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------- | | `rpc` | [`Rpc`](/api/type-aliases/Rpc)\<`GetAccountInfoApi`> | | `address` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `config?` | [`FetchAccountConfig`](/api/interfaces/FetchAccountConfig) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| \{ `address`: [`Address`](/api/type-aliases/Address)\<`TAddress`>; `exists`: `false`; } \| [`BaseAccount`](/api/interfaces/BaseAccount) & `object` & `object` \| [`BaseAccount`](/api/interfaces/BaseAccount) & `object` & `object`> ## Example ```ts type TokenData = { mint: Address; owner: Address }; const myAccount = await fetchJsonParsedAccount(rpc, myAddress); myAccount satisfies MaybeAccount | MaybeEncodedAccount; // With custom configuration. const myAccount = await fetchJsonParsedAccount(rpc, myAddress, { abortSignal: myAbortController.signal, commitment: 'confirmed', }); ``` # fetchJsonParsedAccounts (/api/functions/fetchJsonParsedAccounts) ```ts function fetchJsonParsedAccounts( rpc, addresses, config?): Promise<{ [P in string | number | symbol]: { address: Address; exists: false } | BaseAccount & { address: Address; data: TData[P & keyof TData] & { parsedAccountMeta?: { program: string; type?: (...) | (...) } } } & { exists: true } | BaseAccount & { address: Address; data: Uint8Array } & { exists: true } } & { [P_1 in string | number | symbol]: { address: Address; exists: false } | BaseAccount & { address: Address; data: TData[P_1] & { parsedAccountMeta?: { program: string; type?: (...) | (...) } } } & { exists: true } | BaseAccount & { address: Address; data: Uint8Array } & { exists: true } }>; ``` Fetches an array of [MaybeAccounts](/api/type-aliases/MaybeAccount) from a provided RPC client and an array of addresses. It uses the [getMultipleAccounts](/api/type-aliases/GetMultipleAccountsApi#getmultipleaccounts) RPC method under the hood with the `jsonParsed` encoding. It may also return a [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount) instead of the expected [MaybeAccount](/api/type-aliases/MaybeAccount) if the RPC client does not know how to parse some of the requested accounts. In any case, the array of expected data types should be explicitly provided as the first type parameter. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `TData` *extends* `object`\[] | - | The expected types of these accounts' data. | | `TAddresses` *extends* `string`\[] | `string`\[] | Supply an array of string literals to define accounts having particular addresses. | | `TWrappedAddresses` *extends* \{ \[P in string \| number \| symbol]: Address\ } | \{ \[P in string \| number \| symbol]: Address\ } | - | ## Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------ | | `rpc` | [`Rpc`](/api/type-aliases/Rpc)\<`GetMultipleAccountsApi`> | | `addresses` | `TWrappedAddresses` | | `config?` | [`FetchAccountsConfig`](/api/interfaces/FetchAccountsConfig) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ \[P in string | number | symbol]: \{ address: Address\; exists: false } | BaseAccount & \{ address: Address\; data: TData\[P & keyof TData] & \{ parsedAccountMeta?: \{ program: string; type?: (...) | (...) } } } & \{ exists: true } | BaseAccount & \{ address: Address\; data: Uint8Array\ } & \{ exists: true } } & \{ \[P\_1 in string | number | symbol]: \{ address: Address\; exists: false } | BaseAccount & \{ address: Address\; data: TData\[P\_1] & \{ parsedAccountMeta?: \{ program: string; type?: (...) | (...) } } } & \{ exists: true } | BaseAccount & \{ address: Address\; data: Uint8Array\ } & \{ exists: true } }> ## Example ```ts type TokenData = { mint: Address; owner: Address }; type MintData = { supply: bigint }; const [myAccountA, myAccountB] = await fetchJsonParsedAccounts<[TokenData, MintData]>(rpc, [myAddressA, myAddressB]); myAccountA satisfies MaybeAccount | MaybeEncodedAccount; myAccountB satisfies MaybeAccount | MaybeEncodedAccount; ``` # fetchJsonParsedSysvarAccount (/api/functions/fetchJsonParsedSysvarAccount) ```ts function fetchJsonParsedSysvarAccount( rpc, address, config?, ): Promise< | { address: Address; exists: false; } | (BaseAccount & object & object) | (BaseAccount & object & object) >; ``` Fetch a JSON-parsed sysvar account. Sysvars are special accounts that contain dynamically-updated data about the network cluster, the blockchain history, and the executing transaction. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TAddress` *extends* `SysvarAddress` | ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `address` | `TAddress` | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| \{ `address`: `Address`\<`TAddress`>; `exists`: `false`; } \| `BaseAccount` & `object` & `object` \| `BaseAccount` & `object` & `object`> # fetchSysvarClock (/api/functions/fetchSysvarClock) ```ts function fetchSysvarClock( rpc, config?, ): Promise< Readonly<{ epoch: bigint; epochStartTimestamp: UnixTimestamp; leaderScheduleEpoch: bigint; slot: bigint; unixTimestamp: UnixTimestamp; }> >; ``` Fetches the `Clock` sysvar account using any RPC that supports the GetAccountInfoApi. ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `epoch`: `bigint`; `epochStartTimestamp`: `UnixTimestamp`; `leaderScheduleEpoch`: `bigint`; `slot`: `bigint`; `unixTimestamp`: `UnixTimestamp`; }>> # fetchSysvarEpochRewards (/api/functions/fetchSysvarEpochRewards) ```ts function fetchSysvarEpochRewards( rpc, config?, ): Promise< Readonly<{ active: boolean; distributedRewards: Lamports; distributionStartingBlockHeight: bigint; numPartitions: bigint; parentBlockhash: Blockhash; totalPoints: bigint; totalRewards: Lamports; }> >; ``` Fetch the `EpochRewards` sysvar account using any RPC that supports the GetAccountInfoApi. ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `active`: `boolean`; `distributedRewards`: `Lamports`; `distributionStartingBlockHeight`: `bigint`; `numPartitions`: `bigint`; `parentBlockhash`: `Blockhash`; `totalPoints`: `bigint`; `totalRewards`: `Lamports`; }>> # fetchSysvarEpochSchedule (/api/functions/fetchSysvarEpochSchedule) ```ts function fetchSysvarEpochSchedule( rpc, config?, ): Promise< Readonly<{ firstNormalEpoch: bigint; firstNormalSlot: bigint; leaderScheduleSlotOffset: bigint; slotsPerEpoch: bigint; warmup: boolean; }> >; ``` Fetches the `EpochSchedule` sysvar account using any RPC that supports the GetAccountInfoApi. ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `firstNormalEpoch`: `bigint`; `firstNormalSlot`: `bigint`; `leaderScheduleSlotOffset`: `bigint`; `slotsPerEpoch`: `bigint`; `warmup`: `boolean`; }>> # fetchSysvarLastRestartSlot (/api/functions/fetchSysvarLastRestartSlot) ```ts function fetchSysvarLastRestartSlot( rpc, config?, ): Promise< Readonly<{ lastRestartSlot: bigint; }> >; ``` Fetches the `LastRestartSlot` sysvar account using any RPC that supports the GetAccountInfoApi. ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lastRestartSlot`: `bigint`; }>> # fetchSysvarRecentBlockhashes (/api/functions/fetchSysvarRecentBlockhashes) ```ts function fetchSysvarRecentBlockhashes( rpc, config?, ): Promise; ``` Fetches the `RecentBlockhashes` sysvar account using any RPC that supports the GetAccountInfoApi. ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`SysvarRecentBlockhashes`](/api/type-aliases/SysvarRecentBlockhashes)> ## Deprecated Transaction fees should be determined with the GetFeeForMessageApi.getFeeForMessage RPC method. For additional context see the [Comprehensive Compute Fees proposal](https://docs.anza.xyz/proposals/comprehensive-compute-fees/). # fetchSysvarRent (/api/functions/fetchSysvarRent) ```ts function fetchSysvarRent( rpc, config?, ): Promise< Readonly<{ burnPercent: number; exemptionThreshold: number; lamportsPerByteYear: Lamports; }> >; ``` Fetches the `Rent` sysvar account using any RPC that supports the GetAccountInfoApi. ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `burnPercent`: `number`; `exemptionThreshold`: `number`; `lamportsPerByteYear`: `Lamports`; }>> # fetchSysvarSlotHashes (/api/functions/fetchSysvarSlotHashes) ```ts function fetchSysvarSlotHashes(rpc, config?): Promise; ``` Fetches the `SlotHashes` sysvar account using any RPC that supports the GetAccountInfoApi. ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`SysvarSlotHashes`](/api/type-aliases/SysvarSlotHashes)> # fetchSysvarSlotHistory (/api/functions/fetchSysvarSlotHistory) ```ts function fetchSysvarSlotHistory( rpc, config?, ): Promise; ``` Fetches the `SlotHistory` sysvar account using any RPC that supports the GetAccountInfoApi. ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`SysvarSlotHistory`](/api/type-aliases/SysvarSlotHistory)> # fetchSysvarStakeHistory (/api/functions/fetchSysvarStakeHistory) ```ts function fetchSysvarStakeHistory( rpc, config?, ): Promise; ``` Fetches the `StakeHistory` sysvar account using any RPC that supports the GetAccountInfoApi. ## Parameters | Parameter | Type | | --------- | --------------------------- | | `rpc` | `Rpc`\<`GetAccountInfoApi`> | | `config?` | `FetchAccountConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`SysvarStakeHistory`](/api/type-aliases/SysvarStakeHistory)> # fillTransactionMessageProvisoryResourceLimits (/api/functions/fillTransactionMessageProvisoryResourceLimits) ```ts function fillTransactionMessageProvisoryResourceLimits< TTransactionMessage, >(transactionMessage): TTransactionMessage; ``` Sets resource limits to a provisory value of 0 if no limit is currently set on the transaction message. For all versions, this fills the compute unit limit. For version 1 messages, it also fills the loaded accounts data size limit. If a limit is already set (any value, including 0), that limit is left unchanged. This is useful during transaction construction to reserve space for resource limits that will later be replaced with actual estimates via [estimateAndSetResourceLimitsFactory](/api/functions/estimateAndSetResourceLimitsFactory). ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | ## Parameters | Parameter | Type | Description | | -------------------- | --------------------- | --------------------------------------------------- | | `transactionMessage` | `TTransactionMessage` | The transaction message to add provisory limits to. | ## Returns `TTransactionMessage` The transaction message with provisory resource limits set, or unchanged if all applicable limits were already present. ## Example ```ts import { fillTransactionMessageProvisoryResourceLimits } from '@solana/kit'; const messageWithProvisoryLimits = fillTransactionMessageProvisoryResourceLimits(transactionMessage); ``` # findInstructionPlan (/api/functions/findInstructionPlan) ```ts function findInstructionPlan( instructionPlan, predicate, ): InstructionPlan | undefined; ``` Finds the first instruction plan in the tree that matches the given predicate. This function performs a depth-first search through the instruction plan tree, returning the first plan that satisfies the predicate. It checks the root plan first, then recursively searches through nested plans. ## Parameters | Parameter | Type | Description | | ----------------- | ------------------------------------------------------ | ---------------------------------------------------- | | `instructionPlan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan tree to search. | | `predicate` | (`plan`) => `boolean` | A function that returns `true` for the plan to find. | ## Returns [`InstructionPlan`](/api/type-aliases/InstructionPlan) | `undefined` The first matching instruction plan, or `undefined` if no match is found. ## Examples Finding a non-divisible sequential plan. ```ts const plan = parallelInstructionPlan([ sequentialInstructionPlan([instructionA, instructionB]), nonDivisibleSequentialInstructionPlan([instructionC, instructionD]), ]); const nonDivisible = findInstructionPlan( plan, (p) => p.kind === 'sequential' && !p.divisible, ); // Returns the non-divisible sequential plan containing instructionC and instructionD. ``` Finding a specific single instruction plan. ```ts const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]); const found = findInstructionPlan( plan, (p) => p.kind === 'single' && p.instruction === instructionB, ); // Returns the SingleInstructionPlan wrapping instructionB. ``` ## See * [InstructionPlan](/api/type-aliases/InstructionPlan) * [everyInstructionPlan](/api/functions/everyInstructionPlan) * [transformInstructionPlan](/api/functions/transformInstructionPlan) * [flattenInstructionPlan](/api/functions/flattenInstructionPlan) # findTransactionPlan (/api/functions/findTransactionPlan) ```ts function findTransactionPlan( transactionPlan, predicate, ): TransactionPlan | undefined; ``` Finds the first transaction plan in the tree that matches the given predicate. This function performs a depth-first search through the transaction plan tree, returning the first plan that satisfies the predicate. It checks the root plan first, then recursively searches through nested plans. ## Parameters | Parameter | Type | Description | | ----------------- | ------------------------------------------------------ | ---------------------------------------------------- | | `transactionPlan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan tree to search. | | `predicate` | (`plan`) => `boolean` | A function that returns `true` for the plan to find. | ## Returns [`TransactionPlan`](/api/type-aliases/TransactionPlan) | `undefined` The first matching transaction plan, or `undefined` if no match is found. ## Examples Finding a non-divisible sequential plan. ```ts const plan = parallelTransactionPlan([ sequentialTransactionPlan([messageA, messageB]), nonDivisibleSequentialTransactionPlan([messageC, messageD]), ]); const nonDivisible = findTransactionPlan( plan, (p) => p.kind === 'sequential' && !p.divisible, ); // Returns the non-divisible sequential plan containing messageC and messageD. ``` Finding a specific single transaction plan. ```ts const plan = sequentialTransactionPlan([messageA, messageB, messageC]); const found = findTransactionPlan( plan, (p) => p.kind === 'single' && p.message === messageB, ); // Returns the SingleTransactionPlan wrapping messageB. ``` ## See * [TransactionPlan](/api/type-aliases/TransactionPlan) * [everyTransactionPlan](/api/functions/everyTransactionPlan) * [transformTransactionPlan](/api/functions/transformTransactionPlan) * [flattenTransactionPlan](/api/functions/flattenTransactionPlan) # findTransactionPlanResult (/api/functions/findTransactionPlanResult) ```ts function findTransactionPlanResult< TContext, TTransactionMessage, TSingle, >( transactionPlanResult, predicate, ): | TransactionPlanResult | undefined; ``` Finds the first transaction plan result in the tree that matches the given predicate. This function performs a depth-first search through the transaction plan result tree, returning the first result that satisfies the predicate. It checks the root result first, then recursively searches through nested results. ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | The type of the transaction message | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The type of single transaction plan results in this tree | ## Parameters | Parameter | Type | Description | | ----------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | | `transactionPlanResult` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result tree to search. | | `predicate` | (`result`) => `boolean` | A function that returns `true` for the result to find. | ## Returns \| [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> \| `undefined` The first matching transaction plan result, or `undefined` if no match is found. ## Example Finding a failed transaction result. ```ts const result = parallelTransactionPlanResult([ successfulSingleTransactionPlanResult(messageA, { signature: signatureA }), failedSingleTransactionPlanResult(messageB, error), ]); const failed = findTransactionPlanResult( result, (r) => r.kind === 'single' && r.status === 'failed', ); // Returns the failed single transaction plan result for messageB. ``` ## See * [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) * [everyTransactionPlanResult](/api/functions/everyTransactionPlanResult) * [transformTransactionPlanResult](/api/functions/transformTransactionPlanResult) * [flattenTransactionPlanResult](/api/functions/flattenTransactionPlanResult) # fixBytes (/api/functions/fixBytes) ```ts function fixBytes( bytes, length, ): Uint8Array | ReadonlyUint8Array; ``` Fixes a `Uint8Array` to the specified length. If the array is longer than the specified length, it is truncated. If the array is shorter than the specified length, it is padded with zeroes. ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | | `bytes` | \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | The byte array to truncate or pad. | | `length` | `number` | The desired length of the byte array. | ## Returns \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> ## Examples Truncates the byte array to the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]); const fixedBytes = fixBytes(bytes, 2); // ^ [0x01, 0x02] ``` Adds zeroes to the end of the byte array to reach the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02]); const fixedBytes = fixBytes(bytes, 4); // ^ [0x01, 0x02, 0x00, 0x00] ``` Returns the original byte array if it is already at the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02]); const fixedBytes = fixBytes(bytes, 2); // bytes === fixedBytes ``` # fixCodecSize (/api/functions/fixCodecSize) ```ts function fixCodecSize( codec, fixedBytes, ): FixedSizeCodec; ``` Creates a fixed-size codec from a given codec. The resulting codec ensures that both encoding and decoding operate on a fixed number of bytes. When encoding: * If the encoded value is larger than `fixedBytes`, it is truncated. * If it is smaller, it is padded with trailing zeroes. * If it is exactly `fixedBytes`, it remains unchanged. When decoding: * Exactly `fixedBytes` bytes are read from the input. * If the nested decoder has a smaller fixed size, bytes are truncated or padded as necessary. ## Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ## Parameters | Parameter | Type | Description | | ------------ | --------------------------------------------------- | ------------------------------------------ | | `codec` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | The codec to wrap into a fixed-size codec. | | `fixedBytes` | `TSize` | The fixed number of bytes to read/write. | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`> A `FixedSizeCodec` that ensures both encoding and decoding conform to a fixed size. ## Example ```ts const codec = fixCodecSize(getUtf8Codec(), 4); const bytes1 = codec.encode("Hello"); // 0x48656c6c (truncated) const value1 = codec.decode(bytes1); // "Hell" const bytes2 = codec.encode("Hi"); // 0x48690000 (padded) const value2 = codec.decode(bytes2); // "Hi" const bytes3 = codec.encode("Hiya"); // 0x48697961 (same length) const value3 = codec.decode(bytes3); // "Hiya" ``` ## Remarks If you only need to enforce a fixed size for encoding, use [fixEncoderSize](/api/functions/fixEncoderSize). If you only need to enforce a fixed size for decoding, use [fixDecoderSize](/api/functions/fixDecoderSize). ```ts const bytes = fixEncoderSize(getUtf8Encoder(), 4).encode("Hiya"); const value = fixDecoderSize(getUtf8Decoder(), 4).decode(bytes); ``` ## See * [fixEncoderSize](/api/functions/fixEncoderSize) * [fixDecoderSize](/api/functions/fixDecoderSize) # fixDecoderSize (/api/functions/fixDecoderSize) ```ts function fixDecoderSize( decoder, fixedBytes, ): FixedSizeDecoder; ``` Creates a fixed-size decoder from a given decoder. The resulting decoder always reads exactly `fixedBytes` bytes from the input. If the nested decoder is also fixed-size, the bytes are truncated or padded as needed. For more details, see [fixCodecSize](/api/functions/fixCodecSize). ## Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ## Parameters | Parameter | Type | Description | | ------------ | ---------------------------------------------- | ---------------------------------------------- | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | The decoder to wrap into a fixed-size decoder. | | `fixedBytes` | `TSize` | The fixed number of bytes to read. | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `TSize`> A `FixedSizeDecoder` that ensures a consistent input size. ## Example ```ts const decoder = fixDecoderSize(getUtf8Decoder(), 4); decoder.decode(new Uint8Array([72, 101, 108, 108, 111])); // "Hell" (truncated) decoder.decode(new Uint8Array([72, 105, 0, 0])); // "Hi" (zeroes ignored) decoder.decode(new Uint8Array([72, 105, 121, 97])); // "Hiya" (same length) ``` ## Remarks If you need a full codec with both encoding and decoding, use [fixCodecSize](/api/functions/fixCodecSize). ## See * [fixCodecSize](/api/functions/fixCodecSize) * [fixEncoderSize](/api/functions/fixEncoderSize) # fixEncoderSize (/api/functions/fixEncoderSize) ```ts function fixEncoderSize( encoder, fixedBytes, ): FixedSizeEncoder; ``` Creates a fixed-size encoder from a given encoder. The resulting encoder ensures that encoded values always have the specified number of bytes. If the original encoded value is larger than `fixedBytes`, it is truncated. If it is smaller, it is padded with trailing zeroes. For more details, see [fixCodecSize](/api/functions/fixCodecSize). ## Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ## Parameters | Parameter | Type | Description | | ------------ | ------------------------------------------------ | ---------------------------------------------- | | `encoder` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | The encoder to wrap into a fixed-size encoder. | | `fixedBytes` | `TSize` | The fixed number of bytes to write. | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`> A `FixedSizeEncoder` that ensures a consistent output size. ## Example ```ts const encoder = fixEncoderSize(getUtf8Encoder(), 4); encoder.encode("Hello"); // 0x48656c6c (truncated) encoder.encode("Hi"); // 0x48690000 (padded) encoder.encode("Hiya"); // 0x48697961 (same length) ``` ## Remarks If you need a full codec with both encoding and decoding, use [fixCodecSize](/api/functions/fixCodecSize). ## See * [fixCodecSize](/api/functions/fixCodecSize) * [fixDecoderSize](/api/functions/fixDecoderSize) # flattenInstructionPlan (/api/functions/flattenInstructionPlan) ```ts function flattenInstructionPlan(instructionPlan): ( | Readonly<{ getMessagePacker: () => MessagePacker; kind: 'messagePacker'; planType: 'instructionPlan'; }> | Readonly<{ instruction: Instruction; kind: 'single'; planType: 'instructionPlan'; }> )[]; ``` Retrieves all individual [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan) and [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) instances from an instruction plan tree. This function recursively traverses any nested structure of instruction plans and extracts all the leaf plans they contain. It's useful when you need to access all the individual instructions or message packers that will be executed, regardless of their organization in the plan tree (parallel or sequential). ## Parameters | Parameter | Type | Description | | ----------------- | ------------------------------------------------------ | ----------------------------------------------- | | `instructionPlan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to extract leaf plans from | ## Returns ( \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `getMessagePacker`: () => [`MessagePacker`](/api/type-aliases/MessagePacker); `kind`: `"messagePacker"`; `planType`: `"instructionPlan"`; }> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `instruction`: [`Instruction`](/api/interfaces/Instruction); `kind`: `"single"`; `planType`: `"instructionPlan"`; }>)\[] An array of all single and message packer instruction plans contained in the tree ## Example ```ts const plan = parallelInstructionPlan([ sequentialInstructionPlan([instructionA, instructionB]), nonDivisibleSequentialInstructionPlan([instructionC, instructionD]), instructionE, ]); const leafPlans = flattenInstructionPlan(plan); // Array of `SingleInstructionPlan` containing: // instructionA, instructionB, instructionC, instructionD and instructionE. ``` ## See * [InstructionPlan](/api/type-aliases/InstructionPlan) * [findInstructionPlan](/api/functions/findInstructionPlan) * [everyInstructionPlan](/api/functions/everyInstructionPlan) * [transformInstructionPlan](/api/functions/transformInstructionPlan) # flattenTransactionPlan (/api/functions/flattenTransactionPlan) ```ts function flattenTransactionPlan(transactionPlan): Readonly<{ kind: 'single'; message: TransactionMessage & TransactionMessageWithFeePayer; planType: 'transactionPlan'; }>[]; ``` Retrieves all individual [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan) instances from a transaction plan tree. This function recursively traverses any nested structure of transaction plans and extracts all the single transaction plans they contain. It's useful when you need to access all the actual transaction messages that will be executed, regardless of their organization in the plan tree (parallel or sequential). ## Parameters | Parameter | Type | Description | | ----------------- | ------------------------------------------------------ | ------------------------------------------------- | | `transactionPlan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to extract single plans from | ## Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `kind`: `"single"`; `message`: [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>; `planType`: `"transactionPlan"`; }>\[] An array of all single transaction plans contained in the tree ## Example ```ts const plan = parallelTransactionPlan([ sequentialTransactionPlan([messageA, messageB]), nonDivisibleSequentialTransactionPlan([messageC, messageD]), messageE, ]); const singlePlans = flattenTransactionPlan(plan); // Array of `SingleTransactionPlan` containing: // messageA, messageB, messageC and messageD. @see {@link TransactionPlan} @see {@link findTransactionPlan} @see {@link everyTransactionPlan} @see {@link transformTransactionPlan} ``` # flattenTransactionPlanResult (/api/functions/flattenTransactionPlanResult) ```ts function flattenTransactionPlanResult< TContext, TTransactionMessage, TSingle, >(result): TSingle[]; ``` Retrieves all individual [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) instances from a transaction plan result tree. This function recursively traverses any nested structure of transaction plan results and extracts all the single results they contain. It's useful when you need to access all the individual transaction results, regardless of their organization in the result tree (parallel or sequential). ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | The type of the transaction message | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The type of single transaction plan results in this tree | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | `result` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result to extract single results from | ## Returns `TSingle`\[] An array of all single transaction plan results contained in the tree ## Example ```ts const result = parallelTransactionPlanResult([ sequentialTransactionPlanResult([resultA, resultB]), nonDivisibleSequentialTransactionPlanResult([resultC, resultD]), resultE, ]); const singleResults = flattenTransactionPlanResult(result); // Array of `SingleTransactionPlanResult` containing: // resultA, resultB, resultC, resultD and resultE. ``` ## See * [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) * [findTransactionPlanResult](/api/functions/findTransactionPlanResult) * [everyTransactionPlanResult](/api/functions/everyTransactionPlanResult) * [transformTransactionPlanResult](/api/functions/transformTransactionPlanResult) # formatBinaryFixedPoint (/api/functions/formatBinaryFixedPoint) ```ts function formatBinaryFixedPoint(formatter, value): string; ``` Formats a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) using a user-supplied `Intl.NumberFormat` instance, preserving full precision regardless of the value's magnitude. Internally calls [binaryFixedPointToBase10](/api/functions/binaryFixedPointToBase10) and forwards the resulting integer to `formatter.format` using ES2023 string scientific notation (`"E-"`). This preserves precision in fully-compliant runtimes and bypasses the JavaScript `number` mantissa limit. Use this when you want locale-aware output, currency formatting, grouping separators, or rounding modes from the rich `Intl.NumberFormat` API. Prefer [binaryFixedPointToString](/api/functions/binaryFixedPointToString) when portability across older runtimes (older Hermes/React Native, etc.) is a concern. ## Parameters | Parameter | Type | | ----------- | --------------------------------------------------------------------------------------------------------------------------- | | `formatter` | [`NumberFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) | | `value` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `number`> | ## Returns `string` ## Example ```ts const q1_15 = binaryFixedPoint('signed', 16, 15); const formatter = new Intl.NumberFormat('fr-FR', { maximumFractionDigits: 4, }); formatBinaryFixedPoint(formatter, q1_15('0.1')); // "0,1" ``` ## See * [binaryFixedPointToString](/api/functions/binaryFixedPointToString) * [binaryFixedPointToBase10](/api/functions/binaryFixedPointToBase10) # formatDecimalFixedPoint (/api/functions/formatDecimalFixedPoint) ```ts function formatDecimalFixedPoint(formatter, value): string; ``` Formats a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) using a user-supplied `Intl.NumberFormat` instance, preserving full precision regardless of the value's magnitude. Forwards `value.raw` to `formatter.format` using ES2023 string scientific notation (`"E-"`). This preserves precision in fully-compliant runtimes and bypasses the JavaScript `number` mantissa limit. Use this when you want locale-aware output, currency formatting, grouping separators, or rounding modes from the rich `Intl.NumberFormat` API. Prefer [decimalFixedPointToString](/api/functions/decimalFixedPointToString) when portability across older runtimes (older Hermes/React Native, etc.) is a concern. ## Parameters | Parameter | Type | | ----------- | ----------------------------------------------------------------------------------------------------------------------------- | | `formatter` | [`NumberFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) | | `value` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `number`> | ## Returns `string` ## Example ```ts const usdc = decimalFixedPoint('unsigned', 64, 6); const formatter = new Intl.NumberFormat('en-US', { currency: 'USD', style: 'currency', }); formatDecimalFixedPoint(formatter, usdc('1234.5')); // "$1,234.50" ``` ## See [decimalFixedPointToString](/api/functions/decimalFixedPointToString) # fromLegacyKeypair (/api/functions/fromLegacyKeypair) ```ts function fromLegacyKeypair( keypair, extractable?, ): Promise; ``` Converts a legacy [Keypair](https://solana-foundation.github.io/solana-web3.js/classes/Keypair.html) object to a native Ed25519 CryptoKeyPair object. ## Parameters | Parameter | Type | | -------------- | --------- | | `keypair` | `Keypair` | | `extractable?` | `boolean` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`CryptoKeyPair`> ## Example ```ts import { fromLegacyKeypair } from '@solana/compat'; const legacyKeyPair = Keypair.generate(); const { privateKey, publicKey } = await fromLegacyKeypair(legacyKeyPair); ``` # fromLegacyPublicKey (/api/functions/fromLegacyPublicKey) ```ts function fromLegacyPublicKey(publicKey): Address; ``` Converts a legacy [PublicKey](https://solana-foundation.github.io/solana-web3.js/classes/PublicKey.html) object to an Address. ## Type Parameters | Type Parameter | | ----------------------------- | | `TAddress` *extends* `string` | ## Parameters | Parameter | Type | | ----------- | ----------- | | `publicKey` | `PublicKey` | ## Returns `Address`\<`TAddress`> ## Example ```ts import { fromLegacyPublicKey } from '@solana/compat'; const legacyPublicKey = new PublicKey('49XBVQsvSW44ULKL9qufS9YqQPbdcps1TQRijx4FQ9sH'); const address = fromLegacyPublicKey(legacyPublicKey); ``` # fromLegacyTransactionInstruction (/api/functions/fromLegacyTransactionInstruction) ```ts function fromLegacyTransactionInstruction( legacyInstruction, ): Instruction; ``` This can be used to convert a legacy [`TransactionInstruction`](https://solana-foundation.github.io/solana-web3.js/classes/TransactionInstruction.html) object to an Instruction. ## Parameters | Parameter | Type | | ------------------- | ------------------------ | | `legacyInstruction` | `TransactionInstruction` | ## Returns `Instruction` ## Example ```ts import { fromLegacyTransactionInstruction } from '@solana/compat'; // Imagine a function that returns a legacy `TransactionInstruction` const legacyInstruction = getMyLegacyInstruction(); const instruction = fromLegacyTransactionInstruction(legacyInstruction); ``` # fromVersionedTransaction (/api/functions/fromVersionedTransaction) ```ts function fromVersionedTransaction(transaction): Transaction; ``` This can be used to convert a legacy [VersionedTransaction](https://solana-foundation.github.io/solana-web3.js/classes/VersionedTransaction.html) object to a Transaction. ## Parameters | Parameter | Type | | ------------- | ---------------------- | | `transaction` | `VersionedTransaction` | ## Returns `Transaction` ## Example ```ts import { fromVersionedTransaction } from '@solana/compat'; // Imagine a function that returns a legacy `VersionedTransaction` const legacyVersionedTransaction = getMyLegacyVersionedTransaction(); const transaction = fromVersionedTransaction(legacyVersionedTransaction); ``` # generateKeyPair (/api/functions/generateKeyPair) ```ts function generateKeyPair(extractable?): Promise; ``` Generates an Ed25519 public/private key pair for use with other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects. ## Parameters | Parameter | Type | Description | | -------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `extractable?` | `boolean` | Setting this to `true` makes it possible to extract the bytes of the private key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey) API. Defaults to `false`, which prevents the bytes of the private key from being visible to JS. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`CryptoKeyPair`> ## Example ```ts import { generateKeyPair } from '@solana/keys'; const { privateKey, publicKey } = await generateKeyPair(); ``` # generateKeyPairSigner (/api/functions/generateKeyPairSigner) ```ts function generateKeyPairSigner( extractable?, ): Promise>; ``` Generates a signer capable of signing messages and transactions by generating a CryptoKeyPair and creating a [KeyPairSigner](/api/type-aliases/KeyPairSigner) from it. ## Parameters | Parameter | Type | Default value | Description | | ------------- | --------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `extractable` | `boolean` | `false` | Setting this to `true` makes it possible to extract the bytes of the private key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey) API. Defaults to `false`, which prevents the bytes of the private key from being visible to JS. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`KeyPairSigner`](/api/type-aliases/KeyPairSigner)\<`string`>> ## Example ```ts import { generateKeyPairSigner } from '@solana/signers'; const signer = await generateKeyPairSigner(); ``` ## See [createSignerFromKeyPair](/api/functions/createSignerFromKeyPair) # getAbortablePromise (/api/functions/getAbortablePromise) ```ts function getAbortablePromise(promise, abortSignal?): Promise; ``` Returns a new promise that will reject if the abort signal fires before the original promise settles. Resolves or rejects with the value of the original promise otherwise. ## Type Parameters | Type Parameter | | -------------- | | `T` | ## Parameters | Parameter | Type | | -------------- | ----------------------------------------------------------------------------------------------------- | | `promise` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`T`> | | `abortSignal?` | [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`T`> ## Example ```ts const result = await getAbortablePromise( // Resolves or rejects when `fetch` settles. fetch('https://example.com/json').then(r => r.json()), // ...unless it takes longer than 5 seconds, after which the `AbortSignal` is triggered. AbortSignal.timeout(5000), ); ``` # getAccountMetaFactory (/api/functions/getAccountMetaFactory) ```ts function getAccountMetaFactory( programAddress, optionalAccountStrategy, ): ( inputName, account, ) => | AccountMeta | AccountSignerMeta> | undefined; ``` Creates a factory function that converts resolved instruction accounts to account metas. The factory handles the conversion of [ResolvedInstructionAccount](/api/type-aliases/ResolvedInstructionAccount) objects into AccountMeta or AccountSignerMeta objects suitable for building instructions. It also determines how to handle optional accounts based on the provided strategy. ## Parameters | Parameter | Type | Description | | ------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `programAddress` | `Address` | The program address, used when optional accounts use the `programId` strategy. | | `optionalAccountStrategy` | `"omitted"` \| `"programId"` | How to handle null account values: - `'omitted'`: Optional accounts are excluded from the instruction entirely. - `'programId'`: Optional accounts are replaced with the program address as a read-only account. | ## Returns A factory function that converts a resolved account to an account meta. (`inputName`, `account`) => \| `AccountMeta`\<`string`> \| `AccountSignerMeta`\<`string`, `TransactionSigner`\<`string`>> \| `undefined` ## Example ```ts const toAccountMeta = getAccountMetaFactory(programAddress, 'programId'); const mintMeta = toAccountMeta('mint', resolvedMint); ``` # getAccountMetasFromCompiledTransactionMessage (/api/functions/getAccountMetasFromCompiledTransactionMessage) ```ts function getAccountMetasFromCompiledTransactionMessage( compiledMessage, loadedAddresses?, ): AccountMeta[]; ``` Builds the full ordered list of AccountMetas for a compiled transaction message. The order matches the runtime's resolution order: 1. Static accounts, with role bits derived from the message header (writable signers, readonly signers, writable non-signers, readonly non-signers). 2. ALT-loaded writable accounts (always non-signer, writable). 3. ALT-loaded readonly accounts (always non-signer, readonly). Inner-instruction account indices reference the same flat list, so this helper is also useful for resolving inner instructions. ## Parameters | Parameter | Type | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `compiledMessage` | `CompiledTransactionMessage` | | `loadedAddresses?` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `readonly`: readonly `Address`\[]; `writable`: readonly `Address`\[]; }> \| `null` | ## Returns `AccountMeta`\<`string`>\[] # getAddressCodec (/api/functions/getAddressCodec) ```ts function getAddressCodec(): FixedSizeCodec< Address, Address, 32 >; ``` Returns a codec that you can use to encode from or decode to a base-58 encoded address. ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<[`Address`](/api/type-aliases/Address)\<`string`>, [`Address`](/api/type-aliases/Address)\<`string`>, `32`> ## See * [getAddressDecoder](/api/functions/getAddressDecoder) * [getAddressEncoder](/api/functions/getAddressEncoder) # getAddressComparator (/api/functions/getAddressComparator) ```ts function getAddressComparator(): (x, y) => number; ``` ## Returns (`x`, `y`) => `number` # getAddressDecoder (/api/functions/getAddressDecoder) ```ts function getAddressDecoder(): FixedSizeDecoder, 32>; ``` Returns a decoder that you can use to convert an array of 32 bytes representing an address to the base58-encoded representation of that address. ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<[`Address`](/api/type-aliases/Address)\<`string`>, `32`> ## Example ```ts import { getAddressDecoder } from '@solana/addresses'; const addressBytes = new Uint8Array([ 150, 183, 190, 48, 171, 8, 39, 156, 122, 213, 172, 108, 193, 95, 26, 158, 149, 243, 115, 254, 20, 200, 36, 30, 248, 179, 178, 232, 220, 89, 53, 127 ]); const addressDecoder = getAddressDecoder(); const address = addressDecoder.decode(addressBytes); // B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka ``` # getAddressEncoder (/api/functions/getAddressEncoder) ```ts function getAddressEncoder(): FixedSizeEncoder, 32>; ``` Returns an encoder that you can use to encode a base58-encoded address to a byte array. ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<[`Address`](/api/type-aliases/Address)\<`string`>, `32`> ## Example ```ts import { getAddressEncoder } from '@solana/addresses'; const address = 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address; const addressEncoder = getAddressEncoder(); const addressBytes = addressEncoder.encode(address); // Uint8Array(32) [ // 150, 183, 190, 48, 171, 8, 39, 156, // 122, 213, 172, 108, 193, 95, 26, 158, // 149, 243, 115, 254, 20, 200, 36, 30, // 248, 179, 178, 232, 220, 89, 53, 127 // ] ``` # getAddressFromPublicKey (/api/functions/getAddressFromPublicKey) ```ts function getAddressFromPublicKey(publicKey): Promise
; ``` Given a public [CryptoKey](https://developer.mozilla.org/docs/Web/API/CryptoKey), this method will return its associated [Address](/api/type-aliases/Address). ## Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------- | | `publicKey` | [`CryptoKey`](https://developer.mozilla.org/docs/Web/API/CryptoKey) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Address`](/api/type-aliases/Address)> ## Example ```ts import { getAddressFromPublicKey } from '@solana/addresses'; const address = await getAddressFromPublicKey(publicKey); ``` # getAddressFromResolvedInstructionAccount (/api/functions/getAddressFromResolvedInstructionAccount) ```ts function getAddressFromResolvedInstructionAccount( inputName, value, ): Address; ``` Extracts the address from a resolved instruction account. A resolved instruction account can be an Address, a ProgramDerivedAddress, or a TransactionSigner. This function extracts the underlying address from any of these types. ## Type Parameters | Type Parameter | Default type | Description | | ---------------------- | ------------ | --------------------------------------- | | `T` *extends* `string` | `string` | The address type, defaults to `string`. | ## Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------- | | `inputName` | `string` | The name of the instruction input, used in error messages. | | `value` | \| `Address`\<`T`> \| readonly \[`Address`\<`T`>, `ProgramDerivedAddressBump`] \| `TransactionSigner`\<`T`> \| `null` \| `undefined` | The resolved account value to extract the address from. | ## Returns `Address`\<`T`> The extracted address. ## Throws Throws a SolanaError if the value is null or undefined. ## Example ```ts const address = getAddressFromResolvedInstructionAccount('mint', resolvedMint); ``` # getArrayCodec (/api/functions/getArrayCodec) ## Call Signature ```ts function getArrayCodec( item, config, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding arrays of values. This codec serializes arrays by encoding each element using the provided item codec. By default, a `u32` size prefix is included to indicate the number of items in the array. The `size` option can be used to modify this behaviour. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ----------------------------------- | | `TFrom` | - | The type of the elements to encode. | | `TTo` | `TFrom` | The type of the decoded elements. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | `item` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | The codec for each item in the array. | | `config` | [`ArrayCodecConfig`](/api/type-aliases/ArrayCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Optional configuration for the size encoding/decoding strategy. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`\[], `TTo`\[], `0`> A `VariableSizeCodec` for encoding and decoding arrays. ### Examples Encoding and decoding an array of `u8` numbers. ```ts const codec = getArrayCodec(getU8Codec()); const bytes = codec.encode([1, 2, 3]); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. const array = codec.decode(bytes); // [1, 2, 3] ``` Using a `u16` size prefix instead of `u32`. ```ts const codec = getArrayCodec(getU8Codec(), { size: getU16Codec() }); const bytes = codec.encode([1, 2, 3]); // 0x0300010203 // | β””-- 3 items of 1 byte each. // β””-- 2-byte prefix telling us to read 3 items. ``` Using a fixed-size array of 3 items. ```ts const codec = getArrayCodec(getU8Codec(), { size: 3 }); codec.encode([1, 2, 3]); // 0x010203 // β””-- 3 items of 1 byte each. There must always be 3 items in the array. ``` Using the `"remainder"` size strategy. ```ts const codec = getArrayCodec(getU8Codec(), { size: 'remainder' }); codec.encode([1, 2, 3]); // 0x010203 // β””-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes. ``` ### Remarks The size of the array can be controlled using the `size` option: * A `Codec` (e.g. `getU16Codec()`) stores a size prefix before the array. * A `number` enforces a fixed number of elements. * `"remainder"` uses all remaining bytes to infer the array length. Separate [getArrayEncoder](/api/functions/getArrayEncoder) and [getArrayDecoder](/api/functions/getArrayDecoder) functions are available. ```ts const bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]); const array = getArrayDecoder(getU8Decoder()).decode(bytes); ``` ### See * [getArrayEncoder](/api/functions/getArrayEncoder) * [getArrayDecoder](/api/functions/getArrayDecoder) ## Call Signature ```ts function getArrayCodec( item, config, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding arrays of values. This codec serializes arrays by encoding each element using the provided item codec. By default, a `u32` size prefix is included to indicate the number of items in the array. The `size` option can be used to modify this behaviour. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ----------------------------------- | | `TFrom` | - | The type of the elements to encode. | | `TTo` | `TFrom` | The type of the decoded elements. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | `item` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> | The codec for each item in the array. | | `config` | [`ArrayCodecConfig`](/api/type-aliases/ArrayCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Optional configuration for the size encoding/decoding strategy. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`\[], `TTo`\[]> A `VariableSizeCodec` for encoding and decoding arrays. ### Examples Encoding and decoding an array of `u8` numbers. ```ts const codec = getArrayCodec(getU8Codec()); const bytes = codec.encode([1, 2, 3]); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. const array = codec.decode(bytes); // [1, 2, 3] ``` Using a `u16` size prefix instead of `u32`. ```ts const codec = getArrayCodec(getU8Codec(), { size: getU16Codec() }); const bytes = codec.encode([1, 2, 3]); // 0x0300010203 // | β””-- 3 items of 1 byte each. // β””-- 2-byte prefix telling us to read 3 items. ``` Using a fixed-size array of 3 items. ```ts const codec = getArrayCodec(getU8Codec(), { size: 3 }); codec.encode([1, 2, 3]); // 0x010203 // β””-- 3 items of 1 byte each. There must always be 3 items in the array. ``` Using the `"remainder"` size strategy. ```ts const codec = getArrayCodec(getU8Codec(), { size: 'remainder' }); codec.encode([1, 2, 3]); // 0x010203 // β””-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes. ``` ### Remarks The size of the array can be controlled using the `size` option: * A `Codec` (e.g. `getU16Codec()`) stores a size prefix before the array. * A `number` enforces a fixed number of elements. * `"remainder"` uses all remaining bytes to infer the array length. Separate [getArrayEncoder](/api/functions/getArrayEncoder) and [getArrayDecoder](/api/functions/getArrayDecoder) functions are available. ```ts const bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]); const array = getArrayDecoder(getU8Decoder()).decode(bytes); ``` ### See * [getArrayEncoder](/api/functions/getArrayEncoder) * [getArrayDecoder](/api/functions/getArrayDecoder) ## Call Signature ```ts function getArrayCodec( item, config?, ): VariableSizeCodec; ``` Returns a codec for encoding and decoding arrays of values. This codec serializes arrays by encoding each element using the provided item codec. By default, a `u32` size prefix is included to indicate the number of items in the array. The `size` option can be used to modify this behaviour. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ----------------------------------- | | `TFrom` | - | The type of the elements to encode. | | `TTo` | `TFrom` | The type of the decoded elements. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | `item` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | The codec for each item in the array. | | `config?` | [`ArrayCodecConfig`](/api/type-aliases/ArrayCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> | Optional configuration for the size encoding/decoding strategy. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`\[], `TTo`\[]> A `VariableSizeCodec` for encoding and decoding arrays. ### Examples Encoding and decoding an array of `u8` numbers. ```ts const codec = getArrayCodec(getU8Codec()); const bytes = codec.encode([1, 2, 3]); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. const array = codec.decode(bytes); // [1, 2, 3] ``` Using a `u16` size prefix instead of `u32`. ```ts const codec = getArrayCodec(getU8Codec(), { size: getU16Codec() }); const bytes = codec.encode([1, 2, 3]); // 0x0300010203 // | β””-- 3 items of 1 byte each. // β””-- 2-byte prefix telling us to read 3 items. ``` Using a fixed-size array of 3 items. ```ts const codec = getArrayCodec(getU8Codec(), { size: 3 }); codec.encode([1, 2, 3]); // 0x010203 // β””-- 3 items of 1 byte each. There must always be 3 items in the array. ``` Using the `"remainder"` size strategy. ```ts const codec = getArrayCodec(getU8Codec(), { size: 'remainder' }); codec.encode([1, 2, 3]); // 0x010203 // β””-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes. ``` ### Remarks The size of the array can be controlled using the `size` option: * A `Codec` (e.g. `getU16Codec()`) stores a size prefix before the array. * A `number` enforces a fixed number of elements. * `"remainder"` uses all remaining bytes to infer the array length. Separate [getArrayEncoder](/api/functions/getArrayEncoder) and [getArrayDecoder](/api/functions/getArrayDecoder) functions are available. ```ts const bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]); const array = getArrayDecoder(getU8Decoder()).decode(bytes); ``` ### See * [getArrayEncoder](/api/functions/getArrayEncoder) * [getArrayDecoder](/api/functions/getArrayDecoder) # getArrayDecoder (/api/functions/getArrayDecoder) ## Call Signature ```ts function getArrayDecoder(item, config): FixedSizeDecoder; ``` Returns a decoder for arrays of values. This decoder deserializes arrays by decoding each element using the provided item decoder. By default, a `u32` size prefix is expected to indicate the number of items in the array. The `size` option can be used to modify this behaviour. For more details, see [getArrayCodec](/api/functions/getArrayCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ---------------------------------------------- | | `TTo` | The type of the decoded elements in the array. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | | `item` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | The decoder for each item in the array. | | `config` | [`ArrayCodecConfig`](/api/type-aliases/ArrayCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Optional configuration for the size decoding strategy. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`\[], `0`> A `VariableSizeDecoder` for decoding arrays. ### Example Decoding an array of `u8` numbers. ```ts const decoder = getArrayDecoder(getU8Decoder()); const array = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03])); // [1, 2, 3] // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. ``` ### See [getArrayCodec](/api/functions/getArrayCodec) ## Call Signature ```ts function getArrayDecoder(item, config): FixedSizeDecoder; ``` Returns a decoder for arrays of values. This decoder deserializes arrays by decoding each element using the provided item decoder. By default, a `u32` size prefix is expected to indicate the number of items in the array. The `size` option can be used to modify this behaviour. For more details, see [getArrayCodec](/api/functions/getArrayCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ---------------------------------------------- | | `TTo` | The type of the decoded elements in the array. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | | `item` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> | The decoder for each item in the array. | | `config` | [`ArrayCodecConfig`](/api/type-aliases/ArrayCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Optional configuration for the size decoding strategy. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`\[]> A `VariableSizeDecoder` for decoding arrays. ### Example Decoding an array of `u8` numbers. ```ts const decoder = getArrayDecoder(getU8Decoder()); const array = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03])); // [1, 2, 3] // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. ``` ### See [getArrayCodec](/api/functions/getArrayCodec) ## Call Signature ```ts function getArrayDecoder( item, config?, ): VariableSizeDecoder; ``` Returns a decoder for arrays of values. This decoder deserializes arrays by decoding each element using the provided item decoder. By default, a `u32` size prefix is expected to indicate the number of items in the array. The `size` option can be used to modify this behaviour. For more details, see [getArrayCodec](/api/functions/getArrayCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ---------------------------------------------- | | `TTo` | The type of the decoded elements in the array. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | | `item` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | The decoder for each item in the array. | | `config?` | [`ArrayCodecConfig`](/api/type-aliases/ArrayCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> | Optional configuration for the size decoding strategy. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`\[]> A `VariableSizeDecoder` for decoding arrays. ### Example Decoding an array of `u8` numbers. ```ts const decoder = getArrayDecoder(getU8Decoder()); const array = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03])); // [1, 2, 3] // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. ``` ### See [getArrayCodec](/api/functions/getArrayCodec) # getArrayEncoder (/api/functions/getArrayEncoder) ## Call Signature ```ts function getArrayEncoder( item, config, ): FixedSizeEncoder; ``` Returns an encoder for arrays of values. This encoder serializes arrays by encoding each element using the provided item encoder. By default, a `u32` size prefix is included to indicate the number of items in the array. The `size` option can be used to modify this behaviour. For more details, see [getArrayCodec](/api/functions/getArrayCodec). ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------------- | | `TFrom` | The type of the elements in the array. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | | `item` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | The encoder for each item in the array. | | `config` | [`ArrayCodecConfig`](/api/type-aliases/ArrayCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Optional configuration for the size encoding strategy and description. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`\[], `0`> A `VariableSizeEncoder` for encoding arrays. ### Example Encoding an array of `u8` numbers. ```ts const encoder = getArrayEncoder(getU8Encoder()); const bytes = encoder.encode([1, 2, 3]); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. ``` ### See [getArrayCodec](/api/functions/getArrayCodec) ## Call Signature ```ts function getArrayEncoder( item, config, ): FixedSizeEncoder; ``` Returns an encoder for arrays of values. This encoder serializes arrays by encoding each element using the provided item encoder. By default, a `u32` size prefix is included to indicate the number of items in the array. The `size` option can be used to modify this behaviour. For more details, see [getArrayCodec](/api/functions/getArrayCodec). ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------------- | | `TFrom` | The type of the elements in the array. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | | `item` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> | The encoder for each item in the array. | | `config` | [`ArrayCodecConfig`](/api/type-aliases/ArrayCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Optional configuration for the size encoding strategy and description. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`\[]> A `VariableSizeEncoder` for encoding arrays. ### Example Encoding an array of `u8` numbers. ```ts const encoder = getArrayEncoder(getU8Encoder()); const bytes = encoder.encode([1, 2, 3]); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. ``` ### See [getArrayCodec](/api/functions/getArrayCodec) ## Call Signature ```ts function getArrayEncoder( item, config?, ): VariableSizeEncoder; ``` Returns an encoder for arrays of values. This encoder serializes arrays by encoding each element using the provided item encoder. By default, a `u32` size prefix is included to indicate the number of items in the array. The `size` option can be used to modify this behaviour. For more details, see [getArrayCodec](/api/functions/getArrayCodec). ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------------- | | `TFrom` | The type of the elements in the array. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | `item` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | The encoder for each item in the array. | | `config?` | [`ArrayCodecConfig`](/api/type-aliases/ArrayCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> | Optional configuration for the size encoding strategy and description. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`\[]> A `VariableSizeEncoder` for encoding arrays. ### Example Encoding an array of `u8` numbers. ```ts const encoder = getArrayEncoder(getU8Encoder()); const bytes = encoder.encode([1, 2, 3]); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix telling us to read 3 items. ``` ### See [getArrayCodec](/api/functions/getArrayCodec) # getBase10Codec (/api/functions/getBase10Codec) ```ts function getBase10Codec(): VariableSizeCodec; ``` Returns a codec for encoding and decoding base-10 strings. This codec serializes strings using a base-10 encoding scheme. The output consists of bytes representing the numerical values of the input string. ## Returns `VariableSizeCodec`\<`string`> A `VariableSizeCodec` for encoding and decoding base-10 strings. ## Example Encoding and decoding a base-10 string. ```ts const codec = getBase10Codec(); const bytes = codec.encode('1024'); // 0x0400 const value = codec.decode(bytes); // "1024" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-10 codec, consider using fixCodecSize. ```ts const codec = fixCodecSize(getBase10Codec(), 5); ``` If you need a size-prefixed base-10 codec, consider using addCodecSizePrefix. ```ts const codec = addCodecSizePrefix(getBase10Codec(), getU32Codec()); ``` Separate [getBase10Encoder](/api/functions/getBase10Encoder) and [getBase10Decoder](/api/functions/getBase10Decoder) functions are available. ```ts const bytes = getBase10Encoder().encode('1024'); const value = getBase10Decoder().decode(bytes); ``` ## See * [getBase10Encoder](/api/functions/getBase10Encoder) * [getBase10Decoder](/api/functions/getBase10Decoder) # getBase10Decoder (/api/functions/getBase10Decoder) ```ts function getBase10Decoder(): VariableSizeDecoder; ``` Returns a decoder for base-10 strings. This decoder deserializes base-10 encoded strings from a byte array. For more details, see [getBase10Codec](/api/functions/getBase10Codec). ## Returns `VariableSizeDecoder`\<`string`> A `VariableSizeDecoder` for decoding base-10 strings. ## Example Decoding a base-10 string. ```ts const decoder = getBase10Decoder(); const value = decoder.decode(new Uint8Array([0x04, 0x00])); // "1024" ``` ## See [getBase10Codec](/api/functions/getBase10Codec) # getBase10Encoder (/api/functions/getBase10Encoder) ```ts function getBase10Encoder(): VariableSizeEncoder; ``` Returns an encoder for base-10 strings. This encoder serializes strings using a base-10 encoding scheme. The output consists of bytes representing the numerical values of the input string. For more details, see [getBase10Codec](/api/functions/getBase10Codec). ## Returns `VariableSizeEncoder`\<`string`> A `VariableSizeEncoder` for encoding base-10 strings. ## Example Encoding a base-10 string. ```ts const encoder = getBase10Encoder(); const bytes = encoder.encode('1024'); // 0x0400 ``` ## See [getBase10Codec](/api/functions/getBase10Codec) # getBase16Codec (/api/functions/getBase16Codec) ```ts function getBase16Codec(): VariableSizeCodec; ``` Returns a codec for encoding and decoding base-16 (hexadecimal) strings. This codec serializes strings using a base-16 encoding scheme. The output consists of bytes representing the hexadecimal values of the input string. ## Returns `VariableSizeCodec`\<`string`> A `VariableSizeCodec` for encoding and decoding base-16 strings. ## Example Encoding and decoding a base-16 string. ```ts const codec = getBase16Codec(); const bytes = codec.encode('deadface'); // 0xdeadface const value = codec.decode(bytes); // "deadface" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-16 codec, consider using fixCodecSize. ```ts const codec = fixCodecSize(getBase16Codec(), 8); ``` If you need a size-prefixed base-16 codec, consider using addCodecSizePrefix. ```ts const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec()); ``` Separate [getBase16Encoder](/api/functions/getBase16Encoder) and [getBase16Decoder](/api/functions/getBase16Decoder) functions are available. ```ts const bytes = getBase16Encoder().encode('deadface'); const value = getBase16Decoder().decode(bytes); ``` ## See * [getBase16Encoder](/api/functions/getBase16Encoder) * [getBase16Decoder](/api/functions/getBase16Decoder) # getBase16Decoder (/api/functions/getBase16Decoder) ```ts function getBase16Decoder(): VariableSizeDecoder; ``` Returns a decoder for base-16 (hexadecimal) strings. This decoder deserializes base-16 encoded strings from a byte array. For more details, see [getBase16Codec](/api/functions/getBase16Codec). ## Returns `VariableSizeDecoder`\<`string`> A `VariableSizeDecoder` for decoding base-16 strings. ## Example Decoding a base-16 string. ```ts const decoder = getBase16Decoder(); const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // "deadface" ``` ## See [getBase16Codec](/api/functions/getBase16Codec) # getBase16Encoder (/api/functions/getBase16Encoder) ```ts function getBase16Encoder(): VariableSizeEncoder; ``` Returns an encoder for base-16 (hexadecimal) strings. This encoder serializes strings using a base-16 encoding scheme. The output consists of bytes representing the hexadecimal values of the input string. For more details, see [getBase16Codec](/api/functions/getBase16Codec). ## Returns `VariableSizeEncoder`\<`string`> A `VariableSizeEncoder` for encoding base-16 strings. ## Example Encoding a base-16 string. ```ts const encoder = getBase16Encoder(); const bytes = encoder.encode('deadface'); // 0xdeadface ``` ## See [getBase16Codec](/api/functions/getBase16Codec) # getBase58Codec (/api/functions/getBase58Codec) ```ts function getBase58Codec(): VariableSizeCodec; ``` Returns a codec for encoding and decoding base-58 strings. This codec serializes strings using a base-58 encoding scheme, commonly used in cryptocurrency addresses and other compact representations. ## Returns `VariableSizeCodec`\<`string`> A `VariableSizeCodec` for encoding and decoding base-58 strings. ## Example Encoding and decoding a base-58 string. ```ts const codec = getBase58Codec(); const bytes = codec.encode('heLLo'); // 0x1b6a3070 const value = codec.decode(bytes); // "heLLo" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-58 codec, consider using fixCodecSize. ```ts const codec = fixCodecSize(getBase58Codec(), 8); ``` If you need a size-prefixed base-58 codec, consider using addCodecSizePrefix. ```ts const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec()); ``` Separate [getBase58Encoder](/api/functions/getBase58Encoder) and [getBase58Decoder](/api/functions/getBase58Decoder) functions are available. ```ts const bytes = getBase58Encoder().encode('heLLo'); const value = getBase58Decoder().decode(bytes); ``` ## See * [getBase58Encoder](/api/functions/getBase58Encoder) * [getBase58Decoder](/api/functions/getBase58Decoder) # getBase58Decoder (/api/functions/getBase58Decoder) ```ts function getBase58Decoder(): VariableSizeDecoder; ``` Returns a decoder for base-58 strings. This decoder deserializes base-58 encoded strings from a byte array. For more details, see [getBase58Codec](/api/functions/getBase58Codec). ## Returns `VariableSizeDecoder`\<`string`> A `VariableSizeDecoder` for decoding base-58 strings. ## Example Decoding a base-58 string. ```ts const decoder = getBase58Decoder(); const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // "heLLo" ``` ## See [getBase58Codec](/api/functions/getBase58Codec) # getBase58Encoder (/api/functions/getBase58Encoder) ```ts function getBase58Encoder(): VariableSizeEncoder; ``` Returns an encoder for base-58 strings. This encoder serializes strings using a base-58 encoding scheme, commonly used in cryptocurrency addresses and other compact representations. For more details, see [getBase58Codec](/api/functions/getBase58Codec). ## Returns `VariableSizeEncoder`\<`string`> A `VariableSizeEncoder` for encoding base-58 strings. ## Example Encoding a base-58 string. ```ts const encoder = getBase58Encoder(); const bytes = encoder.encode('heLLo'); // 0x1b6a3070 ``` ## See [getBase58Codec](/api/functions/getBase58Codec) # getBase64Codec (/api/functions/getBase64Codec) ```ts function getBase64Codec(): VariableSizeCodec; ``` Returns a codec for encoding and decoding base-64 strings. This codec serializes strings using a base-64 encoding scheme, commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding. ## Returns `VariableSizeCodec`\<`string`> A `VariableSizeCodec` for encoding and decoding base-64 strings. ## Example Encoding and decoding a base-64 string. ```ts const codec = getBase64Codec(); const bytes = codec.encode('hello+world'); // 0x85e965a3ec28ae57 const value = codec.decode(bytes); // "hello+world" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-64 codec, consider using fixCodecSize. ```ts const codec = fixCodecSize(getBase64Codec(), 8); ``` If you need a size-prefixed base-64 codec, consider using addCodecSizePrefix. ```ts const codec = addCodecSizePrefix(getBase64Codec(), getU32Codec()); ``` Separate [getBase64Encoder](/api/functions/getBase64Encoder) and [getBase64Decoder](/api/functions/getBase64Decoder) functions are available. ```ts const bytes = getBase64Encoder().encode('hello+world'); const value = getBase64Decoder().decode(bytes); ``` ## See * [getBase64Encoder](/api/functions/getBase64Encoder) * [getBase64Decoder](/api/functions/getBase64Decoder) # getBase64Decoder (/api/functions/getBase64Decoder) ```ts function getBase64Decoder(): VariableSizeDecoder; ``` Returns a decoder for base-64 strings. This decoder deserializes base-64 encoded strings from a byte array. For more details, see [getBase64Codec](/api/functions/getBase64Codec). ## Returns `VariableSizeDecoder`\<`string`> A `VariableSizeDecoder` for decoding base-64 strings. ## Example Decoding a base-64 string. ```ts const decoder = getBase64Decoder(); const value = decoder.decode(new Uint8Array([0x85, 0xe9, 0x65, 0xa3, 0xec, 0x28, 0xae, 0x57])); // "hello+world" ``` ## See [getBase64Codec](/api/functions/getBase64Codec) # getBase64EncodedWireTransaction (/api/functions/getBase64EncodedWireTransaction) ```ts function getBase64EncodedWireTransaction( transaction, ): Base64EncodedWireTransaction; ``` Given a signed transaction, this method returns the transaction as a string that conforms to the [Base64EncodedWireTransaction](/api/type-aliases/Base64EncodedWireTransaction) type. ## Parameters | Parameter | Type | | ------------- | ---------------------------------------------- | | `transaction` | [`Transaction`](/api/type-aliases/Transaction) | ## Returns [`Base64EncodedWireTransaction`](/api/type-aliases/Base64EncodedWireTransaction) ## Example ```ts import { getBase64EncodedWireTransaction, signTransaction } from '@solana/transactions'; const serializedTransaction = getBase64EncodedWireTransaction(signedTransaction); const signature = await rpc.sendTransaction(serializedTransaction, { encoding: 'base64' }).send(); ``` # getBase64Encoder (/api/functions/getBase64Encoder) ```ts function getBase64Encoder(): VariableSizeEncoder; ``` Returns an encoder for base-64 strings. This encoder serializes strings using a base-64 encoding scheme, commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding. For more details, see [getBase64Codec](/api/functions/getBase64Codec). ## Returns `VariableSizeEncoder`\<`string`> A `VariableSizeEncoder` for encoding base-64 strings. ## Example Encoding a base-64 string. ```ts const encoder = getBase64Encoder(); const bytes = encoder.encode('hello+world'); // 0x85e965a3ec28ae57 ``` ## See [getBase64Codec](/api/functions/getBase64Codec) # getBaseXCodec (/api/functions/getBaseXCodec) ```ts function getBaseXCodec(alphabet): VariableSizeCodec; ``` Returns a codec for encoding and decoding base-X strings. This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base. The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes. The decoding process reverses this transformation to reconstruct the original string. This codec supports leading zeroes by treating the first character of the alphabet as the zero character. ## Parameters | Parameter | Type | Description | | ---------- | -------- | --------------------------------------------------- | | `alphabet` | `string` | The set of characters defining the base-X encoding. | ## Returns `VariableSizeCodec`\<`string`> A `VariableSizeCodec` for encoding and decoding base-X strings. ## Example Encoding and decoding a base-X string using a custom alphabet. ```ts const codec = getBaseXCodec('0123456789abcdef'); const bytes = codec.encode('deadface'); // 0xdeadface const value = codec.decode(bytes); // "deadface" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-X codec, consider using fixCodecSize. ```ts const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8); ``` If you need a size-prefixed base-X codec, consider using addCodecSizePrefix. ```ts const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec()); ``` Separate [getBaseXEncoder](/api/functions/getBaseXEncoder) and [getBaseXDecoder](/api/functions/getBaseXDecoder) functions are available. ```ts const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface'); const value = getBaseXDecoder('0123456789abcdef').decode(bytes); ``` ## See * [getBaseXEncoder](/api/functions/getBaseXEncoder) * [getBaseXDecoder](/api/functions/getBaseXDecoder) # getBaseXDecoder (/api/functions/getBaseXDecoder) ```ts function getBaseXDecoder(alphabet): VariableSizeDecoder; ``` Returns a decoder for base-X encoded strings. This decoder deserializes base-X encoded strings from a byte array using a custom alphabet. The decoding process converts the byte array into a numeric value in base-10, then maps that value back to characters in the specified base-X alphabet. For more details, see [getBaseXCodec](/api/functions/getBaseXCodec). ## Parameters | Parameter | Type | Description | | ---------- | -------- | --------------------------------------------------- | | `alphabet` | `string` | The set of characters defining the base-X encoding. | ## Returns `VariableSizeDecoder`\<`string`> A `VariableSizeDecoder` for decoding base-X strings. ## Example Decoding a base-X string using a custom alphabet. ```ts const decoder = getBaseXDecoder('0123456789abcdef'); const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // "deadface" ``` ## See [getBaseXCodec](/api/functions/getBaseXCodec) # getBaseXEncoder (/api/functions/getBaseXEncoder) ```ts function getBaseXEncoder(alphabet): VariableSizeEncoder; ``` Returns an encoder for base-X encoded strings. This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base. The encoding process involves converting the input string to a numeric value in base-X, then encoding that value into bytes while preserving leading zeroes. For more details, see [getBaseXCodec](/api/functions/getBaseXCodec). ## Parameters | Parameter | Type | Description | | ---------- | -------- | --------------------------------------------------- | | `alphabet` | `string` | The set of characters defining the base-X encoding. | ## Returns `VariableSizeEncoder`\<`string`> A `VariableSizeEncoder` for encoding base-X strings. ## Example Encoding a base-X string using a custom alphabet. ```ts const encoder = getBaseXEncoder('0123456789abcdef'); const bytes = encoder.encode('deadface'); // 0xdeadface ``` ## See [getBaseXCodec](/api/functions/getBaseXCodec) # getBaseXResliceCodec (/api/functions/getBaseXResliceCodec) ```ts function getBaseXResliceCodec( alphabet, bits, ): VariableSizeCodec; ``` Returns a codec for encoding and decoding base-X strings using bit re-slicing. This codec serializes strings by dividing the input into custom-sized bit chunks, mapping them to a given alphabet, and encoding the result into bytes. It is particularly suited for encoding schemes where the alphabet's length is a power of 2, such as base-16 or base-64. ## Parameters | Parameter | Type | Description | | ---------- | -------- | ------------------------------------------------------------------------ | | `alphabet` | `string` | The set of characters defining the base-X encoding. | | `bits` | `number` | The number of bits per encoded chunk, typically `log2(alphabet.length)`. | ## Returns `VariableSizeCodec`\<`string`> A `VariableSizeCodec` for encoding and decoding base-X strings using bit re-slicing. ## Example Encoding and decoding a base-X string using bit re-slicing. ```ts const codec = getBaseXResliceCodec('elho', 2); const bytes = codec.encode('hellolol'); // 0x4aee const value = codec.decode(bytes); // "hellolol" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-X codec, consider using fixCodecSize. ```ts const codec = fixCodecSize(getBaseXResliceCodec('elho', 2), 8); ``` If you need a size-prefixed base-X codec, consider using addCodecSizePrefix. ```ts const codec = addCodecSizePrefix(getBaseXResliceCodec('elho', 2), getU32Codec()); ``` Separate [getBaseXResliceEncoder](/api/functions/getBaseXResliceEncoder) and [getBaseXResliceDecoder](/api/functions/getBaseXResliceDecoder) functions are available. ```ts const bytes = getBaseXResliceEncoder('elho', 2).encode('hellolol'); const value = getBaseXResliceDecoder('elho', 2).decode(bytes); ``` ## See * [getBaseXResliceEncoder](/api/functions/getBaseXResliceEncoder) * [getBaseXResliceDecoder](/api/functions/getBaseXResliceDecoder) # getBaseXResliceDecoder (/api/functions/getBaseXResliceDecoder) ```ts function getBaseXResliceDecoder( alphabet, bits, ): VariableSizeDecoder; ``` Returns a decoder for base-X encoded strings using bit re-slicing. This decoder deserializes base-X encoded strings by re-slicing the bits of a byte array into custom-sized chunks and mapping them to a specified alphabet. This is typically used for encoding schemes where the alphabet's length is a power of 2, such as base-16 or base-64. For more details, see [getBaseXResliceCodec](/api/functions/getBaseXResliceCodec). ## Parameters | Parameter | Type | Description | | ---------- | -------- | ------------------------------------------------------------------------ | | `alphabet` | `string` | The set of characters defining the base-X encoding. | | `bits` | `number` | The number of bits per encoded chunk, typically `log2(alphabet.length)`. | ## Returns `VariableSizeDecoder`\<`string`> A `VariableSizeDecoder` for decoding base-X strings using bit re-slicing. ## Example Decoding a base-X string using bit re-slicing. ```ts const decoder = getBaseXResliceDecoder('elho', 2); const value = decoder.decode(new Uint8Array([0x4a, 0xee])); // "hellolol" ``` ## See [getBaseXResliceCodec](/api/functions/getBaseXResliceCodec) # getBaseXResliceEncoder (/api/functions/getBaseXResliceEncoder) ```ts function getBaseXResliceEncoder( alphabet, bits, ): VariableSizeEncoder; ``` Returns an encoder for base-X encoded strings using bit re-slicing. This encoder serializes strings by dividing the input into custom-sized bit chunks, mapping them to an alphabet, and encoding the result into a byte array. This approach is commonly used for encoding schemes where the alphabet's length is a power of 2, such as base-16 or base-64. For more details, see [getBaseXResliceCodec](/api/functions/getBaseXResliceCodec). ## Parameters | Parameter | Type | Description | | ---------- | -------- | ------------------------------------------------------------------------ | | `alphabet` | `string` | The set of characters defining the base-X encoding. | | `bits` | `number` | The number of bits per encoded chunk, typically `log2(alphabet.length)`. | ## Returns `VariableSizeEncoder`\<`string`> A `VariableSizeEncoder` for encoding base-X strings using bit re-slicing. ## Example Encoding a base-X string using bit re-slicing. ```ts const encoder = getBaseXResliceEncoder('elho', 2); const bytes = encoder.encode('hellolol'); // 0x4aee ``` ## See [getBaseXResliceCodec](/api/functions/getBaseXResliceCodec) # getBigIntUpcastResponseTransformer (/api/functions/getBigIntUpcastResponseTransformer) ```ts function getBigIntUpcastResponseTransformer( allowedNumericKeyPaths, ): RpcResponseTransformer; ``` Returns a transformer that upcasts all `Number` values to `BigInts` unless they match within the provided [KeyPaths](/api/type-aliases/KeyPath). In other words, the provided [KeyPaths](/api/type-aliases/KeyPath) will remain as `Number` values, any other numeric value will be upcasted to a `BigInt`. Note that you can use [KEYPATH\_WILDCARD](/api/variables/KEYPATH_WILDCARD) to match any key within a [KeyPath](/api/type-aliases/KeyPath). ## Parameters | Parameter | Type | | ------------------------ | -------------------------------------------------- | | `allowedNumericKeyPaths` | readonly [`KeyPath`](/api/type-aliases/KeyPath)\[] | ## Returns `RpcResponseTransformer` ## Example ```ts import { getBigIntUpcastResponseTransformer } from '@solana/rpc-transformers'; const responseTransformer = getBigIntUpcastResponseTransformer([ ['index'], ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD], ['instructions', KEYPATH_WILDCARD, 'programIdIndex'], ['instructions', KEYPATH_WILDCARD, 'stackHeight'], ]); ``` # getBinaryFixedPointCodec (/api/functions/getBinaryFixedPointCodec) ```ts function getBinaryFixedPointCodec< TSignedness, TTotalBits, TFractionalBits, >( signedness, totalBits, fractionalBits, config?, ): FixedSizeCodec< BinaryFixedPoint, BinaryFixedPoint, BytesForTotalBits >; ``` Returns a codec for [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) values of a specific shape, combining [getBinaryFixedPointEncoder](/api/functions/getBinaryFixedPointEncoder) and [getBinaryFixedPointDecoder](/api/functions/getBinaryFixedPointDecoder). ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | ---------------- | ------------------------------------------------------------------ | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `fractionalBits` | `TFractionalBits` | | `config?` | [`FixedPointCodecConfig`](/api/type-aliases/FixedPointCodecConfig) | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<[`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`>, [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`>, `BytesForTotalBits`\<`TTotalBits`>> ## Example ```ts const codec = getBinaryFixedPointCodec('signed', 16, 15); const bytes = codec.encode(binaryFixedPoint('signed', 16, 15)('0.5')); const value = codec.decode(bytes); // represents 0.5 ``` ## See * [getBinaryFixedPointEncoder](/api/functions/getBinaryFixedPointEncoder) * [getBinaryFixedPointDecoder](/api/functions/getBinaryFixedPointDecoder) # getBinaryFixedPointDecoder (/api/functions/getBinaryFixedPointDecoder) ```ts function getBinaryFixedPointDecoder< TSignedness, TTotalBits, TFractionalBits, >( signedness, totalBits, fractionalBits, config?, ): FixedSizeDecoder< BinaryFixedPoint, BytesForTotalBits >; ``` Returns a decoder for [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) values of a specific shape. The decoder reads a fixed-size integer using two's-complement for signed values and little-endian byte order by default, and reconstructs a frozen [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) from the bytes. Throws `SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED` when `totalBits` is not a multiple of 8. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | ---------------- | ------------------------------------------------------------------ | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `fractionalBits` | `TFractionalBits` | | `config?` | [`FixedPointCodecConfig`](/api/type-aliases/FixedPointCodecConfig) | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<[`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`>, `BytesForTotalBits`\<`TTotalBits`>> ## Example ```ts const decoder = getBinaryFixedPointDecoder('signed', 16, 15); decoder.decode(new Uint8Array([0x00, 0x40])); // represents 0.5 ``` ## See * [getBinaryFixedPointEncoder](/api/functions/getBinaryFixedPointEncoder) * [getBinaryFixedPointCodec](/api/functions/getBinaryFixedPointCodec) # getBinaryFixedPointEncoder (/api/functions/getBinaryFixedPointEncoder) ```ts function getBinaryFixedPointEncoder< TSignedness, TTotalBits, TFractionalBits, >( signedness, totalBits, fractionalBits, config?, ): FixedSizeEncoder< BinaryFixedPoint, BytesForTotalBits >; ``` Returns an encoder for [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) values of a specific shape. The encoder serializes `value.raw` as a fixed-size integer using two's-complement for signed values and little-endian byte order by default. Throws `SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED` when `totalBits` is not a multiple of 8. Encoding a value whose shape does not match the codec's shape throws `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH`. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | ---------------- | ------------------------------------------------------------------ | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `fractionalBits` | `TFractionalBits` | | `config?` | [`FixedPointCodecConfig`](/api/type-aliases/FixedPointCodecConfig) | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<[`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`>, `BytesForTotalBits`\<`TTotalBits`>> ## Example ```ts const encoder = getBinaryFixedPointEncoder('signed', 16, 15); encoder.encode(binaryFixedPoint('signed', 16, 15)('0.5')); // 0x0040 ``` ## See * [getBinaryFixedPointDecoder](/api/functions/getBinaryFixedPointDecoder) * [getBinaryFixedPointCodec](/api/functions/getBinaryFixedPointCodec) # getBitArrayCodec (/api/functions/getBitArrayCodec) ```ts function getBitArrayCodec( size, config?, ): FixedSizeCodec; ``` Returns a codec that encodes and decodes boolean arrays as compact bit representations. This codec efficiently stores boolean arrays as bits, packing 8 values per byte. The `backward` config option determines whether bits are stored in MSB-first (`false`) or LSB-first (`true`). ## Type Parameters | Type Parameter | Description | | -------------------------- | ------------------------------------------------ | | `TSize` *extends* `number` | The number of bytes used to store the bit array. | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | `size` | `TSize` | The number of bytes allocated for the bit array (must be sufficient for the expected boolean count). | | `config?` | \| `boolean` \| [`BitArrayCodecConfig`](/api/type-aliases/BitArrayCodecConfig) | Configuration options for encoding and decoding the bit array. | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`boolean`\[], `boolean`\[], `TSize`> A `FixedSizeCodec` for encoding and decoding bit arrays. ## Examples Encoding and decoding a bit array. ```ts const codec = getBitArrayCodec(1); codec.encode([true, false, true, false, false, false, false, false]); // 0xa0 (0b10100000) codec.decode(new Uint8Array([0xa0])); // [true, false, true, false, false, false, false, false] ``` Encoding and decoding a bit array backwards. ```ts const codec = getBitArrayCodec(1, { backward: true }); codec.encode([true, false, true, false, false, false, false, false]); // 0x05 (0b00000101) codec.decode(new Uint8Array([0x05])); // [true, false, true, false, false, false, false, false] ``` ## Remarks Separate [getBitArrayEncoder](/api/functions/getBitArrayEncoder) and [getBitArrayDecoder](/api/functions/getBitArrayDecoder) functions are available. ```ts const bytes = getBitArrayEncoder(1).encode([true, false, true, false]); const value = getBitArrayDecoder(1).decode(bytes); ``` ## See * [getBitArrayEncoder](/api/functions/getBitArrayEncoder) * [getBitArrayDecoder](/api/functions/getBitArrayDecoder) # getBitArrayDecoder (/api/functions/getBitArrayDecoder) ```ts function getBitArrayDecoder( size, config?, ): FixedSizeDecoder; ``` Returns a decoder that unpacks bits into an array of booleans. This decoder converts a compact bit representation back into a list of `boolean` values. Each byte is expanded into 8 booleans. The `backward` config option determines whether the bits are read in MSB-first (`false`) or LSB-first (`true`). For more details, see [getBitArrayCodec](/api/functions/getBitArrayCodec). ## Type Parameters | Type Parameter | Description | | -------------------------- | ------------------------------------------------ | | `TSize` *extends* `number` | The number of bytes used to store the bit array. | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | `size` | `TSize` | The number of bytes allocated for the bit array (must be sufficient for the expected boolean count). | | `config?` | \| `boolean` \| [`BitArrayCodecConfig`](/api/type-aliases/BitArrayCodecConfig) | Configuration options for decoding the bit array. | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`boolean`\[], `TSize`> A `FixedSizeDecoder` for decoding bit arrays. ## Example Decoding a bit array. ```ts const decoder = getBitArrayDecoder(1); decoder.decode(new Uint8Array([0xa0])); // [true, false, true, false, false, false, false, false] ``` ## See [getBitArrayCodec](/api/functions/getBitArrayCodec) # getBitArrayEncoder (/api/functions/getBitArrayEncoder) ```ts function getBitArrayEncoder( size, config?, ): FixedSizeEncoder; ``` Returns an encoder that packs an array of booleans into bits. This encoder converts a list of `boolean` values into a compact bit representation, storing 8 booleans per byte. The `backward` config option determines whether the bits are stored in MSB-first (`false`) or LSB-first (`true`). For more details, see [getBitArrayCodec](/api/functions/getBitArrayCodec). ## Type Parameters | Type Parameter | Description | | -------------------------- | ------------------------------------------------ | | `TSize` *extends* `number` | The number of bytes used to store the bit array. | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | `size` | `TSize` | The number of bytes allocated for the bit array (must be sufficient for the expected boolean count). | | `config?` | \| `boolean` \| [`BitArrayCodecConfig`](/api/type-aliases/BitArrayCodecConfig) | Configuration options for encoding the bit array. | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`boolean`\[], `TSize`> A `FixedSizeEncoder` for encoding bit arrays. ## Example Encoding a bit array. ```ts const encoder = getBitArrayEncoder(1); encoder.encode([true, false, true, false, false, false, false, false]); // 0xa0 (0b10100000) ``` ## See [getBitArrayCodec](/api/functions/getBitArrayCodec) # getBlockhashCodec (/api/functions/getBlockhashCodec) ```ts function getBlockhashCodec(): FixedSizeCodec; ``` Returns a codec that you can use to encode from or decode to a base-58 encoded blockhash. ## Returns `FixedSizeCodec`\<[`Blockhash`](/api/type-aliases/Blockhash), [`Blockhash`](/api/type-aliases/Blockhash), `32`> ## See * [getBlockhashDecoder](/api/functions/getBlockhashDecoder) * [getBlockhashEncoder](/api/functions/getBlockhashEncoder) # getBlockhashComparator (/api/functions/getBlockhashComparator) ```ts function getBlockhashComparator(): (x, y) => number; ``` ## Returns (`x`, `y`) => `number` # getBlockhashDecoder (/api/functions/getBlockhashDecoder) ```ts function getBlockhashDecoder(): FixedSizeDecoder; ``` Returns a decoder that you can use to convert an array of 32 bytes representing a blockhash to the base58-encoded representation of that blockhash. ## Returns `FixedSizeDecoder`\<[`Blockhash`](/api/type-aliases/Blockhash), `32`> ## Example ```ts import { getBlockhashDecoder } from '@solana/rpc-types'; const blockhashBytes = new Uint8Array([ 136, 123, 44, 249, 43, 19, 60, 14, 144, 16, 168, 241, 121, 111, 70, 232, 186, 26, 140, 202, 213, 64, 231, 82, 179, 66, 103, 237, 52, 117, 217, 93 ]); const blockhashDecoder = getBlockhashDecoder(); const blockhash = blockhashDecoder.decode(blockhashBytes); // ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48 ``` # getBlockhashEncoder (/api/functions/getBlockhashEncoder) ```ts function getBlockhashEncoder(): FixedSizeEncoder; ``` Returns an encoder that you can use to encode a base58-encoded blockhash to a byte array. ## Returns `FixedSizeEncoder`\<[`Blockhash`](/api/type-aliases/Blockhash), `32`> ## Example ```ts import { getBlockhashEncoder } from '@solana/rpc-types'; const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash; const blockhashEncoder = getBlockhashEncoder(); const blockhashBytes = blockhashEncoder.encode(blockhash); // Uint8Array(32) [ // 136, 123, 44, 249, 43, 19, 60, 14, // 144, 16, 168, 241, 121, 111, 70, 232, // 186, 26, 140, 202, 213, 64, 231, 82, // 179, 66, 103, 237, 52, 117, 217, 93 // ] ``` # getBooleanCodec (/api/functions/getBooleanCodec) ## Call Signature ```ts function getBooleanCodec(): FixedSizeCodec; ``` Returns a codec for encoding and decoding boolean values. By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`). The `size` option allows customizing the number codec used for storage. ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`boolean`, `boolean`, `1`> A `FixedSizeCodec` where `N` is the size of the number codec. ### Examples Encoding and decoding booleans using a `u8` (default). ```ts const codec = getBooleanCodec(); codec.encode(false); // 0x00 codec.encode(true); // 0x01 codec.decode(new Uint8Array([0x00])); // false codec.decode(new Uint8Array([0x01])); // true ``` Encoding and decoding booleans using a custom number codec. ```ts const codec = getBooleanCodec({ size: getU16Codec() }); codec.encode(false); // 0x0000 codec.encode(true); // 0x0100 codec.decode(new Uint8Array([0x00, 0x00])); // false codec.decode(new Uint8Array([0x01, 0x00])); // true ``` ### Remarks Separate [getBooleanEncoder](/api/functions/getBooleanEncoder) and [getBooleanDecoder](/api/functions/getBooleanDecoder) functions are available. ```ts const bytes = getBooleanEncoder().encode(true); const value = getBooleanDecoder().decode(bytes); ``` ### See * [getBooleanEncoder](/api/functions/getBooleanEncoder) * [getBooleanDecoder](/api/functions/getBooleanDecoder) ## Call Signature ```ts function getBooleanCodec( config, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding boolean values. By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`). The `size` option allows customizing the number codec used for storage. ### Type Parameters | Type Parameter | | -------------------------- | | `TSize` *extends* `number` | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | | `config` | [`BooleanCodecConfig`](/api/type-aliases/BooleanCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Configuration options for encoding and decoding booleans. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`boolean`, `boolean`, `TSize`> A `FixedSizeCodec` where `N` is the size of the number codec. ### Examples Encoding and decoding booleans using a `u8` (default). ```ts const codec = getBooleanCodec(); codec.encode(false); // 0x00 codec.encode(true); // 0x01 codec.decode(new Uint8Array([0x00])); // false codec.decode(new Uint8Array([0x01])); // true ``` Encoding and decoding booleans using a custom number codec. ```ts const codec = getBooleanCodec({ size: getU16Codec() }); codec.encode(false); // 0x0000 codec.encode(true); // 0x0100 codec.decode(new Uint8Array([0x00, 0x00])); // false codec.decode(new Uint8Array([0x01, 0x00])); // true ``` ### Remarks Separate [getBooleanEncoder](/api/functions/getBooleanEncoder) and [getBooleanDecoder](/api/functions/getBooleanDecoder) functions are available. ```ts const bytes = getBooleanEncoder().encode(true); const value = getBooleanDecoder().decode(bytes); ``` ### See * [getBooleanEncoder](/api/functions/getBooleanEncoder) * [getBooleanDecoder](/api/functions/getBooleanDecoder) ## Call Signature ```ts function getBooleanCodec(config): VariableSizeCodec; ``` Returns a codec for encoding and decoding boolean values. By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`). The `size` option allows customizing the number codec used for storage. ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | `config` | [`BooleanCodecConfig`](/api/type-aliases/BooleanCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> | Configuration options for encoding and decoding booleans. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`boolean`> A `FixedSizeCodec` where `N` is the size of the number codec. ### Examples Encoding and decoding booleans using a `u8` (default). ```ts const codec = getBooleanCodec(); codec.encode(false); // 0x00 codec.encode(true); // 0x01 codec.decode(new Uint8Array([0x00])); // false codec.decode(new Uint8Array([0x01])); // true ``` Encoding and decoding booleans using a custom number codec. ```ts const codec = getBooleanCodec({ size: getU16Codec() }); codec.encode(false); // 0x0000 codec.encode(true); // 0x0100 codec.decode(new Uint8Array([0x00, 0x00])); // false codec.decode(new Uint8Array([0x01, 0x00])); // true ``` ### Remarks Separate [getBooleanEncoder](/api/functions/getBooleanEncoder) and [getBooleanDecoder](/api/functions/getBooleanDecoder) functions are available. ```ts const bytes = getBooleanEncoder().encode(true); const value = getBooleanDecoder().decode(bytes); ``` ### See * [getBooleanEncoder](/api/functions/getBooleanEncoder) * [getBooleanDecoder](/api/functions/getBooleanDecoder) # getBooleanDecoder (/api/functions/getBooleanDecoder) ## Call Signature ```ts function getBooleanDecoder(): FixedSizeDecoder; ``` Returns a decoder for boolean values. This decoder reads a number and interprets `1` as `true` and `0` as `false`. The `size` option allows customizing the number codec used for storage. For more details, see [getBooleanCodec](/api/functions/getBooleanCodec). ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`boolean`, `1`> A `FixedSizeDecoder` where `N` is the size of the number codec. ### Example Decoding booleans. ```ts const decoder = getBooleanDecoder(); decoder.decode(new Uint8Array([0x00])); // false decoder.decode(new Uint8Array([0x01])); // true ``` ### See [getBooleanCodec](/api/functions/getBooleanCodec) ## Call Signature ```ts function getBooleanDecoder( config, ): FixedSizeDecoder; ``` Returns a decoder for boolean values. This decoder reads a number and interprets `1` as `true` and `0` as `false`. The `size` option allows customizing the number codec used for storage. For more details, see [getBooleanCodec](/api/functions/getBooleanCodec). ### Type Parameters | Type Parameter | | -------------------------- | | `TSize` *extends* `number` | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `config` | [`BooleanCodecConfig`](/api/type-aliases/BooleanCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Configuration options for decoding booleans. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`boolean`, `TSize`> A `FixedSizeDecoder` where `N` is the size of the number codec. ### Example Decoding booleans. ```ts const decoder = getBooleanDecoder(); decoder.decode(new Uint8Array([0x00])); // false decoder.decode(new Uint8Array([0x01])); // true ``` ### See [getBooleanCodec](/api/functions/getBooleanCodec) ## Call Signature ```ts function getBooleanDecoder(config): VariableSizeDecoder; ``` Returns a decoder for boolean values. This decoder reads a number and interprets `1` as `true` and `0` as `false`. The `size` option allows customizing the number codec used for storage. For more details, see [getBooleanCodec](/api/functions/getBooleanCodec). ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `config` | [`BooleanCodecConfig`](/api/type-aliases/BooleanCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> | Configuration options for decoding booleans. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`boolean`> A `FixedSizeDecoder` where `N` is the size of the number codec. ### Example Decoding booleans. ```ts const decoder = getBooleanDecoder(); decoder.decode(new Uint8Array([0x00])); // false decoder.decode(new Uint8Array([0x01])); // true ``` ### See [getBooleanCodec](/api/functions/getBooleanCodec) # getBooleanEncoder (/api/functions/getBooleanEncoder) ## Call Signature ```ts function getBooleanEncoder(): FixedSizeEncoder; ``` Returns an encoder for boolean values. This encoder converts `true` into `1` and `false` into `0`. The `size` option allows customizing the number codec used for storage. For more details, see [getBooleanCodec](/api/functions/getBooleanCodec). ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`boolean`, `1`> A `FixedSizeEncoder` where `N` is the size of the number codec. ### Example Encoding booleans. ```ts const encoder = getBooleanEncoder(); encoder.encode(false); // 0x00 encoder.encode(true); // 0x01 ``` ### See [getBooleanCodec](/api/functions/getBooleanCodec) ## Call Signature ```ts function getBooleanEncoder( config, ): FixedSizeEncoder; ``` Returns an encoder for boolean values. This encoder converts `true` into `1` and `false` into `0`. The `size` option allows customizing the number codec used for storage. For more details, see [getBooleanCodec](/api/functions/getBooleanCodec). ### Type Parameters | Type Parameter | | -------------------------- | | `TSize` *extends* `number` | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `config` | [`BooleanCodecConfig`](/api/type-aliases/BooleanCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Configuration options for encoding booleans. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`boolean`, `TSize`> A `FixedSizeEncoder` where `N` is the size of the number codec. ### Example Encoding booleans. ```ts const encoder = getBooleanEncoder(); encoder.encode(false); // 0x00 encoder.encode(true); // 0x01 ``` ### See [getBooleanCodec](/api/functions/getBooleanCodec) ## Call Signature ```ts function getBooleanEncoder(config): VariableSizeEncoder; ``` Returns an encoder for boolean values. This encoder converts `true` into `1` and `false` into `0`. The `size` option allows customizing the number codec used for storage. For more details, see [getBooleanCodec](/api/functions/getBooleanCodec). ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `config` | [`BooleanCodecConfig`](/api/type-aliases/BooleanCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> | Configuration options for encoding booleans. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`boolean`> A `FixedSizeEncoder` where `N` is the size of the number codec. ### Example Encoding booleans. ```ts const encoder = getBooleanEncoder(); encoder.encode(false); // 0x00 encoder.encode(true); // 0x01 ``` ### See [getBooleanCodec](/api/functions/getBooleanCodec) # getBytesCodec (/api/functions/getBytesCodec) ```ts function getBytesCodec(): VariableSizeCodec< ReadonlyUint8Array | Uint8Array, ReadonlyUint8Array >; ``` Returns a codec for encoding and decoding raw byte arrays. This codec serializes and deserializes byte arrays without modification. The size of the encoded and decoded byte array is determined dynamically. This means, when reading, the codec will consume all remaining bytes in the input. * To enforce a fixed size, consider using [fixCodecSize](/api/functions/fixCodecSize). * To add a size prefix, use [addCodecSizePrefix](/api/functions/addCodecSizePrefix). * To add a sentinel value, use [addCodecSentinel](/api/functions/addCodecSentinel). ## Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\< \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`>, [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`>> A `VariableSizeCodec`. ## Example Encoding and decoding a byte array. ```ts const codec = getBytesCodec(); codec.encode(new Uint8Array([1, 2, 3])); // 0x010203 codec.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127]) ``` ## Remarks Separate [getBytesEncoder](/api/functions/getBytesEncoder) and [getBytesDecoder](/api/functions/getBytesDecoder) functions are available. ```ts const bytes = getBytesEncoder().encode(new Uint8Array([1, 2, 3])); const value = getBytesDecoder().decode(bytes); ``` ## See * [getBytesEncoder](/api/functions/getBytesEncoder) * [getBytesDecoder](/api/functions/getBytesDecoder) # getBytesDecoder (/api/functions/getBytesDecoder) ```ts function getBytesDecoder(): VariableSizeDecoder< ReadonlyUint8Array >; ``` Returns a decoder for raw byte arrays. This decoder reads byte arrays exactly as provided without modification. The decoded byte array extends from the provided offset to the end of the input. * To enforce a fixed size, consider using [fixDecoderSize](/api/functions/fixDecoderSize). * To add a size prefix, use [addDecoderSizePrefix](/api/functions/addDecoderSizePrefix). * To add a sentinel value, use [addDecoderSentinel](/api/functions/addDecoderSentinel). For more details, see [getBytesCodec](/api/functions/getBytesCodec). ## Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<[`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`>> A `VariableSizeDecoder`. ## Example Decoding a byte array as-is. ```ts const decoder = getBytesDecoder(); decoder.decode(new Uint8Array([1, 2, 3])); // Uint8Array([1, 2, 3]) decoder.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127]) ``` ## See [getBytesCodec](/api/functions/getBytesCodec) # getBytesEncoder (/api/functions/getBytesEncoder) ```ts function getBytesEncoder(): VariableSizeEncoder< ReadonlyUint8Array | Uint8Array >; ``` Returns an encoder for raw byte arrays. This encoder writes byte arrays exactly as provided without modification. The size of the encoded byte array is determined by the length of the input. * To enforce a fixed size, consider using [fixEncoderSize](/api/functions/fixEncoderSize). * To add a size prefix, use [addEncoderSizePrefix](/api/functions/addEncoderSizePrefix). * To add a sentinel value, use [addEncoderSentinel](/api/functions/addEncoderSentinel). For more details, see [getBytesCodec](/api/functions/getBytesCodec). ## Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\< \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`>> A `VariableSizeEncoder`. ## Example Encoding a byte array as-is. ```ts const encoder = getBytesEncoder(); encoder.encode(new Uint8Array([1, 2, 3])); // 0x010203 encoder.encode(new Uint8Array([255, 0, 127])); // 0xff007f ``` ## See [getBytesCodec](/api/functions/getBytesCodec) # getChannelPoolingChannelCreator (/api/functions/getChannelPoolingChannelCreator) ```ts function getChannelPoolingChannelCreator( createChannel, __namedParameters, ): TChannelCreator; ``` Given a channel creator, will return a new channel creator with the following behavior. 1. When called, returns a [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel). Adds that channel to a pool. 2. When called again, creates and returns new RpcSubscriptionChannel | RpcSubscriptionChannels up to the number specified by `minChannels`. 3. When `minChannels` channels have been created, subsequent calls vend whichever existing channel from the pool has the fewest subscribers, or the next one in rotation in the event of a tie. 4. Once all channels carry the number of subscribers specified by the number `maxSubscriptionsPerChannel`, new channels in excess of `minChannel` will be created, returned, and added to the pool. 5. A channel will be destroyed once all of its subscribers' abort signals fire. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------------------------------------------------------------- | | `TChannelCreator` *extends* [`RpcSubscriptionsChannelCreator`](/api/type-aliases/RpcSubscriptionsChannelCreator)\<`unknown`, `unknown`> | ## Parameters | Parameter | Type | | ------------------- | ----------------- | | `createChannel` | `TChannelCreator` | | `__namedParameters` | `Config` | ## Returns `TChannelCreator` # getCompiledTransactionMessageCodec (/api/functions/getCompiledTransactionMessageCodec) ```ts function getCompiledTransactionMessageCodec(): VariableSizeCodec< | CompiledTransactionMessage | (CompiledTransactionMessage & Readonly<{ lifetimeToken: string }>), CompiledTransactionMessage & Readonly<{ lifetimeToken: string; }> >; ``` Returns a codec that you can use to encode from or decode to [CompiledTransactionMessage](/api/type-aliases/CompiledTransactionMessage) ## Returns `VariableSizeCodec`\< \| [`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage) \| CompiledTransactionMessage & Readonly\<\{ lifetimeToken: string; }>, [`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }>> ## See * [getCompiledTransactionMessageDecoder](/api/functions/getCompiledTransactionMessageDecoder) * [getCompiledTransactionMessageEncoder](/api/functions/getCompiledTransactionMessageEncoder) # getCompiledTransactionMessageDecoder (/api/functions/getCompiledTransactionMessageDecoder) ```ts function getCompiledTransactionMessageDecoder(): VariableSizeDecoder< CompiledTransactionMessage & Readonly<{ lifetimeToken: string; }> >; ``` Returns a decoder that you can use to decode a byte array representing a [CompiledTransactionMessage](/api/type-aliases/CompiledTransactionMessage). The wire format of a Solana transaction consists of signatures followed by a compiled transaction message. You can use this decoder to decode the message part. ## Returns `VariableSizeDecoder`\<[`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage) & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }>> # getCompiledTransactionMessageEncoder (/api/functions/getCompiledTransactionMessageEncoder) ```ts function getCompiledTransactionMessageEncoder(): VariableSizeEncoder< | CompiledTransactionMessage | (CompiledTransactionMessage & Readonly<{ lifetimeToken: string }>) >; ``` Returns an encoder that you can use to encode a [CompiledTransactionMessage](/api/type-aliases/CompiledTransactionMessage) to a byte array. The wire format of a Solana transaction consists of signatures followed by a compiled transaction message. The byte array produced by this encoder is the message part. ## Returns `VariableSizeEncoder`\< \| [`CompiledTransactionMessage`](/api/type-aliases/CompiledTransactionMessage) \| CompiledTransactionMessage & Readonly\<\{ lifetimeToken: string; }>> # getConstantCodec (/api/functions/getConstantCodec) ```ts function getConstantCodec( constant, ): FixedSizeCodec; ``` Returns a codec that encodes and decodes a predefined constant byte sequence. * **Encoding:** Always writes the specified byte array. * **Decoding:** Asserts that the next bytes match the constant, throwing an error if they do not. This is useful for encoding fixed byte patterns required in a binary format or to use in conjunction with other codecs such as [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec) or [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec). ## Type Parameters | Type Parameter | Description | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | `TConstant` *extends* [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | The fixed byte sequence to encode and verify during decoding. | ## Parameters | Parameter | Type | Description | | ---------- | ----------- | --------------------------------------------------------------- | | `constant` | `TConstant` | The predefined byte array to encode and assert during decoding. | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`void`, `void`, `TConstant`\[`"length"`]> A `FixedSizeCodec` where `N` is the length of the constant. ## Example Encoding and decoding a constant magic number. ```ts const codec = getConstantCodec(new Uint8Array([1, 2, 3])); codec.encode(); // 0x010203 codec.decode(new Uint8Array([1, 2, 3])); // Passes codec.decode(new Uint8Array([1, 2, 4])); // Throws an error ``` ## Remarks Separate [getConstantEncoder](/api/functions/getConstantEncoder) and [getConstantDecoder](/api/functions/getConstantDecoder) functions are available. ```ts const bytes = getConstantEncoder(new Uint8Array([1, 2, 3])).encode(); getConstantDecoder(new Uint8Array([1, 2, 3])).decode(bytes); ``` ## See * [getConstantEncoder](/api/functions/getConstantEncoder) * [getConstantDecoder](/api/functions/getConstantDecoder) # getConstantDecoder (/api/functions/getConstantDecoder) ```ts function getConstantDecoder( constant, ): FixedSizeDecoder; ``` Returns a decoder that verifies a predefined constant byte sequence. This decoder reads the next bytes and checks that they match the provided constant. If the bytes differ, it throws an error. For more details, see [getConstantCodec](/api/functions/getConstantCodec). ## Type Parameters | Type Parameter | Description | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------- | | `TConstant` *extends* [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | The fixed byte sequence expected during decoding. | ## Parameters | Parameter | Type | Description | | ---------- | ----------- | ------------------------------------ | | `constant` | `TConstant` | The predefined byte array to verify. | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`void`, `TConstant`\[`"length"`]> A `FixedSizeDecoder` where `N` is the length of the constant. ## Example Decoding a constant magic number. ```ts const decoder = getConstantDecoder(new Uint8Array([1, 2, 3])); decoder.decode(new Uint8Array([1, 2, 3])); // Passes decoder.decode(new Uint8Array([1, 2, 4])); // Throws an error ``` ## See [getConstantCodec](/api/functions/getConstantCodec) # getConstantEncoder (/api/functions/getConstantEncoder) ```ts function getConstantEncoder( constant, ): FixedSizeEncoder; ``` Returns an encoder that always writes a predefined constant byte sequence. This encoder ensures that encoding always produces the specified byte array, ignoring any input values. For more details, see [getConstantCodec](/api/functions/getConstantCodec). ## Type Parameters | Type Parameter | Description | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | `TConstant` *extends* [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | The fixed byte sequence that will be written during encoding. | ## Parameters | Parameter | Type | Description | | ---------- | ----------- | ------------------------------------ | | `constant` | `TConstant` | The predefined byte array to encode. | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`void`, `TConstant`\[`"length"`]> A `FixedSizeEncoder` where `N` is the length of the constant. ## Example Encoding a constant magic number. ```ts const encoder = getConstantEncoder(new Uint8Array([1, 2, 3, 4])); const bytes = encoder.encode(); // 0x01020304 // β””β”€β”€β”€β”€β”€β”€β”˜ The predefined 4-byte constant. ``` ## See [getConstantCodec](/api/functions/getConstantCodec) # getDataPublisherFromEventEmitter (/api/functions/getDataPublisherFromEventEmitter) ```ts function getDataPublisherFromEventEmitter( eventEmitter, ): DataPublisher<{ [TEventType in | string | number | symbol]: TEventMap[TEventType] extends CustomEvent ? any[any]['detail'] : null; }>; ``` Returns an object with an `on` function that you can call to subscribe to certain data over a named channel. The `on` function returns an unsubscribe function. ## Type Parameters | Type Parameter | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TEventMap` *extends* [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Event`](https://developer.mozilla.org/docs/Web/API/Event)> | ## Parameters | Parameter | Type | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `eventEmitter` | \| [`TypedEventEmitter`](/api/interfaces/TypedEventEmitter)\<`TEventMap`> \| [`TypedEventTarget`](/api/interfaces/TypedEventTarget)\<`TEventMap`> | ## Returns [`DataPublisher`](/api/interfaces/DataPublisher)\<\{ \[TEventType in string | number | symbol]: TEventMap\[TEventType] extends CustomEvent\ ? any\[any]\["detail"] : null }> ## Example ```ts const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com')); const unsubscribe = socketDataPublisher.on('message', message => { if (JSON.parse(message.data).id === 42) { console.log('Got response 42'); unsubscribe(); } }); ``` # getDecimalFixedPointCodec (/api/functions/getDecimalFixedPointCodec) ```ts function getDecimalFixedPointCodec( signedness, totalBits, decimals, config?, ): FixedSizeCodec< DecimalFixedPoint, DecimalFixedPoint, BytesForTotalBits >; ``` Returns a codec for [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) values of a specific shape, combining [getDecimalFixedPointEncoder](/api/functions/getDecimalFixedPointEncoder) and [getDecimalFixedPointDecoder](/api/functions/getDecimalFixedPointDecoder). ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | ------------ | ------------------------------------------------------------------ | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `decimals` | `TDecimals` | | `config?` | [`FixedPointCodecConfig`](/api/type-aliases/FixedPointCodecConfig) | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<[`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`>, [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`>, `BytesForTotalBits`\<`TTotalBits`>> ## Example ```ts const codec = getDecimalFixedPointCodec('unsigned', 64, 6); const bytes = codec.encode(decimalFixedPoint('unsigned', 64, 6)('42.5')); const value = codec.decode(bytes); // represents 42.5 ``` ## See * [getDecimalFixedPointEncoder](/api/functions/getDecimalFixedPointEncoder) * [getDecimalFixedPointDecoder](/api/functions/getDecimalFixedPointDecoder) # getDecimalFixedPointDecoder (/api/functions/getDecimalFixedPointDecoder) ```ts function getDecimalFixedPointDecoder< TSignedness, TTotalBits, TDecimals, >( signedness, totalBits, decimals, config?, ): FixedSizeDecoder< DecimalFixedPoint, BytesForTotalBits >; ``` Returns a decoder for [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) values of a specific shape. The decoder reads a fixed-size integer using two's-complement for signed values and little-endian byte order by default, and reconstructs a frozen [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) from the bytes. Throws `SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED` when `totalBits` is not a multiple of 8. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | ------------ | ------------------------------------------------------------------ | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `decimals` | `TDecimals` | | `config?` | [`FixedPointCodecConfig`](/api/type-aliases/FixedPointCodecConfig) | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<[`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`>, `BytesForTotalBits`\<`TTotalBits`>> ## Example ```ts const decoder = getDecimalFixedPointDecoder('unsigned', 64, 6); decoder.decode(bytes); // represents 42.5 for appropriately encoded bytes ``` ## See * [getDecimalFixedPointEncoder](/api/functions/getDecimalFixedPointEncoder) * [getDecimalFixedPointCodec](/api/functions/getDecimalFixedPointCodec) # getDecimalFixedPointEncoder (/api/functions/getDecimalFixedPointEncoder) ```ts function getDecimalFixedPointEncoder< TSignedness, TTotalBits, TDecimals, >( signedness, totalBits, decimals, config?, ): FixedSizeEncoder< DecimalFixedPoint, BytesForTotalBits >; ``` Returns an encoder for [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) values of a specific shape. The encoder serializes `value.raw` as a fixed-size integer using two's-complement for signed values and little-endian byte order by default. Throws `SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED` when `totalBits` is not a multiple of 8. Encoding a value whose shape does not match the codec's shape throws `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH`. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | ------------ | ------------------------------------------------------------------ | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `decimals` | `TDecimals` | | `config?` | [`FixedPointCodecConfig`](/api/type-aliases/FixedPointCodecConfig) | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<[`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`>, `BytesForTotalBits`\<`TTotalBits`>> ## Example ```ts const encoder = getDecimalFixedPointEncoder('unsigned', 64, 6); encoder.encode(decimalFixedPoint('unsigned', 64, 6)('42.5')); ``` ## See * [getDecimalFixedPointDecoder](/api/functions/getDecimalFixedPointDecoder) * [getDecimalFixedPointCodec](/api/functions/getDecimalFixedPointCodec) # getDefaultCommitmentRequestTransformer (/api/functions/getDefaultCommitmentRequestTransformer) ```ts function getDefaultCommitmentRequestTransformer( config, ): RpcRequestTransformer; ``` Creates a transformer that adds the provided default commitment to the configuration object of the request when applicable. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | `config` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `defaultCommitment?`: `Commitment`; `optionsObjectPositionByMethod`: [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `number`>; }> | - | ## Returns `RpcRequestTransformer` ## Example ```ts import { getDefaultCommitmentRequestTransformer, OPTIONS_OBJECT_POSITION_BY_METHOD } from '@solana/rpc-transformers'; const requestTransformer = getDefaultCommitmentRequestTransformer({ defaultCommitment: 'confirmed', optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD, }); ``` # getDefaultLamportsCodec (/api/functions/getDefaultLamportsCodec) ```ts function getDefaultLamportsCodec(): FixedSizeCodec< Sol | Lamports, Lamports, 8 >; ``` Returns a codec that you can use to encode from or decode to a 64-bit [Lamports](/api/type-aliases/Lamports) value. The encoder also accepts a [Sol](/api/type-aliases/Sol) fixed-point value; the decoder always returns [Lamports](/api/type-aliases/Lamports). ## Returns `FixedSizeCodec`\< \| [`Sol`](/api/type-aliases/Sol) \| [`Lamports`](/api/type-aliases/Lamports), [`Lamports`](/api/type-aliases/Lamports), `8`> ## See * [getDefaultLamportsDecoder](/api/functions/getDefaultLamportsDecoder) * [getDefaultLamportsEncoder](/api/functions/getDefaultLamportsEncoder) # getDefaultLamportsDecoder (/api/functions/getDefaultLamportsDecoder) ```ts function getDefaultLamportsDecoder(): FixedSizeDecoder; ``` Returns a decoder that you can use to decode a byte array representing a 64-bit little endian number to a [Lamports](/api/type-aliases/Lamports) value. ## Returns `FixedSizeDecoder`\<[`Lamports`](/api/type-aliases/Lamports), `8`> # getDefaultLamportsEncoder (/api/functions/getDefaultLamportsEncoder) ```ts function getDefaultLamportsEncoder(): FixedSizeEncoder< Sol | Lamports, 8 >; ``` Returns an encoder that you can use to encode a 64-bit [Lamports](/api/type-aliases/Lamports) value to 8 bytes in little endian order. The encoder also accepts a [Sol](/api/type-aliases/Sol) fixed-point value. ## Returns `FixedSizeEncoder`\< \| [`Sol`](/api/type-aliases/Sol) \| [`Lamports`](/api/type-aliases/Lamports), `8`> # getDefaultRequestTransformerForSolanaRpc (/api/functions/getDefaultRequestTransformerForSolanaRpc) ```ts function getDefaultRequestTransformerForSolanaRpc( config?, ): RpcRequestTransformer; ``` Returns the default request transformer for the Solana RPC API. Under the hood, this function composes multiple RpcRequestTransformer | RpcRequestTransformers together such as the getDefaultCommitmentTransformer and the [getIntegerOverflowRequestTransformer](/api/functions/getIntegerOverflowRequestTransformer). ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `defaultCommitment?`: `Commitment`; `onIntegerOverflow?`: [`IntegerOverflowHandler`](/api/type-aliases/IntegerOverflowHandler); }> | ## Returns `RpcRequestTransformer` ## Example ```ts import { getDefaultRequestTransformerForSolanaRpc } from '@solana/rpc-transformers'; const requestTransformer = getDefaultRequestTransformerForSolanaRpc({ defaultCommitment: 'confirmed', onIntegerOverflow: (request, keyPath, value) => { throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`); }, }); ``` # getDefaultResponseTransformerForSolanaRpc (/api/functions/getDefaultResponseTransformerForSolanaRpc) ```ts function getDefaultResponseTransformerForSolanaRpc( config?, ): RpcResponseTransformer; ``` Returns the default response transformer for the Solana RPC API. Under the hood, this function composes multiple RpcResponseTransformer | RpcResponseTransformers together such as the [getThrowSolanaErrorResponseTransformer](/api/functions/getThrowSolanaErrorResponseTransformer), the [getResultResponseTransformer](/api/functions/getResultResponseTransformer) and the [getBigIntUpcastResponseTransformer](/api/functions/getBigIntUpcastResponseTransformer). ## Type Parameters | Type Parameter | | -------------- | | `TApi` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `allowedNumericKeyPaths?`: [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\>; }> | ## Returns `RpcResponseTransformer` ## Example ```ts import { getDefaultResponseTransformerForSolanaRpc } from '@solana/rpc-transformers'; const responseTransformer = getDefaultResponseTransformerForSolanaRpc({ allowedNumericKeyPaths: getAllowedNumericKeypaths(), }); ``` # getDefaultResponseTransformerForSolanaRpcSubscriptions (/api/functions/getDefaultResponseTransformerForSolanaRpcSubscriptions) ```ts function getDefaultResponseTransformerForSolanaRpcSubscriptions( config?, ): RpcResponseTransformer; ``` Returns the default response transformer for the Solana RPC Subscriptions API. Under the hood, this function composes the [getBigIntUpcastResponseTransformer](/api/functions/getBigIntUpcastResponseTransformer). ## Type Parameters | Type Parameter | | -------------- | | `TApi` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `allowedNumericKeyPaths?`: [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\>; }> | ## Returns `RpcResponseTransformer` ## Example ```ts import { getDefaultResponseTransformerForSolanaRpcSubscriptions } from '@solana/rpc-transformers'; const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({ allowedNumericKeyPaths: getAllowedNumericKeypaths(), }); ``` # getDiscriminatedUnionCodec (/api/functions/getDiscriminatedUnionCodec) ```ts function getDiscriminatedUnionCodec( variants, config?, ): UnionCodec; ``` Returns a codec for encoding and decoding [DiscriminatedUnion](/api/type-aliases/DiscriminatedUnion). A [DiscriminatedUnion](/api/type-aliases/DiscriminatedUnion) is a TypeScript representation of Rust-like enums, where each variant is distinguished by a discriminator field (default: `__kind`). This codec inserts a numerical prefix to represent the variant index. ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------------------------------------------------ | ------------ | ---------------------------------------- | | `TVariants` *extends* `Variants`\<[`Codec`](/api/type-aliases/Codec)\<`any`, `any`>> | - | The variants of the discriminated union. | | `TDiscriminatorProperty` *extends* `string` | `"__kind"` | The property used as the discriminator. | ## Parameters | Parameter | Type | Description | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | `variants` | `TVariants` | The variant codecs as `[discriminator, codec]` pairs. | | `config?` | [`DiscriminatedUnionCodecConfig`](/api/type-aliases/DiscriminatedUnionCodecConfig)\<`TDiscriminatorProperty`, [`NumberCodec`](/api/type-aliases/NumberCodec)> | Configuration options for encoding/decoding. | ## Returns `UnionCodec`\<`TVariants`, `TDiscriminatorProperty`> A `Codec` for encoding and decoding discriminated union objects. ## Examples Encoding and decoding a discriminated union. ```ts type Message = | { __kind: 'Quit' } // Empty variant. | { __kind: 'Write'; fields: [string] } // Tuple variant. | { __kind: 'Move'; x: number; y: number }; // Struct variant. const messageCodec = getDiscriminatedUnionCodec([ ['Quit', getUnitCodec()], ['Write', getStructCodec([['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])]])], ['Move', getStructCodec([['x', getI32Codec()], ['y', getI32Codec()]])] ]); messageCodec.encode({ __kind: 'Move', x: 5, y: 6 }); // 0x020500000006000000 // | | └── Field y (6) // | └── Field x (5) // └── 1-byte discriminator (Index 2 β€” the "Move" variant) const value = messageCodec.decode(bytes); // { __kind: 'Move', x: 5, y: 6 } ``` Using a `u32` discriminator instead of `u8`. ```ts const codec = getDiscriminatedUnionCodec([...], { size: getU32Codec() }); codec.encode({ __kind: 'Quit' }); // 0x00000000 // β””------β”˜ 4-byte discriminator (Index 0) codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00])); // { __kind: 'Quit' } ``` Customizing the discriminator property. ```ts const codec = getDiscriminatedUnionCodec([...], { discriminator: 'message' }); codec.encode({ message: 'Quit' }); // 0x00 codec.decode(new Uint8Array([0x00])); // { message: 'Quit' } ``` ## Remarks Separate `getDiscriminatedUnionEncoder` and `getDiscriminatedUnionDecoder` functions are available. ```ts const bytes = getDiscriminatedUnionEncoder(variantEncoders).encode({ __kind: 'Quit' }); const message = getDiscriminatedUnionDecoder(variantDecoders).decode(bytes); ``` ## See * [getDiscriminatedUnionEncoder](/api/functions/getDiscriminatedUnionEncoder) * [getDiscriminatedUnionDecoder](/api/functions/getDiscriminatedUnionDecoder) # getDiscriminatedUnionDecoder (/api/functions/getDiscriminatedUnionDecoder) ```ts function getDiscriminatedUnionDecoder< TVariants, TDiscriminatorProperty, >(variants, config?): UnionDecoder; ``` Returns a decoder for discriminated unions. This decoder deserializes objects that follow the discriminated union pattern by **reading a numerical discriminator** and mapping it to the corresponding variant. Unlike [getUnionDecoder](/api/functions/getUnionDecoder), this decoder automatically inserts the discriminator property (default: `__kind`) into the decoded object. For more details, see [getDiscriminatedUnionCodec](/api/functions/getDiscriminatedUnionCodec). ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------- | ------------ | ---------------------------------------- | | `TVariants` *extends* `Variants`\<[`Decoder`](/api/type-aliases/Decoder)\<`any`>> | - | The variants of the discriminated union. | | `TDiscriminatorProperty` *extends* `string` | `"__kind"` | The property used as the discriminator. | ## Parameters | Parameter | Type | Description | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | `variants` | `TVariants` | The variant decoders as `[discriminator, decoder]` pairs. | | `config?` | [`DiscriminatedUnionCodecConfig`](/api/type-aliases/DiscriminatedUnionCodecConfig)\<`TDiscriminatorProperty`, [`NumberDecoder`](/api/type-aliases/NumberDecoder)> | Configuration options for decoding. | ## Returns `UnionDecoder`\<`TVariants`, `TDiscriminatorProperty`> A `Decoder` for decoding discriminated union objects. ## Example Decoding a discriminated union. ```ts type Message = | { __kind: 'Quit' } // Empty variant. | { __kind: 'Write'; fields: [string] } // Tuple variant. | { __kind: 'Move'; x: number; y: number }; // Struct variant. const messageDecoder = getDiscriminatedUnionDecoder([ ['Quit', getUnitDecoder()], ['Write', getStructDecoder([['fields', getTupleDecoder([addCodecSizePrefix(getUtf8Decoder(), getU32Decoder())])]])], ['Move', getStructDecoder([['x', getI32Decoder()], ['y', getI32Decoder()]])] ]); messageDecoder.decode(new Uint8Array([0x02,0x05,0x00,0x00,0x00,0x06,0x00,0x00,0x00])); // { __kind: 'Move', x: 5, y: 6 } ``` ## See [getDiscriminatedUnionCodec](/api/functions/getDiscriminatedUnionCodec) # getDiscriminatedUnionEncoder (/api/functions/getDiscriminatedUnionEncoder) ```ts function getDiscriminatedUnionEncoder< TVariants, TDiscriminatorProperty, >(variants, config?): UnionEncoder; ``` Returns an encoder for discriminated unions. This encoder serializes objects that follow the discriminated union pattern by prefixing them with a numerical discriminator that represents their variant. Unlike [getUnionEncoder](/api/functions/getUnionEncoder), this encoder automatically extracts and processes the discriminator property (default: `__kind`) from each variant. For more details, see [getDiscriminatedUnionCodec](/api/functions/getDiscriminatedUnionCodec). ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------------------- | ------------ | ---------------------------------------- | | `TVariants` *extends* `Variants`\<[`Encoder`](/api/type-aliases/Encoder)\<`any`>> | - | The variants of the discriminated union. | | `TDiscriminatorProperty` *extends* `string` | `"__kind"` | The property used as the discriminator. | ## Parameters | Parameter | Type | Description | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | `variants` | `TVariants` | The variant encoders as `[discriminator, encoder]` pairs. | | `config?` | [`DiscriminatedUnionCodecConfig`](/api/type-aliases/DiscriminatedUnionCodecConfig)\<`TDiscriminatorProperty`, [`NumberEncoder`](/api/type-aliases/NumberEncoder)> | Configuration options for encoding. | ## Returns `UnionEncoder`\<`TVariants`, `TDiscriminatorProperty`> An `Encoder` for encoding discriminated union objects. ## Example Encoding a discriminated union. ```ts type Message = | { __kind: 'Quit' } // Empty variant. | { __kind: 'Write'; fields: [string] } // Tuple variant. | { __kind: 'Move'; x: number; y: number }; // Struct variant. const messageEncoder = getDiscriminatedUnionEncoder([ ['Quit', getUnitEncoder()], ['Write', getStructEncoder([['fields', getTupleEncoder([addCodecSizePrefix(getUtf8Encoder(), getU32Encoder())])]])], ['Move', getStructEncoder([['x', getI32Encoder()], ['y', getI32Encoder()]])] ]); messageEncoder.encode({ __kind: 'Move', x: 5, y: 6 }); // 0x020500000006000000 // | | └── Field y (6) // | └── Field x (5) // └── 1-byte discriminator (Index 2 β€” the "Move" variant) ``` ## See [getDiscriminatedUnionCodec](/api/functions/getDiscriminatedUnionCodec) # getEncodedSize (/api/functions/getEncodedSize) ```ts function getEncodedSize(value, encoder): number; ``` Gets the encoded size of a given value in bytes using the provided encoder. ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ## Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------- | ----------------------------------------------- | | `value` | `TFrom` | The value to be encoded. | | `encoder` | \| \{ `fixedSize`: `number`; } \| \{ `getSizeFromValue`: (`value`) => `number`; } | The encoder used to determine the encoded size. | ## Returns `number` The size of the encoded value in bytes. ## Example ```ts const fixedSizeEncoder = { fixedSize: 4 }; getEncodedSize(123, fixedSizeEncoder); // Returns 4. const variableSizeEncoder = { getSizeFromValue: (value: string) => value.length }; getEncodedSize("hello", variableSizeEncoder); // Returns 5. ``` ## See [Encoder](/api/type-aliases/Encoder) # getEnumCodec (/api/functions/getEnumCodec) ## Call Signature ```ts function getEnumCodec( constructor, config?, ): FixedSizeCodec, GetEnumTo, 1>; ``` Returns a codec for encoding and decoding enums. This codec serializes enums as a numerical discriminator, allowing them to be efficiently stored and reconstructed from binary data. By default, the discriminator is derived from the positional index of the enum variant, but it can be configured to use the enum's numeric values instead. ### Type Parameters | Type Parameter | Description | | ------------------------------------ | ---------------------------------------------------------- | | `TEnum` *extends* `EnumLookupObject` | The TypeScript enum or object mapping enum keys to values. | ### Parameters | Parameter | Type | Description | | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | `constructor` | `TEnum` | The constructor of the enum. | | `config?` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`EnumCodecConfig`](/api/type-aliases/EnumCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)>, `"size"`> | Configuration options for encoding and decoding the enum. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`GetEnumFrom`\<`TEnum`>, `GetEnumTo`\<`TEnum`>, `1`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding enums. ### Examples Encoding and decoding enums using positional indexes. ```ts enum Direction { Up, Down, Left, Right } const codec = getEnumCodec(Direction); codec.encode(Direction.Up); // 0x00 codec.encode(Direction.Down); // 0x01 codec.encode(Direction.Left); // 0x02 codec.encode(Direction.Right); // 0x03 codec.decode(new Uint8Array([0x00])); // Direction.Up codec.decode(new Uint8Array([0x01])); // Direction.Down codec.decode(new Uint8Array([0x02])); // Direction.Left codec.decode(new Uint8Array([0x03])); // Direction.Right ``` Encoding and decoding enums using their numeric values. ```ts enum GameDifficulty { Easy = 1, Normal = 4, Hard = 7, Expert = 9 } const codec = getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); codec.encode(GameDifficulty.Easy); // 0x01 codec.encode(GameDifficulty.Normal); // 0x04 codec.encode(GameDifficulty.Hard); // 0x07 codec.encode(GameDifficulty.Expert); // 0x09 codec.decode(new Uint8Array([0x01])); // GameDifficulty.Easy codec.decode(new Uint8Array([0x04])); // GameDifficulty.Normal codec.decode(new Uint8Array([0x07])); // GameDifficulty.Hard codec.decode(new Uint8Array([0x09])); // GameDifficulty.Expert ``` Note that, when using values as discriminators, the enum values must be numerical. Otherwise, an error will be thrown. ```ts enum GameDifficulty { Easy = 'EASY', Normal = 'NORMAL', Hard = 'HARD' } getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); // Throws an error. ``` Using a custom discriminator size. ```ts enum Status { Pending, Approved, Rejected } const codec = getEnumCodec(Status, { size: getU16Codec() }); codec.encode(Status.Pending); // 0x0000 codec.encode(Status.Approved); // 0x0100 codec.encode(Status.Rejected); // 0x0200 codec.decode(new Uint8Array([0x00, 0x00])); // Status.Pending codec.decode(new Uint8Array([0x01, 0x00])); // Status.Approved codec.decode(new Uint8Array([0x02, 0x00])); // Status.Rejected ``` ### Remarks Separate [getEnumEncoder](/api/functions/getEnumEncoder) and [getEnumDecoder](/api/functions/getEnumDecoder) functions are available. ```ts const bytes = getEnumEncoder(Direction).encode(Direction.Up); const value = getEnumDecoder(Direction).decode(bytes); ``` ### See * [getEnumEncoder](/api/functions/getEnumEncoder) * [getEnumDecoder](/api/functions/getEnumDecoder) ## Call Signature ```ts function getEnumCodec( constructor, config, ): FixedSizeCodec, GetEnumTo, TSize>; ``` Returns a codec for encoding and decoding enums. This codec serializes enums as a numerical discriminator, allowing them to be efficiently stored and reconstructed from binary data. By default, the discriminator is derived from the positional index of the enum variant, but it can be configured to use the enum's numeric values instead. ### Type Parameters | Type Parameter | Description | | ------------------------------------ | ---------------------------------------------------------- | | `TEnum` *extends* `EnumLookupObject` | The TypeScript enum or object mapping enum keys to values. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | ------------- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | | `constructor` | `TEnum` | The constructor of the enum. | | `config` | [`EnumCodecConfig`](/api/type-aliases/EnumCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Configuration options for encoding and decoding the enum. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`GetEnumFrom`\<`TEnum`>, `GetEnumTo`\<`TEnum`>, `TSize`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding enums. ### Examples Encoding and decoding enums using positional indexes. ```ts enum Direction { Up, Down, Left, Right } const codec = getEnumCodec(Direction); codec.encode(Direction.Up); // 0x00 codec.encode(Direction.Down); // 0x01 codec.encode(Direction.Left); // 0x02 codec.encode(Direction.Right); // 0x03 codec.decode(new Uint8Array([0x00])); // Direction.Up codec.decode(new Uint8Array([0x01])); // Direction.Down codec.decode(new Uint8Array([0x02])); // Direction.Left codec.decode(new Uint8Array([0x03])); // Direction.Right ``` Encoding and decoding enums using their numeric values. ```ts enum GameDifficulty { Easy = 1, Normal = 4, Hard = 7, Expert = 9 } const codec = getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); codec.encode(GameDifficulty.Easy); // 0x01 codec.encode(GameDifficulty.Normal); // 0x04 codec.encode(GameDifficulty.Hard); // 0x07 codec.encode(GameDifficulty.Expert); // 0x09 codec.decode(new Uint8Array([0x01])); // GameDifficulty.Easy codec.decode(new Uint8Array([0x04])); // GameDifficulty.Normal codec.decode(new Uint8Array([0x07])); // GameDifficulty.Hard codec.decode(new Uint8Array([0x09])); // GameDifficulty.Expert ``` Note that, when using values as discriminators, the enum values must be numerical. Otherwise, an error will be thrown. ```ts enum GameDifficulty { Easy = 'EASY', Normal = 'NORMAL', Hard = 'HARD' } getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); // Throws an error. ``` Using a custom discriminator size. ```ts enum Status { Pending, Approved, Rejected } const codec = getEnumCodec(Status, { size: getU16Codec() }); codec.encode(Status.Pending); // 0x0000 codec.encode(Status.Approved); // 0x0100 codec.encode(Status.Rejected); // 0x0200 codec.decode(new Uint8Array([0x00, 0x00])); // Status.Pending codec.decode(new Uint8Array([0x01, 0x00])); // Status.Approved codec.decode(new Uint8Array([0x02, 0x00])); // Status.Rejected ``` ### Remarks Separate [getEnumEncoder](/api/functions/getEnumEncoder) and [getEnumDecoder](/api/functions/getEnumDecoder) functions are available. ```ts const bytes = getEnumEncoder(Direction).encode(Direction.Up); const value = getEnumDecoder(Direction).decode(bytes); ``` ### See * [getEnumEncoder](/api/functions/getEnumEncoder) * [getEnumDecoder](/api/functions/getEnumDecoder) ## Call Signature ```ts function getEnumCodec( constructor, config?, ): VariableSizeCodec, GetEnumTo>; ``` Returns a codec for encoding and decoding enums. This codec serializes enums as a numerical discriminator, allowing them to be efficiently stored and reconstructed from binary data. By default, the discriminator is derived from the positional index of the enum variant, but it can be configured to use the enum's numeric values instead. ### Type Parameters | Type Parameter | Description | | ------------------------------------ | ---------------------------------------------------------- | | `TEnum` *extends* `EnumLookupObject` | The TypeScript enum or object mapping enum keys to values. | ### Parameters | Parameter | Type | Description | | ------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | `constructor` | `TEnum` | The constructor of the enum. | | `config?` | [`EnumCodecConfig`](/api/type-aliases/EnumCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> | Configuration options for encoding and decoding the enum. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`GetEnumFrom`\<`TEnum`>, `GetEnumTo`\<`TEnum`>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding enums. ### Examples Encoding and decoding enums using positional indexes. ```ts enum Direction { Up, Down, Left, Right } const codec = getEnumCodec(Direction); codec.encode(Direction.Up); // 0x00 codec.encode(Direction.Down); // 0x01 codec.encode(Direction.Left); // 0x02 codec.encode(Direction.Right); // 0x03 codec.decode(new Uint8Array([0x00])); // Direction.Up codec.decode(new Uint8Array([0x01])); // Direction.Down codec.decode(new Uint8Array([0x02])); // Direction.Left codec.decode(new Uint8Array([0x03])); // Direction.Right ``` Encoding and decoding enums using their numeric values. ```ts enum GameDifficulty { Easy = 1, Normal = 4, Hard = 7, Expert = 9 } const codec = getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); codec.encode(GameDifficulty.Easy); // 0x01 codec.encode(GameDifficulty.Normal); // 0x04 codec.encode(GameDifficulty.Hard); // 0x07 codec.encode(GameDifficulty.Expert); // 0x09 codec.decode(new Uint8Array([0x01])); // GameDifficulty.Easy codec.decode(new Uint8Array([0x04])); // GameDifficulty.Normal codec.decode(new Uint8Array([0x07])); // GameDifficulty.Hard codec.decode(new Uint8Array([0x09])); // GameDifficulty.Expert ``` Note that, when using values as discriminators, the enum values must be numerical. Otherwise, an error will be thrown. ```ts enum GameDifficulty { Easy = 'EASY', Normal = 'NORMAL', Hard = 'HARD' } getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); // Throws an error. ``` Using a custom discriminator size. ```ts enum Status { Pending, Approved, Rejected } const codec = getEnumCodec(Status, { size: getU16Codec() }); codec.encode(Status.Pending); // 0x0000 codec.encode(Status.Approved); // 0x0100 codec.encode(Status.Rejected); // 0x0200 codec.decode(new Uint8Array([0x00, 0x00])); // Status.Pending codec.decode(new Uint8Array([0x01, 0x00])); // Status.Approved codec.decode(new Uint8Array([0x02, 0x00])); // Status.Rejected ``` ### Remarks Separate [getEnumEncoder](/api/functions/getEnumEncoder) and [getEnumDecoder](/api/functions/getEnumDecoder) functions are available. ```ts const bytes = getEnumEncoder(Direction).encode(Direction.Up); const value = getEnumDecoder(Direction).decode(bytes); ``` ### See * [getEnumEncoder](/api/functions/getEnumEncoder) * [getEnumDecoder](/api/functions/getEnumDecoder) # getEnumDecoder (/api/functions/getEnumDecoder) ## Call Signature ```ts function getEnumDecoder( constructor, config?, ): FixedSizeDecoder, 1>; ``` Returns a decoder for enums. This decoder deserializes enums from a numerical discriminator. By default, the discriminator is based on the positional index of the enum variants. For more details, see [getEnumCodec](/api/functions/getEnumCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------ | ---------------------------------------------------------- | | `TEnum` *extends* `EnumLookupObject` | The TypeScript enum or object mapping enum keys to values. | ### Parameters | Parameter | Type | Description | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `constructor` | `TEnum` | The constructor of the enum. | | `config?` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`EnumCodecConfig`](/api/type-aliases/EnumCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)>, `"size"`> | Configuration options for decoding the enum. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`GetEnumTo`\<`TEnum`>, `1`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding enums. ### Example Decoding enum values. ```ts enum Direction { Up, Down, Left, Right } const decoder = getEnumDecoder(Direction); decoder.decode(new Uint8Array([0x00])); // Direction.Up decoder.decode(new Uint8Array([0x01])); // Direction.Down decoder.decode(new Uint8Array([0x02])); // Direction.Left decoder.decode(new Uint8Array([0x03])); // Direction.Right ``` ### See [getEnumCodec](/api/functions/getEnumCodec) ## Call Signature ```ts function getEnumDecoder( constructor, config, ): FixedSizeDecoder, TSize>; ``` Returns a decoder for enums. This decoder deserializes enums from a numerical discriminator. By default, the discriminator is based on the positional index of the enum variants. For more details, see [getEnumCodec](/api/functions/getEnumCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------ | ---------------------------------------------------------- | | `TEnum` *extends* `EnumLookupObject` | The TypeScript enum or object mapping enum keys to values. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | ------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `constructor` | `TEnum` | The constructor of the enum. | | `config` | [`EnumCodecConfig`](/api/type-aliases/EnumCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Configuration options for decoding the enum. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`GetEnumTo`\<`TEnum`>, `TSize`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding enums. ### Example Decoding enum values. ```ts enum Direction { Up, Down, Left, Right } const decoder = getEnumDecoder(Direction); decoder.decode(new Uint8Array([0x00])); // Direction.Up decoder.decode(new Uint8Array([0x01])); // Direction.Down decoder.decode(new Uint8Array([0x02])); // Direction.Left decoder.decode(new Uint8Array([0x03])); // Direction.Right ``` ### See [getEnumCodec](/api/functions/getEnumCodec) ## Call Signature ```ts function getEnumDecoder( constructor, config?, ): VariableSizeDecoder>; ``` Returns a decoder for enums. This decoder deserializes enums from a numerical discriminator. By default, the discriminator is based on the positional index of the enum variants. For more details, see [getEnumCodec](/api/functions/getEnumCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------ | ---------------------------------------------------------- | | `TEnum` *extends* `EnumLookupObject` | The TypeScript enum or object mapping enum keys to values. | ### Parameters | Parameter | Type | Description | | ------------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `constructor` | `TEnum` | The constructor of the enum. | | `config?` | [`EnumCodecConfig`](/api/type-aliases/EnumCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> | Configuration options for decoding the enum. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`GetEnumTo`\<`TEnum`>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding enums. ### Example Decoding enum values. ```ts enum Direction { Up, Down, Left, Right } const decoder = getEnumDecoder(Direction); decoder.decode(new Uint8Array([0x00])); // Direction.Up decoder.decode(new Uint8Array([0x01])); // Direction.Down decoder.decode(new Uint8Array([0x02])); // Direction.Left decoder.decode(new Uint8Array([0x03])); // Direction.Right ``` ### See [getEnumCodec](/api/functions/getEnumCodec) # getEnumEncoder (/api/functions/getEnumEncoder) ## Call Signature ```ts function getEnumEncoder( constructor, config?, ): FixedSizeEncoder, 1>; ``` Returns an encoder for enums. This encoder serializes enums as a numerical discriminator. By default, the discriminator is based on the positional index of the enum variants. For more details, see [getEnumCodec](/api/functions/getEnumCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------ | ---------------------------------------------------------- | | `TEnum` *extends* `EnumLookupObject` | The TypeScript enum or object mapping enum keys to values. | ### Parameters | Parameter | Type | Description | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `constructor` | `TEnum` | The constructor of the enum. | | `config?` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`EnumCodecConfig`](/api/type-aliases/EnumCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)>, `"size"`> | Configuration options for encoding the enum. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`GetEnumFrom`\<`TEnum`>, `1`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding enums. ### Example Encoding enum values. ```ts enum Direction { Up, Down, Left, Right } const encoder = getEnumEncoder(Direction); encoder.encode(Direction.Up); // 0x00 encoder.encode(Direction.Down); // 0x01 encoder.encode(Direction.Left); // 0x02 encoder.encode(Direction.Right); // 0x03 ``` ### See [getEnumCodec](/api/functions/getEnumCodec) ## Call Signature ```ts function getEnumEncoder( constructor, config, ): FixedSizeEncoder, TSize>; ``` Returns an encoder for enums. This encoder serializes enums as a numerical discriminator. By default, the discriminator is based on the positional index of the enum variants. For more details, see [getEnumCodec](/api/functions/getEnumCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------ | ---------------------------------------------------------- | | `TEnum` *extends* `EnumLookupObject` | The TypeScript enum or object mapping enum keys to values. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | ------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `constructor` | `TEnum` | The constructor of the enum. | | `config` | [`EnumCodecConfig`](/api/type-aliases/EnumCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Configuration options for encoding the enum. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`GetEnumFrom`\<`TEnum`>, `TSize`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding enums. ### Example Encoding enum values. ```ts enum Direction { Up, Down, Left, Right } const encoder = getEnumEncoder(Direction); encoder.encode(Direction.Up); // 0x00 encoder.encode(Direction.Down); // 0x01 encoder.encode(Direction.Left); // 0x02 encoder.encode(Direction.Right); // 0x03 ``` ### See [getEnumCodec](/api/functions/getEnumCodec) ## Call Signature ```ts function getEnumEncoder( constructor, config?, ): VariableSizeEncoder>; ``` Returns an encoder for enums. This encoder serializes enums as a numerical discriminator. By default, the discriminator is based on the positional index of the enum variants. For more details, see [getEnumCodec](/api/functions/getEnumCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------ | ---------------------------------------------------------- | | `TEnum` *extends* `EnumLookupObject` | The TypeScript enum or object mapping enum keys to values. | ### Parameters | Parameter | Type | Description | | ------------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `constructor` | `TEnum` | The constructor of the enum. | | `config?` | [`EnumCodecConfig`](/api/type-aliases/EnumCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> | Configuration options for encoding the enum. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`GetEnumFrom`\<`TEnum`>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding enums. ### Example Encoding enum values. ```ts enum Direction { Up, Down, Left, Right } const encoder = getEnumEncoder(Direction); encoder.encode(Direction.Up); // 0x00 encoder.encode(Direction.Down); // 0x01 encoder.encode(Direction.Left); // 0x02 encoder.encode(Direction.Right); // 0x03 ``` ### See [getEnumCodec](/api/functions/getEnumCodec) # getF32Codec (/api/functions/getF32Codec) ```ts function getF32Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 32-bit floating-point numbers (`f32`). This codec serializes `f32` values using 4 bytes. Due to the IEEE 754 floating-point representation, some precision loss may occur. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `number`, `4`> A `FixedSizeCodec` for encoding and decoding `f32` values. ## Examples Encoding and decoding an `f32` value. ```ts const codec = getF32Codec(); const bytes = codec.encode(-1.5); // 0x0000c0bf const value = codec.decode(bytes); // -1.5 ``` Using big-endian encoding. ```ts const codec = getF32Codec({ endian: Endian.Big }); const bytes = codec.encode(-1.5); // 0xbfc00000 ``` ## Remarks `f32` values follow the IEEE 754 single-precision floating-point standard. Precision loss may occur for certain values. * If you need higher precision, consider using [getF64Codec](/api/functions/getF64Codec). * If you need integer values, consider using [getI32Codec](/api/functions/getI32Codec) or [getU32Codec](/api/functions/getU32Codec). Separate [getF32Encoder](/api/functions/getF32Encoder) and [getF32Decoder](/api/functions/getF32Decoder) functions are available. ```ts const bytes = getF32Encoder().encode(-1.5); const value = getF32Decoder().decode(bytes); ``` ## See * [getF32Encoder](/api/functions/getF32Encoder) * [getF32Decoder](/api/functions/getF32Decoder) # getF32Decoder (/api/functions/getF32Decoder) ```ts function getF32Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 32-bit floating-point numbers (`f32`). This decoder deserializes `f32` values from 4 bytes. Some precision may be lost during decoding due to floating-point representation. For more details, see [getF32Codec](/api/functions/getF32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeDecoder`\<`number`, `4`> A `FixedSizeDecoder` for decoding `f32` values. ## Example Decoding an `f32` value. ```ts const decoder = getF32Decoder(); const value = decoder.decode(new Uint8Array([0x00, 0x00, 0xc0, 0xbf])); // -1.5 ``` ## See [getF32Codec](/api/functions/getF32Codec) # getF32Encoder (/api/functions/getF32Encoder) ```ts function getF32Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 32-bit floating-point numbers (`f32`). This encoder serializes `f32` values using 4 bytes. Floating-point values may lose precision when encoded. For more details, see [getF32Codec](/api/functions/getF32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `4`> A `FixedSizeEncoder` for encoding `f32` values. ## Example Encoding an `f32` value. ```ts const encoder = getF32Encoder(); const bytes = encoder.encode(-1.5); // 0x0000c0bf ``` ## See [getF32Codec](/api/functions/getF32Codec) # getF64Codec (/api/functions/getF64Codec) ```ts function getF64Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 64-bit floating-point numbers (`f64`). This codec serializes `f64` values using 8 bytes. Due to the IEEE 754 floating-point representation, some precision loss may occur. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `number`, `8`> A `FixedSizeCodec` for encoding and decoding `f64` values. ## Examples Encoding and decoding an `f64` value. ```ts const codec = getF64Codec(); const bytes = codec.encode(-1.5); // 0x000000000000f8bf const value = codec.decode(bytes); // -1.5 ``` Using big-endian encoding. ```ts const codec = getF64Codec({ endian: Endian.Big }); const bytes = codec.encode(-1.5); // 0xbff8000000000000 ``` ## Remarks `f64` values follow the IEEE 754 double-precision floating-point standard. Precision loss may still occur but is significantly lower than `f32`. * If you need smaller floating-point values, consider using [getF32Codec](/api/functions/getF32Codec). * If you need integer values, consider using [getI64Codec](/api/functions/getI64Codec) or [getU64Codec](/api/functions/getU64Codec). Separate [getF64Encoder](/api/functions/getF64Encoder) and [getF64Decoder](/api/functions/getF64Decoder) functions are available. ```ts const bytes = getF64Encoder().encode(-1.5); const value = getF64Decoder().decode(bytes); ``` ## See * [getF64Encoder](/api/functions/getF64Encoder) * [getF64Decoder](/api/functions/getF64Decoder) # getF64Decoder (/api/functions/getF64Decoder) ```ts function getF64Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 64-bit floating-point numbers (`f64`). This decoder deserializes `f64` values from 8 bytes. Some precision may be lost during decoding due to floating-point representation. For more details, see [getF64Codec](/api/functions/getF64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeDecoder`\<`number`, `8`> A `FixedSizeDecoder` for decoding `f64` values. ## Example Decoding an `f64` value. ```ts const decoder = getF64Decoder(); const value = decoder.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf])); // -1.5 ``` ## See [getF64Codec](/api/functions/getF64Codec) # getF64Encoder (/api/functions/getF64Encoder) ```ts function getF64Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 64-bit floating-point numbers (`f64`). This encoder serializes `f64` values using 8 bytes. Floating-point values may lose precision when encoded. For more details, see [getF64Codec](/api/functions/getF64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `8`> A `FixedSizeEncoder` for encoding `f64` values. ## Example Encoding an `f64` value. ```ts const encoder = getF64Encoder(); const bytes = encoder.encode(-1.5); // 0x000000000000f8bf ``` ## See [getF64Codec](/api/functions/getF64Codec) # getFirstFailedSingleTransactionPlanResult (/api/functions/getFirstFailedSingleTransactionPlanResult) ```ts function getFirstFailedSingleTransactionPlanResult< TContext, TTransactionMessage, >( transactionPlanResult, ): FailedSingleTransactionPlanResult; ``` Retrieves the first failed transaction plan result from a transaction plan result tree. This function searches the transaction plan result tree using a depth-first traversal and returns the first single transaction result with a 'failed' status. If no failed result is found, it throws a [SolanaError](/api/classes/SolanaError). ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | The type of the transaction message | ## Parameters | Parameter | Type | Description | | ----------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------- | | `transactionPlanResult` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result tree to search. | ## Returns [`FailedSingleTransactionPlanResult`](/api/type-aliases/FailedSingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> The first failed single transaction plan result. ## Throws Throws a [SolanaError](/api/classes/SolanaError) with code `SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND` if no failed transaction plan result is found. The error context contains a non-enumerable `transactionPlanResult` property for recovery purposes. ## Example Retrieving the first failed result from a parallel execution. ```ts const result = parallelTransactionPlanResult([ successfulSingleTransactionPlanResult(messageA, { signature: signatureA }), failedSingleTransactionPlanResult(messageB, error), failedSingleTransactionPlanResult(messageC, anotherError), ]); const firstFailed = getFirstFailedSingleTransactionPlanResult(result); // Returns the failed result for messageB. ``` ## See * [FailedSingleTransactionPlanResult](/api/type-aliases/FailedSingleTransactionPlanResult) * [findTransactionPlanResult](/api/functions/findTransactionPlanResult) # getHiddenPrefixCodec (/api/functions/getHiddenPrefixCodec) ## Call Signature ```ts function getHiddenPrefixCodec( codec, prefixedCodecs, ): FixedSizeCodec; ``` Returns a codec that encodes and decodes values with a hidden prefix. * **Encoding:** Prefixes the value with hidden data before encoding. * **Decoding:** Skips the hidden prefix before decoding the main value. This is useful for any implicit metadata that should be present in binary formats but omitted from the API. ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | ---------------- | ----------------------------------------------------------------------- | ----------------------------------------------------- | | `codec` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> | The codec for the main value. | | `prefixedCodecs` | readonly [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`void`>\[] | A list of void codecs that produce the hidden prefix. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden prefix. ### Example Encoding and decoding a value with prefixed constants. ```ts const codec = getHiddenPrefixCodec(getUtf8Codec(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); const bytes = codec.encode('Hello'); // 0x01020304050648656c6c6f // | | β””-- Our encoded value ("Hello"). // | β””-- Our second hidden prefix. // β””-- Our first hidden prefix. codec.decode(bytes); // 'Hello' ``` ### Remarks If all you need is padding zeroes before a value, consider using [padLeftCodec](/api/functions/padLeftCodec) instead. Separate [getHiddenPrefixEncoder](/api/functions/getHiddenPrefixEncoder) and [getHiddenPrefixDecoder](/api/functions/getHiddenPrefixDecoder) functions are available. ```ts const bytes = getHiddenPrefixEncoder(getUtf8Encoder(), [ getConstantEncoder(new Uint8Array([1, 2, 3])), getConstantEncoder(new Uint8Array([4, 5, 6])), ]).encode('Hello'); const value = getHiddenPrefixDecoder(getUtf8Decoder(), [ getConstantDecoder(new Uint8Array([1, 2, 3])), getConstantDecoder(new Uint8Array([4, 5, 6])), ]).decode(bytes); ``` ### See * [getHiddenPrefixEncoder](/api/functions/getHiddenPrefixEncoder) * [getHiddenPrefixDecoder](/api/functions/getHiddenPrefixDecoder) ## Call Signature ```ts function getHiddenPrefixCodec( codec, prefixedCodecs, ): VariableSizeCodec; ``` Returns a codec that encodes and decodes values with a hidden prefix. * **Encoding:** Prefixes the value with hidden data before encoding. * **Decoding:** Skips the hidden prefix before decoding the main value. This is useful for any implicit metadata that should be present in binary formats but omitted from the API. ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | ---------------- | ------------------------------------------------------- | ----------------------------------------------------- | | `codec` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | The codec for the main value. | | `prefixedCodecs` | readonly [`Codec`](/api/type-aliases/Codec)\<`void`>\[] | A list of void codecs that produce the hidden prefix. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden prefix. ### Example Encoding and decoding a value with prefixed constants. ```ts const codec = getHiddenPrefixCodec(getUtf8Codec(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); const bytes = codec.encode('Hello'); // 0x01020304050648656c6c6f // | | β””-- Our encoded value ("Hello"). // | β””-- Our second hidden prefix. // β””-- Our first hidden prefix. codec.decode(bytes); // 'Hello' ``` ### Remarks If all you need is padding zeroes before a value, consider using [padLeftCodec](/api/functions/padLeftCodec) instead. Separate [getHiddenPrefixEncoder](/api/functions/getHiddenPrefixEncoder) and [getHiddenPrefixDecoder](/api/functions/getHiddenPrefixDecoder) functions are available. ```ts const bytes = getHiddenPrefixEncoder(getUtf8Encoder(), [ getConstantEncoder(new Uint8Array([1, 2, 3])), getConstantEncoder(new Uint8Array([4, 5, 6])), ]).encode('Hello'); const value = getHiddenPrefixDecoder(getUtf8Decoder(), [ getConstantDecoder(new Uint8Array([1, 2, 3])), getConstantDecoder(new Uint8Array([4, 5, 6])), ]).decode(bytes); ``` ### See * [getHiddenPrefixEncoder](/api/functions/getHiddenPrefixEncoder) * [getHiddenPrefixDecoder](/api/functions/getHiddenPrefixDecoder) # getHiddenPrefixDecoder (/api/functions/getHiddenPrefixDecoder) ## Call Signature ```ts function getHiddenPrefixDecoder( decoder, prefixedDecoders, ): FixedSizeDecoder; ``` Returns a decoder that skips hidden prefixed data before decoding the main value. This decoder applies a list of void decoders before decoding the main value. The prefixed data is skipped during decoding without being exposed to the user. For more details, see [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | ------------------ | --------------------------------------------------------------------------- | ------------------------------------------------------- | | `decoder` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> | The decoder for the main value. | | `prefixedDecoders` | readonly [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`void`>\[] | A list of void decoders that produce the hidden prefix. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden prefix. ### Example Decoding a value with prefixed constants. ```ts const decoder = getHiddenPrefixDecoder(getUtf8Decoder(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); decoder.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 0x48, 0x65, 0x6C, 0x6C, 0x6F])); // 'Hello' ``` ### See [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec) ## Call Signature ```ts function getHiddenPrefixDecoder( decoder, prefixedDecoders, ): VariableSizeDecoder; ``` Returns a decoder that skips hidden prefixed data before decoding the main value. This decoder applies a list of void decoders before decoding the main value. The prefixed data is skipped during decoding without being exposed to the user. For more details, see [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | ------------------ | ----------------------------------------------------------- | ------------------------------------------------------- | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | The decoder for the main value. | | `prefixedDecoders` | readonly [`Decoder`](/api/type-aliases/Decoder)\<`void`>\[] | A list of void decoders that produce the hidden prefix. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`> A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden prefix. ### Example Decoding a value with prefixed constants. ```ts const decoder = getHiddenPrefixDecoder(getUtf8Decoder(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); decoder.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 0x48, 0x65, 0x6C, 0x6C, 0x6F])); // 'Hello' ``` ### See [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec) # getHiddenPrefixEncoder (/api/functions/getHiddenPrefixEncoder) ## Call Signature ```ts function getHiddenPrefixEncoder( encoder, prefixedEncoders, ): FixedSizeEncoder; ``` Returns an encoder that prefixes encoded values with hidden data. This encoder applies a list of void encoders before encoding the main value. The prefixed data is encoded before the main value without being exposed to the user. For more details, see [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | ------------------ | --------------------------------------------------------------------------- | ------------------------------------------------------- | | `encoder` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> | The encoder for the main value. | | `prefixedEncoders` | readonly [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`void`>\[] | A list of void encoders that produce the hidden prefix. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden prefix. ### Example Prefixing a value with constants. ```ts const encoder = getHiddenPrefixEncoder(getUtf8Encoder(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); encoder.encode('Hello'); // 0x01020304050648656c6c6f // | | β””-- Our encoded value ("Hello"). // | β””-- Our second hidden prefix. // β””-- Our first hidden prefix. ``` ### See [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec) ## Call Signature ```ts function getHiddenPrefixEncoder( encoder, prefixedEncoders, ): VariableSizeEncoder; ``` Returns an encoder that prefixes encoded values with hidden data. This encoder applies a list of void encoders before encoding the main value. The prefixed data is encoded before the main value without being exposed to the user. For more details, see [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | ------------------ | ----------------------------------------------------------- | ------------------------------------------------------- | | `encoder` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | The encoder for the main value. | | `prefixedEncoders` | readonly [`Encoder`](/api/type-aliases/Encoder)\<`void`>\[] | A list of void encoders that produce the hidden prefix. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`> A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden prefix. ### Example Prefixing a value with constants. ```ts const encoder = getHiddenPrefixEncoder(getUtf8Encoder(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); encoder.encode('Hello'); // 0x01020304050648656c6c6f // | | β””-- Our encoded value ("Hello"). // | β””-- Our second hidden prefix. // β””-- Our first hidden prefix. ``` ### See [getHiddenPrefixCodec](/api/functions/getHiddenPrefixCodec) # getHiddenSuffixCodec (/api/functions/getHiddenSuffixCodec) ## Call Signature ```ts function getHiddenSuffixCodec( codec, suffixedCodecs, ): FixedSizeCodec; ``` Returns a codec that encodes and decodes values with a hidden suffix. * **Encoding:** Appends hidden data after encoding the main value. * **Decoding:** Skips the hidden suffix after decoding the main value. This is useful for any implicit metadata that should be present in binary formats but omitted from the API. ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | ---------------- | ----------------------------------------------------------------------- | ----------------------------------------------------- | | `codec` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> | The codec for the main value. | | `suffixedCodecs` | readonly [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`void`>\[] | A list of void codecs that produce the hidden suffix. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden suffix. ### Example Encoding and decoding a value with suffixed constants. ```ts const codec = getHiddenSuffixCodec(getUtf8Codec(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); const bytes = codec.encode('Hello'); // 0x48656c6c6f010203040506 // | | β””-- Our second hidden suffix. // | β””-- Our first hidden suffix. // β””-- Our encoded value ("Hello"). codec.decode(bytes); // 'Hello' ``` ### Remarks If all you need is padding zeroes after a value, consider using [padRightCodec](/api/functions/padRightCodec) instead. Separate [getHiddenSuffixEncoder](/api/functions/getHiddenSuffixEncoder) and [getHiddenSuffixDecoder](/api/functions/getHiddenSuffixDecoder) functions are available. ```ts const bytes = getHiddenSuffixEncoder(getUtf8Encoder(), [ getConstantEncoder(new Uint8Array([1, 2, 3])), getConstantEncoder(new Uint8Array([4, 5, 6])), ]).encode('Hello'); const value = getHiddenSuffixDecoder(getUtf8Decoder(), [ getConstantDecoder(new Uint8Array([1, 2, 3])), getConstantDecoder(new Uint8Array([4, 5, 6])), ]).decode(bytes); ``` ### See * [getHiddenSuffixEncoder](/api/functions/getHiddenSuffixEncoder) * [getHiddenSuffixDecoder](/api/functions/getHiddenSuffixDecoder) ## Call Signature ```ts function getHiddenSuffixCodec( codec, suffixedCodecs, ): VariableSizeCodec; ``` Returns a codec that encodes and decodes values with a hidden suffix. * **Encoding:** Appends hidden data after encoding the main value. * **Decoding:** Skips the hidden suffix after decoding the main value. This is useful for any implicit metadata that should be present in binary formats but omitted from the API. ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | ---------------- | ------------------------------------------------------- | ----------------------------------------------------- | | `codec` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | The codec for the main value. | | `suffixedCodecs` | readonly [`Codec`](/api/type-aliases/Codec)\<`void`>\[] | A list of void codecs that produce the hidden suffix. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden suffix. ### Example Encoding and decoding a value with suffixed constants. ```ts const codec = getHiddenSuffixCodec(getUtf8Codec(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); const bytes = codec.encode('Hello'); // 0x48656c6c6f010203040506 // | | β””-- Our second hidden suffix. // | β””-- Our first hidden suffix. // β””-- Our encoded value ("Hello"). codec.decode(bytes); // 'Hello' ``` ### Remarks If all you need is padding zeroes after a value, consider using [padRightCodec](/api/functions/padRightCodec) instead. Separate [getHiddenSuffixEncoder](/api/functions/getHiddenSuffixEncoder) and [getHiddenSuffixDecoder](/api/functions/getHiddenSuffixDecoder) functions are available. ```ts const bytes = getHiddenSuffixEncoder(getUtf8Encoder(), [ getConstantEncoder(new Uint8Array([1, 2, 3])), getConstantEncoder(new Uint8Array([4, 5, 6])), ]).encode('Hello'); const value = getHiddenSuffixDecoder(getUtf8Decoder(), [ getConstantDecoder(new Uint8Array([1, 2, 3])), getConstantDecoder(new Uint8Array([4, 5, 6])), ]).decode(bytes); ``` ### See * [getHiddenSuffixEncoder](/api/functions/getHiddenSuffixEncoder) * [getHiddenSuffixDecoder](/api/functions/getHiddenSuffixDecoder) # getHiddenSuffixDecoder (/api/functions/getHiddenSuffixDecoder) ## Call Signature ```ts function getHiddenSuffixDecoder( decoder, suffixedDecoders, ): FixedSizeDecoder; ``` Returns a decoder that skips hidden suffixed data after decoding the main value. This decoder applies a list of void decoders after decoding the main value. The suffixed data is skipped during decoding without being exposed to the user. For more details, see [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | ------------------ | --------------------------------------------------------------------------- | ------------------------------------------------------- | | `decoder` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> | The decoder for the main value. | | `suffixedDecoders` | readonly [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`void`>\[] | A list of void decoders that produce the hidden suffix. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden suffix. ### Example Decoding a value with suffixed constants. ```ts const decoder = getHiddenSuffixDecoder(getUtf8Decoder(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); decoder.decode(new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F, 1, 2, 3, 4, 5, 6])); // 'Hello' ``` ### See [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec) ## Call Signature ```ts function getHiddenSuffixDecoder( decoder, suffixedDecoders, ): VariableSizeDecoder; ``` Returns a decoder that skips hidden suffixed data after decoding the main value. This decoder applies a list of void decoders after decoding the main value. The suffixed data is skipped during decoding without being exposed to the user. For more details, see [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | ------------------ | ----------------------------------------------------------- | ------------------------------------------------------- | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | The decoder for the main value. | | `suffixedDecoders` | readonly [`Decoder`](/api/type-aliases/Decoder)\<`void`>\[] | A list of void decoders that produce the hidden suffix. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`> A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden suffix. ### Example Decoding a value with suffixed constants. ```ts const decoder = getHiddenSuffixDecoder(getUtf8Decoder(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); decoder.decode(new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F, 1, 2, 3, 4, 5, 6])); // 'Hello' ``` ### See [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec) # getHiddenSuffixEncoder (/api/functions/getHiddenSuffixEncoder) ## Call Signature ```ts function getHiddenSuffixEncoder( encoder, suffixedEncoders, ): FixedSizeEncoder; ``` Returns an encoder that appends hidden data after the encoded value. This encoder applies a list of void encoders after encoding the main value. The suffixed data is encoded after the main value without being exposed to the user. For more details, see [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | ------------------ | --------------------------------------------------------------------------- | ------------------------------------------------------- | | `encoder` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> | The encoder for the main value. | | `suffixedEncoders` | readonly [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`void`>\[] | A list of void encoders that produce the hidden suffix. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden suffix. ### Example Suffixing a value with constants. ```ts const encoder = getHiddenSuffixEncoder(getUtf8Encoder(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); encoder.encode('Hello'); // 0x48656c6c6f010203040506 // | | β””-- Our second hidden suffix. // | β””-- Our first hidden suffix. // β””-- Our encoded value ("Hello"). ``` ### See [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec) ## Call Signature ```ts function getHiddenSuffixEncoder( encoder, suffixedEncoders, ): VariableSizeEncoder; ``` Returns an encoder that appends hidden data after the encoded value. This encoder applies a list of void encoders after encoding the main value. The suffixed data is encoded after the main value without being exposed to the user. For more details, see [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | ------------------ | ----------------------------------------------------------- | ------------------------------------------------------- | | `encoder` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | The encoder for the main value. | | `suffixedEncoders` | readonly [`Encoder`](/api/type-aliases/Encoder)\<`void`>\[] | A list of void encoders that produce the hidden suffix. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`> A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden suffix. ### Example Suffixing a value with constants. ```ts const encoder = getHiddenSuffixEncoder(getUtf8Encoder(), [ getConstantCodec(new Uint8Array([1, 2, 3])), getConstantCodec(new Uint8Array([4, 5, 6])), ]); encoder.encode('Hello'); // 0x48656c6c6f010203040506 // | | β””-- Our second hidden suffix. // | β””-- Our first hidden suffix. // β””-- Our encoded value ("Hello"). ``` ### See [getHiddenSuffixCodec](/api/functions/getHiddenSuffixCodec) # getI128Codec (/api/functions/getI128Codec) ```ts function getI128Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 128-bit signed integers (`i128`). This codec serializes `i128` values using 16 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `bigint`, `16`> A `FixedSizeCodec` for encoding and decoding `i128` values. ## Examples Encoding and decoding an `i128` value. ```ts const codec = getI128Codec(); const bytes = codec.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff const value = codec.decode(bytes); // -42n ``` Using big-endian encoding. ```ts const codec = getI128Codec({ endian: Endian.Big }); const bytes = codec.encode(-42n); // 0xffffffffffffffffffffffffffffd6 ``` ## Remarks This codec supports values between `-2^127` and `2^127 - 1`. Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`. * If you need a smaller signed integer, consider using [getI64Codec](/api/functions/getI64Codec) or [getI32Codec](/api/functions/getI32Codec). * If you need a larger signed integer, consider using a custom codec. * If you need unsigned integers, consider using [getU128Codec](/api/functions/getU128Codec). Separate [getI128Encoder](/api/functions/getI128Encoder) and [getI128Decoder](/api/functions/getI128Decoder) functions are available. ```ts const bytes = getI128Encoder().encode(-42); const value = getI128Decoder().decode(bytes); ``` ## See * [getI128Encoder](/api/functions/getI128Encoder) * [getI128Decoder](/api/functions/getI128Decoder) # getI128Decoder (/api/functions/getI128Decoder) ```ts function getI128Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 128-bit signed integers (`i128`). This decoder deserializes `i128` values from 16 bytes. The decoded value is always a `bigint`. For more details, see [getI128Codec](/api/functions/getI128Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeDecoder`\<`bigint`, `16`> A `FixedSizeDecoder` for decoding `i128` values. ## Example Decoding an `i128` value. ```ts const decoder = getI128Decoder(); const value = decoder.decode(new Uint8Array([ 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ])); // -42n ``` ## See [getI128Codec](/api/functions/getI128Codec) # getI128Encoder (/api/functions/getI128Encoder) ```ts function getI128Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 128-bit signed integers (`i128`). This encoder serializes `i128` values using 16 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getI128Codec](/api/functions/getI128Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `16`> A `FixedSizeEncoder` for encoding `i128` values. ## Example Encoding an `i128` value. ```ts const encoder = getI128Encoder(); const bytes = encoder.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff ``` ## See [getI128Codec](/api/functions/getI128Codec) # getI16Codec (/api/functions/getI16Codec) ```ts function getI16Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 16-bit signed integers (`i16`). This codec serializes `i16` values using 2 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `number`, `2`> A `FixedSizeCodec` for encoding and decoding `i16` values. ## Examples Encoding and decoding an `i16` value. ```ts const codec = getI16Codec(); const bytes = codec.encode(-42); // 0xd6ff const value = codec.decode(bytes); // -42 ``` Using big-endian encoding. ```ts const codec = getI16Codec({ endian: Endian.Big }); const bytes = codec.encode(-42); // 0xffd6 ``` ## Remarks This codec supports values between `-2^15` (`-32,768`) and `2^15 - 1` (`32,767`). * If you need a smaller signed integer, consider using [getI8Codec](/api/functions/getI8Codec). * If you need a larger signed integer, consider using [getI32Codec](/api/functions/getI32Codec). * If you need unsigned integers, consider using [getU16Codec](/api/functions/getU16Codec). Separate [getI16Encoder](/api/functions/getI16Encoder) and [getI16Decoder](/api/functions/getI16Decoder) functions are available. ```ts const bytes = getI16Encoder().encode(-42); const value = getI16Decoder().decode(bytes); ``` ## See * [getI16Encoder](/api/functions/getI16Encoder) * [getI16Decoder](/api/functions/getI16Decoder) # getI16Decoder (/api/functions/getI16Decoder) ```ts function getI16Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 16-bit signed integers (`i16`). This decoder deserializes `i16` values from 2 bytes. The decoded value is always a `number`. For more details, see [getI16Codec](/api/functions/getI16Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeDecoder`\<`number`, `2`> A `FixedSizeDecoder` for decoding `i16` values. ## Example Decoding an `i16` value. ```ts const decoder = getI16Decoder(); const value = decoder.decode(new Uint8Array([0xd6, 0xff])); // -42 ``` ## See [getI16Codec](/api/functions/getI16Codec) # getI16Encoder (/api/functions/getI16Encoder) ```ts function getI16Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 16-bit signed integers (`i16`). This encoder serializes `i16` values using 2 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getI16Codec](/api/functions/getI16Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `2`> A `FixedSizeEncoder` for encoding `i16` values. ## Example Encoding an `i16` value. ```ts const encoder = getI16Encoder(); const bytes = encoder.encode(-42); // 0xd6ff ``` ## See [getI16Codec](/api/functions/getI16Codec) # getI32Codec (/api/functions/getI32Codec) ```ts function getI32Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 32-bit signed integers (`i32`). This codec serializes `i32` values using 4 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `number`, `4`> A `FixedSizeCodec` for encoding and decoding `i32` values. ## Examples Encoding and decoding an `i32` value. ```ts const codec = getI32Codec(); const bytes = codec.encode(-42); // 0xd6ffffff const value = codec.decode(bytes); // -42 ``` Using big-endian encoding. ```ts const codec = getI32Codec({ endian: Endian.Big }); const bytes = codec.encode(-42); // 0xffffffd6 ``` ## Remarks This codec supports values between `-2^31` (`-2,147,483,648`) and `2^31 - 1` (`2,147,483,647`). * If you need a smaller signed integer, consider using [getI16Codec](/api/functions/getI16Codec) or [getI8Codec](/api/functions/getI8Codec). * If you need a larger signed integer, consider using [getI64Codec](/api/functions/getI64Codec). * If you need unsigned integers, consider using [getU32Codec](/api/functions/getU32Codec). Separate [getI32Encoder](/api/functions/getI32Encoder) and [getI32Decoder](/api/functions/getI32Decoder) functions are available. ```ts const bytes = getI32Encoder().encode(-42); const value = getI32Decoder().decode(bytes); ``` ## See * [getI32Encoder](/api/functions/getI32Encoder) * [getI32Decoder](/api/functions/getI32Decoder) # getI32Decoder (/api/functions/getI32Decoder) ```ts function getI32Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 32-bit signed integers (`i32`). This decoder deserializes `i32` values from 4 bytes. The decoded value is always a `number`. For more details, see [getI32Codec](/api/functions/getI32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeDecoder`\<`number`, `4`> A `FixedSizeDecoder` for decoding `i32` values. ## Example Decoding an `i32` value. ```ts const decoder = getI32Decoder(); const value = decoder.decode(new Uint8Array([0xd6, 0xff, 0xff, 0xff])); // -42 ``` ## See [getI32Codec](/api/functions/getI32Codec) # getI32Encoder (/api/functions/getI32Encoder) ```ts function getI32Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 32-bit signed integers (`i32`). This encoder serializes `i32` values using 4 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getI32Codec](/api/functions/getI32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `4`> A `FixedSizeEncoder` for encoding `i32` values. ## Example Encoding an `i32` value. ```ts const encoder = getI32Encoder(); const bytes = encoder.encode(-42); // 0xd6ffffff ``` ## See [getI32Codec](/api/functions/getI32Codec) # getI64Codec (/api/functions/getI64Codec) ```ts function getI64Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 64-bit signed integers (`i64`). This codec serializes `i64` values using 8 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `bigint`, `8`> A `FixedSizeCodec` for encoding and decoding `i64` values. ## Examples Encoding and decoding an `i64` value. ```ts const codec = getI64Codec(); const bytes = codec.encode(-42n); // 0xd6ffffffffffffff const value = codec.decode(bytes); // -42n ``` Using big-endian encoding. ```ts const codec = getI64Codec({ endian: Endian.Big }); const bytes = codec.encode(-42n); // 0xffffffffffffffd6 ``` ## Remarks This codec supports values between `-2^63` and `2^63 - 1`. Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`. * If you need a smaller signed integer, consider using [getI32Codec](/api/functions/getI32Codec) or [getI16Codec](/api/functions/getI16Codec). * If you need a larger signed integer, consider using [getI128Codec](/api/functions/getI128Codec). * If you need unsigned integers, consider using [getU64Codec](/api/functions/getU64Codec). Separate [getI64Encoder](/api/functions/getI64Encoder) and [getI64Decoder](/api/functions/getI64Decoder) functions are available. ```ts const bytes = getI64Encoder().encode(-42); const value = getI64Decoder().decode(bytes); ``` ## See * [getI64Encoder](/api/functions/getI64Encoder) * [getI64Decoder](/api/functions/getI64Decoder) # getI64Decoder (/api/functions/getI64Decoder) ```ts function getI64Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 64-bit signed integers (`i64`). This decoder deserializes `i64` values from 8 bytes. The decoded value is always a `bigint`. For more details, see [getI64Codec](/api/functions/getI64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeDecoder`\<`bigint`, `8`> A `FixedSizeDecoder` for decoding `i64` values. ## Example Decoding an `i64` value. ```ts const decoder = getI64Decoder(); const value = decoder.decode(new Uint8Array([ 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ])); // -42n ``` ## See [getI64Codec](/api/functions/getI64Codec) # getI64Encoder (/api/functions/getI64Encoder) ```ts function getI64Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 64-bit signed integers (`i64`). This encoder serializes `i64` values using 8 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getI64Codec](/api/functions/getI64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `8`> A `FixedSizeEncoder` for encoding `i64` values. ## Example Encoding an `i64` value. ```ts const encoder = getI64Encoder(); const bytes = encoder.encode(-42n); // 0xd6ffffffffffffff ``` ## See [getI64Codec](/api/functions/getI64Codec) # getI8Codec (/api/functions/getI8Codec) ```ts function getI8Codec(): FixedSizeCodec; ``` Returns a codec for encoding and decoding 8-bit signed integers (`i8`). This codec serializes `i8` values using 1 byte. Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. ## Returns `FixedSizeCodec`\<`number` | `bigint`, `number`, `1`> A `FixedSizeCodec` for encoding and decoding `i8` values. ## Example Encoding and decoding an `i8` value. ```ts const codec = getI8Codec(); const bytes = codec.encode(-42); // 0xd6 const value = codec.decode(bytes); // -42 ``` ## Remarks This codec supports values between `-2^7` (`-128`) and `2^7 - 1` (`127`). * If you need a larger signed integer, consider using [getI16Codec](/api/functions/getI16Codec). * If you need an unsigned integer, consider using [getU8Codec](/api/functions/getU8Codec). Separate [getI8Encoder](/api/functions/getI8Encoder) and [getI8Decoder](/api/functions/getI8Decoder) functions are available. ```ts const bytes = getI8Encoder().encode(-42); const value = getI8Decoder().decode(bytes); ``` ## See * [getI8Encoder](/api/functions/getI8Encoder) * [getI8Decoder](/api/functions/getI8Decoder) # getI8Decoder (/api/functions/getI8Decoder) ```ts function getI8Decoder(): FixedSizeDecoder; ``` Returns a decoder for 8-bit signed integers (`i8`). This decoder deserializes `i8` values from 1 byte. The decoded value is always a `number`. For more details, see [getI8Codec](/api/functions/getI8Codec). ## Returns `FixedSizeDecoder`\<`number`, `1`> A `FixedSizeDecoder` for decoding `i8` values. ## Example Decoding an `i8` value. ```ts const decoder = getI8Decoder(); const value = decoder.decode(new Uint8Array([0xd6])); // -42 ``` ## See [getI8Codec](/api/functions/getI8Codec) # getI8Encoder (/api/functions/getI8Encoder) ```ts function getI8Encoder(): FixedSizeEncoder; ``` Returns an encoder for 8-bit signed integers (`i8`). This encoder serializes `i8` values using 1 byte. Values can be provided as either `number` or `bigint`. For more details, see [getI8Codec](/api/functions/getI8Codec). ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `1`> A `FixedSizeEncoder` for encoding `i8` values. ## Example Encoding an `i8` value. ```ts const encoder = getI8Encoder(); const bytes = encoder.encode(-42); // 0xd6 ``` ## See [getI8Codec](/api/functions/getI8Codec) # getInnerInstructionsFromMeta (/api/functions/getInnerInstructionsFromMeta) ```ts function getInnerInstructionsFromMeta( meta, accountMetas, ): TracedInstruction[]; ``` Returns the inner instructions in a `getTransaction` response as [TracedInstruction](/api/type-aliases/TracedInstruction)s. The RPC returns inner instructions in a different shape from the wire format: indices reference the same flat account list as the outer instructions, but `data` is a base58-encoded string. This helper decodes the data, resolves the indices against the supplied AccountMeta list, and tags each instruction with an `inner` trace. Throws if any `programIdIndex` or account index falls outside the supplied `accountMetas` list. ## Parameters | Parameter | Type | | -------------- | -------------------------------------------------------------------------- | | `meta` | [`MetaWithInnerInstructions`](/api/type-aliases/MetaWithInnerInstructions) | | `accountMetas` | readonly `AccountMeta`\<`string`>\[] | ## Returns [`TracedInstruction`](/api/type-aliases/TracedInstruction)\[] ## Example ```ts const accountMetas = getAccountMetasFromCompiledTransactionMessage(compiledMessage, loadedAddresses); const inner = getInnerInstructionsFromMeta(rpcResponse.meta, accountMetas); ``` # getInstructionsFromCompiledTransactionMessage (/api/functions/getInstructionsFromCompiledTransactionMessage) ```ts function getInstructionsFromCompiledTransactionMessage( compiledMessage, loadedAddresses?, ): ResolvedInstruction[]; ``` Returns the outer instructions of a compiled transaction message as kit Instruction objects. Each returned instruction has its account indices resolved to AccountMetas (with the proper signer/writable bits) and its data exposed as a `ReadonlyUint8Array` β€” the form the auto-generated `@solana-program/*` `parseXInstruction` functions expect. `accounts` and `data` are omitted when empty. Supports `legacy`, `v0`, and `v1` compiled messages. Throws SOLANA\_ERROR\_\_TRANSACTION\_\_VERSION\_NUMBER\_NOT\_SUPPORTED for any other version, SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_TO\_DECOMPILE\_INSTRUCTION\_PROGRAM\_ADDRESS\_NOT\_FOUND if a `programAddressIndex` falls outside the resolved account list, and SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_TO\_DECOMPILE\_INSTRUCTION\_ACCOUNT\_INDEX\_OUT\_OF\_RANGE if an account index does. ## Parameters | Parameter | Type | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `compiledMessage` | `CompiledTransactionMessage` | | `loadedAddresses?` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `readonly`: readonly `Address`\[]; `writable`: readonly `Address`\[]; }> \| `null` | ## Returns [`ResolvedInstruction`](/api/type-aliases/ResolvedInstruction)\<`string`>\[] ## Example ```ts const instructions = getInstructionsFromCompiledTransactionMessage( compiled, rpcResponse.meta?.loadedAddresses, ); for (const ix of instructions) { if (ix.programAddress === TOKEN_PROGRAM_ADDRESS && isInstructionWithData(ix)) { const kind = identifyTokenInstruction(ix); // ... } } ``` # getIntegerOverflowRequestTransformer (/api/functions/getIntegerOverflowRequestTransformer) ```ts function getIntegerOverflowRequestTransformer( onIntegerOverflow, ): (request) => RpcRequest; ``` Creates a transformer that traverses the request parameters and executes the provided handler when an integer overflow is detected. ## Parameters | Parameter | Type | | ------------------- | -------------------------------------------------------------------- | | `onIntegerOverflow` | [`IntegerOverflowHandler`](/api/type-aliases/IntegerOverflowHandler) | ## Returns \<`TParams`>(`request`) => `RpcRequest` ## Example ```ts import { getIntegerOverflowRequestTransformer } from '@solana/rpc-transformers'; const requestTransformer = getIntegerOverflowRequestTransformer((request, keyPath, value) => { throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`); }); ``` # getLamportsCodec (/api/functions/getLamportsCodec) ```ts function getLamportsCodec( innerCodec, ): Codec & ExtractAdditionalProps; ``` Returns a codec that you can use to encode from or decode to a [Lamports](/api/type-aliases/Lamports) value. The encoder also accepts a [Sol](/api/type-aliases/Sol) fixed-point value; the decoder always returns [Lamports](/api/type-aliases/Lamports). ## Type Parameters | Type Parameter | | -------------------------------- | | `TCodec` *extends* `NumberCodec` | ## Parameters | Parameter | Type | | ------------ | -------- | | `innerCodec` | `TCodec` | ## Returns `Codec`\< \| [`Sol`](/api/type-aliases/Sol) \| [`Lamports`](/api/type-aliases/Lamports), [`Lamports`](/api/type-aliases/Lamports)> & `ExtractAdditionalProps`\<`TCodec`, `NumberCodec`> ## See * [getLamportsDecoder](/api/functions/getLamportsDecoder) * [getLamportsEncoder](/api/functions/getLamportsEncoder) # getLamportsDecoder (/api/functions/getLamportsDecoder) ```ts function getLamportsDecoder( innerDecoder, ): Decoder & ExtractAdditionalProps; ``` Returns a decoder that you can use to convert an array of bytes representing a number to a [Lamports](/api/type-aliases/Lamports) value. You must supply a number decoder that will determine how many bits to use to decode the numeric value. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TDecoder` *extends* `NumberDecoder` | ## Parameters | Parameter | Type | | -------------- | ---------- | | `innerDecoder` | `TDecoder` | ## Returns `Decoder`\<[`Lamports`](/api/type-aliases/Lamports)> & `ExtractAdditionalProps`\<`TDecoder`, `NumberDecoder`> ## Example ```ts import { getLamportsDecoder } from '@solana/rpc-types'; import { getU16Decoder } from '@solana/codecs-numbers'; const lamportsBytes = new Uint8Array([ 0, 1 ]); const lamportsDecoder = getLamportsDecoder(getU16Decoder()); const lamports = lamportsDecoder.decode(lamportsBytes); // lamports(256n) ``` # getLamportsEncoder (/api/functions/getLamportsEncoder) ```ts function getLamportsEncoder( innerEncoder, ): Encoder & ExtractAdditionalProps; ``` Returns an encoder that you can use to encode a [Lamports](/api/type-aliases/Lamports) value to a byte array. The encoder also accepts a [Sol](/api/type-aliases/Sol) fixed-point value, whose `raw` bigint is written as if it were a Lamports value. You must supply a number decoder that will determine how encode the numeric value. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TEncoder` *extends* `NumberEncoder` | ## Parameters | Parameter | Type | | -------------- | ---------- | | `innerEncoder` | `TEncoder` | ## Returns `Encoder`\< \| [`Sol`](/api/type-aliases/Sol) \| [`Lamports`](/api/type-aliases/Lamports)> & `ExtractAdditionalProps`\<`TEncoder`, `NumberEncoder`> ## Example ```ts import { getLamportsEncoder } from '@solana/rpc-types'; import { getU16Encoder } from '@solana/codecs-numbers'; const lamports = lamports(256n); const lamportsEncoder = getLamportsEncoder(getU16Encoder()); const lamportsBytes = lamportsEncoder.encode(lamports); // Uint8Array(2) [ 0, 1 ] ``` # getLinearMessagePackerInstructionPlan (/api/functions/getLinearMessagePackerInstructionPlan) ```ts function getLinearMessagePackerInstructionPlan( getInstruction, ): MessagePackerInstructionPlan; ``` Creates a [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) that packs instructions such that each instruction consumes as many bytes as possible from the given `totalLength` while still being able to fit into the given transaction messages. This is particularly useful for instructions that write data to accounts and must span multiple transactions due to their size limit. This message packer will first call `getInstruction` with a length of zero to determine the base size of the instruction before figuring out how many additional bytes can be packed into the transaction message. That remaining space will then be used to call `getInstruction` again with the appropriate length. ## Parameters | Parameter | Type | Description | | ------------------------------- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | `getInstruction` | \{ `getInstruction`: (`offset`, `length`) => [`Instruction`](/api/interfaces/Instruction); `totalLength`: `number`; } | A function that returns an instruction for a given offset and length. | | `getInstruction.getInstruction` | (`offset`, `length`) => [`Instruction`](/api/interfaces/Instruction) | - | | `getInstruction.totalLength` | `number` | - | ## Returns [`MessagePackerInstructionPlan`](/api/type-aliases/MessagePackerInstructionPlan) ## Example ```ts const plan = getLinearMessagePackerInstructionPlan({ totalLength: dataToWrite.length, getInstruction: (offset, length) => getWriteInstruction({ offset, data: dataToWrite.slice(offset, offset + length), }), }); plan satisfies MessagePackerInstructionPlan; ``` ## See [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) # getLiteralUnionCodec (/api/functions/getLiteralUnionCodec) ## Call Signature ```ts function getLiteralUnionCodec( variants, ): FixedSizeCodec< GetTypeFromVariants, GetTypeFromVariants, 1 >; ``` Returns a codec for encoding and decoding literal unions. A literal union codec serializes and deserializes values from a predefined set of literals, using a numerical index to represent each value in the `variants` array. This allows efficient storage and retrieval of common predefined values such as enum-like structures in TypeScript. ### Type Parameters | Type Parameter | Description | | ------------------------------------------- | ---------------------------------- | | `TVariants` *extends* readonly `Variant`\[] | A tuple of allowed literal values. | ### Parameters | Parameter | Type | Description | | ---------- | ----------- | ------------------------------------------ | | `variants` | `TVariants` | The possible literal values for the union. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`GetTypeFromVariants`\<`TVariants`>, `GetTypeFromVariants`\<`TVariants`>, `1`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding literal unions. ### Examples Encoding and decoding a union of string literals. ```ts type Size = 'small' | 'medium' | 'large'; const sizeCodec = getLiteralUnionCodec(['small', 'medium', 'large']); sizeCodec.encode('small'); // 0x00 sizeCodec.encode('medium'); // 0x01 sizeCodec.encode('large'); // 0x02 sizeCodec.decode(new Uint8Array([0x00])); // 'small' sizeCodec.decode(new Uint8Array([0x01])); // 'medium' sizeCodec.decode(new Uint8Array([0x02])); // 'large' ``` Encoding and decoding a union of number literals. ```ts type Level = 10 | 20 | 30; const levelCodec = getLiteralUnionCodec([10, 20, 30]); levelCodec.encode(10); // 0x00 levelCodec.encode(20); // 0x01 levelCodec.encode(30); // 0x02 levelCodec.decode(new Uint8Array([0x00])); // 10 levelCodec.decode(new Uint8Array([0x01])); // 20 levelCodec.decode(new Uint8Array([0x02])); // 30 ``` Using a custom discriminator size with different variant types. ```ts type MaybeBoolean = false | true | "either"; const codec = getLiteralUnionCodec([false, true, 'either'], { size: getU16Codec() }); codec.encode(false); // 0x0000 codec.encode(true); // 0x0100 codec.encode('either'); // 0x0200 codec.decode(new Uint8Array([0x00, 0x00])); // false codec.decode(new Uint8Array([0x01, 0x00])); // true codec.decode(new Uint8Array([0x02, 0x00])); // 'either' ``` ### Remarks Separate [getLiteralUnionEncoder](/api/functions/getLiteralUnionEncoder) and [getLiteralUnionDecoder](/api/functions/getLiteralUnionDecoder) functions are available. ```ts const bytes = getLiteralUnionEncoder(['red', 'green', 'blue']).encode('green'); const value = getLiteralUnionDecoder(['red', 'green', 'blue']).decode(bytes); ``` ### See * [getLiteralUnionEncoder](/api/functions/getLiteralUnionEncoder) * [getLiteralUnionDecoder](/api/functions/getLiteralUnionDecoder) ## Call Signature ```ts function getLiteralUnionCodec( variants, config, ): FixedSizeCodec< GetTypeFromVariants, GetTypeFromVariants, TSize >; ``` Returns a codec for encoding and decoding literal unions. A literal union codec serializes and deserializes values from a predefined set of literals, using a numerical index to represent each value in the `variants` array. This allows efficient storage and retrieval of common predefined values such as enum-like structures in TypeScript. ### Type Parameters | Type Parameter | Description | | ------------------------------------------- | ---------------------------------- | | `TVariants` *extends* readonly `Variant`\[] | A tuple of allowed literal values. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | ---------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | `variants` | `TVariants` | The possible literal values for the union. | | `config` | [`LiteralUnionCodecConfig`](/api/type-aliases/LiteralUnionCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Configuration options for encoding and decoding the literal union. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`GetTypeFromVariants`\<`TVariants`>, `GetTypeFromVariants`\<`TVariants`>, `TSize`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding literal unions. ### Examples Encoding and decoding a union of string literals. ```ts type Size = 'small' | 'medium' | 'large'; const sizeCodec = getLiteralUnionCodec(['small', 'medium', 'large']); sizeCodec.encode('small'); // 0x00 sizeCodec.encode('medium'); // 0x01 sizeCodec.encode('large'); // 0x02 sizeCodec.decode(new Uint8Array([0x00])); // 'small' sizeCodec.decode(new Uint8Array([0x01])); // 'medium' sizeCodec.decode(new Uint8Array([0x02])); // 'large' ``` Encoding and decoding a union of number literals. ```ts type Level = 10 | 20 | 30; const levelCodec = getLiteralUnionCodec([10, 20, 30]); levelCodec.encode(10); // 0x00 levelCodec.encode(20); // 0x01 levelCodec.encode(30); // 0x02 levelCodec.decode(new Uint8Array([0x00])); // 10 levelCodec.decode(new Uint8Array([0x01])); // 20 levelCodec.decode(new Uint8Array([0x02])); // 30 ``` Using a custom discriminator size with different variant types. ```ts type MaybeBoolean = false | true | "either"; const codec = getLiteralUnionCodec([false, true, 'either'], { size: getU16Codec() }); codec.encode(false); // 0x0000 codec.encode(true); // 0x0100 codec.encode('either'); // 0x0200 codec.decode(new Uint8Array([0x00, 0x00])); // false codec.decode(new Uint8Array([0x01, 0x00])); // true codec.decode(new Uint8Array([0x02, 0x00])); // 'either' ``` ### Remarks Separate [getLiteralUnionEncoder](/api/functions/getLiteralUnionEncoder) and [getLiteralUnionDecoder](/api/functions/getLiteralUnionDecoder) functions are available. ```ts const bytes = getLiteralUnionEncoder(['red', 'green', 'blue']).encode('green'); const value = getLiteralUnionDecoder(['red', 'green', 'blue']).decode(bytes); ``` ### See * [getLiteralUnionEncoder](/api/functions/getLiteralUnionEncoder) * [getLiteralUnionDecoder](/api/functions/getLiteralUnionDecoder) ## Call Signature ```ts function getLiteralUnionCodec( variants, config?, ): VariableSizeCodec>; ``` Returns a codec for encoding and decoding literal unions. A literal union codec serializes and deserializes values from a predefined set of literals, using a numerical index to represent each value in the `variants` array. This allows efficient storage and retrieval of common predefined values such as enum-like structures in TypeScript. ### Type Parameters | Type Parameter | Description | | ------------------------------------------- | ---------------------------------- | | `TVariants` *extends* readonly `Variant`\[] | A tuple of allowed literal values. | ### Parameters | Parameter | Type | Description | | ---------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | `variants` | `TVariants` | The possible literal values for the union. | | `config?` | [`LiteralUnionCodecConfig`](/api/type-aliases/LiteralUnionCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> | Configuration options for encoding and decoding the literal union. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`GetTypeFromVariants`\<`TVariants`>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding literal unions. ### Examples Encoding and decoding a union of string literals. ```ts type Size = 'small' | 'medium' | 'large'; const sizeCodec = getLiteralUnionCodec(['small', 'medium', 'large']); sizeCodec.encode('small'); // 0x00 sizeCodec.encode('medium'); // 0x01 sizeCodec.encode('large'); // 0x02 sizeCodec.decode(new Uint8Array([0x00])); // 'small' sizeCodec.decode(new Uint8Array([0x01])); // 'medium' sizeCodec.decode(new Uint8Array([0x02])); // 'large' ``` Encoding and decoding a union of number literals. ```ts type Level = 10 | 20 | 30; const levelCodec = getLiteralUnionCodec([10, 20, 30]); levelCodec.encode(10); // 0x00 levelCodec.encode(20); // 0x01 levelCodec.encode(30); // 0x02 levelCodec.decode(new Uint8Array([0x00])); // 10 levelCodec.decode(new Uint8Array([0x01])); // 20 levelCodec.decode(new Uint8Array([0x02])); // 30 ``` Using a custom discriminator size with different variant types. ```ts type MaybeBoolean = false | true | "either"; const codec = getLiteralUnionCodec([false, true, 'either'], { size: getU16Codec() }); codec.encode(false); // 0x0000 codec.encode(true); // 0x0100 codec.encode('either'); // 0x0200 codec.decode(new Uint8Array([0x00, 0x00])); // false codec.decode(new Uint8Array([0x01, 0x00])); // true codec.decode(new Uint8Array([0x02, 0x00])); // 'either' ``` ### Remarks Separate [getLiteralUnionEncoder](/api/functions/getLiteralUnionEncoder) and [getLiteralUnionDecoder](/api/functions/getLiteralUnionDecoder) functions are available. ```ts const bytes = getLiteralUnionEncoder(['red', 'green', 'blue']).encode('green'); const value = getLiteralUnionDecoder(['red', 'green', 'blue']).decode(bytes); ``` ### See * [getLiteralUnionEncoder](/api/functions/getLiteralUnionEncoder) * [getLiteralUnionDecoder](/api/functions/getLiteralUnionDecoder) # getLiteralUnionDecoder (/api/functions/getLiteralUnionDecoder) ## Call Signature ```ts function getLiteralUnionDecoder( variants, ): FixedSizeDecoder, 1>; ``` Returns a decoder for literal unions. This decoder deserializes a numerical index into a corresponding value from a predefined set of literals. For more details, see [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------------- | ---------------------------------- | | `TVariants` *extends* readonly `Variant`\[] | A tuple of allowed literal values. | ### Parameters | Parameter | Type | Description | | ---------- | ----------- | ------------------------------------------ | | `variants` | `TVariants` | The possible literal values for the union. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`GetTypeFromVariants`\<`TVariants`>, `1`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding literal unions. ### Example Decoding a union of string literals. ```ts type Size = 'small' | 'medium' | 'large'; const sizeDecoder = getLiteralUnionDecoder(['small', 'medium', 'large']); sizeDecoder.decode(new Uint8Array([0x00])); // 'small' sizeDecoder.decode(new Uint8Array([0x01])); // 'medium' sizeDecoder.decode(new Uint8Array([0x02])); // 'large' ``` ### See [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec) ## Call Signature ```ts function getLiteralUnionDecoder( variants, config, ): FixedSizeDecoder, TSize>; ``` Returns a decoder for literal unions. This decoder deserializes a numerical index into a corresponding value from a predefined set of literals. For more details, see [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------------- | ---------------------------------- | | `TVariants` *extends* readonly `Variant`\[] | A tuple of allowed literal values. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | `variants` | `TVariants` | The possible literal values for the union. | | `config` | [`LiteralUnionCodecConfig`](/api/type-aliases/LiteralUnionCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Configuration options for decoding the literal union. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`GetTypeFromVariants`\<`TVariants`>, `TSize`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding literal unions. ### Example Decoding a union of string literals. ```ts type Size = 'small' | 'medium' | 'large'; const sizeDecoder = getLiteralUnionDecoder(['small', 'medium', 'large']); sizeDecoder.decode(new Uint8Array([0x00])); // 'small' sizeDecoder.decode(new Uint8Array([0x01])); // 'medium' sizeDecoder.decode(new Uint8Array([0x02])); // 'large' ``` ### See [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec) ## Call Signature ```ts function getLiteralUnionDecoder( variants, config?, ): VariableSizeDecoder>; ``` Returns a decoder for literal unions. This decoder deserializes a numerical index into a corresponding value from a predefined set of literals. For more details, see [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------------- | ---------------------------------- | | `TVariants` *extends* readonly `Variant`\[] | A tuple of allowed literal values. | ### Parameters | Parameter | Type | Description | | ---------- | --------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | `variants` | `TVariants` | The possible literal values for the union. | | `config?` | [`LiteralUnionCodecConfig`](/api/type-aliases/LiteralUnionCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> | Configuration options for decoding the literal union. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`GetTypeFromVariants`\<`TVariants`>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding literal unions. ### Example Decoding a union of string literals. ```ts type Size = 'small' | 'medium' | 'large'; const sizeDecoder = getLiteralUnionDecoder(['small', 'medium', 'large']); sizeDecoder.decode(new Uint8Array([0x00])); // 'small' sizeDecoder.decode(new Uint8Array([0x01])); // 'medium' sizeDecoder.decode(new Uint8Array([0x02])); // 'large' ``` ### See [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec) # getLiteralUnionEncoder (/api/functions/getLiteralUnionEncoder) ## Call Signature ```ts function getLiteralUnionEncoder( variants, ): FixedSizeEncoder, 1>; ``` Returns an encoder for literal unions. This encoder serializes a value from a predefined set of literals as a numerical index representing its position in the `variants` array. For more details, see [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------------- | ---------------------------------- | | `TVariants` *extends* readonly `Variant`\[] | A tuple of allowed literal values. | ### Parameters | Parameter | Type | Description | | ---------- | ----------- | ------------------------------------------ | | `variants` | `TVariants` | The possible literal values for the union. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`GetTypeFromVariants`\<`TVariants`>, `1`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding literal unions. ### Example Encoding a union of string literals. ```ts type Size = 'small' | 'medium' | 'large'; const sizeEncoder = getLiteralUnionEncoder(['small', 'medium', 'large']); sizeEncoder.encode('small'); // 0x00 sizeEncoder.encode('medium'); // 0x01 sizeEncoder.encode('large'); // 0x02 ``` ### See [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec) ## Call Signature ```ts function getLiteralUnionEncoder( variants, config, ): FixedSizeEncoder, TSize>; ``` Returns an encoder for literal unions. This encoder serializes a value from a predefined set of literals as a numerical index representing its position in the `variants` array. For more details, see [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------------- | ---------------------------------- | | `TVariants` *extends* readonly `Variant`\[] | A tuple of allowed literal values. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | `variants` | `TVariants` | The possible literal values for the union. | | `config` | [`LiteralUnionCodecConfig`](/api/type-aliases/LiteralUnionCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Configuration options for encoding the literal union. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`GetTypeFromVariants`\<`TVariants`>, `TSize`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding literal unions. ### Example Encoding a union of string literals. ```ts type Size = 'small' | 'medium' | 'large'; const sizeEncoder = getLiteralUnionEncoder(['small', 'medium', 'large']); sizeEncoder.encode('small'); // 0x00 sizeEncoder.encode('medium'); // 0x01 sizeEncoder.encode('large'); // 0x02 ``` ### See [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec) ## Call Signature ```ts function getLiteralUnionEncoder( variants, config?, ): VariableSizeEncoder>; ``` Returns an encoder for literal unions. This encoder serializes a value from a predefined set of literals as a numerical index representing its position in the `variants` array. For more details, see [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec). ### Type Parameters | Type Parameter | Description | | ------------------------------------------- | ---------------------------------- | | `TVariants` *extends* readonly `Variant`\[] | A tuple of allowed literal values. | ### Parameters | Parameter | Type | Description | | ---------- | --------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | `variants` | `TVariants` | The possible literal values for the union. | | `config?` | [`LiteralUnionCodecConfig`](/api/type-aliases/LiteralUnionCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> | Configuration options for encoding the literal union. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`GetTypeFromVariants`\<`TVariants`>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding literal unions. ### Example Encoding a union of string literals. ```ts type Size = 'small' | 'medium' | 'large'; const sizeEncoder = getLiteralUnionEncoder(['small', 'medium', 'large']); sizeEncoder.encode('small'); // 0x00 sizeEncoder.encode('medium'); // 0x01 sizeEncoder.encode('large'); // 0x02 ``` ### See [getLiteralUnionCodec](/api/functions/getLiteralUnionCodec) # getMapCodec (/api/functions/getMapCodec) ## Call Signature ```ts function getMapCodec( key, value, config, ): FixedSizeCodec, Map, 0>; ``` Returns a codec for encoding and decoding maps. This codec serializes maps where the key/value pairs are encoded and decoded one after another using the provided key and value codecs. The number of entries is determined by the `size` configuration and defaults to a `u32` size prefix. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | --------------------------------------- | | `TFromKey` | - | The type of the keys before encoding. | | `TFromValue` | - | The type of the values before encoding. | | `TToKey` | `TFromKey` | The type of the keys after decoding. | | `TToValue` | `TFromValue` | The type of the values after decoding. | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | `key` | [`Codec`](/api/type-aliases/Codec)\<`TFromKey`, `TToKey`> | The codec for the map's keys. | | `value` | [`Codec`](/api/type-aliases/Codec)\<`TFromValue`, `TToValue`> | The codec for the map's values. | | `config` | [`MapCodecConfig`](/api/type-aliases/MapCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Configuration options for encoding and decoding the map. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<[`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TFromKey`, `TFromValue`>, [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TToKey`, `TToValue`>, `0`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding maps. ### Examples Encoding and decoding a map with a `u32` size prefix (default). ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec()); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x02000000616c6963652a626f62000005 // | | | | └── Value (5) // | | | └── Key ("bob", 5 bytes fixed, null-padded) // | | └── Value (42) // | └── Key ("alice", 5 bytes fixed) // └── 4-byte prefix (2 entries) const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` Encoding and decoding a map with a `u16` size prefix. ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: getU16Codec() }); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x0200616c6963652a626f62000005 // | | | | └── Value (5) // | | | └── Key ("bob", 5 bytes fixed, null-padded) // | | └── Value (42) // | └── Key ("alice", 5 bytes fixed) // └── 2-byte prefix (2 entries) const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` Encoding and decoding a fixed-size map. ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 2 }); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x616c6963652a626f62000005 // | | | └── Value (5) // | | └── Key ("bob", 5 bytes fixed, null-padded) // | └── Value (42) // └── Key ("alice", 5 bytes fixed) const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` Encoding and decoding a map with remainder size. ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 'remainder' }); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x616c6963652a626f62000005 // | | | └── Value (5) // | | └── Key ("bob", 5 bytes fixed, null-padded) // | └── Value (42) // └── Key ("alice", 5 bytes fixed) // No size prefix, the size is inferred from the remaining bytes. const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` ### Remarks Separate [getMapEncoder](/api/functions/getMapEncoder) and [getMapDecoder](/api/functions/getMapDecoder) functions are available. ```ts const bytes = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()).encode(new Map([['alice', 42]])); const map = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()).decode(bytes); ``` ### See * [getMapEncoder](/api/functions/getMapEncoder) * [getMapDecoder](/api/functions/getMapDecoder) ## Call Signature ```ts function getMapCodec( key, value, config, ): FixedSizeCodec, Map>; ``` Returns a codec for encoding and decoding maps. This codec serializes maps where the key/value pairs are encoded and decoded one after another using the provided key and value codecs. The number of entries is determined by the `size` configuration and defaults to a `u32` size prefix. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | --------------------------------------- | | `TFromKey` | - | The type of the keys before encoding. | | `TFromValue` | - | The type of the values before encoding. | | `TToKey` | `TFromKey` | The type of the keys after decoding. | | `TToValue` | `TFromValue` | The type of the values after decoding. | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | `key` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFromKey`, `TToKey`> | The codec for the map's keys. | | `value` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFromValue`, `TToValue`> | The codec for the map's values. | | `config` | [`MapCodecConfig`](/api/type-aliases/MapCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Configuration options for encoding and decoding the map. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<[`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TFromKey`, `TFromValue`>, [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TToKey`, `TToValue`>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding maps. ### Examples Encoding and decoding a map with a `u32` size prefix (default). ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec()); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x02000000616c6963652a626f62000005 // | | | | └── Value (5) // | | | └── Key ("bob", 5 bytes fixed, null-padded) // | | └── Value (42) // | └── Key ("alice", 5 bytes fixed) // └── 4-byte prefix (2 entries) const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` Encoding and decoding a map with a `u16` size prefix. ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: getU16Codec() }); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x0200616c6963652a626f62000005 // | | | | └── Value (5) // | | | └── Key ("bob", 5 bytes fixed, null-padded) // | | └── Value (42) // | └── Key ("alice", 5 bytes fixed) // └── 2-byte prefix (2 entries) const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` Encoding and decoding a fixed-size map. ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 2 }); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x616c6963652a626f62000005 // | | | └── Value (5) // | | └── Key ("bob", 5 bytes fixed, null-padded) // | └── Value (42) // └── Key ("alice", 5 bytes fixed) const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` Encoding and decoding a map with remainder size. ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 'remainder' }); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x616c6963652a626f62000005 // | | | └── Value (5) // | | └── Key ("bob", 5 bytes fixed, null-padded) // | └── Value (42) // └── Key ("alice", 5 bytes fixed) // No size prefix, the size is inferred from the remaining bytes. const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` ### Remarks Separate [getMapEncoder](/api/functions/getMapEncoder) and [getMapDecoder](/api/functions/getMapDecoder) functions are available. ```ts const bytes = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()).encode(new Map([['alice', 42]])); const map = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()).decode(bytes); ``` ### See * [getMapEncoder](/api/functions/getMapEncoder) * [getMapDecoder](/api/functions/getMapDecoder) ## Call Signature ```ts function getMapCodec( key, value, config?, ): VariableSizeCodec, Map>; ``` Returns a codec for encoding and decoding maps. This codec serializes maps where the key/value pairs are encoded and decoded one after another using the provided key and value codecs. The number of entries is determined by the `size` configuration and defaults to a `u32` size prefix. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | --------------------------------------- | | `TFromKey` | - | The type of the keys before encoding. | | `TFromValue` | - | The type of the values before encoding. | | `TToKey` | `TFromKey` | The type of the keys after decoding. | | `TToValue` | `TFromValue` | The type of the values after decoding. | ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | `key` | [`Codec`](/api/type-aliases/Codec)\<`TFromKey`, `TToKey`> | The codec for the map's keys. | | `value` | [`Codec`](/api/type-aliases/Codec)\<`TFromValue`, `TToValue`> | The codec for the map's values. | | `config?` | [`MapCodecConfig`](/api/type-aliases/MapCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> | Configuration options for encoding and decoding the map. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<[`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TFromKey`, `TFromValue`>, [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TToKey`, `TToValue`>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding maps. ### Examples Encoding and decoding a map with a `u32` size prefix (default). ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec()); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x02000000616c6963652a626f62000005 // | | | | └── Value (5) // | | | └── Key ("bob", 5 bytes fixed, null-padded) // | | └── Value (42) // | └── Key ("alice", 5 bytes fixed) // └── 4-byte prefix (2 entries) const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` Encoding and decoding a map with a `u16` size prefix. ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: getU16Codec() }); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x0200616c6963652a626f62000005 // | | | | └── Value (5) // | | | └── Key ("bob", 5 bytes fixed, null-padded) // | | └── Value (42) // | └── Key ("alice", 5 bytes fixed) // └── 2-byte prefix (2 entries) const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` Encoding and decoding a fixed-size map. ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 2 }); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x616c6963652a626f62000005 // | | | └── Value (5) // | | └── Key ("bob", 5 bytes fixed, null-padded) // | └── Value (42) // └── Key ("alice", 5 bytes fixed) const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` Encoding and decoding a map with remainder size. ```ts const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 'remainder' }); const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]])); // 0x616c6963652a626f62000005 // | | | └── Value (5) // | | └── Key ("bob", 5 bytes fixed, null-padded) // | └── Value (42) // └── Key ("alice", 5 bytes fixed) // No size prefix, the size is inferred from the remaining bytes. const map = codec.decode(bytes); // new Map([['alice', 42], ['bob', 5]]) ``` ### Remarks Separate [getMapEncoder](/api/functions/getMapEncoder) and [getMapDecoder](/api/functions/getMapDecoder) functions are available. ```ts const bytes = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()).encode(new Map([['alice', 42]])); const map = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()).decode(bytes); ``` ### See * [getMapEncoder](/api/functions/getMapEncoder) * [getMapDecoder](/api/functions/getMapDecoder) # getMapDecoder (/api/functions/getMapDecoder) ## Call Signature ```ts function getMapDecoder( key, value, config, ): FixedSizeDecoder, 0>; ``` Returns a decoder for maps. This decoder deserializes maps where the keys and values are decoded using the provided key and value decoders. The number of entries is determined by the `size` configuration. For more details, see [getMapCodec](/api/functions/getMapCodec). ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------------- | | `TToKey` | The type of the keys after decoding. | | `TToValue` | The type of the values after decoding. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | `key` | [`Decoder`](/api/type-aliases/Decoder)\<`TToKey`> | The decoder for the map's keys. | | `value` | [`Decoder`](/api/type-aliases/Decoder)\<`TToValue`> | The decoder for the map's values. | | `config` | [`MapCodecConfig`](/api/type-aliases/MapCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Configuration options for decoding the map. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<[`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TToKey`, `TToValue`>, `0`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding maps. ### Example Decoding a map with a `u32` size prefix. ```ts const decoder = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()); const map = decoder.decode(new Uint8Array([ 0x02,0x00,0x00,0x00,0x61,0x6c,0x69,0x63,0x65,0x2a,0x62,0x6f,0x62,0x00,0x00,0x05 ])); // new Map([['alice', 42], ['bob', 5]]) ``` ### See [getMapCodec](/api/functions/getMapCodec) ## Call Signature ```ts function getMapDecoder( key, value, config, ): FixedSizeDecoder>; ``` Returns a decoder for maps. This decoder deserializes maps where the keys and values are decoded using the provided key and value decoders. The number of entries is determined by the `size` configuration. For more details, see [getMapCodec](/api/functions/getMapCodec). ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------------- | | `TToKey` | The type of the keys after decoding. | | `TToValue` | The type of the values after decoding. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | `key` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TToKey`> | The decoder for the map's keys. | | `value` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TToValue`> | The decoder for the map's values. | | `config` | [`MapCodecConfig`](/api/type-aliases/MapCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Configuration options for decoding the map. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<[`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TToKey`, `TToValue`>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding maps. ### Example Decoding a map with a `u32` size prefix. ```ts const decoder = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()); const map = decoder.decode(new Uint8Array([ 0x02,0x00,0x00,0x00,0x61,0x6c,0x69,0x63,0x65,0x2a,0x62,0x6f,0x62,0x00,0x00,0x05 ])); // new Map([['alice', 42], ['bob', 5]]) ``` ### See [getMapCodec](/api/functions/getMapCodec) ## Call Signature ```ts function getMapDecoder( key, value, config?, ): VariableSizeDecoder>; ``` Returns a decoder for maps. This decoder deserializes maps where the keys and values are decoded using the provided key and value decoders. The number of entries is determined by the `size` configuration. For more details, see [getMapCodec](/api/functions/getMapCodec). ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------------- | | `TToKey` | The type of the keys after decoding. | | `TToValue` | The type of the values after decoding. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | `key` | [`Decoder`](/api/type-aliases/Decoder)\<`TToKey`> | The decoder for the map's keys. | | `value` | [`Decoder`](/api/type-aliases/Decoder)\<`TToValue`> | The decoder for the map's values. | | `config?` | [`MapCodecConfig`](/api/type-aliases/MapCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> | Configuration options for decoding the map. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<[`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TToKey`, `TToValue`>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding maps. ### Example Decoding a map with a `u32` size prefix. ```ts const decoder = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()); const map = decoder.decode(new Uint8Array([ 0x02,0x00,0x00,0x00,0x61,0x6c,0x69,0x63,0x65,0x2a,0x62,0x6f,0x62,0x00,0x00,0x05 ])); // new Map([['alice', 42], ['bob', 5]]) ``` ### See [getMapCodec](/api/functions/getMapCodec) # getMapEncoder (/api/functions/getMapEncoder) ## Call Signature ```ts function getMapEncoder( key, value, config, ): FixedSizeEncoder, 0>; ``` Returns an encoder for maps. This encoder serializes maps where the keys and values are encoded using the provided key and value encoders. The number of entries is determined by the `size` configuration. For more details, see [getMapCodec](/api/functions/getMapCodec). ### Type Parameters | Type Parameter | Description | | -------------- | --------------------------------------- | | `TFromKey` | The type of the keys before encoding. | | `TFromValue` | The type of the values before encoding. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | `key` | [`Encoder`](/api/type-aliases/Encoder)\<`TFromKey`> | The encoder for the map's keys. | | `value` | [`Encoder`](/api/type-aliases/Encoder)\<`TFromValue`> | The encoder for the map's values. | | `config` | [`MapCodecConfig`](/api/type-aliases/MapCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Configuration options for encoding the map. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<[`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TFromKey`, `TFromValue`>, `0`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding maps. ### Example Encoding a map with a `u32` size prefix. ```ts const encoder = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()); const bytes = encoder.encode(new Map([['alice', 42], ['bob', 5]])); // 0x02000000616c6963652a626f62000005 // | | | | └── Value (5) // | | | └── Key ("bob", 5 bytes fixed, null-padded) // | | └── Value (42) // | └── Key ("alice", 5 bytes fixed) // └── 4-byte prefix (2 entries) ``` ### See [getMapCodec](/api/functions/getMapCodec) ## Call Signature ```ts function getMapEncoder( key, value, config, ): FixedSizeEncoder>; ``` Returns an encoder for maps. This encoder serializes maps where the keys and values are encoded using the provided key and value encoders. The number of entries is determined by the `size` configuration. For more details, see [getMapCodec](/api/functions/getMapCodec). ### Type Parameters | Type Parameter | Description | | -------------- | --------------------------------------- | | `TFromKey` | The type of the keys before encoding. | | `TFromValue` | The type of the values before encoding. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | `key` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFromKey`> | The encoder for the map's keys. | | `value` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFromValue`> | The encoder for the map's values. | | `config` | [`MapCodecConfig`](/api/type-aliases/MapCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Configuration options for encoding the map. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<[`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TFromKey`, `TFromValue`>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding maps. ### Example Encoding a map with a `u32` size prefix. ```ts const encoder = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()); const bytes = encoder.encode(new Map([['alice', 42], ['bob', 5]])); // 0x02000000616c6963652a626f62000005 // | | | | └── Value (5) // | | | └── Key ("bob", 5 bytes fixed, null-padded) // | | └── Value (42) // | └── Key ("alice", 5 bytes fixed) // └── 4-byte prefix (2 entries) ``` ### See [getMapCodec](/api/functions/getMapCodec) ## Call Signature ```ts function getMapEncoder( key, value, config?, ): VariableSizeEncoder>; ``` Returns an encoder for maps. This encoder serializes maps where the keys and values are encoded using the provided key and value encoders. The number of entries is determined by the `size` configuration. For more details, see [getMapCodec](/api/functions/getMapCodec). ### Type Parameters | Type Parameter | Description | | -------------- | --------------------------------------- | | `TFromKey` | The type of the keys before encoding. | | `TFromValue` | The type of the values before encoding. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | `key` | [`Encoder`](/api/type-aliases/Encoder)\<`TFromKey`> | The encoder for the map's keys. | | `value` | [`Encoder`](/api/type-aliases/Encoder)\<`TFromValue`> | The encoder for the map's values. | | `config?` | [`MapCodecConfig`](/api/type-aliases/MapCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> | Configuration options for encoding the map. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<[`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)\<`TFromKey`, `TFromValue`>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding maps. ### Example Encoding a map with a `u32` size prefix. ```ts const encoder = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()); const bytes = encoder.encode(new Map([['alice', 42], ['bob', 5]])); // 0x02000000616c6963652a626f62000005 // | | | | └── Value (5) // | | | └── Key ("bob", 5 bytes fixed, null-padded) // | | └── Value (42) // | └── Key ("alice", 5 bytes fixed) // └── 4-byte prefix (2 entries) ``` ### See [getMapCodec](/api/functions/getMapCodec) # getMessagePackerInstructionPlanFromInstructions (/api/functions/getMessagePackerInstructionPlanFromInstructions) ```ts function getMessagePackerInstructionPlanFromInstructions( instructions, ): MessagePackerInstructionPlan; ``` Creates a [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) from a list of instructions. This can be useful to prepare a set of instructions that can be iterated over β€” e.g. to pack a list of instructions that gradually reallocate the size of an account one `REALLOC_LIMIT` (10'240 bytes) at a time. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TInstruction` *extends* [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | ## Parameters | Parameter | Type | | -------------- | ----------------- | | `instructions` | `TInstruction`\[] | ## Returns [`MessagePackerInstructionPlan`](/api/type-aliases/MessagePackerInstructionPlan) ## Example ```ts const plan = getMessagePackerInstructionPlanFromInstructions([ instructionA, instructionB, instructionC, ]); const messagePacker = plan.getMessagePacker(); firstTransactionMessage = messagePacker.packMessageToCapacity(firstTransactionMessage); // Contains instruction A and instruction B. secondTransactionMessage = messagePacker.packMessageToCapacity(secondTransactionMessage); // Contains instruction C. messagePacker.done(); // true ``` ## See * [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) * [getReallocMessagePackerInstructionPlan](/api/functions/getReallocMessagePackerInstructionPlan) # getNonNullResolvedInstructionInput (/api/functions/getNonNullResolvedInstructionInput) ```ts function getNonNullResolvedInstructionInput(inputName, value): T; ``` Ensures a resolved instruction input is not null or undefined. This function is used during instruction resolution to validate that required inputs have been properly resolved to a non-null value. ## Type Parameters | Type Parameter | Description | | -------------- | ---------------------------------------------- | | `T` | The expected type of the resolved input value. | ## Parameters | Parameter | Type | Description | | ----------- | ---------------------------- | ---------------------------------------------------------- | | `inputName` | `string` | The name of the instruction input, used in error messages. | | `value` | `T` \| `null` \| `undefined` | The resolved value to validate. | ## Returns `T` The validated non-null value. ## Throws Throws a SolanaError if the value is null or undefined. ## Example ```ts const resolvedAuthority = getNonNullResolvedInstructionInput( 'authority', maybeAuthority ); // resolvedAuthority is guaranteed to be non-null here. ``` # getNonRpcPropertyValue (/api/functions/getNonRpcPropertyValue) ```ts function getNonRpcPropertyValue(propertyName, receiver): unknown; ``` **`Internal`** Gets the value of a property that must not be treated as an RPC method. ## Parameters | Parameter | Type | | -------------- | -------------------- | | `propertyName` | `string` \| `symbol` | | `receiver` | `unknown` | ## Returns `unknown` ## See [https://github.com/anza-xyz/kit/issues/509](https://github.com/anza-xyz/kit/issues/509) # getNullableCodec (/api/functions/getNullableCodec) ## Call Signature ```ts function getNullableCodec( item, config, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding optional values, allowing `null` values to be handled. This codec serializes and deserializes optional values using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized using a custom number codec or even disabled by setting the `prefix` to `null`. * If `noneValue: 'zeroes'` is set, `null` values are encoded/decoded as zeroes. * If `noneValue` is a byte array, `null` values are represented by the provided constant. For more details on the configuration options, see [NullableCodecConfig](/api/type-aliases/NullableCodecConfig). ### Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | | `TTo` | The type of the main value being decoded. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `item` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`> | The codec for the value that may be present. | | `config` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Configuration options for encoding and decoding optional values. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom` | `null`, `TTo` | `null`, `TSize`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding nullable values. ### Examples Encoding and decoding an optional number using a `u8` prefix (default). ```ts const codec = getNullableCodec(getU32Codec()); codec.encode(null); // 0x00 codec.encode(42); // 0x012a000000 codec.decode(new Uint8Array([0x00])); // null codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding an optional number using a fixed-size codec, by filling `null` values with zeroes. ```ts const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes' }); codec.encode(null); // 0x0000000000 codec.encode(42); // 0x012a000000 codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00])); // null codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding `null` values with zeroes and no prefix. ```ts const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes', prefix: null, }); codec.encode(null); // 0x00000000 codec.encode(42); // 0x2a000000 codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00])); // null codec.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding `null` values with a custom byte sequence and no prefix. ```ts const codec = getNullableCodec(getU16Codec(), { noneValue: new Uint8Array([0xff, 0xff]), prefix: null, }); codec.encode(null); // 0xffff codec.encode(42); // 0x2a00 codec.decode(new Uint8Array([0xff, 0xff])); // null codec.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` Identifying `null` values by the absence of bytes. ```ts const codec = getNullableCodec(getU16Codec(), { prefix: null }); codec.encode(null); // Empty bytes codec.encode(42); // 0x2a00 codec.decode(new Uint8Array([])); // null codec.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` ### Remarks Separate [getNullableEncoder](/api/functions/getNullableEncoder) and [getNullableDecoder](/api/functions/getNullableDecoder) functions are available. ```ts const bytes = getNullableEncoder(getU32Encoder()).encode(42); const value = getNullableDecoder(getU32Decoder()).decode(bytes); ``` ### See * [getNullableEncoder](/api/functions/getNullableEncoder) * [getNullableDecoder](/api/functions/getNullableDecoder) ## Call Signature ```ts function getNullableCodec( item, config, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding optional values, allowing `null` values to be handled. This codec serializes and deserializes optional values using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized using a custom number codec or even disabled by setting the `prefix` to `null`. * If `noneValue: 'zeroes'` is set, `null` values are encoded/decoded as zeroes. * If `noneValue` is a byte array, `null` values are represented by the provided constant. For more details on the configuration options, see [NullableCodecConfig](/api/type-aliases/NullableCodecConfig). ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ----------------------------------------- | | `TFrom` | - | The type of the main value being encoded. | | `TTo` | `TFrom` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `item` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> | The codec for the value that may be present. | | `config` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`FixedSizeNumberCodec`](/api/type-aliases/FixedSizeNumberCodec)> & `object` | Configuration options for encoding and decoding optional values. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom` | `null`, `TTo` | `null`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding nullable values. ### Examples Encoding and decoding an optional number using a `u8` prefix (default). ```ts const codec = getNullableCodec(getU32Codec()); codec.encode(null); // 0x00 codec.encode(42); // 0x012a000000 codec.decode(new Uint8Array([0x00])); // null codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding an optional number using a fixed-size codec, by filling `null` values with zeroes. ```ts const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes' }); codec.encode(null); // 0x0000000000 codec.encode(42); // 0x012a000000 codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00])); // null codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding `null` values with zeroes and no prefix. ```ts const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes', prefix: null, }); codec.encode(null); // 0x00000000 codec.encode(42); // 0x2a000000 codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00])); // null codec.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding `null` values with a custom byte sequence and no prefix. ```ts const codec = getNullableCodec(getU16Codec(), { noneValue: new Uint8Array([0xff, 0xff]), prefix: null, }); codec.encode(null); // 0xffff codec.encode(42); // 0x2a00 codec.decode(new Uint8Array([0xff, 0xff])); // null codec.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` Identifying `null` values by the absence of bytes. ```ts const codec = getNullableCodec(getU16Codec(), { prefix: null }); codec.encode(null); // Empty bytes codec.encode(42); // 0x2a00 codec.decode(new Uint8Array([])); // null codec.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` ### Remarks Separate [getNullableEncoder](/api/functions/getNullableEncoder) and [getNullableDecoder](/api/functions/getNullableDecoder) functions are available. ```ts const bytes = getNullableEncoder(getU32Encoder()).encode(42); const value = getNullableDecoder(getU32Decoder()).decode(bytes); ``` ### See * [getNullableEncoder](/api/functions/getNullableEncoder) * [getNullableDecoder](/api/functions/getNullableDecoder) ## Call Signature ```ts function getNullableCodec( item, config, ): VariableSizeCodec; ``` Returns a codec for encoding and decoding optional values, allowing `null` values to be handled. This codec serializes and deserializes optional values using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized using a custom number codec or even disabled by setting the `prefix` to `null`. * If `noneValue: 'zeroes'` is set, `null` values are encoded/decoded as zeroes. * If `noneValue` is a byte array, `null` values are represented by the provided constant. For more details on the configuration options, see [NullableCodecConfig](/api/type-aliases/NullableCodecConfig). ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ----------------------------------------- | | `TFrom` | - | The type of the main value being encoded. | | `TTo` | `TFrom` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `item` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> | The codec for the value that may be present. | | `config` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Configuration options for encoding and decoding optional values. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom` | `null`, `TTo` | `null`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding nullable values. ### Examples Encoding and decoding an optional number using a `u8` prefix (default). ```ts const codec = getNullableCodec(getU32Codec()); codec.encode(null); // 0x00 codec.encode(42); // 0x012a000000 codec.decode(new Uint8Array([0x00])); // null codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding an optional number using a fixed-size codec, by filling `null` values with zeroes. ```ts const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes' }); codec.encode(null); // 0x0000000000 codec.encode(42); // 0x012a000000 codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00])); // null codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding `null` values with zeroes and no prefix. ```ts const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes', prefix: null, }); codec.encode(null); // 0x00000000 codec.encode(42); // 0x2a000000 codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00])); // null codec.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding `null` values with a custom byte sequence and no prefix. ```ts const codec = getNullableCodec(getU16Codec(), { noneValue: new Uint8Array([0xff, 0xff]), prefix: null, }); codec.encode(null); // 0xffff codec.encode(42); // 0x2a00 codec.decode(new Uint8Array([0xff, 0xff])); // null codec.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` Identifying `null` values by the absence of bytes. ```ts const codec = getNullableCodec(getU16Codec(), { prefix: null }); codec.encode(null); // Empty bytes codec.encode(42); // 0x2a00 codec.decode(new Uint8Array([])); // null codec.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` ### Remarks Separate [getNullableEncoder](/api/functions/getNullableEncoder) and [getNullableDecoder](/api/functions/getNullableDecoder) functions are available. ```ts const bytes = getNullableEncoder(getU32Encoder()).encode(42); const value = getNullableDecoder(getU32Decoder()).decode(bytes); ``` ### See * [getNullableEncoder](/api/functions/getNullableEncoder) * [getNullableDecoder](/api/functions/getNullableDecoder) ## Call Signature ```ts function getNullableCodec( item, config?, ): VariableSizeCodec; ``` Returns a codec for encoding and decoding optional values, allowing `null` values to be handled. This codec serializes and deserializes optional values using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized using a custom number codec or even disabled by setting the `prefix` to `null`. * If `noneValue: 'zeroes'` is set, `null` values are encoded/decoded as zeroes. * If `noneValue` is a byte array, `null` values are represented by the provided constant. For more details on the configuration options, see [NullableCodecConfig](/api/type-aliases/NullableCodecConfig). ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ----------------------------------------- | | `TFrom` | - | The type of the main value being encoded. | | `TTo` | `TFrom` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `item` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | The codec for the value that may be present. | | `config?` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Configuration options for encoding and decoding optional values. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom` | `null`, `TTo` | `null`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding nullable values. ### Examples Encoding and decoding an optional number using a `u8` prefix (default). ```ts const codec = getNullableCodec(getU32Codec()); codec.encode(null); // 0x00 codec.encode(42); // 0x012a000000 codec.decode(new Uint8Array([0x00])); // null codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding an optional number using a fixed-size codec, by filling `null` values with zeroes. ```ts const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes' }); codec.encode(null); // 0x0000000000 codec.encode(42); // 0x012a000000 codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00])); // null codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding `null` values with zeroes and no prefix. ```ts const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes', prefix: null, }); codec.encode(null); // 0x00000000 codec.encode(42); // 0x2a000000 codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00])); // null codec.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42 ``` Encoding and decoding `null` values with a custom byte sequence and no prefix. ```ts const codec = getNullableCodec(getU16Codec(), { noneValue: new Uint8Array([0xff, 0xff]), prefix: null, }); codec.encode(null); // 0xffff codec.encode(42); // 0x2a00 codec.decode(new Uint8Array([0xff, 0xff])); // null codec.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` Identifying `null` values by the absence of bytes. ```ts const codec = getNullableCodec(getU16Codec(), { prefix: null }); codec.encode(null); // Empty bytes codec.encode(42); // 0x2a00 codec.decode(new Uint8Array([])); // null codec.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` ### Remarks Separate [getNullableEncoder](/api/functions/getNullableEncoder) and [getNullableDecoder](/api/functions/getNullableDecoder) functions are available. ```ts const bytes = getNullableEncoder(getU32Encoder()).encode(42); const value = getNullableDecoder(getU32Decoder()).decode(bytes); ``` ### See * [getNullableEncoder](/api/functions/getNullableEncoder) * [getNullableDecoder](/api/functions/getNullableDecoder) # getNullableDecoder (/api/functions/getNullableDecoder) ## Call Signature ```ts function getNullableDecoder( item, config, ): FixedSizeDecoder; ``` Returns a decoder for optional values, allowing `null` values to be recognized. This decoder deserializes an optional value using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `null` values are identified by zeroes. * If `noneValue` is a byte array, `null` values match the provided constant. For more details, see [getNullableCodec](/api/functions/getNullableCodec). ### Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `TSize`> | The decoder for the value that may be present. | | `config` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Configuration options for decoding optional values. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo` | `null`, `TSize`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding nullable values. ### Example Decoding an optional number. ```ts const decoder = getNullableDecoder(getU32Decoder()); decoder.decode(new Uint8Array([0x00])); // null decoder.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` ### See [getNullableCodec](/api/functions/getNullableCodec) ## Call Signature ```ts function getNullableDecoder( item, config, ): FixedSizeDecoder; ``` Returns a decoder for optional values, allowing `null` values to be recognized. This decoder deserializes an optional value using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `null` values are identified by zeroes. * If `noneValue` is a byte array, `null` values match the provided constant. For more details, see [getNullableCodec](/api/functions/getNullableCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> | The decoder for the value that may be present. | | `config` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`FixedSizeNumberDecoder`](/api/type-aliases/FixedSizeNumberDecoder)> & `object` | Configuration options for decoding optional values. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo` | `null`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding nullable values. ### Example Decoding an optional number. ```ts const decoder = getNullableDecoder(getU32Decoder()); decoder.decode(new Uint8Array([0x00])); // null decoder.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` ### See [getNullableCodec](/api/functions/getNullableCodec) ## Call Signature ```ts function getNullableDecoder( item, config, ): VariableSizeDecoder; ``` Returns a decoder for optional values, allowing `null` values to be recognized. This decoder deserializes an optional value using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `null` values are identified by zeroes. * If `noneValue` is a byte array, `null` values match the provided constant. For more details, see [getNullableCodec](/api/functions/getNullableCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> | The decoder for the value that may be present. | | `config` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Configuration options for decoding optional values. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo` | `null`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding nullable values. ### Example Decoding an optional number. ```ts const decoder = getNullableDecoder(getU32Decoder()); decoder.decode(new Uint8Array([0x00])); // null decoder.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` ### See [getNullableCodec](/api/functions/getNullableCodec) ## Call Signature ```ts function getNullableDecoder( item, config?, ): VariableSizeDecoder; ``` Returns a decoder for optional values, allowing `null` values to be recognized. This decoder deserializes an optional value using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `null` values are identified by zeroes. * If `noneValue` is a byte array, `null` values match the provided constant. For more details, see [getNullableCodec](/api/functions/getNullableCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | The decoder for the value that may be present. | | `config?` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Configuration options for decoding optional values. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo` | `null`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding nullable values. ### Example Decoding an optional number. ```ts const decoder = getNullableDecoder(getU32Decoder()); decoder.decode(new Uint8Array([0x00])); // null decoder.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42 ``` ### See [getNullableCodec](/api/functions/getNullableCodec) # getNullableEncoder (/api/functions/getNullableEncoder) ## Call Signature ```ts function getNullableEncoder( item, config, ): FixedSizeEncoder; ``` Returns an encoder for optional values, allowing `null` values to be encoded. This encoder serializes an optional value using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `null` values are encoded as zeroes. * If `noneValue` is a byte array, `null` values are replaced with the provided constant. For more details, see [getNullableCodec](/api/functions/getNullableCodec). ### Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`> | The encoder for the value that may be present. | | `config` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Configuration options for encoding optional values. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom` | `null`, `TSize`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding nullable values. ### Example Encoding an optional number. ```ts const encoder = getNullableEncoder(getU32Encoder()); encoder.encode(null); // 0x00 encoder.encode(42); // 0x012a000000 ``` ### See [getNullableCodec](/api/functions/getNullableCodec) ## Call Signature ```ts function getNullableEncoder( item, config, ): FixedSizeEncoder; ``` Returns an encoder for optional values, allowing `null` values to be encoded. This encoder serializes an optional value using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `null` values are encoded as zeroes. * If `noneValue` is a byte array, `null` values are replaced with the provided constant. For more details, see [getNullableCodec](/api/functions/getNullableCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> | The encoder for the value that may be present. | | `config` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`FixedSizeNumberEncoder`](/api/type-aliases/FixedSizeNumberEncoder)> & `object` | Configuration options for encoding optional values. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom` | `null`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding nullable values. ### Example Encoding an optional number. ```ts const encoder = getNullableEncoder(getU32Encoder()); encoder.encode(null); // 0x00 encoder.encode(42); // 0x012a000000 ``` ### See [getNullableCodec](/api/functions/getNullableCodec) ## Call Signature ```ts function getNullableEncoder( item, config, ): VariableSizeEncoder; ``` Returns an encoder for optional values, allowing `null` values to be encoded. This encoder serializes an optional value using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `null` values are encoded as zeroes. * If `noneValue` is a byte array, `null` values are replaced with the provided constant. For more details, see [getNullableCodec](/api/functions/getNullableCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> | The encoder for the value that may be present. | | `config` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Configuration options for encoding optional values. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom` | `null`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding nullable values. ### Example Encoding an optional number. ```ts const encoder = getNullableEncoder(getU32Encoder()); encoder.encode(null); // 0x00 encoder.encode(42); // 0x012a000000 ``` ### See [getNullableCodec](/api/functions/getNullableCodec) ## Call Signature ```ts function getNullableEncoder( item, config?, ): VariableSizeEncoder; ``` Returns an encoder for optional values, allowing `null` values to be encoded. This encoder serializes an optional value using a configurable approach: * By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `null` values are encoded as zeroes. * If `noneValue` is a byte array, `null` values are replaced with the provided constant. For more details, see [getNullableCodec](/api/functions/getNullableCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | The encoder for the value that may be present. | | `config?` | [`NullableCodecConfig`](/api/type-aliases/NullableCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Configuration options for encoding optional values. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom` | `null`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding nullable values. ### Example Encoding an optional number. ```ts const encoder = getNullableEncoder(getU32Encoder()); encoder.encode(null); // 0x00 encoder.encode(42); // 0x012a000000 ``` ### See [getNullableCodec](/api/functions/getNullableCodec) # getOffchainMessageApplicationDomainCodec (/api/functions/getOffchainMessageApplicationDomainCodec) ```ts function getOffchainMessageApplicationDomainCodec(): FixedSizeCodec< OffchainMessageApplicationDomain, OffchainMessageApplicationDomain, 32 >; ``` Returns a codec that you can use to encode from or decode to a base-58 encoded offchain message application domain. ## Returns `FixedSizeCodec`\<[`OffchainMessageApplicationDomain`](/api/type-aliases/OffchainMessageApplicationDomain), [`OffchainMessageApplicationDomain`](/api/type-aliases/OffchainMessageApplicationDomain), `32`> ## See * [getOffchainMessageApplicationDomainDecoder](/api/functions/getOffchainMessageApplicationDomainDecoder) * [getOffchainMessageApplicationDomainEncoder](/api/functions/getOffchainMessageApplicationDomainEncoder) # getOffchainMessageApplicationDomainDecoder (/api/functions/getOffchainMessageApplicationDomainDecoder) ```ts function getOffchainMessageApplicationDomainDecoder(): FixedSizeDecoder< OffchainMessageApplicationDomain, 32 >; ``` Returns a decoder that you can use to convert an array of 32 bytes representing an offchain message application domain to the base58-encoded representation of that application domain. ## Returns `FixedSizeDecoder`\<[`OffchainMessageApplicationDomain`](/api/type-aliases/OffchainMessageApplicationDomain), `32`> ## Example ```ts import { getOffchainMessageApplicationDomainDecoder } from '@solana/offchain-messages'; const offchainMessageApplicationDomainBytes = new Uint8Array([ 247, 203, 28, 80, 52, 240, 169, 19, 21, 103, 107, 119, 91, 235, 13, 48, 194, 169, 148, 160, 78, 105, 235, 37, 232, 160, 49, 47, 64, 89, 18, 153, ]); const offchainMessageApplicationDomainDecoder = getOffchainMessageApplicationDomainDecoder(); const offchainMessageApplicationDomain = offchainMessageApplicationDomainDecoder.decode(offchainMessageApplicationDomainBytes); // HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx ``` # getOffchainMessageApplicationDomainEncoder (/api/functions/getOffchainMessageApplicationDomainEncoder) ```ts function getOffchainMessageApplicationDomainEncoder(): FixedSizeEncoder< OffchainMessageApplicationDomain, 32 >; ``` Returns an encoder that you can use to encode a base58-encoded offchain message application domain to a byte array. ## Returns `FixedSizeEncoder`\<[`OffchainMessageApplicationDomain`](/api/type-aliases/OffchainMessageApplicationDomain), `32`> ## Example ```ts import { getOffchainMessageApplicationDomainEncoder } from '@solana/offchain-messages'; const offchainMessageApplicationDomain = 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain; const offchainMessageApplicationDomainEncoder = getOffchainMessageApplicationDomainEncoder(); const offchainMessageApplicationDomainBytes = offchainMessageApplicationDomainEncoder.encode(offchainMessageApplicationDomain); // Uint8Array(32) [ // 247, 203, 28, 80, 52, 240, 169, 19, // 21, 103, 107, 119, 91, 235, 13, 48, // 194, 169, 148, 160, 78, 105, 235, 37, // 232, 160, 49, 47, 64, 89, 18, 153, // ] ``` # getOffchainMessageCodec (/api/functions/getOffchainMessageCodec) ```ts function getOffchainMessageCodec(): VariableSizeCodec; ``` Returns a codec that you can use to encode from or decode to an [OffchainMessage](/api/type-aliases/OffchainMessage) ## Returns `VariableSizeCodec`\<[`OffchainMessage`](/api/type-aliases/OffchainMessage)> ## See * [getOffchainMessageDecoder](/api/functions/getOffchainMessageDecoder) * [getOffchainMessageEncoder](/api/functions/getOffchainMessageEncoder) ## Remarks If the offchain message version is known ahead of time, use one of the codecs specific to that version so as not to bundle more code than you need. # getOffchainMessageDecoder (/api/functions/getOffchainMessageDecoder) ```ts function getOffchainMessageDecoder(): VariableSizeDecoder; ``` Returns a decoder that you can use to convert a byte array (eg. one that conforms to the [OffchainMessageBytes](/api/type-aliases/OffchainMessageBytes) type) to an [OffchainMessage](/api/type-aliases/OffchainMessage) object. ## Returns `VariableSizeDecoder`\<[`OffchainMessage`](/api/type-aliases/OffchainMessage)> ## Example ```ts import { getOffchainMessageDecoder } from '@solana/offchain-messages'; const offchainMessageDecoder = getOffchainMessageDecoder(); const offchainMessage = offchainMessageDecoder.decode( offchainMessageEnvelope.content, ); console.log(`Decoded an offchain message (version: ${offchainMessage.version}`); ``` ## Remarks If the offchain message version is known ahead of time, use one of the decoders specific to that version so as not to bundle more code than you need. # getOffchainMessageEncoder (/api/functions/getOffchainMessageEncoder) ```ts function getOffchainMessageEncoder(): VariableSizeEncoder; ``` Returns an encoder that you can use to encode an [OffchainMessage](/api/type-aliases/OffchainMessage) to a byte array appropriate for inclusion in an [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope). ## Returns `VariableSizeEncoder`\<[`OffchainMessage`](/api/type-aliases/OffchainMessage)> ## Remarks If the offchain message version is known ahead of time, use one of the encoders specific to that version so as not to bundle more code than you need. # getOffchainMessageEnvelopeCodec (/api/functions/getOffchainMessageEnvelopeCodec) ```ts function getOffchainMessageEnvelopeCodec(): VariableSizeCodec< OffchainMessageEnvelope, OffchainMessageEnvelope >; ``` Returns a codec that you can use to encode from or decode to an [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope) ## Returns `VariableSizeCodec`\<[`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope), [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope)> ## See * [getOffchainMessageEnvelopeDecoder](/api/functions/getOffchainMessageEnvelopeDecoder) * [getOffchainMessageEnvelopeEncoder](/api/functions/getOffchainMessageEnvelopeEncoder) # getOffchainMessageEnvelopeDecoder (/api/functions/getOffchainMessageEnvelopeDecoder) ```ts function getOffchainMessageEnvelopeDecoder(): VariableSizeDecoder; ``` Returns a decoder that you can use to convert a byte array in the Solana offchain message format to a [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope) object. ## Returns `VariableSizeDecoder`\<[`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope)> ## Example ```ts import { getOffchainMessageEnvelopeDecoder } from '@solana/offchain-messages'; const offchainMessageEnvelopeDecoder = getOffchainMessageEnvelopeDecoder(); const offchainMessageEnvelope = offchainMessageEnvelopeDecoder.decode(offchainMessageEnvelopeBytes); for (const [address, signature] in Object.entries(offchainMessageEnvelope.signatures)) { console.log(`Signature by ${address}`, signature); } ``` # getOffchainMessageEnvelopeEncoder (/api/functions/getOffchainMessageEnvelopeEncoder) ```ts function getOffchainMessageEnvelopeEncoder(): VariableSizeEncoder; ``` Returns an encoder that you can use to encode an [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope) to a byte array appropriate for sharing with a third party for validation. ## Returns `VariableSizeEncoder`\<[`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope)> # getOffchainMessageV0Codec (/api/functions/getOffchainMessageV0Codec) ```ts function getOffchainMessageV0Codec(): VariableSizeCodec; ``` Returns a codec that you can use to encode from or decode to an [OffchainMessageV0](/api/type-aliases/OffchainMessageV0) ## Returns `VariableSizeCodec`\<[`OffchainMessageV0`](/api/type-aliases/OffchainMessageV0)> ## See * [getOffchainMessageV0Decoder](/api/functions/getOffchainMessageV0Decoder) * [getOffchainMessageV0Encoder](/api/functions/getOffchainMessageV0Encoder) # getOffchainMessageV0Decoder (/api/functions/getOffchainMessageV0Decoder) ```ts function getOffchainMessageV0Decoder(): VariableSizeDecoder; ``` Returns a decoder that you can use to convert a byte array (eg. one that conforms to the [OffchainMessageBytes](/api/type-aliases/OffchainMessageBytes) type) to an [OffchainMessageV0](/api/type-aliases/OffchainMessageV0) object. ## Returns `VariableSizeDecoder`\<[`OffchainMessageV0`](/api/type-aliases/OffchainMessageV0)> ## Example ```ts import { getOffchainMessageV0Decoder } from '@solana/offchain-messages'; const offchainMessageDecoder = getOffchainMessageV0Decoder(); const offchainMessage = offchainMessageDecoder.decode( offchainMessageEnvelope.content, ); console.log(`Decoded a v0 offchain message`); ``` Throws in the event that the message bytes represent a message of a version other than 0. # getOffchainMessageV0Encoder (/api/functions/getOffchainMessageV0Encoder) ```ts function getOffchainMessageV0Encoder(): VariableSizeEncoder; ``` Returns an encoder that you can use to encode an [OffchainMessageV0](/api/type-aliases/OffchainMessageV0) to a byte array appropriate for inclusion in an [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope). ## Returns `VariableSizeEncoder`\<[`OffchainMessageV0`](/api/type-aliases/OffchainMessageV0)> # getOffchainMessageV1Codec (/api/functions/getOffchainMessageV1Codec) ```ts function getOffchainMessageV1Codec(): VariableSizeCodec; ``` Returns a codec that you can use to encode from or decode to an [OffchainMessageV1](/api/type-aliases/OffchainMessageV1) ## Returns `VariableSizeCodec`\<[`OffchainMessageV1`](/api/type-aliases/OffchainMessageV1)> ## See * [getOffchainMessageV1Decoder](/api/functions/getOffchainMessageV1Decoder) * [getOffchainMessageV1Encoder](/api/functions/getOffchainMessageV1Encoder) # getOffchainMessageV1Decoder (/api/functions/getOffchainMessageV1Decoder) ```ts function getOffchainMessageV1Decoder(): VariableSizeDecoder; ``` Returns a decoder that you can use to convert a byte array (eg. one that conforms to the [OffchainMessageBytes](/api/type-aliases/OffchainMessageBytes) type) to an [OffchainMessageV1](/api/type-aliases/OffchainMessageV1) object. ## Returns `VariableSizeDecoder`\<[`OffchainMessageV1`](/api/type-aliases/OffchainMessageV1)> ## Example ```ts import { getOffchainMessageV1Decoder } from '@solana/offchain-messages'; const offchainMessageDecoder = getOffchainMessageV1Decoder(); const offchainMessage = offchainMessageDecoder.decode( offchainMessageEnvelope.content, ); console.log(`Decoded a v1 offchain message`); ``` Throws in the event that the message bytes represent a message of a version other than 1. # getOffchainMessageV1Encoder (/api/functions/getOffchainMessageV1Encoder) ```ts function getOffchainMessageV1Encoder(): VariableSizeEncoder; ``` Returns an encoder that you can use to encode an [OffchainMessageV1](/api/type-aliases/OffchainMessageV1) to a byte array appropriate for inclusion in an [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope). ## Returns `VariableSizeEncoder`\<[`OffchainMessageV1`](/api/type-aliases/OffchainMessageV1)> # getOptionCodec (/api/functions/getOptionCodec) ## Call Signature ```ts function getOptionCodec( item, config, ): FixedSizeCodec, Option, TSize>; ``` Returns a codec for encoding and decoding optional values using the [Option](/api/type-aliases/Option) type. This codec serializes and deserializes `Option` values using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). * If `noneValue: 'zeroes'` is set, `None` values are encoded/decoded as zeroes. * If `noneValue` is a byte array, `None` values are represented by the provided constant. * If `prefix: null` is set, the codec determines `None` values solely from `noneValue` or the presence of bytes. For more details on the configuration options, see [OptionCodecConfig](/api/type-aliases/OptionCodecConfig). Note that this behaves similarly to getNullableCodec, except it encodes [OptionOrNullable](/api/type-aliases/OptionOrNullable) values and decodes [Option](/api/type-aliases/Option) values. ### Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | | `TTo` | The type of the main value being decoded. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `item` | `FixedSizeCodec`\<`TFrom`, `TTo`, `TSize`> | The codec for the value that may be present. | | `config` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`NumberCodec`> & `object` | Configuration options for encoding and decoding option values. | ### Returns `FixedSizeCodec`\<[`OptionOrNullable`](/api/type-aliases/OptionOrNullable)\<`TFrom`>, [`Option`](/api/type-aliases/Option)\<`TTo`>, `TSize`> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding option values. ### Examples Encoding and decoding an optional string with a size prefix. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const codec = getOptionCodec(stringCodec); const someBytes = codec.encode(some('Hi')); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (Some). const noneBytes = codec.encode(none()); // 0x00 // β””-- 1-byte prefix (None). codec.decode(someBytes); // some('Hi') codec.decode(noneBytes); // none() ``` Encoding nullable values. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const codec = getOptionCodec(stringCodec); const someBytes = codec.encode('Hi'); // 0x01020000004869 const noneBytes = codec.encode(null); // 0x00 codec.decode(someBytes); // some('Hi') codec.decode(noneBytes); // none() ``` Encoding and decoding an optional number with a fixed size. ```ts const codec = getOptionCodec(getU16Codec(), { noneValue: 'zeroes' }); const someBytes = codec.encode(some(42)); // 0x012a00 const noneBytes = codec.encode(none()); // 0x000000 codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` Encoding and decoding [None](/api/type-aliases/None) values with a custom byte sequence and no prefix. ```ts const codec = getOptionCodec(getU16Codec(), { noneValue: new Uint8Array([0xff, 0xff]), prefix: null, }); const someBytes = codec.encode(some(42)); // 0x2a00 const noneBytes = codec.encode(none()); // 0xffff codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` Identifying [None](/api/type-aliases/None) values by the absence of bytes. ```ts const codec = getOptionCodec(getU16Codec(), { prefix: null }); const someBytes = codec.encode(some(42)); // 0x2a00 const noneBytes = codec.encode(none()); // new Uint8Array(0) codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` ### Remarks Separate [getOptionEncoder](/api/functions/getOptionEncoder) and [getOptionDecoder](/api/functions/getOptionDecoder) functions are available. ```ts const bytes = getOptionEncoder(getU32Encoder()).encode(some(42)); const value = getOptionDecoder(getU32Decoder()).decode(bytes); ``` ### See * [getOptionEncoder](/api/functions/getOptionEncoder) * [getOptionDecoder](/api/functions/getOptionDecoder) ## Call Signature ```ts function getOptionCodec( item, config, ): FixedSizeCodec, Option>; ``` Returns a codec for encoding and decoding optional values using the [Option](/api/type-aliases/Option) type. This codec serializes and deserializes `Option` values using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). * If `noneValue: 'zeroes'` is set, `None` values are encoded/decoded as zeroes. * If `noneValue` is a byte array, `None` values are represented by the provided constant. * If `prefix: null` is set, the codec determines `None` values solely from `noneValue` or the presence of bytes. For more details on the configuration options, see [OptionCodecConfig](/api/type-aliases/OptionCodecConfig). Note that this behaves similarly to getNullableCodec, except it encodes [OptionOrNullable](/api/type-aliases/OptionOrNullable) values and decodes [Option](/api/type-aliases/Option) values. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ----------------------------------------- | | `TFrom` | - | The type of the main value being encoded. | | `TTo` | `TFrom` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `item` | `FixedSizeCodec`\<`TFrom`, `TTo`> | The codec for the value that may be present. | | `config` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`FixedSizeNumberCodec`> & `object` | Configuration options for encoding and decoding option values. | ### Returns `FixedSizeCodec`\<[`OptionOrNullable`](/api/type-aliases/OptionOrNullable)\<`TFrom`>, [`Option`](/api/type-aliases/Option)\<`TTo`>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding option values. ### Examples Encoding and decoding an optional string with a size prefix. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const codec = getOptionCodec(stringCodec); const someBytes = codec.encode(some('Hi')); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (Some). const noneBytes = codec.encode(none()); // 0x00 // β””-- 1-byte prefix (None). codec.decode(someBytes); // some('Hi') codec.decode(noneBytes); // none() ``` Encoding nullable values. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const codec = getOptionCodec(stringCodec); const someBytes = codec.encode('Hi'); // 0x01020000004869 const noneBytes = codec.encode(null); // 0x00 codec.decode(someBytes); // some('Hi') codec.decode(noneBytes); // none() ``` Encoding and decoding an optional number with a fixed size. ```ts const codec = getOptionCodec(getU16Codec(), { noneValue: 'zeroes' }); const someBytes = codec.encode(some(42)); // 0x012a00 const noneBytes = codec.encode(none()); // 0x000000 codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` Encoding and decoding [None](/api/type-aliases/None) values with a custom byte sequence and no prefix. ```ts const codec = getOptionCodec(getU16Codec(), { noneValue: new Uint8Array([0xff, 0xff]), prefix: null, }); const someBytes = codec.encode(some(42)); // 0x2a00 const noneBytes = codec.encode(none()); // 0xffff codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` Identifying [None](/api/type-aliases/None) values by the absence of bytes. ```ts const codec = getOptionCodec(getU16Codec(), { prefix: null }); const someBytes = codec.encode(some(42)); // 0x2a00 const noneBytes = codec.encode(none()); // new Uint8Array(0) codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` ### Remarks Separate [getOptionEncoder](/api/functions/getOptionEncoder) and [getOptionDecoder](/api/functions/getOptionDecoder) functions are available. ```ts const bytes = getOptionEncoder(getU32Encoder()).encode(some(42)); const value = getOptionDecoder(getU32Decoder()).decode(bytes); ``` ### See * [getOptionEncoder](/api/functions/getOptionEncoder) * [getOptionDecoder](/api/functions/getOptionDecoder) ## Call Signature ```ts function getOptionCodec( item, config, ): VariableSizeCodec, Option>; ``` Returns a codec for encoding and decoding optional values using the [Option](/api/type-aliases/Option) type. This codec serializes and deserializes `Option` values using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). * If `noneValue: 'zeroes'` is set, `None` values are encoded/decoded as zeroes. * If `noneValue` is a byte array, `None` values are represented by the provided constant. * If `prefix: null` is set, the codec determines `None` values solely from `noneValue` or the presence of bytes. For more details on the configuration options, see [OptionCodecConfig](/api/type-aliases/OptionCodecConfig). Note that this behaves similarly to getNullableCodec, except it encodes [OptionOrNullable](/api/type-aliases/OptionOrNullable) values and decodes [Option](/api/type-aliases/Option) values. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ----------------------------------------- | | `TFrom` | - | The type of the main value being encoded. | | `TTo` | `TFrom` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `item` | `FixedSizeCodec`\<`TFrom`, `TTo`> | The codec for the value that may be present. | | `config` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`NumberCodec`> & `object` | Configuration options for encoding and decoding option values. | ### Returns `VariableSizeCodec`\<[`OptionOrNullable`](/api/type-aliases/OptionOrNullable)\<`TFrom`>, [`Option`](/api/type-aliases/Option)\<`TTo`>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding option values. ### Examples Encoding and decoding an optional string with a size prefix. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const codec = getOptionCodec(stringCodec); const someBytes = codec.encode(some('Hi')); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (Some). const noneBytes = codec.encode(none()); // 0x00 // β””-- 1-byte prefix (None). codec.decode(someBytes); // some('Hi') codec.decode(noneBytes); // none() ``` Encoding nullable values. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const codec = getOptionCodec(stringCodec); const someBytes = codec.encode('Hi'); // 0x01020000004869 const noneBytes = codec.encode(null); // 0x00 codec.decode(someBytes); // some('Hi') codec.decode(noneBytes); // none() ``` Encoding and decoding an optional number with a fixed size. ```ts const codec = getOptionCodec(getU16Codec(), { noneValue: 'zeroes' }); const someBytes = codec.encode(some(42)); // 0x012a00 const noneBytes = codec.encode(none()); // 0x000000 codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` Encoding and decoding [None](/api/type-aliases/None) values with a custom byte sequence and no prefix. ```ts const codec = getOptionCodec(getU16Codec(), { noneValue: new Uint8Array([0xff, 0xff]), prefix: null, }); const someBytes = codec.encode(some(42)); // 0x2a00 const noneBytes = codec.encode(none()); // 0xffff codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` Identifying [None](/api/type-aliases/None) values by the absence of bytes. ```ts const codec = getOptionCodec(getU16Codec(), { prefix: null }); const someBytes = codec.encode(some(42)); // 0x2a00 const noneBytes = codec.encode(none()); // new Uint8Array(0) codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` ### Remarks Separate [getOptionEncoder](/api/functions/getOptionEncoder) and [getOptionDecoder](/api/functions/getOptionDecoder) functions are available. ```ts const bytes = getOptionEncoder(getU32Encoder()).encode(some(42)); const value = getOptionDecoder(getU32Decoder()).decode(bytes); ``` ### See * [getOptionEncoder](/api/functions/getOptionEncoder) * [getOptionDecoder](/api/functions/getOptionDecoder) ## Call Signature ```ts function getOptionCodec( item, config?, ): VariableSizeCodec, Option>; ``` Returns a codec for encoding and decoding optional values using the [Option](/api/type-aliases/Option) type. This codec serializes and deserializes `Option` values using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). * If `noneValue: 'zeroes'` is set, `None` values are encoded/decoded as zeroes. * If `noneValue` is a byte array, `None` values are represented by the provided constant. * If `prefix: null` is set, the codec determines `None` values solely from `noneValue` or the presence of bytes. For more details on the configuration options, see [OptionCodecConfig](/api/type-aliases/OptionCodecConfig). Note that this behaves similarly to getNullableCodec, except it encodes [OptionOrNullable](/api/type-aliases/OptionOrNullable) values and decodes [Option](/api/type-aliases/Option) values. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ----------------------------------------- | | `TFrom` | - | The type of the main value being encoded. | | `TTo` | `TFrom` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `item` | `Codec`\<`TFrom`, `TTo`> | The codec for the value that may be present. | | `config?` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`NumberCodec`> & `object` | Configuration options for encoding and decoding option values. | ### Returns `VariableSizeCodec`\<[`OptionOrNullable`](/api/type-aliases/OptionOrNullable)\<`TFrom`>, [`Option`](/api/type-aliases/Option)\<`TTo`>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding option values. ### Examples Encoding and decoding an optional string with a size prefix. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const codec = getOptionCodec(stringCodec); const someBytes = codec.encode(some('Hi')); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (Some). const noneBytes = codec.encode(none()); // 0x00 // β””-- 1-byte prefix (None). codec.decode(someBytes); // some('Hi') codec.decode(noneBytes); // none() ``` Encoding nullable values. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const codec = getOptionCodec(stringCodec); const someBytes = codec.encode('Hi'); // 0x01020000004869 const noneBytes = codec.encode(null); // 0x00 codec.decode(someBytes); // some('Hi') codec.decode(noneBytes); // none() ``` Encoding and decoding an optional number with a fixed size. ```ts const codec = getOptionCodec(getU16Codec(), { noneValue: 'zeroes' }); const someBytes = codec.encode(some(42)); // 0x012a00 const noneBytes = codec.encode(none()); // 0x000000 codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` Encoding and decoding [None](/api/type-aliases/None) values with a custom byte sequence and no prefix. ```ts const codec = getOptionCodec(getU16Codec(), { noneValue: new Uint8Array([0xff, 0xff]), prefix: null, }); const someBytes = codec.encode(some(42)); // 0x2a00 const noneBytes = codec.encode(none()); // 0xffff codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` Identifying [None](/api/type-aliases/None) values by the absence of bytes. ```ts const codec = getOptionCodec(getU16Codec(), { prefix: null }); const someBytes = codec.encode(some(42)); // 0x2a00 const noneBytes = codec.encode(none()); // new Uint8Array(0) codec.decode(someBytes); // some(42) codec.decode(noneBytes); // none() ``` ### Remarks Separate [getOptionEncoder](/api/functions/getOptionEncoder) and [getOptionDecoder](/api/functions/getOptionDecoder) functions are available. ```ts const bytes = getOptionEncoder(getU32Encoder()).encode(some(42)); const value = getOptionDecoder(getU32Decoder()).decode(bytes); ``` ### See * [getOptionEncoder](/api/functions/getOptionEncoder) * [getOptionDecoder](/api/functions/getOptionDecoder) # getOptionDecoder (/api/functions/getOptionDecoder) ## Call Signature ```ts function getOptionDecoder( item, config, ): FixedSizeDecoder, TSize>; ``` Returns a decoder for optional values using the [Option](/api/type-aliases/Option) type. This decoder deserializes an `Option` value using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `None` values are identified by zeroes. * If `noneValue` is a byte array, `None` values match the provided constant. Unlike getNullableDecoder, this decoder always outputs an [Option](/api/type-aliases/Option) type. For more details, see [getOptionCodec](/api/functions/getOptionCodec). ### Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------- | --------------------------------------------------- | | `item` | `FixedSizeDecoder`\<`TTo`, `TSize`> | The decoder for the value that may be present. | | `config` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`NumberDecoder`> & `object` | Configuration options for decoding optional values. | ### Returns `FixedSizeDecoder`\<[`Option`](/api/type-aliases/Option)\<`TTo`>, `TSize`> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding option values. ### Example Decoding an optional string with a size prefix. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const decoder = getOptionDecoder(stringCodec); decoder.decode(new Uint8Array([0x01, 0x02, 0x00, 0x00, 0x00, 0x48, 0x69])); // some('Hi') decoder.decode(new Uint8Array([0x00])); // none() ``` ### See [getOptionCodec](/api/functions/getOptionCodec) ## Call Signature ```ts function getOptionDecoder( item, config, ): FixedSizeDecoder>; ``` Returns a decoder for optional values using the [Option](/api/type-aliases/Option) type. This decoder deserializes an `Option` value using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `None` values are identified by zeroes. * If `noneValue` is a byte array, `None` values match the provided constant. Unlike getNullableDecoder, this decoder always outputs an [Option](/api/type-aliases/Option) type. For more details, see [getOptionCodec](/api/functions/getOptionCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | `FixedSizeDecoder`\<`TTo`> | The decoder for the value that may be present. | | `config` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`FixedSizeNumberDecoder`> & `object` | Configuration options for decoding optional values. | ### Returns `FixedSizeDecoder`\<[`Option`](/api/type-aliases/Option)\<`TTo`>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding option values. ### Example Decoding an optional string with a size prefix. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const decoder = getOptionDecoder(stringCodec); decoder.decode(new Uint8Array([0x01, 0x02, 0x00, 0x00, 0x00, 0x48, 0x69])); // some('Hi') decoder.decode(new Uint8Array([0x00])); // none() ``` ### See [getOptionCodec](/api/functions/getOptionCodec) ## Call Signature ```ts function getOptionDecoder( item, config, ): VariableSizeDecoder>; ``` Returns a decoder for optional values using the [Option](/api/type-aliases/Option) type. This decoder deserializes an `Option` value using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `None` values are identified by zeroes. * If `noneValue` is a byte array, `None` values match the provided constant. Unlike getNullableDecoder, this decoder always outputs an [Option](/api/type-aliases/Option) type. For more details, see [getOptionCodec](/api/functions/getOptionCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------- | --------------------------------------------------- | | `item` | `FixedSizeDecoder`\<`TTo`> | The decoder for the value that may be present. | | `config` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`NumberDecoder`> & `object` | Configuration options for decoding optional values. | ### Returns `VariableSizeDecoder`\<[`Option`](/api/type-aliases/Option)\<`TTo`>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding option values. ### Example Decoding an optional string with a size prefix. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const decoder = getOptionDecoder(stringCodec); decoder.decode(new Uint8Array([0x01, 0x02, 0x00, 0x00, 0x00, 0x48, 0x69])); // some('Hi') decoder.decode(new Uint8Array([0x00])); // none() ``` ### See [getOptionCodec](/api/functions/getOptionCodec) ## Call Signature ```ts function getOptionDecoder( item, config?, ): VariableSizeDecoder>; ``` Returns a decoder for optional values using the [Option](/api/type-aliases/Option) type. This decoder deserializes an `Option` value using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, `None` values are identified by zeroes. * If `noneValue` is a byte array, `None` values match the provided constant. Unlike getNullableDecoder, this decoder always outputs an [Option](/api/type-aliases/Option) type. For more details, see [getOptionCodec](/api/functions/getOptionCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TTo` | The type of the main value being decoded. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------- | --------------------------------------------------- | | `item` | `Decoder`\<`TTo`> | The decoder for the value that may be present. | | `config?` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`NumberDecoder`> & `object` | Configuration options for decoding optional values. | ### Returns `VariableSizeDecoder`\<[`Option`](/api/type-aliases/Option)\<`TTo`>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding option values. ### Example Decoding an optional string with a size prefix. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const decoder = getOptionDecoder(stringCodec); decoder.decode(new Uint8Array([0x01, 0x02, 0x00, 0x00, 0x00, 0x48, 0x69])); // some('Hi') decoder.decode(new Uint8Array([0x00])); // none() ``` ### See [getOptionCodec](/api/functions/getOptionCodec) # getOptionEncoder (/api/functions/getOptionEncoder) ## Call Signature ```ts function getOptionEncoder( item, config, ): FixedSizeEncoder, TSize>; ``` Returns an encoder for optional values using the [Option](/api/type-aliases/Option) type. This encoder serializes an [OptionOrNullable](/api/type-aliases/OptionOrNullable) value using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, [None](/api/type-aliases/None) values are encoded as zeroes. * If `noneValue` is a byte array, [None](/api/type-aliases/None) values are replaced with the provided constant. Unlike getNullableEncoder, this encoder accepts both [Option](/api/type-aliases/Option) and Nullable values. For more details, see [getOptionCodec](/api/functions/getOptionCodec). ### Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------- | --------------------------------------------------- | | `item` | `FixedSizeEncoder`\<`TFrom`, `TSize`> | The encoder for the value that may be present. | | `config` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`NumberEncoder`> & `object` | Configuration options for encoding optional values. | ### Returns `FixedSizeEncoder`\<[`OptionOrNullable`](/api/type-aliases/OptionOrNullable)\<`TFrom`>, `TSize`> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding option values. ### Example Encoding an optional string. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const encoder = getOptionEncoder(stringCodec); encoder.encode(some('Hi')); encoder.encode('Hi'); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (Some). encoder.encode(none()); encoder.encode(null); // 0x00 // β””-- 1-byte prefix (None). ``` ### See [getOptionCodec](/api/functions/getOptionCodec) ## Call Signature ```ts function getOptionEncoder( item, config, ): FixedSizeEncoder>; ``` Returns an encoder for optional values using the [Option](/api/type-aliases/Option) type. This encoder serializes an [OptionOrNullable](/api/type-aliases/OptionOrNullable) value using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, [None](/api/type-aliases/None) values are encoded as zeroes. * If `noneValue` is a byte array, [None](/api/type-aliases/None) values are replaced with the provided constant. Unlike getNullableEncoder, this encoder accepts both [Option](/api/type-aliases/Option) and Nullable values. For more details, see [getOptionCodec](/api/functions/getOptionCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | `item` | `FixedSizeEncoder`\<`TFrom`> | The encoder for the value that may be present. | | `config` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`FixedSizeNumberEncoder`> & `object` | Configuration options for encoding optional values. | ### Returns `FixedSizeEncoder`\<[`OptionOrNullable`](/api/type-aliases/OptionOrNullable)\<`TFrom`>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding option values. ### Example Encoding an optional string. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const encoder = getOptionEncoder(stringCodec); encoder.encode(some('Hi')); encoder.encode('Hi'); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (Some). encoder.encode(none()); encoder.encode(null); // 0x00 // β””-- 1-byte prefix (None). ``` ### See [getOptionCodec](/api/functions/getOptionCodec) ## Call Signature ```ts function getOptionEncoder( item, config, ): VariableSizeEncoder>; ``` Returns an encoder for optional values using the [Option](/api/type-aliases/Option) type. This encoder serializes an [OptionOrNullable](/api/type-aliases/OptionOrNullable) value using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, [None](/api/type-aliases/None) values are encoded as zeroes. * If `noneValue` is a byte array, [None](/api/type-aliases/None) values are replaced with the provided constant. Unlike getNullableEncoder, this encoder accepts both [Option](/api/type-aliases/Option) and Nullable values. For more details, see [getOptionCodec](/api/functions/getOptionCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------- | --------------------------------------------------- | | `item` | `FixedSizeEncoder`\<`TFrom`> | The encoder for the value that may be present. | | `config` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`NumberEncoder`> & `object` | Configuration options for encoding optional values. | ### Returns `VariableSizeEncoder`\<[`OptionOrNullable`](/api/type-aliases/OptionOrNullable)\<`TFrom`>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding option values. ### Example Encoding an optional string. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const encoder = getOptionEncoder(stringCodec); encoder.encode(some('Hi')); encoder.encode('Hi'); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (Some). encoder.encode(none()); encoder.encode(null); // 0x00 // β””-- 1-byte prefix (None). ``` ### See [getOptionCodec](/api/functions/getOptionCodec) ## Call Signature ```ts function getOptionEncoder( item, config?, ): VariableSizeEncoder>; ``` Returns an encoder for optional values using the [Option](/api/type-aliases/Option) type. This encoder serializes an [OptionOrNullable](/api/type-aliases/OptionOrNullable) value using a configurable approach: * By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled. * If `noneValue: 'zeroes'` is set, [None](/api/type-aliases/None) values are encoded as zeroes. * If `noneValue` is a byte array, [None](/api/type-aliases/None) values are replaced with the provided constant. Unlike getNullableEncoder, this encoder accepts both [Option](/api/type-aliases/Option) and Nullable values. For more details, see [getOptionCodec](/api/functions/getOptionCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------- | | `TFrom` | The type of the main value being encoded. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------- | --------------------------------------------------- | | `item` | `Encoder`\<`TFrom`> | The encoder for the value that may be present. | | `config?` | [`OptionCodecConfig`](/api/type-aliases/OptionCodecConfig)\<`NumberEncoder`> & `object` | Configuration options for encoding optional values. | ### Returns `VariableSizeEncoder`\<[`OptionOrNullable`](/api/type-aliases/OptionOrNullable)\<`TFrom`>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding option values. ### Example Encoding an optional string. ```ts const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); const encoder = getOptionEncoder(stringCodec); encoder.encode(some('Hi')); encoder.encode('Hi'); // 0x01020000004869 // | | β””-- utf8 string content ("Hi"). // | β””-- u32 string prefix (2 characters). // β””-- 1-byte prefix (Some). encoder.encode(none()); encoder.encode(null); // 0x00 // β””-- 1-byte prefix (None). ``` ### See [getOptionCodec](/api/functions/getOptionCodec) # getPatternMatchCodec (/api/functions/getPatternMatchCodec) ```ts function getPatternMatchCodec( patterns, ): GetUnionCodecType>; ``` Returns a codec that selects which variant codec to use based on pattern matching. This codec evaluates values and byte arrays against a series of predicate functions in order, using the first matching codec for encoding or decoding. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TPatterns` *extends* readonly ( \| readonly \[(`value`) => `value is any`, (`bytes`) => `boolean`, [`Codec`](/api/type-aliases/Codec)\<`any`, `any`>] \| readonly \[(`value`) => `boolean`, (`bytes`) => `boolean`, [`Codec`](/api/type-aliases/Codec)\<`any`, `any`>])\[] | ## Parameters | Parameter | Type | Description | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `patterns` | `TPatterns` & readonly `PatternMatchCodecEntry`\<`GetEncoderTypeFromVariants`\<`GetPatternMatchCodecs`\<`TPatterns`>>, `GetEncoderTypeFromVariants`\<`GetPatternMatchCodecs`\<`TPatterns`>>, `GetEncoderTypeFromVariants`\<`GetPatternMatchCodecs`\<`TPatterns`>>>\[] | An array of `[valuePredicate, bytesPredicate, codec]` triples. Predicates are tested in order and the first match determines the codec used. During encoding, `valuePredicate` receives the value to encode. During decoding, `bytesPredicate` receives the byte array. | ## Returns `GetUnionCodecType`\<`GetPatternMatchCodecs`\<`TPatterns`>> A codec that selects the appropriate variant based on the matched pattern. ## Throws Throws a [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_PATTERN\_MATCH\_VALUE](/api/variables/SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE) error if a value being encoded does not match any of the specified patterns. ## Throws Throws a [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_PATTERN\_MATCH\_BYTES](/api/variables/SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES) error if a byte array being decoded does not match any of the specified patterns. ## Example Encoding and decoding using pattern matching. ```ts const codec = getPatternMatchCodec([ [ (n: number) => n < 256, (bytes) => bytes.length === 1, getU8Codec(), ], [ (n: number) => n < 2 ** 16, (bytes) => bytes.length === 2, getU16Codec(), ], [ (n: number) => n < 2 ** 32, (bytes) => bytes.length <= 4, getU32Codec(), ] ]); const bytes1 = codec.encode(42); // 0x2a, encoded as u8 const value1 = codec.decode(bytes1); // 42, decoded as u8 const bytes2 = codec.encode(1000); // 0xe803, encoded as u16 const value2 = codec.decode(bytes2); // 1000, decoded as u16 const bytes3 = codec.encode(100_000); //0xa0860100, encoded as u32 const value3 = codec.decode(bytes3); // 100_000, decoded as u32 codec.encode(2 ** 32 + 1); // throws, no encode pattern matches codec.decode(new Uint8Array([0xa0, 0x86, 0x01, 0x00, 0x00])) // throws, no decode pattern matches ``` ## See * [getPatternMatchEncoder](/api/functions/getPatternMatchEncoder) * [getPatternMatchDecoder](/api/functions/getPatternMatchDecoder) * [getUnionCodec](/api/functions/getUnionCodec) # getPatternMatchDecoder (/api/functions/getPatternMatchDecoder) ```ts function getPatternMatchDecoder( patterns, ): GetUnionDecoderType>; ``` Returns a decoder that selects which variant decoder to use based on pattern matching. This decoder evaluates the byte array against a series of predicate functions in order, and uses the first matching decoder to decode the value. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TPatterns` *extends* readonly `PatternMatchDecoderEntry`\<`any`>\[] | ## Parameters | Parameter | Type | Description | | ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `patterns` | `TPatterns` | An array of `[predicate, decoder]` pairs. Predicates are tested in order and the first matching decoder is used to decode the byte array. | ## Returns `GetUnionDecoderType`\<`GetPatternMatchDecoders`\<`TPatterns`>> A decoder that selects the appropriate variant based on the matched byte pattern. ## Throws Throws a [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_PATTERN\_MATCH\_BYTES](/api/variables/SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES) error if the byte array does not match any of the specified patterns. ## Example Decoding values using pattern matching on bytes. ```ts const decoder = getPatternMatchDecoder([ [(bytes) => bytes.length === 1, getU8Decoder()], [(bytes) => bytes.length === 2, getU16Decoder()], [(bytes) => bytes.length <= 4, getU32Decoder()] ]); decoder.decode(new Uint8Array([0x2a])); // 42 (decoded as u8) decoder.decode(new Uint8Array([0xe8, 0x03])) // 1000 (decoded as u16) decoder.decode(new Uint8Array([0xa0, 0x86, 0x01, 0x00])) // 100_000 (decoded as u32) decoder.decode(new Uint8Array([0xa0, 0x86, 0x01, 0x00, 0x00])) // Throws an error because the bytes do not match any pattern ``` ## See * [getPatternMatchCodec](/api/functions/getPatternMatchCodec) * [getPatternMatchEncoder](/api/functions/getPatternMatchEncoder) # getPatternMatchEncoder (/api/functions/getPatternMatchEncoder) ```ts function getPatternMatchEncoder( patterns, ): GetUnionEncoderType>; ``` Returns an encoder that selects which variant encoder to use based on pattern matching. This encoder evaluates the value against a series of predicate functions in order, and uses the first matching encoder to encode the value. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TPatterns` *extends* readonly ( \| readonly \[(`value`) => `value is any`, [`Encoder`](/api/type-aliases/Encoder)\<`any`>] \| readonly \[(`value`) => `boolean`, [`Encoder`](/api/type-aliases/Encoder)\<`any`>])\[] | ## Parameters | Parameter | Type | Description | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `patterns` | `TPatterns` & readonly `PatternMatchEncoderEntry`\<`GetEncoderTypeFromVariants`\<`GetPatternMatchEncoders`\<`TPatterns`>>, `GetEncoderTypeFromVariants`\<`GetPatternMatchEncoders`\<`TPatterns`>>>\[] | An array of `[predicate, encoder]` pairs. Predicates are tested in order and the first matching encoder is used to encode the value. Note that predicates can be either type predicates that narrow the type of the value, or boolean predicates. If using type predicates, the encoder can be for the narrowed type. | ## Returns `GetUnionEncoderType`\<`GetPatternMatchEncoders`\<`TPatterns`>> An encoder that selects the appropriate variant based on the matched pattern. ## Throws Throws a [SOLANA\_ERROR\_\_CODECS\_\_INVALID\_PATTERN\_MATCH\_VALUE](/api/variables/SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE) error if the value does not match any of the specified patterns. ## Example Encoding values using pattern matching. ```ts const encoder = getPatternMatchEncoder([ [(n: number) => n < 256, getU8Encoder()], [(n: number) => n < 2 ** 16, getU16Encoder()], [(n: number) => n < 2 ** 32, getU32Encoder()] ]); encoder.encode(42); // 0x2a // └── Small number encoded as u8 encoder.encode(1000); // 0xe803 // └── Medium number encoded as u16 encoder.encode(100_000); // 0xa0860100 // └── Large number encoded as u32 ender.encode(2 ** 32 + 1); // Throws an error because the value does not match any pattern ``` ## See [getPatternMatchCodec](/api/functions/getPatternMatchCodec) # getPredicateCodec (/api/functions/getPredicateCodec) ```ts function getPredicateCodec( encodePredicate, decodePredicate, ifTrue, ifFalse, ): GetUnionCodecType; ``` Returns a codec that selects between two codecs based on predicates. This codec uses boolean predicate functions to determine which of two codecs to use for encoding and decoding. If the encoding predicate returns `true` for a value, the `ifTrue` codec is used to encode it; otherwise `ifFalse`. Similarly, if the decoding predicate returns `true` for the bytes, the `ifTrue` codec is used to decode them. ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------------------------------------ | --------------------------------------------------- | -------------------------------- | | `TFrom` | `any` | The type of the value to encode. | | `TTo` | `TFrom` | The type of the value to decode. | | `TIfTrue` *extends* [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | - | | `TIfFalse` *extends* [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | - | ## Parameters | Parameter | Type | Description | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | | `encodePredicate` | (`value`) => `boolean` | A function that returns `true` or `false` for a given value. | | `decodePredicate` | (`value`) => `boolean` | A function that returns `true` or `false` for a given byte array. | | `ifTrue` | `TIfTrue` | The codec to use when the respective predicate returns `true`. | | `ifFalse` | `SameType`\<`TIfTrue` *extends* [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> ? `TFrom` : `never`, `TIfFalse` *extends* [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> ? `TFrom` : `never`> & `SameType`\<`TIfTrue` *extends* [`Decoder`](/api/type-aliases/Decoder)\<`TFrom`> ? `TFrom` : `never`, `TIfFalse` *extends* [`Decoder`](/api/type-aliases/Decoder)\<`TFrom`> ? `TFrom` : `never`> & `TIfFalse` | The codec to use when the respective predicate returns `false`. | ## Returns `GetUnionCodecType`\ A `Codec` based on the provided codecs. ## Example Encoding and decoding small and large numbers differently. ```ts const codec = getPredicateCodec( (n: number) => n < 256, bytes => bytes.length === 1, getU8Codec(), getU32Codec() ); const smallBytes = codec.encode(42); // 0x2a (encoded as u8) const largeBytes = codec.encode(1000); // 0xe8030000 (encoded as u32) codec.decode(smallBytes); // 42 codec.decode(largeBytes); // 1000 ``` ## See * [getPredicateEncoder](/api/functions/getPredicateEncoder) * [getPredicateDecoder](/api/functions/getPredicateDecoder) # getPredicateDecoder (/api/functions/getPredicateDecoder) ```ts function getPredicateDecoder( predicate, ifTrue, ifFalse, ): GetUnionDecoderType; ``` Returns a decoder that selects between two decoders based on a predicate. This decoder uses a boolean predicate function on the raw bytes to determine which of two decoders to use. If the predicate returns `true`, the `ifTrue` decoder is used; otherwise, the `ifFalse` decoder is used. ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------------------------------- | ---------------------------------------------- | -------------------------------- | | `TTo` | `any` | The type of the value to decode. | | `TIfTrue` *extends* [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | - | | `TIfFalse` *extends* [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | - | ## Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | | `predicate` | (`value`) => `boolean` | A function that returns `true` or `false` for a given byte array. | | `ifTrue` | `TIfTrue` | The decoder to use when the predicate returns `true`. | | `ifFalse` | `SameType`\<`TIfTrue` *extends* [`Decoder`](/api/type-aliases/Decoder)\<`TFrom`> ? `TFrom` : `never`, `TIfFalse` *extends* [`Decoder`](/api/type-aliases/Decoder)\<`TFrom`> ? `TFrom` : `never`> & `TIfFalse` | The decoder to use when the predicate returns `false`. | ## Returns `GetUnionDecoderType`\ A `Decoder` based on the provided decoders. ## Example Decoding small and large numbers based on byte length. ```ts const decoder = getPredicateDecoder( bytes => bytes.length === 1, getU8Decoder(), getU32Decoder() ); decoder.decode(new Uint8Array([0x2a])); // 42 (decoded as u8) decoder.decode(new Uint8Array([0xe8, 0x03, 0x00, 0x00])); // 1000 (decoded as u32) ``` ## See [getPredicateCodec](/api/functions/getPredicateCodec) # getPredicateEncoder (/api/functions/getPredicateEncoder) ```ts function getPredicateEncoder( predicate, ifTrue, ifFalse, ): GetUnionEncoderType; ``` Returns an encoder that selects between two encoders based on a predicate. This encoder uses a boolean predicate function to determine which of two encoders to use for a given value. If the predicate returns `true`, the `ifTrue` encoder is used; otherwise, the `ifFalse` encoder is used. ## Type Parameters | Type Parameter | Default type | Description | | --------------------------------------------------------------------- | ------------------------------------------------ | -------------------------------- | | `TFrom` | `any` | The type of the value to encode. | | `TIfTrue` *extends* [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | - | | `TIfFalse` *extends* [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | - | ## Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `predicate` | (`value`) => `boolean` | A function that returns `true` or `false` for a given value. | | `ifTrue` | `TIfTrue` | The encoder to use when the predicate returns `true`. | | `ifFalse` | `SameType`\<`TIfTrue` *extends* [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> ? `TFrom` : `never`, `TIfFalse` *extends* [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> ? `TFrom` : `never`> & `TIfFalse` | The encoder to use when the predicate returns `false`. | ## Returns `GetUnionEncoderType`\ An `Encoder` based on the provided encoders. ## Example Encoding small and large numbers differently. ```ts const encoder = getPredicateEncoder( (n: number) => n < 256, getU8Encoder(), getU32Encoder() ); encoder.encode(42); // 0x2a // └── Small number encoded as u8 encoder.encode(1000); // 0xe8030000 // └── Large number encoded as u32 ``` ## See [getPredicateCodec](/api/functions/getPredicateCodec) # getProgramDerivedAddress (/api/functions/getProgramDerivedAddress) ```ts function getProgramDerivedAddress( __namedParameters, ): Promise, ProgramDerivedAddressBump]>; ``` Given a program's [Address](/api/type-aliases/Address) and up to 16 Seed | Seeds, this method will return the program derived address (PDA) associated with each. ## Parameters | Parameter | Type | | ------------------- | ---------------------------- | | `__namedParameters` | `ProgramDerivedAddressInput` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\, [`ProgramDerivedAddressBump`](/api/type-aliases/ProgramDerivedAddressBump)]> ## Example ```ts import { getAddressEncoder, getProgramDerivedAddress } from '@solana/addresses'; const addressEncoder = getAddressEncoder(); const [pda, bumpSeed] = await getProgramDerivedAddress({ programAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address, seeds: [ // Owner addressEncoder.encode('9fYLFVoVqwH37C3dyPi6cpeobfbQ2jtLpN5HgAYDDdkm' as Address), // Token program addressEncoder.encode('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address), // Mint addressEncoder.encode('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' as Address), ], }); ``` # getPublicKeyFromAddress (/api/functions/getPublicKeyFromAddress) ```ts function getPublicKeyFromAddress(address): Promise; ``` Given an [Address](/api/type-aliases/Address), return a [CryptoKey](https://developer.mozilla.org/docs/Web/API/CryptoKey) that can be used to verify signatures. ## Parameters | Parameter | Type | | --------- | -------------------------------------- | | `address` | [`Address`](/api/type-aliases/Address) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`CryptoKey`](https://developer.mozilla.org/docs/Web/API/CryptoKey)> ## Example ```ts import { getAddressFromPublicKey } from '@solana/addresses'; const publicKey = await getPublicKeyFromAddress(address); ``` # getPublicKeyFromPrivateKey (/api/functions/getPublicKeyFromPrivateKey) ```ts function getPublicKeyFromPrivateKey( privateKey, extractable?, ): Promise; ``` Given an extractable [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) private key, gets the corresponding public key as a [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey). ## Parameters | Parameter | Type | Description | | -------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `privateKey` | [`CryptoKey`](https://developer.mozilla.org/docs/Web/API/CryptoKey) | - | | `extractable?` | `boolean` | Setting this to `true` makes it possible to extract the bytes of the public key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey) API. Defaults to `false`. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`CryptoKey`](https://developer.mozilla.org/docs/Web/API/CryptoKey)> ## 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); ``` # getReallocMessagePackerInstructionPlan (/api/functions/getReallocMessagePackerInstructionPlan) ```ts function getReallocMessagePackerInstructionPlan( __namedParameters, ): MessagePackerInstructionPlan; ``` Creates a [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) that packs a list of realloc instructions. That is, it splits instruction by chunks of `REALLOC_LIMIT` (10'240) bytes until the given total size is reached. ## Parameters | Parameter | Type | | ---------------------------------- | ------------------------------------------------------------------------------------------------------- | | `__namedParameters` | \{ `getInstruction`: (`size`) => [`Instruction`](/api/interfaces/Instruction); `totalSize`: `number`; } | | `__namedParameters.getInstruction` | (`size`) => [`Instruction`](/api/interfaces/Instruction) | | `__namedParameters.totalSize` | `number` | ## Returns [`MessagePackerInstructionPlan`](/api/type-aliases/MessagePackerInstructionPlan) ## Example ```ts const plan = getReallocMessagePackerInstructionPlan({ totalSize: additionalDataSize, getInstruction: (size) => getExtendInstruction({ length: size }), }); ``` ## See [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) # getResolvedInstructionAccountAsProgramDerivedAddress (/api/functions/getResolvedInstructionAccountAsProgramDerivedAddress) ```ts function getResolvedInstructionAccountAsProgramDerivedAddress( inputName, value, ): readonly [Address, ProgramDerivedAddressBump]; ``` Extracts a ProgramDerivedAddress from a resolved instruction account. This function validates that the resolved account is a PDA and returns it. Use this when you need access to both the address and the bump seed of a PDA. ## Type Parameters | Type Parameter | Default type | Description | | ---------------------- | ------------ | --------------------------------------- | | `T` *extends* `string` | `string` | The address type, defaults to `string`. | ## Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------- | | `inputName` | `string` | The name of the instruction input, used in error messages. | | `value` | \| `Address`\<`T`> \| readonly \[`Address`\<`T`>, `ProgramDerivedAddressBump`] \| `TransactionSigner`\<`T`> \| `null` \| `undefined` | The resolved account value expected to be a PDA. | ## Returns readonly \[`Address`\<`T`>, `ProgramDerivedAddressBump`] The program-derived address. ## Throws Throws a SolanaError if the value is not a ProgramDerivedAddress. ## Example ```ts const pda = getResolvedInstructionAccountAsProgramDerivedAddress('metadata', resolvedMetadata); const [address, bump] = pda; ``` # getResolvedInstructionAccountAsTransactionSigner (/api/functions/getResolvedInstructionAccountAsTransactionSigner) ```ts function getResolvedInstructionAccountAsTransactionSigner( inputName, value, ): TransactionSigner; ``` Extracts a TransactionSigner from a resolved instruction account. This function validates that the resolved account is a transaction signer and returns it. Use this when you need the resolved account to be a signer. ## Type Parameters | Type Parameter | Default type | Description | | ---------------------- | ------------ | --------------------------------------- | | `T` *extends* `string` | `string` | The address type, defaults to `string`. | ## Parameters | Parameter | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------- | | `inputName` | `string` | The name of the instruction input, used in error messages. | | `value` | \| `Address`\<`T`> \| readonly \[`Address`\<`T`>, `ProgramDerivedAddressBump`] \| `TransactionSigner`\<`T`> \| `null` \| `undefined` | The resolved account value expected to be a signer. | ## Returns `TransactionSigner`\<`T`> The transaction signer. ## Throws Throws a SolanaError if the value is not a TransactionSigner. ## Example ```ts const signer = getResolvedInstructionAccountAsTransactionSigner('authority', resolvedAuthority); ``` # getResultResponseTransformer (/api/functions/getResultResponseTransformer) ```ts function getResultResponseTransformer(): RpcResponseTransformer; ``` Returns a transformer that extracts the `result` field from the body of the RPC response. For instance, we go from `{ jsonrpc: '2.0', result: 'foo', id: 1 }` to `'foo'`. ## Returns `RpcResponseTransformer` ## Example ```ts import { getResultResponseTransformer } from '@solana/rpc-transformers'; const responseTransformer = getResultResponseTransformer(); ``` # getRpcSubscriptionsChannelWithAutoping (/api/functions/getRpcSubscriptionsChannelWithAutoping) ```ts function getRpcSubscriptionsChannelWithAutoping( __namedParameters, ): TChannel; ``` Given a [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel), will return a new channel that sends a ping message to the inner channel if a message has not been sent or received in the last `intervalMs`. In web browsers, this implementation sends no ping when the network is down, and sends a ping immediately upon the network coming back up. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------------------------------------- | | `TChannel` *extends* [`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`object`, `unknown`> | ## Parameters | Parameter | Type | | ------------------- | --------------------- | | `__namedParameters` | `Config`\<`TChannel`> | ## Returns `TChannel` # getRpcSubscriptionsChannelWithBigIntJSONSerialization (/api/functions/getRpcSubscriptionsChannelWithBigIntJSONSerialization) ```ts function getRpcSubscriptionsChannelWithBigIntJSONSerialization( channel, ): RpcSubscriptionsChannel; ``` Similarly, to [getRpcSubscriptionsChannelWithJSONSerialization](/api/functions/getRpcSubscriptionsChannelWithJSONSerialization), this function will stringify and parse JSON message to and from the given `string` channel. However, this function parses any integer value as a `BigInt` in order to safely handle numbers that exceed the JavaScript [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) value. ## Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------- | | `channel` | [`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`string`, `string`> | ## Returns [`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`unknown`, `unknown`> # getRpcSubscriptionsChannelWithJSONSerialization (/api/functions/getRpcSubscriptionsChannelWithJSONSerialization) ```ts function getRpcSubscriptionsChannelWithJSONSerialization( channel, ): RpcSubscriptionsChannel; ``` Given a [RpcSubscriptionsChannel](/api/interfaces/RpcSubscriptionsChannel), will return a new channel that parses data published to the `'message'` channel as JSON, and JSON-stringifies messages sent via the [send(message)](/api/interfaces/RpcSubscriptionsChannel#send) method. ## Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------------------------- | | `channel` | [`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`string`, `string`> | ## Returns [`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`unknown`, `unknown`> # getRpcSubscriptionsTransportWithSubscriptionCoalescing (/api/functions/getRpcSubscriptionsTransportWithSubscriptionCoalescing) ```ts function getRpcSubscriptionsTransportWithSubscriptionCoalescing< TTransport, >(transport): TTransport; ``` Given a [RpcSubscriptionsTransport](/api/interfaces/RpcSubscriptionsTransport), will return a new transport that coalesces identical subscriptions into a single subscription request to the server. The determination of whether a subscription is the same as another is based on the `rpcRequest` returned by its [RpcSubscriptionsPlan](/api/type-aliases/RpcSubscriptionsPlan). The subscription will only be aborted once all subscribers abort, or there is an error. ## Type Parameters | Type Parameter | | ----------------------------------------------------------------------------------------------- | | `TTransport` *extends* [`RpcSubscriptionsTransport`](/api/interfaces/RpcSubscriptionsTransport) | ## Parameters | Parameter | Type | | ----------- | ------------ | | `transport` | `TTransport` | ## Returns `TTransport` # getSetCodec (/api/functions/getSetCodec) ## Call Signature ```ts function getSetCodec( item, config, ): FixedSizeCodec, Set, 0>; ``` Returns a codec for encoding and decoding sets of items. This codec serializes `Set` values by encoding each item using the provided item codec. The number of items is stored as a prefix using a `u32` codec by default. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ------------------------------------------------- | | `TFrom` | - | The type of the items in the set before encoding. | | `TTo` | `TFrom` | The type of the items in the set after decoding. | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `item` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | The codec to use for each set item. | | `config` | [`SetCodecConfig`](/api/type-aliases/SetCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Optional configuration specifying the size strategy. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<[`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TFrom`>, [`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TTo`>, `0`> A `Codec, Set>` for encoding and decoding sets. ### Examples Encoding and decoding a set of `u8` numbers. ```ts const codec = getSetCodec(getU8Codec()); const bytes = codec.encode(new Set([1, 2, 3])); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix indicating 3 items. const value = codec.decode(bytes); // new Set([1, 2, 3]) ``` Using a `u16` prefix for size. ```ts const codec = getSetCodec(getU8Codec(), { size: getU16Codec() }); const bytes = codec.encode(new Set([1, 2, 3])); // 0x0300010203 // | β””-- 3 items of 1 byte each. // β””-- 2-byte prefix indicating 3 items. ``` Using a fixed-size set. ```ts const codec = getSetCodec(getU8Codec(), { size: 3 }); const bytes = codec.encode(new Set([1, 2, 3])); // 0x010203 // β””-- Exactly 3 items of 1 byte each. ``` Using remainder to infer set size. ```ts const codec = getSetCodec(getU8Codec(), { size: 'remainder' }); const bytes = codec.encode(new Set([1, 2, 3])); // 0x010203 // β””-- 3 items of 1 byte each. The size is inferred from the remaining bytes. ``` ### Remarks Separate [getSetEncoder](/api/functions/getSetEncoder) and [getSetDecoder](/api/functions/getSetDecoder) functions are available. ```ts const bytes = getSetEncoder(getU8Encoder()).encode(new Set([1, 2, 3])); const value = getSetDecoder(getU8Decoder()).decode(bytes); ``` ### See * [getSetEncoder](/api/functions/getSetEncoder) * [getSetDecoder](/api/functions/getSetDecoder) ## Call Signature ```ts function getSetCodec( item, config, ): FixedSizeCodec, Set>; ``` Returns a codec for encoding and decoding sets of items. This codec serializes `Set` values by encoding each item using the provided item codec. The number of items is stored as a prefix using a `u32` codec by default. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ------------------------------------------------- | | `TFrom` | - | The type of the items in the set before encoding. | | `TTo` | `TFrom` | The type of the items in the set after decoding. | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `item` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`> | The codec to use for each set item. | | `config` | [`SetCodecConfig`](/api/type-aliases/SetCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> & `object` | Optional configuration specifying the size strategy. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<[`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TFrom`>, [`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TTo`>> A `Codec, Set>` for encoding and decoding sets. ### Examples Encoding and decoding a set of `u8` numbers. ```ts const codec = getSetCodec(getU8Codec()); const bytes = codec.encode(new Set([1, 2, 3])); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix indicating 3 items. const value = codec.decode(bytes); // new Set([1, 2, 3]) ``` Using a `u16` prefix for size. ```ts const codec = getSetCodec(getU8Codec(), { size: getU16Codec() }); const bytes = codec.encode(new Set([1, 2, 3])); // 0x0300010203 // | β””-- 3 items of 1 byte each. // β””-- 2-byte prefix indicating 3 items. ``` Using a fixed-size set. ```ts const codec = getSetCodec(getU8Codec(), { size: 3 }); const bytes = codec.encode(new Set([1, 2, 3])); // 0x010203 // β””-- Exactly 3 items of 1 byte each. ``` Using remainder to infer set size. ```ts const codec = getSetCodec(getU8Codec(), { size: 'remainder' }); const bytes = codec.encode(new Set([1, 2, 3])); // 0x010203 // β””-- 3 items of 1 byte each. The size is inferred from the remaining bytes. ``` ### Remarks Separate [getSetEncoder](/api/functions/getSetEncoder) and [getSetDecoder](/api/functions/getSetDecoder) functions are available. ```ts const bytes = getSetEncoder(getU8Encoder()).encode(new Set([1, 2, 3])); const value = getSetDecoder(getU8Decoder()).decode(bytes); ``` ### See * [getSetEncoder](/api/functions/getSetEncoder) * [getSetDecoder](/api/functions/getSetDecoder) ## Call Signature ```ts function getSetCodec( item, config?, ): VariableSizeCodec, Set>; ``` Returns a codec for encoding and decoding sets of items. This codec serializes `Set` values by encoding each item using the provided item codec. The number of items is stored as a prefix using a `u32` codec by default. ### Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | ------------------------------------------------- | | `TFrom` | - | The type of the items in the set before encoding. | | `TTo` | `TFrom` | The type of the items in the set after decoding. | ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `item` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | The codec to use for each set item. | | `config?` | [`SetCodecConfig`](/api/type-aliases/SetCodecConfig)\<[`NumberCodec`](/api/type-aliases/NumberCodec)> | Optional configuration specifying the size strategy. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<[`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TFrom`>, [`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TTo`>> A `Codec, Set>` for encoding and decoding sets. ### Examples Encoding and decoding a set of `u8` numbers. ```ts const codec = getSetCodec(getU8Codec()); const bytes = codec.encode(new Set([1, 2, 3])); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix indicating 3 items. const value = codec.decode(bytes); // new Set([1, 2, 3]) ``` Using a `u16` prefix for size. ```ts const codec = getSetCodec(getU8Codec(), { size: getU16Codec() }); const bytes = codec.encode(new Set([1, 2, 3])); // 0x0300010203 // | β””-- 3 items of 1 byte each. // β””-- 2-byte prefix indicating 3 items. ``` Using a fixed-size set. ```ts const codec = getSetCodec(getU8Codec(), { size: 3 }); const bytes = codec.encode(new Set([1, 2, 3])); // 0x010203 // β””-- Exactly 3 items of 1 byte each. ``` Using remainder to infer set size. ```ts const codec = getSetCodec(getU8Codec(), { size: 'remainder' }); const bytes = codec.encode(new Set([1, 2, 3])); // 0x010203 // β””-- 3 items of 1 byte each. The size is inferred from the remaining bytes. ``` ### Remarks Separate [getSetEncoder](/api/functions/getSetEncoder) and [getSetDecoder](/api/functions/getSetDecoder) functions are available. ```ts const bytes = getSetEncoder(getU8Encoder()).encode(new Set([1, 2, 3])); const value = getSetDecoder(getU8Decoder()).decode(bytes); ``` ### See * [getSetEncoder](/api/functions/getSetEncoder) * [getSetDecoder](/api/functions/getSetDecoder) # getSetDecoder (/api/functions/getSetDecoder) ## Call Signature ```ts function getSetDecoder( item, config, ): FixedSizeDecoder, 0>; ``` Returns a decoder for sets of items. This decoder deserializes a `Set` from a byte array by decoding each item using the provided item decoder. The number of items is determined by a `u32` size prefix by default. For more details, see [getSetCodec](/api/functions/getSetCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------ | | `TTo` | The type of the items in the set after decoding. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `item` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | The decoder to use for each set item. | | `config` | [`SetCodecConfig`](/api/type-aliases/SetCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Optional configuration specifying the size strategy. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<[`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TTo`>, `0`> A `Decoder>` for decoding sets of items. ### Example Decoding a set of `u8` numbers. ```ts const decoder = getSetDecoder(getU8Decoder()); const value = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03])); // new Set([1, 2, 3]) ``` ### See [getSetCodec](/api/functions/getSetCodec) ## Call Signature ```ts function getSetDecoder(item, config): FixedSizeDecoder>; ``` Returns a decoder for sets of items. This decoder deserializes a `Set` from a byte array by decoding each item using the provided item decoder. The number of items is determined by a `u32` size prefix by default. For more details, see [getSetCodec](/api/functions/getSetCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------ | | `TTo` | The type of the items in the set after decoding. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `item` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`> | The decoder to use for each set item. | | `config` | [`SetCodecConfig`](/api/type-aliases/SetCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> & `object` | Optional configuration specifying the size strategy. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<[`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TTo`>> A `Decoder>` for decoding sets of items. ### Example Decoding a set of `u8` numbers. ```ts const decoder = getSetDecoder(getU8Decoder()); const value = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03])); // new Set([1, 2, 3]) ``` ### See [getSetCodec](/api/functions/getSetCodec) ## Call Signature ```ts function getSetDecoder( item, config?, ): VariableSizeDecoder>; ``` Returns a decoder for sets of items. This decoder deserializes a `Set` from a byte array by decoding each item using the provided item decoder. The number of items is determined by a `u32` size prefix by default. For more details, see [getSetCodec](/api/functions/getSetCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------ | | `TTo` | The type of the items in the set after decoding. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `item` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | The decoder to use for each set item. | | `config?` | [`SetCodecConfig`](/api/type-aliases/SetCodecConfig)\<[`NumberDecoder`](/api/type-aliases/NumberDecoder)> | Optional configuration specifying the size strategy. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<[`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TTo`>> A `Decoder>` for decoding sets of items. ### Example Decoding a set of `u8` numbers. ```ts const decoder = getSetDecoder(getU8Decoder()); const value = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03])); // new Set([1, 2, 3]) ``` ### See [getSetCodec](/api/functions/getSetCodec) # getSetEncoder (/api/functions/getSetEncoder) ## Call Signature ```ts function getSetEncoder( item, config, ): FixedSizeEncoder, 0>; ``` Returns an encoder for sets of items. This encoder serializes `Set` values by encoding each item using the provided item encoder. The number of items is stored as a prefix using a `u32` codec by default. For more details, see [getSetCodec](/api/functions/getSetCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------- | | `TFrom` | The type of the items in the set before encoding. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `item` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | The encoder to use for each set item. | | `config` | [`SetCodecConfig`](/api/type-aliases/SetCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Optional configuration specifying the size strategy. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<[`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TFrom`>, `0`> An `Encoder>` for encoding sets of items. ### Example Encoding a set of `u8` numbers. ```ts const encoder = getSetEncoder(getU8Encoder()); const bytes = encoder.encode(new Set([1, 2, 3])); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix indicating 3 items. ``` ### See [getSetCodec](/api/functions/getSetCodec) ## Call Signature ```ts function getSetEncoder( item, config, ): FixedSizeEncoder>; ``` Returns an encoder for sets of items. This encoder serializes `Set` values by encoding each item using the provided item encoder. The number of items is stored as a prefix using a `u32` codec by default. For more details, see [getSetCodec](/api/functions/getSetCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------- | | `TFrom` | The type of the items in the set before encoding. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `item` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`> | The encoder to use for each set item. | | `config` | [`SetCodecConfig`](/api/type-aliases/SetCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> & `object` | Optional configuration specifying the size strategy. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<[`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TFrom`>> An `Encoder>` for encoding sets of items. ### Example Encoding a set of `u8` numbers. ```ts const encoder = getSetEncoder(getU8Encoder()); const bytes = encoder.encode(new Set([1, 2, 3])); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix indicating 3 items. ``` ### See [getSetCodec](/api/functions/getSetCodec) ## Call Signature ```ts function getSetEncoder( item, config?, ): VariableSizeEncoder>; ``` Returns an encoder for sets of items. This encoder serializes `Set` values by encoding each item using the provided item encoder. The number of items is stored as a prefix using a `u32` codec by default. For more details, see [getSetCodec](/api/functions/getSetCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------- | | `TFrom` | The type of the items in the set before encoding. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `item` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | The encoder to use for each set item. | | `config?` | [`SetCodecConfig`](/api/type-aliases/SetCodecConfig)\<[`NumberEncoder`](/api/type-aliases/NumberEncoder)> | Optional configuration specifying the size strategy. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<[`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)\<`TFrom`>> An `Encoder>` for encoding sets of items. ### Example Encoding a set of `u8` numbers. ```ts const encoder = getSetEncoder(getU8Encoder()); const bytes = encoder.encode(new Set([1, 2, 3])); // 0x03000000010203 // | β””-- 3 items of 1 byte each. // β””-- 4-byte prefix indicating 3 items. ``` ### See [getSetCodec](/api/functions/getSetCodec) # getShortU16Codec (/api/functions/getShortU16Codec) ```ts function getShortU16Codec(): VariableSizeCodec; ``` Returns a codec for encoding and decoding `shortU16` values. It serializes unsigned integers using **1 to 3 bytes** based on the encoded value. The larger the value, the more bytes it uses. * If the value is `<= 0x7f` (127), it is stored in a **single byte** and the first bit is set to `0` to indicate the end of the value. * Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern. * This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value. In other words, the encoding scheme follows this structure: ```txt 0XXXXXXX <- Values 0 to 127 (1 byte) 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes) 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes) ``` ## Returns `VariableSizeCodec`\<`number` | `bigint`, `number`> A `VariableSizeCodec` for encoding and decoding `shortU16` values. ## Example Encoding and decoding `shortU16` values. ```ts const codec = getShortU16Codec(); const bytes1 = codec.encode(42); // 0x2a const bytes2 = codec.encode(128); // 0x8001 const bytes3 = codec.encode(16384); // 0x808001 codec.decode(bytes1); // 42 codec.decode(bytes2); // 128 codec.decode(bytes3); // 16384 ``` ## Remarks This codec efficiently stores small numbers, making it useful for transactions and compact representations. If you need a fixed-size `u16` codec, consider using [getU16Codec](/api/functions/getU16Codec). Separate [getShortU16Encoder](/api/functions/getShortU16Encoder) and [getShortU16Decoder](/api/functions/getShortU16Decoder) functions are available. ```ts const bytes = getShortU16Encoder().encode(42); const value = getShortU16Decoder().decode(bytes); ``` ## See * [getShortU16Encoder](/api/functions/getShortU16Encoder) * [getShortU16Decoder](/api/functions/getShortU16Decoder) # getShortU16Decoder (/api/functions/getShortU16Decoder) ```ts function getShortU16Decoder(): VariableSizeDecoder; ``` Returns a decoder for `shortU16` values. This decoder deserializes `shortU16` values from **1 to 3 bytes**. The number of bytes used depends on the encoded value. For more details, see [getShortU16Codec](/api/functions/getShortU16Codec). ## Returns `VariableSizeDecoder`\<`number`> A `VariableSizeDecoder` for decoding `shortU16` values. ## Example Decoding a `shortU16` value. ```ts const decoder = getShortU16Decoder(); decoder.decode(new Uint8Array([0x2a])); // 42 decoder.decode(new Uint8Array([0x80, 0x01])); // 128 decoder.decode(new Uint8Array([0x80, 0x80, 0x01])); // 16384 ``` ## See [getShortU16Codec](/api/functions/getShortU16Codec) # getShortU16Encoder (/api/functions/getShortU16Encoder) ```ts function getShortU16Encoder(): VariableSizeEncoder; ``` Returns an encoder for `shortU16` values. This encoder serializes `shortU16` values using **1 to 3 bytes**. Smaller values use fewer bytes, while larger values take up more space. For more details, see [getShortU16Codec](/api/functions/getShortU16Codec). ## Returns `VariableSizeEncoder`\<`number` | `bigint`> A `VariableSizeEncoder` for encoding `shortU16` values. ## Example Encoding a `shortU16` value. ```ts const encoder = getShortU16Encoder(); encoder.encode(42); // 0x2a encoder.encode(128); // 0x8001 encoder.encode(16384); // 0x808001 ``` ## See [getShortU16Codec](/api/functions/getShortU16Codec) # getSignatureFromTransaction (/api/functions/getSignatureFromTransaction) ```ts function getSignatureFromTransaction(transaction): Signature; ``` 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. ## Parameters | Parameter | Type | | ------------- | ---------------------------------------------- | | `transaction` | [`Transaction`](/api/type-aliases/Transaction) | ## Returns `Signature` ## Example ```ts import { getSignatureFromTransaction } from '@solana/transactions'; const signature = getSignatureFromTransaction(tx); console.debug(`Inspect this transaction at https://explorer.solana.com/tx/${signature}`); ``` # getSignersFromInstruction (/api/functions/getSignersFromInstruction) ```ts function getSignersFromInstruction( instruction, ): readonly TSigner[]; ``` Extracts and deduplicates all [TransactionSigners](/api/type-aliases/TransactionSigner) stored inside the account metas of an [instruction](/api/interfaces/InstructionWithSigners). Any extracted signers that share the same Address will be de-duplicated. ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------------------------------------------ | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `TSigner` *extends* [`TransactionSigner`](/api/type-aliases/TransactionSigner) | [`TransactionSigner`](/api/type-aliases/TransactionSigner) | Optionally provide a narrower type for [TransactionSigners](/api/type-aliases/TransactionSigner). | ## Parameters | Parameter | Type | | ------------- | ------------------------------------------------------------------------------ | | `instruction` | [`InstructionWithSigners`](/api/interfaces/InstructionWithSigners)\<`TSigner`> | ## Returns readonly `TSigner`\[] ## Example ```ts import { InstructionWithSigners, getSignersFromInstruction } from '@solana/signers'; const signerA = { address: address('1111..1111'), signTransactions: async () => {} }; const signerB = { address: address('2222..2222'), signTransactions: async () => {} }; const instructionWithSigners: InstructionWithSigners = { accounts: [ { address: signerA.address, signer: signerA, ... }, { address: signerB.address, signer: signerB, ... }, { address: signerA.address, signer: signerA, ... }, ], }; const instructionSigners = getSignersFromInstruction(instructionWithSigners); // ^ [signerA, signerB] ``` # getSignersFromOffchainMessage (/api/functions/getSignersFromOffchainMessage) ```ts function getSignersFromOffchainMessage( __namedParameters, ): readonly MessageSigner[]; ``` Extracts and deduplicates all [MessageSigners](/api/type-aliases/MessageSigner) stored inside a given OffchainMessageWithSigners | offchain message. Any extracted signers that share the same Address will be de-duplicated. ## Parameters | Parameter | Type | | ------------------- | ---------------------------------------- | | `__namedParameters` | `OffchainMessageWithRequiredSignatories` | ## Returns readonly [`MessageSigner`](/api/type-aliases/MessageSigner)\[] ## Example ```ts import { OffchainMessageWithSigners, getSignersFromOffchainMessage } from '@solana/signers'; const signerA = { address: address('1111..1111'), signMessages: async () => {} }; const signerB = { address: address('2222..2222'), modifyAndSignMessages: async () => {} }; const OffchainMessage: OffchainMessageWithSigners = { /* ... */ requiredSignatories: [signerA, signerB], }; const messageSigners = getSignersFromOffchainMessage(offchainMessage); // ^ [signerA, signerB] ``` # getSignersFromTransactionMessage (/api/functions/getSignersFromTransactionMessage) ```ts function getSignersFromTransactionMessage< TAddress, TSigner, TTransactionMessage, >(transaction): readonly TSigner[]; ``` Extracts and deduplicates all [TransactionSigners](/api/type-aliases/TransactionSigner) stored inside a given [transaction message](/api/type-aliases/TransactionMessageWithSigners). This includes any [TransactionSigners](/api/type-aliases/TransactionSigner) stored as the fee payer or in the instructions of the transaction message. Any extracted signers that share the same Address will be de-duplicated. ## Type Parameters | Type Parameter | Default type | Description | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | | `TSigner` *extends* [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TAddress`> | [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TAddress`> | Optionally provide a narrower type for [TransactionSigners](/api/type-aliases/TransactionSigner). | | `TTransactionMessage` *extends* [`TransactionMessageWithSigners`](/api/type-aliases/TransactionMessageWithSigners)\<`TAddress`, `TSigner`, readonly `AccountMetaWithSigner`\<`TSigner`>\[]> | [`TransactionMessageWithSigners`](/api/type-aliases/TransactionMessageWithSigners)\<`TAddress`, `TSigner`, readonly `AccountMetaWithSigner`\<`TSigner`>\[]> | The inferred type of the transaction message provided. | ## Parameters | Parameter | Type | | ------------- | --------------------- | | `transaction` | `TTransactionMessage` | ## Returns readonly `TSigner`\[] ## Example ```ts import { Instruction } from '@solana/instructions'; import { InstructionWithSigners, TransactionMessageWithSigners, getSignersFromTransactionMessage } from '@solana/signers'; const signerA = { address: address('1111..1111'), signTransactions: async () => {} }; const signerB = { address: address('2222..2222'), signTransactions: async () => {} }; const firstInstruction: Instruction & InstructionWithSigners = { programAddress: address('1234..5678'), accounts: [{ address: signerA.address, signer: signerA, ... }], }; const secondInstruction: Instruction & InstructionWithSigners = { programAddress: address('1234..5678'), accounts: [{ address: signerB.address, signer: signerB, ... }], }; const transactionMessage: TransactionMessageWithSigners = { feePayer: signerA, instructions: [firstInstruction, secondInstruction], } const transactionSigners = getSignersFromTransactionMessage(transactionMessage); // ^ [signerA, signerB] ``` # getSolCodec (/api/functions/getSolCodec) ```ts function getSolCodec(): FixedSizeCodec; ``` Returns a codec combining [getSolEncoder](/api/functions/getSolEncoder) and [getSolDecoder](/api/functions/getSolDecoder). The encoder accepts either [Sol](/api/type-aliases/Sol) or [Lamports](/api/type-aliases/Lamports); the decoder always returns [Sol](/api/type-aliases/Sol). ## Returns `FixedSizeCodec`\< \| [`Sol`](/api/type-aliases/Sol) \| [`Lamports`](/api/type-aliases/Lamports), [`Sol`](/api/type-aliases/Sol), `8`> ## See * [getSolEncoder](/api/functions/getSolEncoder) * [getSolDecoder](/api/functions/getSolDecoder) # getSolDecoder (/api/functions/getSolDecoder) ```ts function getSolDecoder(): FixedSizeDecoder; ``` Returns a decoder that reads 8 bytes in little-endian order into a [Sol](/api/type-aliases/Sol) value. ## Returns `FixedSizeDecoder`\<[`Sol`](/api/type-aliases/Sol), `8`> ## See * [getSolEncoder](/api/functions/getSolEncoder) * [getSolCodec](/api/functions/getSolCodec) # getSolEncoder (/api/functions/getSolEncoder) ```ts function getSolEncoder(): FixedSizeEncoder; ``` Returns an encoder that writes a [Sol](/api/type-aliases/Sol) or [Lamports](/api/type-aliases/Lamports) value to 8 bytes in little-endian order. Since Sol and Lamports share the same u64 wire format, either can be passed as input. ## Returns `FixedSizeEncoder`\< \| [`Sol`](/api/type-aliases/Sol) \| [`Lamports`](/api/type-aliases/Lamports), `8`> ## See * [getSolDecoder](/api/functions/getSolDecoder) * [getSolCodec](/api/functions/getSolCodec) # getSolanaErrorFromInstructionError (/api/functions/getSolanaErrorFromInstructionError) ```ts function getSolanaErrorFromInstructionError( index, instructionError, ): SolanaError; ``` ## Parameters | Parameter | Type | Description | | ------------------ | -------------------------------------------------- | ---------------------------------------------------- | | `index` | `number` \| `bigint` | The index of the instruction inside the transaction. | | `instructionError` | \| `string` \| \{ \[`key`: `string`]: `unknown`; } | - | ## Returns [`SolanaError`](/api/classes/SolanaError) # getSolanaErrorFromJsonRpcError (/api/functions/getSolanaErrorFromJsonRpcError) ```ts function getSolanaErrorFromJsonRpcError( putativeErrorResponse, ): SolanaError; ``` ## Parameters | Parameter | Type | | ----------------------- | --------- | | `putativeErrorResponse` | `unknown` | ## Returns [`SolanaError`](/api/classes/SolanaError) # getSolanaErrorFromTransactionError (/api/functions/getSolanaErrorFromTransactionError) ```ts function getSolanaErrorFromTransactionError( transactionError, ): SolanaError; ``` ## Parameters | Parameter | Type | | ------------------ | -------------------------------------------------- | | `transactionError` | \| `string` \| \{ \[`key`: `string`]: `unknown`; } | ## Returns [`SolanaError`](/api/classes/SolanaError) # getStructCodec (/api/functions/getStructCodec) ## Call Signature ```ts function getStructCodec( fields, ): FixedSizeCodec< DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never; }>, DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never; }> & DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never; }>, TFields[0][1]['fixedSize'] >; ``` Returns a codec for encoding and decoding custom objects. This codec serializes objects by encoding and decoding each field sequentially. ### Type Parameters | Type Parameter | Description | | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | `TFields` *extends* readonly \[readonly \[`string`, [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`any`>]] | The fields of the struct, each paired with a codec. | ### Parameters | Parameter | Type | Description | | --------- | --------- | --------------------------------- | | `fields` | `TFields` | The name and codec of each field. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never }`>, `DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never }`> & `DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never }`>, `TFields`\[`0`]\[`1`]\[`"fixedSize"`]> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding custom objects. ### Example Encoding and decoding a custom struct. ```ts const codec = getStructCodec([ ['name', fixCodecSize(getUtf8Codec(), 5)], ['age', getU8Codec()] ]); const bytes = codec.encode({ name: 'Alice', age: 42 }); // 0x416c6963652a // | └── Age (42) // └── Name ("Alice") const struct = codec.decode(bytes); // { name: 'Alice', age: 42 } ``` ### Remarks Separate [getStructEncoder](/api/functions/getStructEncoder) and [getStructDecoder](/api/functions/getStructDecoder) functions are available. ```ts const bytes = getStructEncoder([ ['name', fixCodecSize(getUtf8Encoder(), 5)], ['age', getU8Encoder()] ]).encode({ name: 'Alice', age: 42 }); const struct = getStructDecoder([ ['name', fixCodecSize(getUtf8Decoder(), 5)], ['age', getU8Decoder()] ]).decode(bytes); ``` ### See * [getStructEncoder](/api/functions/getStructEncoder) * [getStructDecoder](/api/functions/getStructDecoder) ## Call Signature ```ts function getStructCodec( fields, ): FixedSizeCodec< DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never; }>, DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never; }> & DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never; }> >; ``` Returns a codec for encoding and decoding custom objects. This codec serializes objects by encoding and decoding each field sequentially. ### Type Parameters | Type Parameter | Description | | ----------------------------------------------------------------------------------------- | --------------------------------------------------- | | `TFields` *extends* `Fields`\<[`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`any`>> | The fields of the struct, each paired with a codec. | ### Parameters | Parameter | Type | Description | | --------- | --------- | --------------------------------- | | `fields` | `TFields` | The name and codec of each field. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never }`>, `DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never }`> & `DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never }`>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding custom objects. ### Example Encoding and decoding a custom struct. ```ts const codec = getStructCodec([ ['name', fixCodecSize(getUtf8Codec(), 5)], ['age', getU8Codec()] ]); const bytes = codec.encode({ name: 'Alice', age: 42 }); // 0x416c6963652a // | └── Age (42) // └── Name ("Alice") const struct = codec.decode(bytes); // { name: 'Alice', age: 42 } ``` ### Remarks Separate [getStructEncoder](/api/functions/getStructEncoder) and [getStructDecoder](/api/functions/getStructDecoder) functions are available. ```ts const bytes = getStructEncoder([ ['name', fixCodecSize(getUtf8Encoder(), 5)], ['age', getU8Encoder()] ]).encode({ name: 'Alice', age: 42 }); const struct = getStructDecoder([ ['name', fixCodecSize(getUtf8Decoder(), 5)], ['age', getU8Decoder()] ]).decode(bytes); ``` ### See * [getStructEncoder](/api/functions/getStructEncoder) * [getStructDecoder](/api/functions/getStructDecoder) ## Call Signature ```ts function getStructCodec( fields, ): VariableSizeCodec< DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never; }>, DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never; }> & DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never; }> >; ``` Returns a codec for encoding and decoding custom objects. This codec serializes objects by encoding and decoding each field sequentially. ### Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------- | --------------------------------------------------- | | `TFields` *extends* `Fields`\<[`Codec`](/api/type-aliases/Codec)\<`any`>> | The fields of the struct, each paired with a codec. | ### Parameters | Parameter | Type | Description | | --------- | --------- | --------------------------------- | | `fields` | `TFields` | The name and codec of each field. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never }`>, `DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never }`> & `DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never }`>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding custom objects. ### Example Encoding and decoding a custom struct. ```ts const codec = getStructCodec([ ['name', fixCodecSize(getUtf8Codec(), 5)], ['age', getU8Codec()] ]); const bytes = codec.encode({ name: 'Alice', age: 42 }); // 0x416c6963652a // | └── Age (42) // └── Name ("Alice") const struct = codec.decode(bytes); // { name: 'Alice', age: 42 } ``` ### Remarks Separate [getStructEncoder](/api/functions/getStructEncoder) and [getStructDecoder](/api/functions/getStructDecoder) functions are available. ```ts const bytes = getStructEncoder([ ['name', fixCodecSize(getUtf8Encoder(), 5)], ['age', getU8Encoder()] ]).encode({ name: 'Alice', age: 42 }); const struct = getStructDecoder([ ['name', fixCodecSize(getUtf8Decoder(), 5)], ['age', getU8Decoder()] ]).decode(bytes); ``` ### See * [getStructEncoder](/api/functions/getStructEncoder) * [getStructDecoder](/api/functions/getStructDecoder) # getStructDecoder (/api/functions/getStructDecoder) ## Call Signature ```ts function getStructDecoder( fields, ): FixedSizeDecoder< DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never; }>, TFields[0][1]['fixedSize'] >; ``` Returns a decoder for custom objects. This decoder deserializes an object by decoding its fields sequentially, using the provided field decoders. For more details, see [getStructCodec](/api/functions/getStructCodec). ### Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | `TFields` *extends* readonly \[readonly \[`string`, [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`any`>]] | The fields of the struct, each paired with a decoder. | ### Parameters | Parameter | Type | Description | | --------- | --------- | ----------------------------------- | | `fields` | `TFields` | The name and decoder of each field. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never }`>, `TFields`\[`0`]\[`1`]\[`"fixedSize"`]> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding custom objects. ### Example Decoding a custom struct. ```ts const decoder = getStructDecoder([ ['name', fixCodecSize(getUtf8Decoder(), 5)], ['age', getU8Decoder()] ]); const struct = decoder.decode(new Uint8Array([ 0x41,0x6c,0x69,0x63,0x65,0x2a ])); // { name: 'Alice', age: 42 } ``` ### See [getStructCodec](/api/functions/getStructCodec) ## Call Signature ```ts function getStructDecoder( fields, ): FixedSizeDecoder< DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never; }> >; ``` Returns a decoder for custom objects. This decoder deserializes an object by decoding its fields sequentially, using the provided field decoders. For more details, see [getStructCodec](/api/functions/getStructCodec). ### Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | `TFields` *extends* `Fields`\<[`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`any`>> | The fields of the struct, each paired with a decoder. | ### Parameters | Parameter | Type | Description | | --------- | --------- | ----------------------------------- | | `fields` | `TFields` | The name and decoder of each field. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never }`>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding custom objects. ### Example Decoding a custom struct. ```ts const decoder = getStructDecoder([ ['name', fixCodecSize(getUtf8Decoder(), 5)], ['age', getU8Decoder()] ]); const struct = decoder.decode(new Uint8Array([ 0x41,0x6c,0x69,0x63,0x65,0x2a ])); // { name: 'Alice', age: 42 } ``` ### See [getStructCodec](/api/functions/getStructCodec) ## Call Signature ```ts function getStructDecoder( fields, ): VariableSizeDecoder< DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never; }> >; ``` Returns a decoder for custom objects. This decoder deserializes an object by decoding its fields sequentially, using the provided field decoders. For more details, see [getStructCodec](/api/functions/getStructCodec). ### Type Parameters | Type Parameter | Description | | ----------------------------------------------------------------------------- | ----------------------------------------------------- | | `TFields` *extends* `Fields`\<[`Decoder`](/api/type-aliases/Decoder)\<`any`>> | The fields of the struct, each paired with a decoder. | ### Parameters | Parameter | Type | Description | | --------- | --------- | ----------------------------------- | | `fields` | `TFields` | The name and decoder of each field. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never }`>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding custom objects. ### Example Decoding a custom struct. ```ts const decoder = getStructDecoder([ ['name', fixCodecSize(getUtf8Decoder(), 5)], ['age', getU8Decoder()] ]); const struct = decoder.decode(new Uint8Array([ 0x41,0x6c,0x69,0x63,0x65,0x2a ])); // { name: 'Alice', age: 42 } ``` ### See [getStructCodec](/api/functions/getStructCodec) # getStructEncoder (/api/functions/getStructEncoder) ## Call Signature ```ts function getStructEncoder( fields, ): FixedSizeEncoder< DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never; }>, TFields[0][1]['fixedSize'] >; ``` Returns an encoder for custom objects. This encoder serializes an object by encoding its fields sequentially, using the provided field encoders. For more details, see [getStructCodec](/api/functions/getStructCodec). ### Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | | `TFields` *extends* readonly \[readonly \[`string`, [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`any`>]] | The fields of the struct, each paired with an encoder. | ### Parameters | Parameter | Type | Description | | --------- | --------- | ----------------------------------- | | `fields` | `TFields` | The name and encoder of each field. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never }`>, `TFields`\[`0`]\[`1`]\[`"fixedSize"`]> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding custom objects. ### Example Encoding a custom struct. ```ts const encoder = getStructEncoder([ ['name', fixCodecSize(getUtf8Encoder(), 5)], ['age', getU8Encoder()] ]); const bytes = encoder.encode({ name: 'Alice', age: 42 }); // 0x416c6963652a // | └── Age (42) // └── Name ("Alice") ``` ### See [getStructCodec](/api/functions/getStructCodec) ## Call Signature ```ts function getStructEncoder( fields, ): FixedSizeEncoder< DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never; }> >; ``` Returns an encoder for custom objects. This encoder serializes an object by encoding its fields sequentially, using the provided field encoders. For more details, see [getStructCodec](/api/functions/getStructCodec). ### Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------- | ------------------------------------------------------ | | `TFields` *extends* `Fields`\<[`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`any`>> | The fields of the struct, each paired with an encoder. | ### Parameters | Parameter | Type | Description | | --------- | --------- | ----------------------------------- | | `fields` | `TFields` | The name and encoder of each field. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never }`>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding custom objects. ### Example Encoding a custom struct. ```ts const encoder = getStructEncoder([ ['name', fixCodecSize(getUtf8Encoder(), 5)], ['age', getU8Encoder()] ]); const bytes = encoder.encode({ name: 'Alice', age: 42 }); // 0x416c6963652a // | └── Age (42) // └── Name ("Alice") ``` ### See [getStructCodec](/api/functions/getStructCodec) ## Call Signature ```ts function getStructEncoder( fields, ): VariableSizeEncoder< DrainOuterGeneric<{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never; }> >; ``` Returns an encoder for custom objects. This encoder serializes an object by encoding its fields sequentially, using the provided field encoders. For more details, see [getStructCodec](/api/functions/getStructCodec). ### Type Parameters | Type Parameter | Description | | ----------------------------------------------------------------------------- | ------------------------------------------------------ | | `TFields` *extends* `Fields`\<[`Encoder`](/api/type-aliases/Encoder)\<`any`>> | The fields of the struct, each paired with an encoder. | ### Parameters | Parameter | Type | Description | | --------- | --------- | ----------------------------------- | | `fields` | `TFields` | The name and encoder of each field. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`DrainOuterGeneric`\<`{ [I in never as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never }`>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding custom objects. ### Example Encoding a custom struct. ```ts const encoder = getStructEncoder([ ['name', fixCodecSize(getUtf8Encoder(), 5)], ['age', getU8Encoder()] ]); const bytes = encoder.encode({ name: 'Alice', age: 42 }); // 0x416c6963652a // | └── Age (42) // └── Name ("Alice") ``` ### See [getStructCodec](/api/functions/getStructCodec) # getSysvarClockCodec (/api/functions/getSysvarClockCodec) ```ts function getSysvarClockCodec(): FixedSizeCodec< Readonly<{ epoch: bigint; epochStartTimestamp: UnixTimestamp; leaderScheduleEpoch: bigint; slot: bigint; unixTimestamp: UnixTimestamp; }>, Readonly<{ epoch: bigint; epochStartTimestamp: UnixTimestamp; leaderScheduleEpoch: bigint; slot: bigint; unixTimestamp: UnixTimestamp; }>, 40 >; ``` Returns a codec that you can use to encode from or decode to [SysvarClock](/api/type-aliases/SysvarClock) ## Returns `FixedSizeCodec`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `epoch`: `bigint`; `epochStartTimestamp`: `UnixTimestamp`; `leaderScheduleEpoch`: `bigint`; `slot`: `bigint`; `unixTimestamp`: `UnixTimestamp`; }>, [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `epoch`: `bigint`; `epochStartTimestamp`: `UnixTimestamp`; `leaderScheduleEpoch`: `bigint`; `slot`: `bigint`; `unixTimestamp`: `UnixTimestamp`; }>, `40`> ## See * [getSysvarClockDecoder](/api/functions/getSysvarClockDecoder) * [getSysvarClockEncoder](/api/functions/getSysvarClockEncoder) # getSysvarClockDecoder (/api/functions/getSysvarClockDecoder) ```ts function getSysvarClockDecoder(): FixedSizeDecoder< Readonly<{ epoch: bigint; epochStartTimestamp: UnixTimestamp; leaderScheduleEpoch: bigint; slot: bigint; unixTimestamp: UnixTimestamp; }>, 40 >; ``` Returns a decoder that you can use to decode a byte array representing the `Clock` sysvar's account data to a [SysvarClock](/api/type-aliases/SysvarClock). ## Returns `FixedSizeDecoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `epoch`: `bigint`; `epochStartTimestamp`: `UnixTimestamp`; `leaderScheduleEpoch`: `bigint`; `slot`: `bigint`; `unixTimestamp`: `UnixTimestamp`; }>, `40`> # getSysvarClockEncoder (/api/functions/getSysvarClockEncoder) ```ts function getSysvarClockEncoder(): FixedSizeEncoder< Readonly<{ epoch: bigint; epochStartTimestamp: UnixTimestamp; leaderScheduleEpoch: bigint; slot: bigint; unixTimestamp: UnixTimestamp; }>, 40 >; ``` Returns an encoder that you can use to encode a [SysvarClock](/api/type-aliases/SysvarClock) to a byte array representing the `Clock` sysvar's account data. ## Returns `FixedSizeEncoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `epoch`: `bigint`; `epochStartTimestamp`: `UnixTimestamp`; `leaderScheduleEpoch`: `bigint`; `slot`: `bigint`; `unixTimestamp`: `UnixTimestamp`; }>, `40`> # getSysvarEpochRewardsCodec (/api/functions/getSysvarEpochRewardsCodec) ```ts function getSysvarEpochRewardsCodec(): FixedSizeCodec< Readonly<{ active: boolean; distributedRewards: Lamports; distributionStartingBlockHeight: bigint; numPartitions: bigint; parentBlockhash: Blockhash; totalPoints: bigint; totalRewards: Lamports; }>, Readonly<{ active: boolean; distributedRewards: Lamports; distributionStartingBlockHeight: bigint; numPartitions: bigint; parentBlockhash: Blockhash; totalPoints: bigint; totalRewards: Lamports; }>, 81 >; ``` Returns a codec that you can use to encode from or decode to [SysvarEpochRewards](/api/type-aliases/SysvarEpochRewards) ## Returns `FixedSizeCodec`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `active`: `boolean`; `distributedRewards`: `Lamports`; `distributionStartingBlockHeight`: `bigint`; `numPartitions`: `bigint`; `parentBlockhash`: `Blockhash`; `totalPoints`: `bigint`; `totalRewards`: `Lamports`; }>, [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `active`: `boolean`; `distributedRewards`: `Lamports`; `distributionStartingBlockHeight`: `bigint`; `numPartitions`: `bigint`; `parentBlockhash`: `Blockhash`; `totalPoints`: `bigint`; `totalRewards`: `Lamports`; }>, `81`> ## See * [getSysvarEpochRewardsDecoder](/api/functions/getSysvarEpochRewardsDecoder) * [getSysvarEpochRewardsEncoder](/api/functions/getSysvarEpochRewardsEncoder) # getSysvarEpochRewardsDecoder (/api/functions/getSysvarEpochRewardsDecoder) ```ts function getSysvarEpochRewardsDecoder(): FixedSizeDecoder< Readonly<{ active: boolean; distributedRewards: Lamports; distributionStartingBlockHeight: bigint; numPartitions: bigint; parentBlockhash: Blockhash; totalPoints: bigint; totalRewards: Lamports; }>, 81 >; ``` Returns a decoder that you can use to decode a byte array representing the `EpochRewards` sysvar's account data to a [SysvarEpochRewards](/api/type-aliases/SysvarEpochRewards). ## Returns `FixedSizeDecoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `active`: `boolean`; `distributedRewards`: `Lamports`; `distributionStartingBlockHeight`: `bigint`; `numPartitions`: `bigint`; `parentBlockhash`: `Blockhash`; `totalPoints`: `bigint`; `totalRewards`: `Lamports`; }>, `81`> # getSysvarEpochRewardsEncoder (/api/functions/getSysvarEpochRewardsEncoder) ```ts function getSysvarEpochRewardsEncoder(): FixedSizeEncoder< Readonly<{ active: boolean; distributedRewards: Lamports; distributionStartingBlockHeight: bigint; numPartitions: bigint; parentBlockhash: Blockhash; totalPoints: bigint; totalRewards: Lamports; }>, 81 >; ``` Returns an encoder that you can use to encode a [SysvarEpochRewards](/api/type-aliases/SysvarEpochRewards) to a byte array representing the `EpochRewards` sysvar's account data. ## Returns `FixedSizeEncoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `active`: `boolean`; `distributedRewards`: `Lamports`; `distributionStartingBlockHeight`: `bigint`; `numPartitions`: `bigint`; `parentBlockhash`: `Blockhash`; `totalPoints`: `bigint`; `totalRewards`: `Lamports`; }>, `81`> # getSysvarEpochScheduleCodec (/api/functions/getSysvarEpochScheduleCodec) ```ts function getSysvarEpochScheduleCodec(): FixedSizeCodec< Readonly<{ firstNormalEpoch: bigint; firstNormalSlot: bigint; leaderScheduleSlotOffset: bigint; slotsPerEpoch: bigint; warmup: boolean; }>, Readonly<{ firstNormalEpoch: bigint; firstNormalSlot: bigint; leaderScheduleSlotOffset: bigint; slotsPerEpoch: bigint; warmup: boolean; }>, 33 >; ``` Returns a codec that you can use to encode from or decode to [SysvarEpochSchedule](/api/type-aliases/SysvarEpochSchedule) ## Returns `FixedSizeCodec`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `firstNormalEpoch`: `bigint`; `firstNormalSlot`: `bigint`; `leaderScheduleSlotOffset`: `bigint`; `slotsPerEpoch`: `bigint`; `warmup`: `boolean`; }>, [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `firstNormalEpoch`: `bigint`; `firstNormalSlot`: `bigint`; `leaderScheduleSlotOffset`: `bigint`; `slotsPerEpoch`: `bigint`; `warmup`: `boolean`; }>, `33`> ## See * [getSysvarEpochScheduleDecoder](/api/functions/getSysvarEpochScheduleDecoder) * [getSysvarEpochScheduleEncoder](/api/functions/getSysvarEpochScheduleEncoder) # getSysvarEpochScheduleDecoder (/api/functions/getSysvarEpochScheduleDecoder) ```ts function getSysvarEpochScheduleDecoder(): FixedSizeDecoder< Readonly<{ firstNormalEpoch: bigint; firstNormalSlot: bigint; leaderScheduleSlotOffset: bigint; slotsPerEpoch: bigint; warmup: boolean; }>, 33 >; ``` Returns a decoder that you can use to decode a byte array representing the `EpochSchedule` sysvar's account data to a [SysvarEpochSchedule](/api/type-aliases/SysvarEpochSchedule). ## Returns `FixedSizeDecoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `firstNormalEpoch`: `bigint`; `firstNormalSlot`: `bigint`; `leaderScheduleSlotOffset`: `bigint`; `slotsPerEpoch`: `bigint`; `warmup`: `boolean`; }>, `33`> # getSysvarEpochScheduleEncoder (/api/functions/getSysvarEpochScheduleEncoder) ```ts function getSysvarEpochScheduleEncoder(): FixedSizeEncoder< Readonly<{ firstNormalEpoch: bigint; firstNormalSlot: bigint; leaderScheduleSlotOffset: bigint; slotsPerEpoch: bigint; warmup: boolean; }>, 33 >; ``` Returns an encoder that you can use to encode a [SysvarEpochSchedule](/api/type-aliases/SysvarEpochSchedule) to a byte array representing the `EpochSchedule` sysvar's account data. ## Returns `FixedSizeEncoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `firstNormalEpoch`: `bigint`; `firstNormalSlot`: `bigint`; `leaderScheduleSlotOffset`: `bigint`; `slotsPerEpoch`: `bigint`; `warmup`: `boolean`; }>, `33`> # getSysvarLastRestartSlotCodec (/api/functions/getSysvarLastRestartSlotCodec) ```ts function getSysvarLastRestartSlotCodec(): FixedSizeCodec< Readonly<{ lastRestartSlot: bigint; }>, Readonly<{ lastRestartSlot: bigint; }>, 8 >; ``` Returns a codec that you can use to encode from or decode to [SysvarLastRestartSlot](/api/type-aliases/SysvarLastRestartSlot) ## Returns `FixedSizeCodec`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lastRestartSlot`: `bigint`; }>, [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lastRestartSlot`: `bigint`; }>, `8`> ## See * [getSysvarLastRestartSlotDecoder](/api/functions/getSysvarLastRestartSlotDecoder) * [getSysvarLastRestartSlotEncoder](/api/functions/getSysvarLastRestartSlotEncoder) # getSysvarLastRestartSlotDecoder (/api/functions/getSysvarLastRestartSlotDecoder) ```ts function getSysvarLastRestartSlotDecoder(): FixedSizeDecoder< Readonly<{ lastRestartSlot: bigint; }>, 8 >; ``` Returns a decoder that you can use to decode a byte array representing the `LastRestartSlot` sysvar's account data to a [SysvarLastRestartSlot](/api/type-aliases/SysvarLastRestartSlot). ## Returns `FixedSizeDecoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lastRestartSlot`: `bigint`; }>, `8`> # getSysvarLastRestartSlotEncoder (/api/functions/getSysvarLastRestartSlotEncoder) ```ts function getSysvarLastRestartSlotEncoder(): FixedSizeEncoder< Readonly<{ lastRestartSlot: bigint; }>, 8 >; ``` Returns an encoder that you can use to encode a [SysvarLastRestartSlot](/api/type-aliases/SysvarLastRestartSlot) to a byte array representing the `LastRestartSlot` sysvar's account data. ## Returns `FixedSizeEncoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lastRestartSlot`: `bigint`; }>, `8`> # getSysvarRecentBlockhashesCodec (/api/functions/getSysvarRecentBlockhashesCodec) ```ts function getSysvarRecentBlockhashesCodec(): VariableSizeCodec; ``` Returns a codec that you can use to encode from or decode to [SysvarRecentBlockhashes](/api/type-aliases/SysvarRecentBlockhashes) ## Returns `VariableSizeCodec`\<[`SysvarRecentBlockhashes`](/api/type-aliases/SysvarRecentBlockhashes)> ## Deprecated Transaction fees should be determined with the GetFeeForMessageApi.getFeeForMessage RPC method. For additional context see the [Comprehensive Compute Fees proposal](https://docs.anza.xyz/proposals/comprehensive-compute-fees/). ## See * [getSysvarRecentBlockhashesDecoder](/api/functions/getSysvarRecentBlockhashesDecoder) * [getSysvarRecentBlockhashesEncoder](/api/functions/getSysvarRecentBlockhashesEncoder) # getSysvarRecentBlockhashesDecoder (/api/functions/getSysvarRecentBlockhashesDecoder) ```ts function getSysvarRecentBlockhashesDecoder(): VariableSizeDecoder; ``` Returns a decoder that you can use to decode a byte array representing the `RecentBlockhashes` sysvar's account data to a [SysvarRecentBlockhashes](/api/type-aliases/SysvarRecentBlockhashes). ## Returns `VariableSizeDecoder`\<[`SysvarRecentBlockhashes`](/api/type-aliases/SysvarRecentBlockhashes)> ## Deprecated Transaction fees should be determined with the GetFeeForMessageApi.getFeeForMessage RPC method. For additional context see the [Comprehensive Compute Fees proposal](https://docs.anza.xyz/proposals/comprehensive-compute-fees/). # getSysvarRecentBlockhashesEncoder (/api/functions/getSysvarRecentBlockhashesEncoder) ```ts function getSysvarRecentBlockhashesEncoder(): VariableSizeEncoder; ``` Returns an encoder that you can use to encode a [SysvarRecentBlockhashes](/api/type-aliases/SysvarRecentBlockhashes) to a byte array representing the `RecentBlockhashes` sysvar's account data. ## Returns `VariableSizeEncoder`\<[`SysvarRecentBlockhashes`](/api/type-aliases/SysvarRecentBlockhashes)> ## Deprecated Transaction fees should be determined with the GetFeeForMessageApi.getFeeForMessage RPC method. For additional context see the [Comprehensive Compute Fees proposal](https://docs.anza.xyz/proposals/comprehensive-compute-fees/). # getSysvarRentCodec (/api/functions/getSysvarRentCodec) ```ts function getSysvarRentCodec(): FixedSizeCodec< Readonly<{ burnPercent: number; exemptionThreshold: number; lamportsPerByteYear: Lamports; }>, Readonly<{ burnPercent: number; exemptionThreshold: number; lamportsPerByteYear: Lamports; }>, 17 >; ``` Returns a codec that you can use to encode from or decode to [SysvarRent](/api/type-aliases/SysvarRent) ## Returns `FixedSizeCodec`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `burnPercent`: `number`; `exemptionThreshold`: `number`; `lamportsPerByteYear`: `Lamports`; }>, [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `burnPercent`: `number`; `exemptionThreshold`: `number`; `lamportsPerByteYear`: `Lamports`; }>, `17`> ## See * [getSysvarRentDecoder](/api/functions/getSysvarRentDecoder) * [getSysvarRentEncoder](/api/functions/getSysvarRentEncoder) # getSysvarRentDecoder (/api/functions/getSysvarRentDecoder) ```ts function getSysvarRentDecoder(): FixedSizeDecoder< Readonly<{ burnPercent: number; exemptionThreshold: number; lamportsPerByteYear: Lamports; }>, 17 >; ``` Returns a decoder that you can use to decode a byte array representing the `Rent` sysvar's account data to a [SysvarRent](/api/type-aliases/SysvarRent). ## Returns `FixedSizeDecoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `burnPercent`: `number`; `exemptionThreshold`: `number`; `lamportsPerByteYear`: `Lamports`; }>, `17`> # getSysvarRentEncoder (/api/functions/getSysvarRentEncoder) ```ts function getSysvarRentEncoder(): FixedSizeEncoder< Readonly<{ burnPercent: number; exemptionThreshold: number; lamportsPerByteYear: Lamports; }>, 17 >; ``` Returns an encoder that you can use to encode a [SysvarRent](/api/type-aliases/SysvarRent) to a byte array representing the `Rent` sysvar's account data. ## Returns `FixedSizeEncoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `burnPercent`: `number`; `exemptionThreshold`: `number`; `lamportsPerByteYear`: `Lamports`; }>, `17`> # getSysvarSlotHashesCodec (/api/functions/getSysvarSlotHashesCodec) ```ts function getSysvarSlotHashesCodec(): VariableSizeCodec; ``` Returns a codec that you can use to encode from or decode to [SysvarSlotHashes](/api/type-aliases/SysvarSlotHashes) ## Returns `VariableSizeCodec`\<[`SysvarSlotHashes`](/api/type-aliases/SysvarSlotHashes)> ## See * [getSysvarSlotHashesDecoder](/api/functions/getSysvarSlotHashesDecoder) * [getSysvarSlotHashesEncoder](/api/functions/getSysvarSlotHashesEncoder) # getSysvarSlotHashesDecoder (/api/functions/getSysvarSlotHashesDecoder) ```ts function getSysvarSlotHashesDecoder(): VariableSizeDecoder; ``` Returns a decoder that you can use to decode a byte array representing the `SlotHashes` sysvar's account data to a [SysvarSlotHashes](/api/type-aliases/SysvarSlotHashes). ## Returns `VariableSizeDecoder`\<[`SysvarSlotHashes`](/api/type-aliases/SysvarSlotHashes)> # getSysvarSlotHashesEncoder (/api/functions/getSysvarSlotHashesEncoder) ```ts function getSysvarSlotHashesEncoder(): VariableSizeEncoder; ``` Returns an encoder that you can use to encode a [SysvarSlotHashes](/api/type-aliases/SysvarSlotHashes) to a byte array representing the `SlotHashes` sysvar's account data. ## Returns `VariableSizeEncoder`\<[`SysvarSlotHashes`](/api/type-aliases/SysvarSlotHashes)> # getSysvarSlotHistoryCodec (/api/functions/getSysvarSlotHistoryCodec) ```ts function getSysvarSlotHistoryCodec(): FixedSizeCodec< SysvarSlotHistory, SysvarSlotHistory, number >; ``` Returns a codec that you can use to encode from or decode to [SysvarSlotHistory](/api/type-aliases/SysvarSlotHistory) ## Returns `FixedSizeCodec`\<[`SysvarSlotHistory`](/api/type-aliases/SysvarSlotHistory), [`SysvarSlotHistory`](/api/type-aliases/SysvarSlotHistory), `number`> ## See * [getSysvarSlotHistoryDecoder](/api/functions/getSysvarSlotHistoryDecoder) * [getSysvarSlotHistoryEncoder](/api/functions/getSysvarSlotHistoryEncoder) # getSysvarSlotHistoryDecoder (/api/functions/getSysvarSlotHistoryDecoder) ```ts function getSysvarSlotHistoryDecoder(): FixedSizeDecoder< SysvarSlotHistory, number >; ``` Returns a decoder that you can use to decode a byte array representing the `SlotHistory` sysvar's account data to a [SysvarSlotHistory](/api/type-aliases/SysvarSlotHistory). ## Returns `FixedSizeDecoder`\<[`SysvarSlotHistory`](/api/type-aliases/SysvarSlotHistory), `number`> # getSysvarSlotHistoryEncoder (/api/functions/getSysvarSlotHistoryEncoder) ```ts function getSysvarSlotHistoryEncoder(): FixedSizeEncoder< SysvarSlotHistory, number >; ``` Returns an encoder that you can use to encode a [SysvarSlotHistory](/api/type-aliases/SysvarSlotHistory) to a byte array representing the `SlotHistory` sysvar's account data. ## Returns `FixedSizeEncoder`\<[`SysvarSlotHistory`](/api/type-aliases/SysvarSlotHistory), `number`> # getSysvarStakeHistoryCodec (/api/functions/getSysvarStakeHistoryCodec) ```ts function getSysvarStakeHistoryCodec(): VariableSizeCodec; ``` Returns a codec that you can use to encode from or decode to [SysvarStakeHistory](/api/type-aliases/SysvarStakeHistory) ## Returns `VariableSizeCodec`\<[`SysvarStakeHistory`](/api/type-aliases/SysvarStakeHistory)> ## See * [getSysvarStakeHistoryDecoder](/api/functions/getSysvarStakeHistoryDecoder) * [getSysvarStakeHistoryEncoder](/api/functions/getSysvarStakeHistoryEncoder) # getSysvarStakeHistoryDecoder (/api/functions/getSysvarStakeHistoryDecoder) ```ts function getSysvarStakeHistoryDecoder(): VariableSizeDecoder; ``` Returns a decoder that you can use to decode a byte array representing the `StakeHistory` sysvar's account data to a [SysvarStakeHistory](/api/type-aliases/SysvarStakeHistory). ## Returns `VariableSizeDecoder`\<[`SysvarStakeHistory`](/api/type-aliases/SysvarStakeHistory)> # getSysvarStakeHistoryEncoder (/api/functions/getSysvarStakeHistoryEncoder) ```ts function getSysvarStakeHistoryEncoder(): VariableSizeEncoder; ``` Returns an encoder that you can use to encode a [SysvarStakeHistory](/api/type-aliases/SysvarStakeHistory) to a byte array representing the `StakeHistory` sysvar's account data. ## Returns `VariableSizeEncoder`\<[`SysvarStakeHistory`](/api/type-aliases/SysvarStakeHistory)> # getThrowSolanaErrorResponseTransformer (/api/functions/getThrowSolanaErrorResponseTransformer) ```ts function getThrowSolanaErrorResponseTransformer(): RpcResponseTransformer; ``` Returns a transformer that throws a SolanaError with the appropriate RPC error code if the body of the RPC response contains an error. ## Returns `RpcResponseTransformer` ## Example ```ts import { getThrowSolanaErrorResponseTransformer } from '@solana/rpc-transformers'; const responseTransformer = getThrowSolanaErrorResponseTransformer(); ``` # getTimeoutPromise (/api/functions/getTimeoutPromise) ```ts function getTimeoutPromise(config): Promise; ``` When no other heuristic exists to infer that a transaction has expired, you can use this promise factory with a commitment level. It throws after 30 seconds when the commitment is `processed`, and 60 seconds otherwise. You would typically race this with another confirmation strategy. ## Parameters | Parameter | Type | Description | | --------- | -------- | ----------- | | `config` | `Config` | - | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`> ## Example ```ts import { safeRace } from '@solana/promises'; import { getTimeoutPromise } from '@solana/transaction-confirmation'; try { await safeRace([getCustomTransactionConfirmationPromise(/* ... */), getTimeoutPromise({ commitment })]); } catch (e) { if (e instanceof DOMException && e.name === 'TimeoutError') { console.log('Could not confirm transaction after a timeout'); } throw e; } ``` # getTransactionCodec (/api/functions/getTransactionCodec) ```ts function getTransactionCodec(): VariableSizeCodec< Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> >; ``` Returns a codec that you can use to encode from or decode to a [Transaction](/api/type-aliases/Transaction) ## Returns `VariableSizeCodec`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }>> ## See * [getTransactionDecoder](/api/functions/getTransactionDecoder) * [getTransactionEncoder](/api/functions/getTransactionEncoder) # getTransactionDecoder (/api/functions/getTransactionDecoder) ```ts function getTransactionDecoder(): VariableSizeDecoder< Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> >; ``` Returns a decoder that you can use to convert a byte array in the Solana transaction wire format to a [Transaction](/api/type-aliases/Transaction) object. ## Returns `VariableSizeDecoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }>> ## Example ```ts import { getTransactionDecoder } from '@solana/transactions'; const transactionDecoder = getTransactionDecoder(); const transaction = transactionDecoder.decode(wireTransactionBytes); for (const [address, signature] in Object.entries(transaction.signatures)) { console.log(`Signature by ${address}`, signature); } ``` # getTransactionEncoder (/api/functions/getTransactionEncoder) ```ts function getTransactionEncoder(): VariableSizeEncoder< Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> >; ``` Returns an encoder that you can use to encode a [Transaction](/api/type-aliases/Transaction) to a byte array in a wire format appropriate for sending to the Solana network for execution. ## Returns `VariableSizeEncoder`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }>> # getTransactionLifetimeConstraintFromCompiledTransactionMessage (/api/functions/getTransactionLifetimeConstraintFromCompiledTransactionMessage) ```ts function getTransactionLifetimeConstraintFromCompiledTransactionMessage( compiledTransactionMessage, ): Promise< TransactionBlockhashLifetime | TransactionDurableNonceLifetime >; ``` Get the lifetime constraint for a transaction from a compiled transaction message that includes a lifetime token. ## Parameters | Parameter | Type | Description | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | `compiledTransactionMessage` | `CompiledTransactionMessage` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `lifetimeToken`: `string`; }> | A compiled transaction message that includes a lifetime token | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| [`TransactionBlockhashLifetime`](/api/type-aliases/TransactionBlockhashLifetime) \| [`TransactionDurableNonceLifetime`](/api/type-aliases/TransactionDurableNonceLifetime)> A lifetime constraint for the transaction Note that this is less precise than checking a decompiled instruction, as we can't inspect the address or role of input accounts (which may be in lookup tables). However, this is sufficient for all valid advance durable nonce instructions. Note that the program address must not be in a lookup table, see [this answer on StackExchange](https://solana.stackexchange.com/a/16224/289) ## See isAdvanceNonceAccountInstruction Note that this function is async to allow for future implementations that may fetch `lastValidBlockHeight` using an RPC # getTransactionMessageComputeUnitLimit (/api/functions/getTransactionMessageComputeUnitLimit) ```ts function getTransactionMessageComputeUnitLimit( transactionMessage, ): number | undefined; ``` Returns the compute unit limit currently set on a transaction message, or `undefined` if none is set. This function works with all transaction versions: * **V1**: Reads from the transaction message's `config.computeUnitLimit`. * **Legacy / V0**: Searches the instructions for a `SetComputeUnitLimit` instruction and decodes its value. ## Parameters | Parameter | Type | Description | | -------------------- | ------------------------------------------------------------ | ----------------------------------- | | `transactionMessage` | [`TransactionMessage`](/api/type-aliases/TransactionMessage) | The transaction message to inspect. | ## Returns `number` | `undefined` The compute unit limit, or `undefined` if none is set. ## Example ```ts const limit = getTransactionMessageComputeUnitLimit(transactionMessage); if (limit !== undefined) { console.log(`Compute unit limit: ${limit}`); } ``` # getTransactionMessageComputeUnitPrice (/api/functions/getTransactionMessageComputeUnitPrice) ```ts function getTransactionMessageComputeUnitPrice( transactionMessage, ): bigint | undefined; ``` Returns the compute unit price currently set on a legacy or v0 transaction message, or `undefined` if none is set. This searches the instructions for a `SetComputeUnitPrice` instruction and decodes its value. The value represents the price in **micro-lamports per compute unit**. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & `object` | ## Parameters | Parameter | Type | Description | | -------------------- | --------------------- | ------------------------------------------------ | | `transactionMessage` | `TTransactionMessage` | The legacy or v0 transaction message to inspect. | ## Returns `bigint` | `undefined` The compute unit price in micro-lamports per compute unit, or `undefined` if none is set. ## Example ```ts const price = getTransactionMessageComputeUnitPrice(transactionMessage); if (price !== undefined) { console.log(`Compute unit price: ${price} micro-lamports`); } ``` ## See * [setTransactionMessageComputeUnitPrice](/api/functions/setTransactionMessageComputeUnitPrice) * [getTransactionMessagePriorityFeeLamports](/api/functions/getTransactionMessagePriorityFeeLamports) for v1 transactions. # getTransactionMessageHeapSize (/api/functions/getTransactionMessageHeapSize) ```ts function getTransactionMessageHeapSize( transactionMessage, ): number | undefined; ``` Returns the heap size currently set on a transaction message, or `undefined` if none is set. This function works with all transaction versions: * **V1**: Reads from the transaction message's `config.heapSize`. * **Legacy / V0**: Searches the instructions for a `RequestHeapFrame` instruction and decodes its value. ## Parameters | Parameter | Type | Description | | -------------------- | ------------------------------------------------------------ | ----------------------------------- | | `transactionMessage` | [`TransactionMessage`](/api/type-aliases/TransactionMessage) | The transaction message to inspect. | ## Returns `number` | `undefined` The heap size in bytes, or `undefined` if none is set. ## Example ```ts const heapSize = getTransactionMessageHeapSize(transactionMessage); if (heapSize !== undefined) { console.log(`Heap size: ${heapSize}`); } ``` # getTransactionMessageLoadedAccountsDataSizeLimit (/api/functions/getTransactionMessageLoadedAccountsDataSizeLimit) ```ts function getTransactionMessageLoadedAccountsDataSizeLimit( transactionMessage, ): number | undefined; ``` Returns the loaded accounts data size limit currently set on a transaction message, or `undefined` if none is set. This function works with all transaction versions: * **V1**: Reads from the transaction message's `config.loadedAccountsDataSizeLimit`. * **Legacy / V0**: Searches the instructions for a `SetLoadedAccountsDataSizeLimit` instruction and decodes its value. ## Parameters | Parameter | Type | Description | | -------------------- | ------------------------------------------------------------ | ----------------------------------- | | `transactionMessage` | [`TransactionMessage`](/api/type-aliases/TransactionMessage) | The transaction message to inspect. | ## Returns `number` | `undefined` The loaded accounts data size limit in bytes, or `undefined` if none is set. ## Example ```ts const limit = getTransactionMessageLoadedAccountsDataSizeLimit(transactionMessage); if (limit !== undefined) { console.log(`Loaded accounts data size limit: ${limit}`); } ``` # getTransactionMessagePriorityFeeLamports (/api/functions/getTransactionMessagePriorityFeeLamports) ```ts function getTransactionMessagePriorityFeeLamports( transactionMessage, ): bigint | undefined; ``` Returns the priority fee in lamports currently set on a v1 transaction message, or `undefined` if none is set. This reads from the transaction message's `config.priorityFeeLamports`. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & `object` | ## Parameters | Parameter | Type | Description | | -------------------- | --------------------- | -------------------------------------- | | `transactionMessage` | `TTransactionMessage` | The v1 transaction message to inspect. | ## Returns `bigint` | `undefined` The priority fee in lamports, or `undefined` if none is set. ## Example ```ts const fee = getTransactionMessagePriorityFeeLamports(transactionMessage); if (fee !== undefined) { console.log(`Priority fee: ${fee}`); } ``` ## See * [setTransactionMessagePriorityFeeLamports](/api/functions/setTransactionMessagePriorityFeeLamports) * [setTransactionMessageComputeUnitPrice](/api/functions/setTransactionMessageComputeUnitPrice) for legacy/v0 transactions. # getTransactionMessageSize (/api/functions/getTransactionMessageSize) ```ts function getTransactionMessageSize(transactionMessage): number; ``` Gets the compiled transaction size of a given transaction message in bytes. ## Parameters | Parameter | Type | | -------------------- | ------------------------------------------------------------------ | | `transactionMessage` | `TransactionMessage` & `TransactionMessageWithFeePayer`\<`string`> | ## Returns `number` ## Example ```ts const transactionSize = getTransactionMessageSize(transactionMessage); ``` # getTransactionMessageSizeLimit (/api/functions/getTransactionMessageSizeLimit) ```ts function getTransactionMessageSizeLimit(transactionMessage): number; ``` Returns the maximum allowed compiled size in bytes for a given transaction message. This depends on the version of the transaction message. ## Parameters | Parameter | Type | | -------------------- | ------------------------------------------------------------------ | | `transactionMessage` | `TransactionMessage` & `TransactionMessageWithFeePayer`\<`string`> | ## Returns `number` ## Example ```ts const sizeLimit = getTransactionMessageSizeLimit(transactionMessage); ``` # getTransactionSize (/api/functions/getTransactionSize) ```ts function getTransactionSize(transaction): number; ``` Gets the size of a given transaction in bytes. ## Parameters | Parameter | Type | | ------------- | ---------------------------------------------- | | `transaction` | [`Transaction`](/api/type-aliases/Transaction) | ## Returns `number` ## Example ```ts const transactionSize = getTransactionSize(transaction); ``` # getTransactionSizeLimit (/api/functions/getTransactionSizeLimit) ```ts function getTransactionSizeLimit(transaction): number; ``` Returns the maximum size in bytes allowed for the given transaction. The size limit depends on the transaction version: version 1 transactions allow up to V1\_TRANSACTION\_SIZE\_LIMIT bytes, while legacy and v0 transactions are capped at LEGACY\_TRANSACTION\_SIZE\_LIMIT bytes. ## Parameters | Parameter | Type | Description | | ------------- | ---------------------------------------------- | --------------------------------------------- | | `transaction` | [`Transaction`](/api/type-aliases/Transaction) | The transaction whose size limit to retrieve. | ## Returns `number` The maximum number of bytes the transaction may occupy. ## Example ```ts const sizeLimit = getTransactionSizeLimit(transaction); ``` ## See * [isTransactionWithinSizeLimit](/api/functions/isTransactionWithinSizeLimit) * [assertIsTransactionWithinSizeLimit](/api/functions/assertIsTransactionWithinSizeLimit) # getTransactionVersionCodec (/api/functions/getTransactionVersionCodec) ```ts function getTransactionVersionCodec(): VariableSizeCodec; ``` Returns a codec that you can use to encode from or decode to [TransactionVersion](/api/type-aliases/TransactionVersion) ## Returns `VariableSizeCodec`\<[`TransactionVersion`](/api/type-aliases/TransactionVersion)> ## See * [getTransactionVersionDecoder](/api/functions/getTransactionVersionDecoder) * [getTransactionVersionEncoder](/api/functions/getTransactionVersionEncoder) # getTransactionVersionDecoder (/api/functions/getTransactionVersionDecoder) ```ts function getTransactionVersionDecoder(): VariableSizeDecoder; ``` Returns a decoder that you can use to decode a byte array representing a [TransactionVersion](/api/type-aliases/TransactionVersion). When the byte at the current offset is determined to represent a legacy transaction, this decoder will return `'legacy'` and will not advance the offset. ## Returns `VariableSizeDecoder`\<[`TransactionVersion`](/api/type-aliases/TransactionVersion)> # getTransactionVersionEncoder (/api/functions/getTransactionVersionEncoder) ```ts function getTransactionVersionEncoder(): VariableSizeEncoder; ``` Returns an encoder that you can use to encode a [TransactionVersion](/api/type-aliases/TransactionVersion) to a byte array. Legacy messages will produce an empty array and will not advance the offset. Versioned messages will produce an array with a single byte. ## Returns `VariableSizeEncoder`\<[`TransactionVersion`](/api/type-aliases/TransactionVersion)> # getTreeWalkerRequestTransformer (/api/functions/getTreeWalkerRequestTransformer) ```ts function getTreeWalkerRequestTransformer( visitors, initialState, ): RpcRequestTransformer; ``` Creates a transformer that traverses the request parameters and executes the provided visitors at each node. A custom initial state can be provided but must at least provide `{ keyPath: [] }`. ## Type Parameters | Type Parameter | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TState` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `keyPath`: [`KeyPath`](/api/type-aliases/KeyPath); }> | ## Parameters | Parameter | Type | | -------------- | ---------------- | | `visitors` | `NodeVisitor`\[] | | `initialState` | `TState` | ## Returns `RpcRequestTransformer` ## Example ```ts import { getTreeWalkerRequestTransformer } from '@solana/rpc-transformers'; const requestTransformer = getTreeWalkerRequestTransformer( [ // Replaces foo.bar with "baz". (node, state) => (state.keyPath === ['foo', 'bar'] ? 'baz' : node), // Increments all numbers by 1. node => (typeof node === number ? node + 1 : node), ], { keyPath: [] }, ); ``` # getTreeWalkerResponseTransformer (/api/functions/getTreeWalkerResponseTransformer) ```ts function getTreeWalkerResponseTransformer( visitors, initialState, ): RpcResponseTransformer; ``` ## Type Parameters | Type Parameter | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TState` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `keyPath`: [`KeyPath`](/api/type-aliases/KeyPath); }> | ## Parameters | Parameter | Type | | -------------- | ---------------- | | `visitors` | `NodeVisitor`\[] | | `initialState` | `TState` | ## Returns `RpcResponseTransformer` # getTupleCodec (/api/functions/getTupleCodec) ## Call Signature ```ts function getTupleCodec( items, config?, ): FixedSizeCodec< DrainOuterGeneric<{ [I in | string | number | symbol]: TItems[I] extends Encoder ? TFrom : never; }>, DrainOuterGeneric<{ [I in string | number | symbol]: TItems[I] extends Decoder ? TTo : never; }> & DrainOuterGeneric<{ [I in | string | number | symbol]: TItems[I] extends Encoder ? TFrom : never; }> >; ``` Returns a codec for encoding and decoding tuples. This codec serializes tuples by encoding and decoding each item sequentially. Unlike the [getArrayCodec](/api/functions/getArrayCodec) codec, each item in the tuple has its own codec and, therefore, can be of a different type. ### Type Parameters | Type Parameter | Description | | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | `TItems` *extends* readonly [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`any`>\[] | An array of codecs, each corresponding to a tuple element. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------- | -------------------------------------- | | `items` | `TItems` | The codecs for each item in the tuple. | | `config?` | [`TupleCodecConfig`](/api/type-aliases/TupleCodecConfig) | - | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Encoder\ ? TFrom : never }>, `DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Decoder\ ? TTo : never }> & `DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Encoder\ ? TFrom : never }>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding tuples. ### Example Encoding and decoding a tuple with 2 items. ```ts const codec = getTupleCodec([fixCodecSize(getUtf8Codec(), 5), getU8Codec()]); const bytes = codec.encode(['Alice', 42]); // 0x416c6963652a // | └── Second item (42) // └── First item ("Alice") const tuple = codec.decode(bytes); // ['Alice', 42] ``` ### Remarks Separate [getTupleEncoder](/api/functions/getTupleEncoder) and [getTupleDecoder](/api/functions/getTupleDecoder) functions are available. ```ts const bytes = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()]) .encode(['Alice', 42]); const tuple = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()]) .decode(bytes); ``` ### See * [getTupleEncoder](/api/functions/getTupleEncoder) * [getTupleDecoder](/api/functions/getTupleDecoder) ## Call Signature ```ts function getTupleCodec( items, config?, ): VariableSizeCodec< DrainOuterGeneric<{ [I in | string | number | symbol]: TItems[I] extends Encoder ? TFrom : never; }>, DrainOuterGeneric<{ [I in string | number | symbol]: TItems[I] extends Decoder ? TTo : never; }> & DrainOuterGeneric<{ [I in | string | number | symbol]: TItems[I] extends Encoder ? TFrom : never; }> >; ``` Returns a codec for encoding and decoding tuples. This codec serializes tuples by encoding and decoding each item sequentially. Unlike the [getArrayCodec](/api/functions/getArrayCodec) codec, each item in the tuple has its own codec and, therefore, can be of a different type. ### Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------- | ---------------------------------------------------------- | | `TItems` *extends* readonly [`Codec`](/api/type-aliases/Codec)\<`any`>\[] | An array of codecs, each corresponding to a tuple element. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------- | -------------------------------------- | | `items` | `TItems` | The codecs for each item in the tuple. | | `config?` | [`TupleCodecConfig`](/api/type-aliases/TupleCodecConfig) | - | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Encoder\ ? TFrom : never }>, `DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Decoder\ ? TTo : never }> & `DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Encoder\ ? TFrom : never }>> A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding tuples. ### Example Encoding and decoding a tuple with 2 items. ```ts const codec = getTupleCodec([fixCodecSize(getUtf8Codec(), 5), getU8Codec()]); const bytes = codec.encode(['Alice', 42]); // 0x416c6963652a // | └── Second item (42) // └── First item ("Alice") const tuple = codec.decode(bytes); // ['Alice', 42] ``` ### Remarks Separate [getTupleEncoder](/api/functions/getTupleEncoder) and [getTupleDecoder](/api/functions/getTupleDecoder) functions are available. ```ts const bytes = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()]) .encode(['Alice', 42]); const tuple = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()]) .decode(bytes); ``` ### See * [getTupleEncoder](/api/functions/getTupleEncoder) * [getTupleDecoder](/api/functions/getTupleDecoder) # getTupleDecoder (/api/functions/getTupleDecoder) ## Call Signature ```ts function getTupleDecoder( items, ): FixedSizeDecoder< DrainOuterGeneric<{ [I in string | number | symbol]: TItems[I] extends Decoder ? TTo : never; }> >; ``` Returns a decoder for tuples. This decoder deserializes a fixed-size array (tuple) by decoding its items sequentially using the provided item decoders. For more details, see [getTupleCodec](/api/functions/getTupleCodec). ### Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `TItems` *extends* readonly [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`any`>\[] | An array of decoders, each corresponding to a tuple element. | ### Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------------------------- | | `items` | `TItems` | The decoders for each item in the tuple. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Decoder\ ? TTo : never }>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding tuples. ### Example Decoding a tuple with 2 items. ```ts const decoder = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()]); const tuple = decoder.decode(new Uint8Array([ 0x41,0x6c,0x69,0x63,0x65,0x2a ])); // ['Alice', 42] ``` ### See [getTupleCodec](/api/functions/getTupleCodec) ## Call Signature ```ts function getTupleDecoder( items, ): VariableSizeDecoder< DrainOuterGeneric<{ [I in string | number | symbol]: TItems[I] extends Decoder ? TTo : never; }> >; ``` Returns a decoder for tuples. This decoder deserializes a fixed-size array (tuple) by decoding its items sequentially using the provided item decoders. For more details, see [getTupleCodec](/api/functions/getTupleCodec). ### Type Parameters | Type Parameter | Description | | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | | `TItems` *extends* readonly [`Decoder`](/api/type-aliases/Decoder)\<`any`>\[] | An array of decoders, each corresponding to a tuple element. | ### Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------------------------- | | `items` | `TItems` | The decoders for each item in the tuple. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Decoder\ ? TTo : never }>> A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding tuples. ### Example Decoding a tuple with 2 items. ```ts const decoder = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()]); const tuple = decoder.decode(new Uint8Array([ 0x41,0x6c,0x69,0x63,0x65,0x2a ])); // ['Alice', 42] ``` ### See [getTupleCodec](/api/functions/getTupleCodec) # getTupleEncoder (/api/functions/getTupleEncoder) ## Call Signature ```ts function getTupleEncoder( items, config?, ): FixedSizeEncoder< DrainOuterGeneric<{ [I in | string | number | symbol]: TItems[I] extends Encoder ? TFrom : never; }> >; ``` Returns an encoder for tuples. This encoder serializes a fixed-size array (tuple) by encoding its items sequentially using the provided item encoders. For more details, see [getTupleCodec](/api/functions/getTupleCodec). ### Type Parameters | Type Parameter | Description | | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `TItems` *extends* readonly [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`any`>\[] | An array of encoders, each corresponding to a tuple element. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------- | ------------------------------------------- | | `items` | `TItems` | The encoders for each item in the tuple. | | `config?` | [`TupleCodecConfig`](/api/type-aliases/TupleCodecConfig) | Optional configuration for the description. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Encoder\ ? TFrom : never }>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding tuples. ### Example Encoding a tuple with 2 items. ```ts const encoder = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()]); const bytes = encoder.encode(['Alice', 42]); // 0x416c6963652a // | └── Second item (42) // └── First item ("Alice") ``` ### See [getTupleCodec](/api/functions/getTupleCodec) ## Call Signature ```ts function getTupleEncoder( items, config?, ): VariableSizeEncoder< DrainOuterGeneric<{ [I in | string | number | symbol]: TItems[I] extends Encoder ? TFrom : never; }> >; ``` Returns an encoder for tuples. This encoder serializes a fixed-size array (tuple) by encoding its items sequentially using the provided item encoders. For more details, see [getTupleCodec](/api/functions/getTupleCodec). ### Type Parameters | Type Parameter | Description | | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | | `TItems` *extends* readonly [`Encoder`](/api/type-aliases/Encoder)\<`any`>\[] | An array of encoders, each corresponding to a tuple element. | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------- | ------------------------------------------- | | `items` | `TItems` | The encoders for each item in the tuple. | | `config?` | [`TupleCodecConfig`](/api/type-aliases/TupleCodecConfig) | Optional configuration for the description. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`DrainOuterGeneric`\<\{ \[I in string | number | symbol]: TItems\[I] extends Encoder\ ? TFrom : never }>> A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding tuples. ### Example Encoding a tuple with 2 items. ```ts const encoder = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()]); const bytes = encoder.encode(['Alice', 42]); // 0x416c6963652a // | └── Second item (42) // └── First item ("Alice") ``` ### See [getTupleCodec](/api/functions/getTupleCodec) # getU128Codec (/api/functions/getU128Codec) ```ts function getU128Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 128-bit unsigned integers (`u128`). This codec serializes `u128` values using 16 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `bigint`, `16`> A `FixedSizeCodec` for encoding and decoding `u128` values. ## Examples Encoding and decoding a `u128` value. ```ts const codec = getU128Codec(); const bytes = codec.encode(42); // 0x2a000000000000000000000000000000 const value = codec.decode(bytes); // 42n ``` Using big-endian encoding. ```ts const codec = getU128Codec({ endian: Endian.Big }); const bytes = codec.encode(42); // 0x0000000000000000000000000000002a ``` ## Remarks This codec supports values between `0` and `2^128 - 1`. Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`. * If you need a smaller unsigned integer, consider using [getU64Codec](/api/functions/getU64Codec) or [getU32Codec](/api/functions/getU32Codec). * If you need signed integers, consider using [getI128Codec](/api/functions/getI128Codec). Separate [getU128Encoder](/api/functions/getU128Encoder) and [getU128Decoder](/api/functions/getU128Decoder) functions are available. ```ts const bytes = getU128Encoder().encode(42); const value = getU128Decoder().decode(bytes); ``` ## See * [getU128Encoder](/api/functions/getU128Encoder) * [getU128Decoder](/api/functions/getU128Decoder) # getU128Decoder (/api/functions/getU128Decoder) ```ts function getU128Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 128-bit unsigned integers (`u128`). This decoder deserializes `u128` values from sixteen bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU128Codec](/api/functions/getU128Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns `FixedSizeDecoder`\<`bigint`, `16`> A `FixedSizeDecoder` for decoding `u128` values. ## Example Decoding a `u128` value. ```ts const decoder = getU128Decoder(); const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n ``` ## See [getU128Codec](/api/functions/getU128Codec) # getU128Encoder (/api/functions/getU128Encoder) ```ts function getU128Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 128-bit unsigned integers (`u128`). This encoder serializes `u128` values using sixteen bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU128Codec](/api/functions/getU128Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `16`> A `FixedSizeEncoder` for encoding `u128` values. ## Example Encoding a `u128` value. ```ts const encoder = getU128Encoder(); const bytes = encoder.encode(42n); // 0x2a000000000000000000000000000000 ``` ## See [getU128Codec](/api/functions/getU128Codec) # getU16Codec (/api/functions/getU16Codec) ```ts function getU16Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 16-bit unsigned integers (`u16`). This codec serializes `u16` values using two bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `number`, `2`> A `FixedSizeCodec` for encoding and decoding `u16` values. ## Examples Encoding and decoding a `u16` value. ```ts const codec = getU16Codec(); const bytes = codec.encode(42); // 0x2a00 (little-endian) const value = codec.decode(bytes); // 42 ``` Storing values in big-endian format. ```ts const codec = getU16Codec({ endian: Endian.Big }); const bytes = codec.encode(42); // 0x002a ``` ## Remarks This codec supports values between `0` and `2^16 - 1`. If you need a larger range, consider using [getU32Codec](/api/functions/getU32Codec) or [getU64Codec](/api/functions/getU64Codec). For signed integers, use [getI16Codec](/api/functions/getI16Codec). Separate [getU16Encoder](/api/functions/getU16Encoder) and [getU16Decoder](/api/functions/getU16Decoder) functions are available. ```ts const bytes = getU16Encoder().encode(42); const value = getU16Decoder().decode(bytes); ``` ## See * [getU16Encoder](/api/functions/getU16Encoder) * [getU16Decoder](/api/functions/getU16Decoder) # getU16Decoder (/api/functions/getU16Decoder) ```ts function getU16Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 16-bit unsigned integers (`u16`). This decoder deserializes `u16` values from two bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU16Codec](/api/functions/getU16Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns `FixedSizeDecoder`\<`number`, `2`> A `FixedSizeDecoder` for decoding `u16` values. ## Example Decoding a `u16` value. ```ts const decoder = getU16Decoder(); const value = decoder.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` ## See [getU16Codec](/api/functions/getU16Codec) # getU16Encoder (/api/functions/getU16Encoder) ```ts function getU16Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 16-bit unsigned integers (`u16`). This encoder serializes `u16` values using two bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU16Codec](/api/functions/getU16Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `2`> A `FixedSizeEncoder` for encoding `u16` values. ## Example Encoding a `u16` value. ```ts const encoder = getU16Encoder(); const bytes = encoder.encode(42); // 0x2a00 ``` ## See [getU16Codec](/api/functions/getU16Codec) # getU32Codec (/api/functions/getU32Codec) ```ts function getU32Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 32-bit unsigned integers (`u32`). This codec serializes `u32` values using four bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `number`, `4`> A `FixedSizeCodec` for encoding and decoding `u32` values. ## Examples Encoding and decoding a `u32` value. ```ts const codec = getU32Codec(); const bytes = codec.encode(42); // 0x2a000000 (little-endian) const value = codec.decode(bytes); // 42 ``` Storing values in big-endian format. ```ts const codec = getU32Codec({ endian: Endian.Big }); const bytes = codec.encode(42); // 0x0000002a ``` ## Remarks This codec only supports values between `0` and `2^32 - 1`. If you need a larger range, consider using [getU64Codec](/api/functions/getU64Codec) or [getU128Codec](/api/functions/getU128Codec). For signed integers, use [getI32Codec](/api/functions/getI32Codec). Separate [getU32Encoder](/api/functions/getU32Encoder) and [getU32Decoder](/api/functions/getU32Decoder) functions are available. ```ts const bytes = getU32Encoder().encode(42); const value = getU32Decoder().decode(bytes); ``` ## See * [getU32Encoder](/api/functions/getU32Encoder) * [getU32Decoder](/api/functions/getU32Decoder) # getU32Decoder (/api/functions/getU32Decoder) ```ts function getU32Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 32-bit unsigned integers (`u32`). This decoder deserializes `u32` values from four bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU32Codec](/api/functions/getU32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns `FixedSizeDecoder`\<`number`, `4`> A `FixedSizeDecoder` for decoding `u32` values. ## Example Decoding a `u32` value. ```ts const decoder = getU32Decoder(); const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42 ``` ## See [getU32Codec](/api/functions/getU32Codec) # getU32Encoder (/api/functions/getU32Encoder) ```ts function getU32Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 32-bit unsigned integers (`u32`). This encoder serializes `u32` values using four bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU32Codec](/api/functions/getU32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `4`> A `FixedSizeEncoder` for encoding `u32` values. ## Example Encoding a `u32` value. ```ts const encoder = getU32Encoder(); const bytes = encoder.encode(42); // 0x2a000000 ``` ## See [getU32Codec](/api/functions/getU32Codec) # getU64Codec (/api/functions/getU64Codec) ```ts function getU64Codec( config?, ): FixedSizeCodec; ``` Returns a codec for encoding and decoding 64-bit unsigned integers (`u64`). This codec serializes `u64` values using 8 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeCodec`\<`number` | `bigint`, `bigint`, `8`> A `FixedSizeCodec` for encoding and decoding `u64` values. ## Examples Encoding and decoding a `u64` value. ```ts const codec = getU64Codec(); const bytes = codec.encode(42); // 0x2a00000000000000 const value = codec.decode(bytes); // 42n ``` Using big-endian encoding. ```ts const codec = getU64Codec({ endian: Endian.Big }); const bytes = codec.encode(42); // 0x000000000000002a ``` ## Remarks This codec supports values between `0` and `2^64 - 1`. Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`. * If you need a smaller unsigned integer, consider using [getU32Codec](/api/functions/getU32Codec) or [getU16Codec](/api/functions/getU16Codec). * If you need a larger unsigned integer, consider using [getU128Codec](/api/functions/getU128Codec). * If you need signed integers, consider using [getI64Codec](/api/functions/getI64Codec). Separate [getU64Encoder](/api/functions/getU64Encoder) and [getU64Decoder](/api/functions/getU64Decoder) functions are available. ```ts const bytes = getU64Encoder().encode(42); const value = getU64Decoder().decode(bytes); ``` ## See * [getU64Encoder](/api/functions/getU64Encoder) * [getU64Decoder](/api/functions/getU64Decoder) # getU64Decoder (/api/functions/getU64Decoder) ```ts function getU64Decoder(config?): FixedSizeDecoder; ``` Returns a decoder for 64-bit unsigned integers (`u64`). This decoder deserializes `u64` values from 8 bytes. The decoded value is always a `bigint`. For more details, see [getU64Codec](/api/functions/getU64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeDecoder`\<`bigint`, `8`> A `FixedSizeDecoder` for decoding `u64` values. ## Example Decoding a `u64` value. ```ts const decoder = getU64Decoder(); const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n ``` ## See [getU64Codec](/api/functions/getU64Codec) # getU64Encoder (/api/functions/getU64Encoder) ```ts function getU64Encoder(config?): FixedSizeEncoder; ``` Returns an encoder for 64-bit unsigned integers (`u64`). This encoder serializes `u64` values using 8 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getU64Codec](/api/functions/getU64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `8`> A `FixedSizeEncoder` for encoding `u64` values. ## Example Encoding a `u64` value. ```ts const encoder = getU64Encoder(); const bytes = encoder.encode(42); // 0x2a00000000000000 ``` ## See [getU64Codec](/api/functions/getU64Codec) # getU8Codec (/api/functions/getU8Codec) ```ts function getU8Codec(): FixedSizeCodec; ``` Returns a codec for encoding and decoding 8-bit unsigned integers (`u8`). This codec serializes `u8` values using a single byte. ## Returns `FixedSizeCodec`\<`number` | `bigint`, `number`, `1`> A `FixedSizeCodec` for encoding and decoding `u8` values. ## Example Encoding and decoding a `u8` value. ```ts const codec = getU8Codec(); const bytes = codec.encode(255); // 0xff const value = codec.decode(bytes); // 255 ``` ## Remarks This codec supports values between `0` and `2^8 - 1` (0 to 255). If you need larger integers, consider using [getU16Codec](/api/functions/getU16Codec), [getU32Codec](/api/functions/getU32Codec), or [getU64Codec](/api/functions/getU64Codec). For signed integers, use [getI8Codec](/api/functions/getI8Codec). Separate [getU8Encoder](/api/functions/getU8Encoder) and [getU8Decoder](/api/functions/getU8Decoder) functions are available. ```ts const bytes = getU8Encoder().encode(42); const value = getU8Decoder().decode(bytes); ``` ## See * [getU8Encoder](/api/functions/getU8Encoder) * [getU8Decoder](/api/functions/getU8Decoder) # getU8Decoder (/api/functions/getU8Decoder) ```ts function getU8Decoder(): FixedSizeDecoder; ``` Returns a decoder for 8-bit unsigned integers (`u8`). This decoder deserializes `u8` values from a single byte. For more details, see [getU8Codec](/api/functions/getU8Codec). ## Returns `FixedSizeDecoder`\<`number`, `1`> A `FixedSizeDecoder` for decoding `u8` values. ## Example Decoding a `u8` value. ```ts const decoder = getU8Decoder(); const value = decoder.decode(new Uint8Array([0xff])); // 255 ``` ## See [getU8Codec](/api/functions/getU8Codec) # getU8Encoder (/api/functions/getU8Encoder) ```ts function getU8Encoder(): FixedSizeEncoder; ``` Returns an encoder for 8-bit unsigned integers (`u8`). This encoder serializes `u8` values using a single byte. For more details, see [getU8Codec](/api/functions/getU8Codec). ## Returns `FixedSizeEncoder`\<`number` | `bigint`, `1`> A `FixedSizeEncoder` for encoding `u8` values. ## Example Encoding a `u8` value. ```ts const encoder = getU8Encoder(); const bytes = encoder.encode(42); // 0x2a ``` ## See [getU8Codec](/api/functions/getU8Codec) # getUnionCodec (/api/functions/getUnionCodec) ```ts function getUnionCodec( variants, getIndexFromValue, getIndexFromBytes, ): GetUnionCodecType; ``` Returns a codec for encoding and decoding union types. This codec serializes and deserializes union values by selecting the correct variant based on the provided index functions. Unlike the [getDiscriminatedUnionCodec](/api/functions/getDiscriminatedUnionCodec), this codec does not assume a stored discriminator and must be used with an explicit mechanism for managing discriminators. ## Type Parameters | Type Parameter | Description | | ---------------------------------------------------------------------------- | ---------------------------------------------------------- | | `TVariants` *extends* readonly [`Codec`](/api/type-aliases/Codec)\<`any`>\[] | An array of codecs, each corresponding to a union variant. | ## Parameters | Parameter | Type | Description | | ------------------- | ------------------------------- | --------------------------------------------------------------------- | | `variants` | `TVariants` | The codecs for each variant of the union. | | `getIndexFromValue` | (`value`) => `number` | A function that determines the variant index from the provided value. | | `getIndexFromBytes` | (`bytes`, `offset`) => `number` | A function that determines the variant index from the byte array. | ## Returns `GetUnionCodecType`\<`TVariants`> A `Codec` for encoding and decoding union values. ## Example Encoding and decoding a union of numbers and booleans. ```ts const codec = getUnionCodec( [getU16Codec(), getBooleanCodec()], value => (typeof value === 'number' ? 0 : 1), (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1) ); const bytes1 = codec.encode(42); // 0x2a00 const value1: number | boolean = codec.decode(bytes1); // 42 const bytes2 = codec.encode(true); // 0x01 const value2: number | boolean = codec.decode(bytes2); // true ``` ## Remarks If you need a codec that includes a stored discriminator, consider using [getDiscriminatedUnionCodec](/api/functions/getDiscriminatedUnionCodec). Separate [getUnionEncoder](/api/functions/getUnionEncoder) and [getUnionDecoder](/api/functions/getUnionDecoder) functions are also available. ```ts const bytes = getUnionEncoder(variantEncoders, getIndexFromValue).encode(42); const value = getUnionDecoder(variantDecoders, getIndexFromBytes).decode(bytes); ``` ## See * [getUnionEncoder](/api/functions/getUnionEncoder) * [getUnionDecoder](/api/functions/getUnionDecoder) * [getDiscriminatedUnionCodec](/api/functions/getDiscriminatedUnionCodec) # getUnionDecoder (/api/functions/getUnionDecoder) ```ts function getUnionDecoder( variants, getIndexFromBytes, ): GetUnionDecoderType; ``` Returns a decoder for union types. This decoder deserializes values by selecting the correct variant decoder based on the `getIndexFromBytes` function. Unlike other codecs, this decoder does not assume a stored discriminator. It is the user's responsibility to manage discriminators separately. For more details, see [getUnionCodec](/api/functions/getUnionCodec). ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `TVariants` *extends* readonly [`Decoder`](/api/type-aliases/Decoder)\<`any`>\[] | An array of decoders, each corresponding to a union variant. | ## Parameters | Parameter | Type | Description | | ------------------- | ------------------------------- | ----------------------------------------------------------------- | | `variants` | `TVariants` | The decoders for each variant of the union. | | `getIndexFromBytes` | (`bytes`, `offset`) => `number` | A function that determines the variant index from the byte array. | ## Returns `GetUnionDecoderType`\<`TVariants`> A `Decoder` for decoding union values. ## Example Decoding a union of numbers and booleans. ```ts const decoder = getUnionDecoder( [getU16Decoder(), getBooleanDecoder()], (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1) ); decoder.decode(new Uint8Array([0x2a, 0x00])); // 42 decoder.decode(new Uint8Array([0x01])); // true // Type is inferred as `number | boolean` ``` ## See [getUnionCodec](/api/functions/getUnionCodec) # getUnionEncoder (/api/functions/getUnionEncoder) ```ts function getUnionEncoder( variants, getIndexFromValue, ): GetUnionEncoderType; ``` Returns an encoder for union types. This encoder serializes values by selecting the correct variant encoder based on the `getIndexFromValue` function. Unlike other codecs, this encoder does not store the variant index. It is the user's responsibility to manage discriminators separately. For more details, see [getUnionCodec](/api/functions/getUnionCodec). ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `TVariants` *extends* readonly [`Encoder`](/api/type-aliases/Encoder)\<`any`>\[] | An array of encoders, each corresponding to a union variant. | ## Parameters | Parameter | Type | Description | | ------------------- | --------------------- | --------------------------------------------------------------------- | | `variants` | `TVariants` | The encoders for each variant of the union. | | `getIndexFromValue` | (`value`) => `number` | A function that determines the variant index from the provided value. | ## Returns `GetUnionEncoderType`\<`TVariants`> An `Encoder` for encoding union values. ## Example Encoding a union of numbers and booleans. ```ts const encoder = getUnionEncoder( [getU16Encoder(), getBooleanEncoder()], value => (typeof value === 'number' ? 0 : 1) ); encoder.encode(42); // 0x2a00 // └── Encoded number (42) as `u16` encoder.encode(true); // 0x01 // └── Encoded boolean (`true`) as `u8` ``` ## See [getUnionCodec](/api/functions/getUnionCodec) # getUnitCodec (/api/functions/getUnitCodec) ```ts function getUnitCodec(): FixedSizeCodec; ``` Returns a codec for `void` values. This codec does nothing when encoding or decoding and has a fixed size of 0 bytes. Namely, it always returns `undefined` when decoding and produces an empty byte array when encoding. This can be useful when working with structures that require a no-op codec, such as empty variants in [getDiscriminatedUnionCodec](/api/functions/getDiscriminatedUnionCodec). ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`void`, `void`, `0`> A `FixedSizeCodec`, representing an empty codec. ## Examples Encoding and decoding a `void` value. ```ts const codec = getUnitCodec(); codec.encode(undefined); // Produces an empty byte array. codec.decode(new Uint8Array([])); // Returns `undefined`. ``` Using unit codecs as empty variants in a discriminated union. ```ts type Message = | { __kind: 'Enter' } | { __kind: 'Leave' } | { __kind: 'Move'; x: number; y: number }; const messageCodec = getDiscriminatedUnionCodec([ ['Enter', getUnitCodec()], // <- No-op codec for empty data ['Leave', getUnitCodec()], // <- No-op codec for empty data ['Move', getStructCodec([...])] ]); ``` ## Remarks Separate [getUnitEncoder](/api/functions/getUnitEncoder) and [getUnitDecoder](/api/functions/getUnitDecoder) functions are available. ```ts const bytes = getUnitEncoder().encode(); const value = getUnitDecoder().decode(bytes); ``` ## See * [getUnitEncoder](/api/functions/getUnitEncoder) * [getUnitDecoder](/api/functions/getUnitDecoder) # getUnitDecoder (/api/functions/getUnitDecoder) ```ts function getUnitDecoder(): FixedSizeDecoder; ``` Returns a decoder for `void` values. This decoder always returns `undefined` and has a fixed size of 0 bytes. It is useful when working with structures that require a no-op decoder, such as empty variants in [getDiscriminatedUnionDecoder](/api/functions/getDiscriminatedUnionDecoder). For more details, see [getUnitCodec](/api/functions/getUnitCodec). ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`void`, `0`> A `FixedSizeDecoder`, representing an empty decoder. ## Example Decoding a `void` value. ```ts getUnitDecoder().decode(anyBytes); // Returns `undefined`. ``` ## See [getUnitCodec](/api/functions/getUnitCodec) # getUnitEncoder (/api/functions/getUnitEncoder) ```ts function getUnitEncoder(): FixedSizeEncoder; ``` Returns an encoder for `void` values. This encoder writes nothing to the byte array and has a fixed size of 0 bytes. It is useful when working with structures that require a no-op encoder, such as empty variants in [getDiscriminatedUnionEncoder](/api/functions/getDiscriminatedUnionEncoder). For more details, see [getUnitCodec](/api/functions/getUnitCodec). ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`void`, `0`> A `FixedSizeEncoder`, representing an empty encoder. ## Example Encoding a `void` value. ```ts getUnitEncoder().encode(undefined); // Produces an empty byte array. ``` ## See [getUnitCodec](/api/functions/getUnitCodec) # getUtf8Codec (/api/functions/getUtf8Codec) ```ts function getUtf8Codec(): VariableSizeCodec; ``` Returns a codec for encoding and decoding UTF-8 strings. This codec serializes strings using UTF-8 encoding. The encoded output contains as many bytes as needed to represent the string. ## Returns `VariableSizeCodec`\<`string`> A `VariableSizeCodec` for encoding and decoding UTF-8 strings. ## Example Encoding and decoding a UTF-8 string. ```ts const codec = getUtf8Codec(); const bytes = codec.encode('hello'); // 0x68656c6c6f const value = codec.decode(bytes); // "hello" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size UTF-8 codec, consider using fixCodecSize. ```ts const codec = fixCodecSize(getUtf8Codec(), 5); ``` If you need a size-prefixed UTF-8 codec, consider using addCodecSizePrefix. ```ts const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); ``` Separate [getUtf8Encoder](/api/functions/getUtf8Encoder) and [getUtf8Decoder](/api/functions/getUtf8Decoder) functions are available. ```ts const bytes = getUtf8Encoder().encode('hello'); const value = getUtf8Decoder().decode(bytes); ``` ## See * [getUtf8Encoder](/api/functions/getUtf8Encoder) * [getUtf8Decoder](/api/functions/getUtf8Decoder) # getUtf8Decoder (/api/functions/getUtf8Decoder) ```ts function getUtf8Decoder(): VariableSizeDecoder; ``` Returns a decoder for UTF-8 strings. This decoder deserializes UTF-8 encoded strings from a byte array. It reads all available bytes starting from the given offset. For more details, see [getUtf8Codec](/api/functions/getUtf8Codec). ## Returns `VariableSizeDecoder`\<`string`> A `VariableSizeDecoder` for decoding UTF-8 strings. ## Example Decoding a UTF-8 string. ```ts const decoder = getUtf8Decoder(); const value = decoder.decode(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // "hello" ``` ## See [getUtf8Codec](/api/functions/getUtf8Codec) # getUtf8Encoder (/api/functions/getUtf8Encoder) ```ts function getUtf8Encoder(): VariableSizeEncoder; ``` Returns an encoder for UTF-8 strings. This encoder serializes strings using UTF-8 encoding. The encoded output contains as many bytes as needed to represent the string. For more details, see [getUtf8Codec](/api/functions/getUtf8Codec). ## Returns `VariableSizeEncoder`\<`string`> A `VariableSizeEncoder` for encoding UTF-8 strings. ## Example Encoding a UTF-8 string. ```ts const encoder = getUtf8Encoder(); const bytes = encoder.encode('hello'); // 0x68656c6c6f ``` ## See [getUtf8Codec](/api/functions/getUtf8Codec) # grindKeyPair (/api/functions/grindKeyPair) ```ts function grindKeyPair(config): Promise; ``` Generates a single Ed25519 key pair whose base58-encoded public key satisfies the provided `matches` criterion. This is the main entry point for mining vanity Solana addresses: the function keeps generating fresh key pairs in parallel batches until one of them matches. When `matches` is a [RegExp](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp), its literal characters (outside of escape sequences, character classes, quantifiers, and groups) are validated against the base58 alphabet up front. This catches common typos such as `/^ab0/` (`0` is not in the base58 alphabet) before any key is generated, preventing a guaranteed infinite loop. When `matches` is a function, it is used as-is with no validation β€” use this form when you need arbitrary matching logic that cannot be expressed as a regex. Be mindful that if the function can never return `true`, the grind loop will never terminate unless you supply an [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal). ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`GrindKeyPairsConfig`](/api/type-aliases/GrindKeyPairsConfig), `"amount"`> | See [GrindKeyPairsConfig](/api/type-aliases/GrindKeyPairsConfig). The `amount` field is omitted because this function always returns a single key pair. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`CryptoKeyPair`> A promise that resolves to a CryptoKeyPair whose base58-encoded public key satisfies the matcher. ## Throws [SOLANA\_ERROR\_\_KEYS\_\_INVALID\_BASE58\_IN\_GRIND\_REGEX](/api/variables/SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX) when the provided regex contains a literal character that is not in the base58 alphabet. ## Throws The `AbortSignal`'s reason when the supplied `abortSignal` is fired (either before the function is called or during the grind loop). ## Examples Mine a vanity address that starts with `anza`: ```ts import { grindKeyPair } from '@solana/keys'; const keyPair = await grindKeyPair({ matches: /^anza/ }); ``` Use the `i` flag for case-insensitive matching: ```ts import { grindKeyPair } from '@solana/keys'; const keyPair = await grindKeyPair({ matches: /^anza/i }); ``` Use a predicate function for arbitrary matching logic: ```ts import { grindKeyPair } from '@solana/keys'; const keyPair = await grindKeyPair({ matches: address => address.startsWith('anza') && address.length === 44, }); ``` Cap the grind at 60 seconds using [`AbortSignal.timeout()`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static): ```ts import { grindKeyPair } from '@solana/keys'; const keyPair = await grindKeyPair({ matches: /^anza/, abortSignal: AbortSignal.timeout(60_000), }); ``` Generate an extractable key pair so you can persist its private key bytes: ```ts import { grindKeyPair } from '@solana/keys'; const keyPair = await grindKeyPair({ matches: /^anza/, extractable: true }); const privateKeyBytes = new Uint8Array( await crypto.subtle.exportKey('pkcs8', keyPair.privateKey), ); ``` ## See * [grindKeyPairs](/api/functions/grindKeyPairs) * [GrindKeyPairsConfig](/api/type-aliases/GrindKeyPairsConfig) * [GrindKeyPairMatches](/api/type-aliases/GrindKeyPairMatches) * [generateKeyPair](/api/functions/generateKeyPair) # grindKeyPairSigner (/api/functions/grindKeyPairSigner) ```ts function grindKeyPairSigner(config): Promise; ``` Generates a single [KeyPairSigner](/api/type-aliases/KeyPairSigner) whose address satisfies the provided `matches` criterion. This is the main entry point for mining vanity signers: the function keeps generating fresh key pairs in parallel batches until one of them matches, and then wraps the result in a [KeyPairSigner](/api/type-aliases/KeyPairSigner). When `matches` is a [RegExp](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp), its literal characters (outside of escape sequences, character classes, quantifiers, and groups) are validated against the base58 alphabet up front. This catches common typos such as `/^ab0/` (`0` is not in the base58 alphabet) before any key is generated, preventing a guaranteed infinite loop. When `matches` is a function, it is used as-is with no validation β€” use this form when you need arbitrary matching logic that cannot be expressed as a regex. Be mindful that if the function can never return `true`, the grind loop will never terminate unless you supply an [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal). ## Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `config` | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`GrindKeyPairsConfig`, `"amount"`> | See GrindKeyPairsConfig. The `amount` field is omitted because this function always returns a single signer. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`KeyPairSigner`](/api/type-aliases/KeyPairSigner)> A promise that resolves to a [KeyPairSigner](/api/type-aliases/KeyPairSigner) whose base58-encoded address satisfies the matcher. ## Throws SOLANA\_ERROR\_\_KEYS\_\_INVALID\_BASE58\_IN\_GRIND\_REGEX when the provided regex contains a literal character that is not in the base58 alphabet. ## Throws The `AbortSignal`'s reason when the supplied `abortSignal` is fired (either before the function is called or during the grind loop). ## Examples Mine a vanity signer whose address starts with `anza`: ```ts import { grindKeyPairSigner } from '@solana/signers'; const signer = await grindKeyPairSigner({ matches: /^anza/ }); ``` Use the `i` flag for case-insensitive matching: ```ts import { grindKeyPairSigner } from '@solana/signers'; const signer = await grindKeyPairSigner({ matches: /^anza/i }); ``` Use a predicate function for arbitrary matching logic: ```ts import { grindKeyPairSigner } from '@solana/signers'; const signer = await grindKeyPairSigner({ matches: address => address.startsWith('anza') && address.length === 44, }); ``` Cap the grind at 60 seconds using [`AbortSignal.timeout()`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static): ```ts import { grindKeyPairSigner } from '@solana/signers'; const signer = await grindKeyPairSigner({ matches: /^anza/, abortSignal: AbortSignal.timeout(60_000), }); ``` ## See * [grindKeyPairSigners](/api/functions/grindKeyPairSigners) * GrindKeyPairsConfig # grindKeyPairSigners (/api/functions/grindKeyPairSigners) ```ts function grindKeyPairSigners(config): Promise; ``` Generates multiple [KeyPairSigners](/api/type-aliases/KeyPairSigner) whose addresses satisfy the provided `matches` criterion. Internally, this calls grindKeyPairs from `@solana/keys` and wraps each resulting CryptoKeyPair in a [KeyPairSigner](/api/type-aliases/KeyPairSigner). ## Parameters | Parameter | Type | Description | | --------- | --------------------- | ------------------------ | | `config` | `GrindKeyPairsConfig` | See GrindKeyPairsConfig. | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`KeyPairSigner`](/api/type-aliases/KeyPairSigner)\[]> ## Example Find four signers whose address starts with `anza`: ```ts import { grindKeyPairSigners } from '@solana/signers'; const signers = await grindKeyPairSigners({ matches: /^anza/, amount: 4 }); ``` ## See * [grindKeyPairSigner](/api/functions/grindKeyPairSigner) * grindKeyPairs # grindKeyPairs (/api/functions/grindKeyPairs) ```ts function grindKeyPairs(config): Promise; ``` Generates multiple Ed25519 key pairs whose base58-encoded public key satisfies the provided `matches` criterion. Key pairs are generated in batches of `concurrency` in parallel and tested against the matcher. The loop continues until `amount` matching key pairs have been found or the provided `abortSignal` is aborted. When `matches` is a [RegExp](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp), its literal characters are validated against the base58 alphabet up front to prevent infinite loops caused by typos (e.g. `/^anza0/`). When `matches` is a function, it is used as-is with no validation. ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------- | ----------------------------------------------------------------- | | `config` | [`GrindKeyPairsConfig`](/api/type-aliases/GrindKeyPairsConfig) | See [GrindKeyPairsConfig](/api/type-aliases/GrindKeyPairsConfig). | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`CryptoKeyPair`\[]> A promise that resolves to an array of exactly `amount` CryptoKeyPair instances, each of which satisfies the matcher. When `amount <= 0`, the promise resolves to an empty array. ## Examples Find four key pairs whose address starts with `anza`: ```ts import { grindKeyPairs } from '@solana/keys'; const keyPairs = await grindKeyPairs({ matches: /^anza/, amount: 4 }); ``` Use a predicate function for arbitrary matching logic: ```ts import { grindKeyPairs } from '@solana/keys'; const keyPairs = await grindKeyPairs({ matches: address => address.startsWith('anza') && address.endsWith('end'), amount: 2, }); ``` Cancel a long-running grind using an [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal): ```ts import { grindKeyPairs } from '@solana/keys'; const keyPairs = await grindKeyPairs({ matches: /^anza/, amount: 10, abortSignal: AbortSignal.timeout(60_000), }); ``` ## See [grindKeyPair](/api/functions/grindKeyPair) # gtBinaryFixedPoint (/api/functions/gtBinaryFixedPoint) ```ts function gtBinaryFixedPoint(a, b): boolean; ``` Returns `true` when `a` is strictly greater than `b`. See [cmpBinaryFixedPoint](/api/functions/cmpBinaryFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TFractionalBits`> | | `b` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TFractionalBits`>> | ## Returns `boolean` # gtDecimalFixedPoint (/api/functions/gtDecimalFixedPoint) ```ts function gtDecimalFixedPoint(a, b): boolean; ``` Returns `true` when `a` is strictly greater than `b`. See [cmpDecimalFixedPoint](/api/functions/cmpDecimalFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------ | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TDecimals`> | | `b` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TDecimals`>> | ## Returns `boolean` # gteBinaryFixedPoint (/api/functions/gteBinaryFixedPoint) ```ts function gteBinaryFixedPoint(a, b): boolean; ``` Returns `true` when `a` is greater than or equal to `b`. See [cmpBinaryFixedPoint](/api/functions/cmpBinaryFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TFractionalBits`> | | `b` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TFractionalBits`>> | ## Returns `boolean` # gteDecimalFixedPoint (/api/functions/gteDecimalFixedPoint) ```ts function gteDecimalFixedPoint(a, b): boolean; ``` Returns `true` when `a` is greater than or equal to `b`. See [cmpDecimalFixedPoint](/api/functions/cmpDecimalFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------ | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TDecimals`> | | `b` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TDecimals`>> | ## Returns `boolean` # install (/api/functions/install) ```ts function install(): void; ``` Polyfills methods on `globalThis.SubtleCrypto` to add support for the Ed25519 algorithm. ## Returns `void` ## Example ```ts 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'); } ``` # isAbortError (/api/functions/isAbortError) ```ts function isAbortError(err): err is Error; ``` Returns `true` if the given value is an `Error` whose `name` is `'AbortError'`. When an [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal) fires without a custom `reason`, or when APIs like `fetch` are aborted, they reject with a `DOMException` (or similar `Error` subclass) whose `name` is `'AbortError'`. This helper lets callers distinguish abort rejections from other failures without having to `instanceof`-check every platform-specific error class. ## Parameters | Parameter | Type | | --------- | --------- | | `err` | `unknown` | ## Returns `err is Error` ## Example ```ts try { await getAbortablePromise(doWork(), signal); } catch (e) { if (isAbortError(e)) { // The operation was aborted; don't surface as an error. return; } throw e; } ``` ## See [getAbortablePromise](/api/functions/getAbortablePromise) # isAddress (/api/functions/isAddress) ```ts function isAddress(putativeAddress): putativeAddress is Address; ``` A type guard that returns `true` if the input string conforms to the [Address](/api/type-aliases/Address) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | ----------------- | -------- | | `putativeAddress` | `string` | ## Returns `putativeAddress is Address` ## Example ```ts import { isAddress } from '@solana/addresses'; if (isAddress(ownerAddress)) { // At this point, `ownerAddress` has been refined to a // `Address` that can be used with the RPC. const { value: lamports } = await rpc.getBalance(ownerAddress).send(); setBalanceLamports(lamports); } else { setError(`${ownerAddress} is not an address`); } ``` # isAdvanceNonceAccountInstruction (/api/functions/isAdvanceNonceAccountInstruction) ```ts function isAdvanceNonceAccountInstruction( instruction, ): instruction is AdvanceNonceAccountInstruction; ``` A type guard that returns `true` if the instruction conforms to the AdvanceNonceAccountInstruction type, and refines its type for use in your program. ## Parameters | Parameter | Type | | ------------- | ------------- | | `instruction` | `Instruction` | ## Returns `instruction is AdvanceNonceAccountInstruction` ## Example ```ts import { isAdvanceNonceAccountInstruction } from '@solana/transaction-messages'; if (isAdvanceNonceAccountInstruction(message.instructions[0])) { // At this point, the first instruction in the message has been refined to a // `AdvanceNonceAccountInstruction`. setNonceAccountAddress(message.instructions[0].accounts[0].address); } else { setError('The first instruction is not an `AdvanceNonce` instruction'); } ``` # isBinaryFixedPoint (/api/functions/isBinaryFixedPoint) ```ts function isBinaryFixedPoint( value, signedness?, totalBits?, fractionalBits?, ): value is BinaryFixedPoint; ``` Type guard that refines an unknown value to a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint). Accepts the same partial-positional shape arguments as [assertIsBinaryFixedPoint](/api/functions/assertIsBinaryFixedPoint) and returns `true` if the assertion would pass, `false` otherwise. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------- | -------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | `number` | | `TFractionalBits` *extends* `number` | `number` | ## Parameters | Parameter | Type | | ----------------- | ----------------- | | `value` | `unknown` | | `signedness?` | `TSignedness` | | `totalBits?` | `TTotalBits` | | `fractionalBits?` | `TFractionalBits` | ## Returns `value is BinaryFixedPoint` ## Example ```ts if (isBinaryFixedPoint(value)) { value satisfies BinaryFixedPoint; } if (isBinaryFixedPoint(value, 'signed', 16, 15)) { value satisfies BinaryFixedPoint<'signed', 16, 15>; } ``` ## See * [assertIsBinaryFixedPoint](/api/functions/assertIsBinaryFixedPoint) * [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) # isBlockhash (/api/functions/isBlockhash) ```ts function isBlockhash(putativeBlockhash): putativeBlockhash is Blockhash; ``` A type guard that returns `true` if the input string conforms to the [Blockhash](/api/type-aliases/Blockhash) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | ------------------- | -------- | | `putativeBlockhash` | `string` | ## Returns `putativeBlockhash is Blockhash` ## Example ```ts import { isBlockhash } from '@solana/rpc-types'; if (isBlockhash(blockhash)) { // At this point, `blockhash` has been refined to a // `Blockhash` that can be used with the RPC. const { value: isValid } = await rpc.isBlockhashValid(blockhash).send(); setBlockhashIsFresh(isValid); } else { setError(`${blockhash} is not a blockhash`); } ``` # isCanceledSingleTransactionPlanResult (/api/functions/isCanceledSingleTransactionPlanResult) ```ts function isCanceledSingleTransactionPlanResult< TContext, TTransactionMessage, >( plan, ): plan is CanceledSingleTransactionPlanResult< TContext, TTransactionMessage >; ``` Checks if the given transaction plan result is a canceled [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result to check. | ## Returns `plan is CanceledSingleTransactionPlanResult` `true` if the result is a canceled single transaction plan result, `false` otherwise. ## Example ```ts const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message); if (isCanceledSingleTransactionPlanResult(result)) { console.log('Transaction was canceled'); // TypeScript knows this is a canceled result. } ``` ## See * [CanceledSingleTransactionPlanResult](/api/type-aliases/CanceledSingleTransactionPlanResult) * [assertIsCanceledSingleTransactionPlanResult](/api/functions/assertIsCanceledSingleTransactionPlanResult) # isDecimalFixedPoint (/api/functions/isDecimalFixedPoint) ```ts function isDecimalFixedPoint( value, signedness?, totalBits?, decimals?, ): value is DecimalFixedPoint; ``` Type guard that refines an unknown value to a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint). Accepts the same partial-positional shape arguments as [assertIsDecimalFixedPoint](/api/functions/assertIsDecimalFixedPoint) and returns `true` if the assertion would pass, `false` otherwise. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------- | -------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | `number` | | `TDecimals` *extends* `number` | `number` | ## Parameters | Parameter | Type | | ------------- | ------------- | | `value` | `unknown` | | `signedness?` | `TSignedness` | | `totalBits?` | `TTotalBits` | | `decimals?` | `TDecimals` | ## Returns `value is DecimalFixedPoint` ## Example ```ts if (isDecimalFixedPoint(value)) { value satisfies DecimalFixedPoint; } if (isDecimalFixedPoint(value, 'unsigned', 64, 6)) { value satisfies DecimalFixedPoint<'unsigned', 64, 6>; } ``` ## See * [assertIsDecimalFixedPoint](/api/functions/assertIsDecimalFixedPoint) * [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) # isFailedSingleTransactionPlanResult (/api/functions/isFailedSingleTransactionPlanResult) ```ts function isFailedSingleTransactionPlanResult< TContext, TTransactionMessage, >( plan, ): plan is FailedSingleTransactionPlanResult< TContext, TTransactionMessage >; ``` Checks if the given transaction plan result is a failed [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result to check. | ## Returns `plan is FailedSingleTransactionPlanResult` `true` if the result is a failed single transaction plan result, `false` otherwise. ## Example ```ts const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error); if (isFailedSingleTransactionPlanResult(result)) { console.log(result.error); // TypeScript knows this is a failed result. } ``` ## See * [FailedSingleTransactionPlanResult](/api/type-aliases/FailedSingleTransactionPlanResult) * [assertIsFailedSingleTransactionPlanResult](/api/functions/assertIsFailedSingleTransactionPlanResult) # isFixedSize (/api/functions/isFixedSize) ## Call Signature ```ts function isFixedSize( encoder, ): encoder is FixedSizeEncoder; ``` Determines whether the given codec, encoder, or decoder is fixed-size. A fixed-size object is identified by the presence of a `fixedSize` property. If this property exists, the object is considered a [FixedSizeCodec](/api/interfaces/FixedSizeCodec), [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder), or [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder). Otherwise, it is assumed to be a [VariableSizeCodec](/api/interfaces/VariableSizeCodec), [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder), or [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). ### Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `encoder` | \| [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`> \| [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TFrom`> | ### Returns `encoder is FixedSizeEncoder` `true` if the object is fixed-size, `false` otherwise. ### Examples Checking a fixed-size encoder. ```ts const encoder = getU32Encoder(); isFixedSize(encoder); // true ``` Checking a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); isFixedSize(encoder); // false ``` ### Remarks This function is commonly used to distinguish between fixed-size and variable-size objects at runtime. If you need to enforce this distinction with type assertions, consider using [assertIsFixedSize](/api/functions/assertIsFixedSize). ### See [assertIsFixedSize](/api/functions/assertIsFixedSize) ## Call Signature ```ts function isFixedSize( decoder, ): decoder is FixedSizeDecoder; ``` Determines whether the given codec, encoder, or decoder is fixed-size. A fixed-size object is identified by the presence of a `fixedSize` property. If this property exists, the object is considered a [FixedSizeCodec](/api/interfaces/FixedSizeCodec), [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder), or [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder). Otherwise, it is assumed to be a [VariableSizeCodec](/api/interfaces/VariableSizeCodec), [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder), or [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). ### Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ### Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `decoder` | \| [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `TSize`> \| [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TTo`> | ### Returns `decoder is FixedSizeDecoder` `true` if the object is fixed-size, `false` otherwise. ### Examples Checking a fixed-size encoder. ```ts const encoder = getU32Encoder(); isFixedSize(encoder); // true ``` Checking a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); isFixedSize(encoder); // false ``` ### Remarks This function is commonly used to distinguish between fixed-size and variable-size objects at runtime. If you need to enforce this distinction with type assertions, consider using [assertIsFixedSize](/api/functions/assertIsFixedSize). ### See [assertIsFixedSize](/api/functions/assertIsFixedSize) ## Call Signature ```ts function isFixedSize( codec, ): codec is FixedSizeCodec; ``` Determines whether the given codec, encoder, or decoder is fixed-size. A fixed-size object is identified by the presence of a `fixedSize` property. If this property exists, the object is considered a [FixedSizeCodec](/api/interfaces/FixedSizeCodec), [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder), or [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder). Otherwise, it is assumed to be a [VariableSizeCodec](/api/interfaces/VariableSizeCodec), [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder), or [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). ### Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `codec` | \| [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`> \| [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TFrom`, `TTo`> | ### Returns `codec is FixedSizeCodec` `true` if the object is fixed-size, `false` otherwise. ### Examples Checking a fixed-size encoder. ```ts const encoder = getU32Encoder(); isFixedSize(encoder); // true ``` Checking a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); isFixedSize(encoder); // false ``` ### Remarks This function is commonly used to distinguish between fixed-size and variable-size objects at runtime. If you need to enforce this distinction with type assertions, consider using [assertIsFixedSize](/api/functions/assertIsFixedSize). ### See [assertIsFixedSize](/api/functions/assertIsFixedSize) ## Call Signature ```ts function isFixedSize(codec): codec is { fixedSize: TSize }; ``` Determines whether the given codec, encoder, or decoder is fixed-size. A fixed-size object is identified by the presence of a `fixedSize` property. If this property exists, the object is considered a [FixedSizeCodec](/api/interfaces/FixedSizeCodec), [FixedSizeEncoder](/api/interfaces/FixedSizeEncoder), or [FixedSizeDecoder](/api/interfaces/FixedSizeDecoder). Otherwise, it is assumed to be a [VariableSizeCodec](/api/interfaces/VariableSizeCodec), [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder), or [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). ### Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------- | | `codec` | \| \{ `fixedSize`: `TSize`; } \| \{ `maxSize?`: `number`; } | ### Returns `codec is { fixedSize: TSize }` `true` if the object is fixed-size, `false` otherwise. ### Examples Checking a fixed-size encoder. ```ts const encoder = getU32Encoder(); isFixedSize(encoder); // true ``` Checking a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); isFixedSize(encoder); // false ``` ### Remarks This function is commonly used to distinguish between fixed-size and variable-size objects at runtime. If you need to enforce this distinction with type assertions, consider using [assertIsFixedSize](/api/functions/assertIsFixedSize). ### See [assertIsFixedSize](/api/functions/assertIsFixedSize) # isFullySignedOffchainMessageEnvelope (/api/functions/isFullySignedOffchainMessageEnvelope) ```ts function isFullySignedOffchainMessageEnvelope( offchainMessage, ): offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope; ``` A type guard that returns `true` if the input [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope) is fully signed, and refines its type for use in your program, adding the [FullySignedOffchainMessageEnvelope](/api/type-aliases/FullySignedOffchainMessageEnvelope) type. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------ | | `TEnvelope` *extends* [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope) | ## Parameters | Parameter | Type | | ----------------- | ----------- | | `offchainMessage` | `TEnvelope` | ## Returns `offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope` ## Example ```ts import { isFullySignedOffchainMessageEnvelope } from '@solana/offchain-messages'; const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes); if (isFullySignedOffchainMessageEnvelope(offchainMessageEnvelope)) { // At this point we know that the offchain message is fully signed. } ``` # isFullySignedTransaction (/api/functions/isFullySignedTransaction) ```ts function isFullySignedTransaction( transaction, ): transaction is FullySignedTransaction & TTransaction; ``` Checks whether a given [Transaction](/api/type-aliases/Transaction) is fully signed. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TTransaction` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> | ## Parameters | Parameter | Type | | ------------- | -------------- | | `transaction` | `TTransaction` | ## Returns `transaction is FullySignedTransaction & TTransaction` ## Example ```ts import { isFullySignedTransaction } from '@solana/transactions'; const transaction = getTransactionDecoder().decode(transactionBytes); if (isFullySignedTransaction(transaction)) { // At this point we know that the transaction is signed and can be sent to the network. } ``` # isInstructionForProgram (/api/functions/isInstructionForProgram) ```ts function isInstructionForProgram( instruction, programAddress, ): instruction is TInstruction & { programAddress: Address; }; ``` ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TProgramAddress` *extends* `string` | | `TInstruction` *extends* [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | ## Parameters | Parameter | Type | | ---------------- | ---------------------------------------------------------- | | `instruction` | `TInstruction` | | `programAddress` | [`Address`](/api/type-aliases/Address)\<`TProgramAddress`> | ## Returns `instruction is TInstruction & { programAddress: Address }` # isInstructionPlan (/api/functions/isInstructionPlan) ```ts function isInstructionPlan(value): value is InstructionPlan; ``` Checks if the given value is an [InstructionPlan](/api/type-aliases/InstructionPlan). This type guard checks the `planType` property to determine if the value is an instruction plan. This is useful when you have a value that could be an [InstructionPlan](/api/type-aliases/InstructionPlan), [TransactionPlan](/api/type-aliases/TransactionPlan), or [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) and need to narrow the type. ## Parameters | Parameter | Type | Description | | --------- | --------- | ------------------- | | `value` | `unknown` | The value to check. | ## Returns `value is InstructionPlan` `true` if the value is an instruction plan, `false` otherwise. ## Example ```ts function processItem(item: InstructionPlan | TransactionPlan | TransactionPlanResult) { if (isInstructionPlan(item)) { // item is narrowed to InstructionPlan console.log(item.kind); } } ``` ## See * [InstructionPlan](/api/type-aliases/InstructionPlan) * [isTransactionPlan](/api/functions/isTransactionPlan) * [isTransactionPlanResult](/api/functions/isTransactionPlanResult) # isInstructionWithAccounts (/api/functions/isInstructionWithAccounts) ```ts function isInstructionWithAccounts( instruction, ): instruction is InstructionWithAccounts & TInstruction; ``` ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TAccounts` *extends* readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[] | readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[] | | `TInstruction` *extends* [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | ## Parameters | Parameter | Type | | ------------- | -------------- | | `instruction` | `TInstruction` | ## Returns `instruction is InstructionWithAccounts & TInstruction` # isInstructionWithData (/api/functions/isInstructionWithData) ```ts function isInstructionWithData( instruction, ): instruction is InstructionWithData & TInstruction; ``` ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TData` *extends* [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> | | `TInstruction` *extends* [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> | ## Parameters | Parameter | Type | | ------------- | -------------- | | `instruction` | `TInstruction` | ## Returns `instruction is InstructionWithData & TInstruction` # isJsonRpcPayload (/api/functions/isJsonRpcPayload) ```ts function isJsonRpcPayload( payload, ): payload is Readonly<{ jsonrpc: '2.0'; method: string; params: unknown; }>; ``` Returns `true` if the given payload is a JSON RPC v2 payload. This means, the payload is an object such that: * It has a `jsonrpc` property with a value of `'2.0'`. * It has a `method` property that is a string. * It has a `params` property of any type. ## Parameters | Parameter | Type | | --------- | --------- | | `payload` | `unknown` | ## Returns `payload is Readonly<{ jsonrpc: "2.0"; method: string; params: unknown }>` ## Example ```ts import { isJsonRpcPayload } from '@solana/rpc-spec'; if (isJsonRpcPayload(payload)) { const payloadMethod: string = payload.method; const payloadParams: unknown = payload.params; } ``` # isKeyPairSigner (/api/functions/isKeyPairSigner) ```ts function isKeyPairSigner( value, ): value is Readonly<{ address: Address; signMessages: any; }> & Readonly<{ address: Address; signTransactions: any }> & { keyPair: CryptoKeyPair; } & TValue; ``` Checks whether the provided value implements the [KeyPairSigner](/api/type-aliases/KeyPairSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `value is Readonly<{ address: Address; signMessages: any }> & Readonly<{ address: Address; signTransactions: any }> & { keyPair: CryptoKeyPair } & TValue` ## Example ```ts import { generateKeyPairSigner, isKeyPairSigner } from '@solana/signers'; const signer = await generateKeyPairSigner(); isKeyPairSigner(signer); // true isKeyPairSigner({ address: address('1234..5678') }); // false ``` # isLamports (/api/functions/isLamports) ```ts function isLamports(putativeLamports): putativeLamports is Lamports; ``` This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer conforms to the [Lamports](/api/type-aliases/Lamports) type and will refine the type for use in your program. ## Parameters | Parameter | Type | | ------------------ | -------- | | `putativeLamports` | `bigint` | ## Returns `putativeLamports is Lamports` ## Example ```ts import { isLamports } from '@solana/rpc-types'; if (isLamports(lamports)) { // At this point, `lamports` has been refined to a // `Lamports` that can be used anywhere Lamports are expected. await transfer(fromAddress, toAddress, lamports); } else { setError(`${lamports} is not a quantity of Lamports`); } ``` # isMessageModifyingSigner (/api/functions/isMessageModifyingSigner) ```ts function isMessageModifyingSigner( value, ): value is Readonly<{ address: Address; modifyAndSignMessages: any; }> & TValue; ``` Checks whether the provided value implements the [MessageModifyingSigner](/api/type-aliases/MessageModifyingSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `value is Readonly<{ address: Address; modifyAndSignMessages: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { isMessageModifyingSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; isMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // true isMessageModifyingSigner({ address }); // false ``` ## See [assertIsMessageModifyingSigner](/api/functions/assertIsMessageModifyingSigner) # isMessagePackerInstructionPlan (/api/functions/isMessagePackerInstructionPlan) ```ts function isMessagePackerInstructionPlan( plan, ): plan is Readonly<{ getMessagePacker: () => MessagePacker; kind: 'messagePacker'; planType: 'instructionPlan'; }>; ``` Checks if the given instruction plan is a [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------ | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to check. | ## Returns `plan is Readonly<{ getMessagePacker: () => MessagePacker; kind: "messagePacker"; planType: "instructionPlan" }>` `true` if the plan is a message packer instruction plan, `false` otherwise. ## Example ```ts const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... */ }); if (isMessagePackerInstructionPlan(plan)) { const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan. } ``` ## See * [MessagePackerInstructionPlan](/api/type-aliases/MessagePackerInstructionPlan) * [assertIsMessagePackerInstructionPlan](/api/functions/assertIsMessagePackerInstructionPlan) # isMessagePartialSigner (/api/functions/isMessagePartialSigner) ```ts function isMessagePartialSigner( value, ): value is Readonly<{ address: Address; signMessages: any; }> & TValue; ``` Checks whether the provided value implements the [MessagePartialSigner](/api/type-aliases/MessagePartialSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `value is Readonly<{ address: Address; signMessages: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { isMessagePartialSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; isMessagePartialSigner({ address, signMessages: async () => {} }); // true isMessagePartialSigner({ address }); // false ``` ## See [assertIsMessagePartialSigner](/api/functions/assertIsMessagePartialSigner) # isMessageSigner (/api/functions/isMessageSigner) ```ts function isMessageSigner( value, ): value is MessageSigner & TValue; ``` Checks whether the provided value implements the [MessageSigner](/api/type-aliases/MessageSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `value is MessageSigner & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { isMessageSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; isMessageSigner({ address, signMessages: async () => {} }); // true isMessageSigner({ address, modifyAndSignMessages: async () => {} }); // true isMessageSigner({ address }); // false ``` ## See [assertIsMessageSigner](/api/functions/assertIsMessageSigner) # isNonDivisibleSequentialInstructionPlan (/api/functions/isNonDivisibleSequentialInstructionPlan) ```ts function isNonDivisibleSequentialInstructionPlan( plan, ): plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: InstructionPlan[]; planType: 'instructionPlan'; }> & { divisible: false }; ``` Checks if the given instruction plan is a non-divisible [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan). A non-divisible sequential plan requires all its instructions to be executed atomically β€” either in a single transaction or in a transaction bundle. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------ | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to check. | ## Returns `plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: InstructionPlan[]; planType: "instructionPlan" }> & { divisible: false }` `true` if the plan is a non-divisible sequential instruction plan, `false` otherwise. ## Example ```ts const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]); if (isNonDivisibleSequentialInstructionPlan(plan)) { // All instructions must be executed atomically. } ``` ## See * [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) * [assertIsNonDivisibleSequentialInstructionPlan](/api/functions/assertIsNonDivisibleSequentialInstructionPlan) # isNonDivisibleSequentialTransactionPlan (/api/functions/isNonDivisibleSequentialTransactionPlan) ```ts function isNonDivisibleSequentialTransactionPlan( plan, ): plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlan[]; planType: 'transactionPlan'; }> & { divisible: false }; ``` Checks if the given transaction plan is a non-divisible [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan). A non-divisible sequential plan requires all its transaction messages to be executed atomically β€” usually in a transaction bundle. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------ | | `plan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to check. | ## Returns `plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlan[]; planType: "transactionPlan" }> & { divisible: false }` `true` if the plan is a non-divisible sequential transaction plan, `false` otherwise. ## Example ```ts const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]); if (isNonDivisibleSequentialTransactionPlan(plan)) { // All transaction messages must be executed atomically. } ``` ## See * [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) * [assertIsNonDivisibleSequentialTransactionPlan](/api/functions/assertIsNonDivisibleSequentialTransactionPlan) # isNonDivisibleSequentialTransactionPlanResult (/api/functions/isNonDivisibleSequentialTransactionPlanResult) ```ts function isNonDivisibleSequentialTransactionPlanResult< TContext, TTransactionMessage, TSingle, >( plan, ): plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlanResult< TContext, TTransactionMessage, TSingle >[]; planType: 'transactionPlanResult'; }> & { divisible: false }; ``` Checks if the given transaction plan result is a non-divisible [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult). A non-divisible sequential result indicates that the transactions were executed atomically β€” usually in a transaction bundle. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result to check. | ## Returns `plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlanResult[]; planType: "transactionPlanResult" }> & { divisible: false }` `true` if the result is a non-divisible sequential transaction plan result, `false` otherwise. ## Example ```ts const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]); if (isNonDivisibleSequentialTransactionPlanResult(result)) { // Transactions were executed atomically. } ``` ## See * [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) * [assertIsNonDivisibleSequentialTransactionPlanResult](/api/functions/assertIsNonDivisibleSequentialTransactionPlanResult) # isNonRpcPropertyName (/api/functions/isNonRpcPropertyName) ```ts function isNonRpcPropertyName(propertyName): boolean; ``` **`Internal`** Returns whether a property name must not be treated as an RPC method. ## Parameters | Parameter | Type | | -------------- | -------------------- | | `propertyName` | `string` \| `symbol` | ## Returns `boolean` ## See [https://github.com/anza-xyz/kit/issues/509](https://github.com/anza-xyz/kit/issues/509) # isNone (/api/functions/isNone) ```ts function isNone(option): option is Readonly<{ __option: 'None' }>; ``` Checks whether the given [Option](/api/type-aliases/Option) contains no value. This function acts as a type guard, ensuring the value is a [None](/api/type-aliases/None). ## Type Parameters | Type Parameter | Description | | -------------- | ------------------------------- | | `T` | The type of the expected value. | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------ | ------------------------------------------------ | | `option` | [`Option`](/api/type-aliases/Option)\<`T`> | The [Option](/api/type-aliases/Option) to check. | ## Returns `option is Readonly<{ __option: "None" }>` `true` if the option is a [None](/api/type-aliases/None), `false` otherwise. ## Example Checking for `None` values. ```ts isNone(some(42)); // false isNone(none()); // true ``` ## See * [Option](/api/type-aliases/Option) * [None](/api/type-aliases/None) # isOffCurveAddress (/api/functions/isOffCurveAddress) ```ts function isOffCurveAddress( putativeOffCurveAddress, ): putativeOffCurveAddress is OffCurveAddress; ``` A type guard that returns `true` if the input address conforms to the [OffCurveAddress](/api/type-aliases/OffCurveAddress) type, and refines its type for use in your application. ## Type Parameters | Type Parameter | | ----------------------------------------------------------- | | `TAddress` *extends* [`Address`](/api/type-aliases/Address) | ## Parameters | Parameter | Type | | ------------------------- | ---------- | | `putativeOffCurveAddress` | `TAddress` | ## Returns `putativeOffCurveAddress is OffCurveAddress` ## Example ```ts import { isOffCurveAddress } from '@solana/addresses'; if (isOffCurveAddress(accountAddress)) { // At this point, `accountAddress` has been refined to a // `OffCurveAddress` that can be used within your business logic. const { value: account } = await rpc.getAccountInfo(accountAddress).send(); } else { setError(`${accountAddress} is not off-curve`); } ``` # isOffchainMessageApplicationDomain (/api/functions/isOffchainMessageApplicationDomain) ```ts function isOffchainMessageApplicationDomain( putativeApplicationDomain, ): putativeApplicationDomain is OffchainMessageApplicationDomain; ``` A type guard that returns `true` if the input string conforms to the [OffchainMessageApplicationDomain](/api/type-aliases/OffchainMessageApplicationDomain) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | --------------------------- | -------- | | `putativeApplicationDomain` | `string` | ## Returns `putativeApplicationDomain is OffchainMessageApplicationDomain` ## Example ```ts import { isOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages'; if (isOffchainMessageApplicationDomain(applicationDomain)) { // At this point, `applicationDomain` has been refined to an // `OffchainMessageApplcationDomain` that can be used to craft a message. const offchainMessage: OffchainMessageV0 = { applicationDomain: offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'), // ... }; } else { setError(`${applicationDomain} is not a valid application domain for an offchain message`); } ``` # isOffchainMessageContentRestrictedAsciiOf1232BytesMax (/api/functions/isOffchainMessageContentRestrictedAsciiOf1232BytesMax) ```ts function isOffchainMessageContentRestrictedAsciiOf1232BytesMax( putativeContent, ): putativeContent is Readonly<{ format: RESTRICTED_ASCII_1232_BYTES_MAX; text: Brand< string, 'offchainMessageContentRestrictedAsciiOf1232BytesMax' >; }>; ``` A type guard that returns `true` when supplied content of a v0 offchain message that conforms to the [OffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | ------------------------ | ------------------------------------------------------------------------------------------------------------------ | | `putativeContent` | \{ `format`: [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat); `text`: `string`; } | | `putativeContent.format` | [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat) | | `putativeContent.text` | `string` | ## Returns `putativeContent is Readonly<{ format: RESTRICTED_ASCII_1232_BYTES_MAX; text: Brand }>` ## See [OffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) for more detail. # isOffchainMessageContentUtf8Of1232BytesMax (/api/functions/isOffchainMessageContentUtf8Of1232BytesMax) ```ts function isOffchainMessageContentUtf8Of1232BytesMax( putativeContent, ): putativeContent is Readonly<{ format: UTF8_1232_BYTES_MAX; text: Brand; }>; ``` A type guard that returns `true` when supplied content of a v0 offchain message that conforms to the [OffchainMessageContentUtf8Of1232BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of1232BytesMax) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | ------------------------ | ------------------------------------------------------------------------------------------------------------------ | | `putativeContent` | \{ `format`: [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat); `text`: `string`; } | | `putativeContent.format` | [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat) | | `putativeContent.text` | `string` | ## Returns `putativeContent is Readonly<{ format: UTF8_1232_BYTES_MAX; text: Brand }>` ## See [OffchainMessageContentUtf8Of1232BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of1232BytesMax) for more detail. # isOffchainMessageContentUtf8Of65535BytesMax (/api/functions/isOffchainMessageContentUtf8Of65535BytesMax) ```ts function isOffchainMessageContentUtf8Of65535BytesMax( putativeContent, ): putativeContent is Readonly<{ format: UTF8_65535_BYTES_MAX; text: Brand; }>; ``` A type guard that returns `true` when supplied content of a v0 offchain message that conforms to the [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | ------------------------ | ------------------------------------------------------------------------------------------------------------------ | | `putativeContent` | \{ `format`: [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat); `text`: `string`; } | | `putativeContent.format` | [`OffchainMessageContentFormat`](/api/enumerations/OffchainMessageContentFormat) | | `putativeContent.text` | `string` | ## Returns `putativeContent is Readonly<{ format: UTF8_65535_BYTES_MAX; text: Brand }>` ## See [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) for more detail. # isOption (/api/functions/isOption) ```ts function isOption(input): input is Option; ``` Checks whether the given value is an [Option](/api/type-aliases/Option). This function determines whether an input follows the `Option` structure. ## Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | -------------------------------- | | `T` | `unknown` | The type of the contained value. | ## Parameters | Parameter | Type | Description | | --------- | --------- | ------------------- | | `input` | `unknown` | The value to check. | ## Returns `input is Option` `true` if the value is an [Option](/api/type-aliases/Option), `false` otherwise. ## Example Checking for `Option` values. ```ts isOption(some(42)); // true isOption(none()); // true isOption(42); // false isOption(null); // false isOption("anything else"); // false ``` ## See [Option](/api/type-aliases/Option) # isParallelInstructionPlan (/api/functions/isParallelInstructionPlan) ```ts function isParallelInstructionPlan( plan, ): plan is Readonly<{ kind: 'parallel'; plans: InstructionPlan[]; planType: 'instructionPlan'; }>; ``` Checks if the given instruction plan is a [ParallelInstructionPlan](/api/type-aliases/ParallelInstructionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------ | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to check. | ## Returns `plan is Readonly<{ kind: "parallel"; plans: InstructionPlan[]; planType: "instructionPlan" }>` `true` if the plan is a parallel instruction plan, `false` otherwise. ## Example ```ts const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]); if (isParallelInstructionPlan(plan)) { console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan. } ``` ## See * [ParallelInstructionPlan](/api/type-aliases/ParallelInstructionPlan) * [assertIsParallelInstructionPlan](/api/functions/assertIsParallelInstructionPlan) # isParallelTransactionPlan (/api/functions/isParallelTransactionPlan) ```ts function isParallelTransactionPlan( plan, ): plan is Readonly<{ kind: 'parallel'; plans: TransactionPlan[]; planType: 'transactionPlan'; }>; ``` Checks if the given transaction plan is a [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------ | | `plan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to check. | ## Returns `plan is Readonly<{ kind: "parallel"; plans: TransactionPlan[]; planType: "transactionPlan" }>` `true` if the plan is a parallel transaction plan, `false` otherwise. ## Example ```ts const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]); if (isParallelTransactionPlan(plan)) { console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan. } ``` ## See * [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan) * [assertIsParallelTransactionPlan](/api/functions/assertIsParallelTransactionPlan) # isParallelTransactionPlanResult (/api/functions/isParallelTransactionPlanResult) ```ts function isParallelTransactionPlanResult< TContext, TTransactionMessage, TSingle, >( plan, ): plan is Readonly<{ kind: 'parallel'; plans: TransactionPlanResult< TContext, TTransactionMessage, TSingle >[]; planType: 'transactionPlanResult'; }>; ``` Checks if the given transaction plan result is a [ParallelTransactionPlanResult](/api/type-aliases/ParallelTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result to check. | ## Returns `plan is Readonly<{ kind: "parallel"; plans: TransactionPlanResult[]; planType: "transactionPlanResult" }>` `true` if the result is a parallel transaction plan result, `false` otherwise. ## Example ```ts const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]); if (isParallelTransactionPlanResult(result)) { console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult. } ``` ## See * [ParallelTransactionPlanResult](/api/type-aliases/ParallelTransactionPlanResult) * [assertIsParallelTransactionPlanResult](/api/functions/assertIsParallelTransactionPlanResult) # isProgramDerivedAddress (/api/functions/isProgramDerivedAddress) ```ts function isProgramDerivedAddress( value, ): value is readonly [Address, ProgramDerivedAddressBump]; ``` A type guard that returns `true` if the input tuple conforms to the [ProgramDerivedAddress](/api/type-aliases/ProgramDerivedAddress) type, and refines its type for use in your program. ## Type Parameters | Type Parameter | Default type | | ----------------------------- | ------------ | | `TAddress` *extends* `string` | `string` | ## Parameters | Parameter | Type | | --------- | --------- | | `value` | `unknown` | ## Returns `value is readonly [Address, ProgramDerivedAddressBump]` ## See The [isAddress](/api/functions/isAddress) function for an example of how to use a type guard. # isProgramError (/api/functions/isProgramError) ```ts function isProgramError( error, transactionMessage, programAddress, code?, ): error is Readonly<{ context: Readonly<{ code: TProgramErrorCode }>; }> & SolanaError<4615026>; ``` Identifies whether an error -- typically caused by a transaction failure -- is a custom program error from the provided program address. ## Type Parameters | Type Parameter | | -------------------------------------- | | `TProgramErrorCode` *extends* `number` | ## Parameters | Parameter | Type | Description | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `error` | `unknown` | - | | `transactionMessage` | \{ `instructions`: [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`number`, \{ `programAddress`: `Address`; }>; } | The transaction message that failed to execute. Since the RPC response only provides the index of the failed instruction, the transaction message is required to determine its program address | | `transactionMessage.instructions` | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`number`, \{ `programAddress`: `Address`; }> | - | | `programAddress` | `Address` | The address of the program from which the error is expected to have originated | | `code?` | `TProgramErrorCode` | The expected error code of the custom program error. When provided, the function will check that the custom program error code matches the given value. | ## Returns `error is Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> & SolanaError<4615026>` ## Example ```ts try { // Send and confirm your transaction. } catch (error) { if (isProgramError(error, transactionMessage, myProgramAddress, 42)) { // Handle custom program error 42 from this program. } else if (isProgramError(error, transactionMessage, myProgramAddress)) { // Handle all other custom program errors from this program. } else { throw error; } } ``` # isSendableTransaction (/api/functions/isSendableTransaction) ```ts function isSendableTransaction( transaction, ): transaction is FullySignedTransaction & TransactionWithinSizeLimit & TTransaction; ``` Checks if a transaction has all the required conditions to be sent to the network. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TTransaction` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> | ## Parameters | Parameter | Type | | ------------- | -------------- | | `transaction` | `TTransaction` | ## Returns `transaction is FullySignedTransaction & TransactionWithinSizeLimit & TTransaction` ## Example ```ts import { isSendableTransaction } from '@solana/transactions'; const transaction = getTransactionDecoder().decode(transactionBytes); if (isSendableTransaction(transaction)) { // At this point we know that the transaction can be sent to the network. } ``` ## See [assertIsSendableTransaction](/api/functions/assertIsSendableTransaction) # isSequentialInstructionPlan (/api/functions/isSequentialInstructionPlan) ```ts function isSequentialInstructionPlan( plan, ): plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: InstructionPlan[]; planType: 'instructionPlan'; }>; ``` Checks if the given instruction plan is a [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------ | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to check. | ## Returns `plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: InstructionPlan[]; planType: "instructionPlan" }>` `true` if the plan is a sequential instruction plan, `false` otherwise. ## Example ```ts const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]); if (isSequentialInstructionPlan(plan)) { console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan. } ``` ## See * [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) * [assertIsSequentialInstructionPlan](/api/functions/assertIsSequentialInstructionPlan) # isSequentialTransactionPlan (/api/functions/isSequentialTransactionPlan) ```ts function isSequentialTransactionPlan( plan, ): plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlan[]; planType: 'transactionPlan'; }>; ``` Checks if the given transaction plan is a [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------ | | `plan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to check. | ## Returns `plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlan[]; planType: "transactionPlan" }>` `true` if the plan is a sequential transaction plan, `false` otherwise. ## Example ```ts const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]); if (isSequentialTransactionPlan(plan)) { console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan. } ``` ## See * [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) * [assertIsSequentialTransactionPlan](/api/functions/assertIsSequentialTransactionPlan) # isSequentialTransactionPlanResult (/api/functions/isSequentialTransactionPlanResult) ```ts function isSequentialTransactionPlanResult< TContext, TTransactionMessage, TSingle, >( plan, ): plan is Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlanResult< TContext, TTransactionMessage, TSingle >[]; planType: 'transactionPlanResult'; }>; ``` Checks if the given transaction plan result is a [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result to check. | ## Returns `plan is Readonly<{ divisible: boolean; kind: "sequential"; plans: TransactionPlanResult[]; planType: "transactionPlanResult" }>` `true` if the result is a sequential transaction plan result, `false` otherwise. ## Example ```ts const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]); if (isSequentialTransactionPlanResult(result)) { console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult. } ``` ## See * [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) * [assertIsSequentialTransactionPlanResult](/api/functions/assertIsSequentialTransactionPlanResult) # isSignature (/api/functions/isSignature) ```ts function isSignature(putativeSignature): putativeSignature is Signature; ``` A type guard that accepts a string as input. It will both return `true` if the string conforms to the [Signature](/api/type-aliases/Signature) type and will refine the type for use in your program. ## Parameters | Parameter | Type | | ------------------- | -------- | | `putativeSignature` | `string` | ## Returns `putativeSignature is Signature` ## Example ```ts import { isSignature } from '@solana/keys'; if (isSignature(signature)) { // At this point, `signature` has been refined to a // `Signature` that can be used with the RPC. const { value: [status], } = await rpc.getSignatureStatuses([signature]).send(); setSignatureStatus(status); } else { setError(`${signature} is not a transaction signature`); } ``` # isSignatureBytes (/api/functions/isSignatureBytes) ```ts function isSignatureBytes( putativeSignatureBytes, ): putativeSignatureBytes is SignatureBytes; ``` A type guard that accepts a `ReadonlyUint8Array` as input. It will both return `true` if the `ReadonlyUint8Array` conforms to the [SignatureBytes](/api/type-aliases/SignatureBytes) type and will refine the type for use in your program. ## Parameters | Parameter | Type | | ------------------------ | ---------------------------------------------------------- | | `putativeSignatureBytes` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ## Returns `putativeSignatureBytes is SignatureBytes` ## Example ```ts import { isSignatureBytes } from '@solana/keys'; if (isSignatureBytes(signatureBytes)) { // At this point, `signatureBytes` has been refined to a // `SignatureBytes` that can be used with `verifySignature`. if (!(await verifySignature(publicKey, signatureBytes, data))) { throw new Error('The data were *not* signed by the private key associated with `publicKey`'); } } else { setError(`${signatureBytes} is not a 64-byte Ed25519 signature`); } ``` # isSignerRole (/api/functions/isSignerRole) ```ts function isSignerRole(role): role is WRITABLE_SIGNER | READONLY_SIGNER; ``` Returns `true` if the [AccountRole](/api/enumerations/AccountRole) given represents that of a signer. Also refines the TypeScript type of the supplied role. ## Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `role` | [`AccountRole`](/api/enumerations/AccountRole) | ## Returns role is WRITABLE\_SIGNER | READONLY\_SIGNER # isSingleInstructionPlan (/api/functions/isSingleInstructionPlan) ```ts function isSingleInstructionPlan( plan, ): plan is Readonly<{ instruction: Instruction; kind: 'single'; planType: 'instructionPlan'; }>; ``` Checks if the given instruction plan is a [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------ | | `plan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan to check. | ## Returns `plan is Readonly<{ instruction: Instruction; kind: "single"; planType: "instructionPlan" }>` `true` if the plan is a single instruction plan, `false` otherwise. ## Example ```ts const plan: InstructionPlan = singleInstructionPlan(myInstruction); if (isSingleInstructionPlan(plan)) { console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan. } ``` ## See * [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan) * [assertIsSingleInstructionPlan](/api/functions/assertIsSingleInstructionPlan) # isSingleTransactionPlan (/api/functions/isSingleTransactionPlan) ```ts function isSingleTransactionPlan( plan, ): plan is Readonly<{ kind: 'single'; message: TransactionMessage & TransactionMessageWithFeePayer; planType: 'transactionPlan'; }>; ``` Checks if the given transaction plan is a [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------ | | `plan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan to check. | ## Returns `plan is Readonly<{ kind: "single"; message: TransactionMessage & TransactionMessageWithFeePayer; planType: "transactionPlan" }>` `true` if the plan is a single transaction plan, `false` otherwise. ## Example ```ts const plan: TransactionPlan = singleTransactionPlan(transactionMessage); if (isSingleTransactionPlan(plan)) { console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan. } ``` ## See * [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan) * [assertIsSingleTransactionPlan](/api/functions/assertIsSingleTransactionPlan) # isSingleTransactionPlanResult (/api/functions/isSingleTransactionPlanResult) ```ts function isSingleTransactionPlanResult< TContext, TTransactionMessage, TSingle, >(plan): plan is TSingle; ``` Checks if the given transaction plan result is a [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | | `TSingle` *extends* [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`, `TSingle`> | The transaction plan result to check. | ## Returns `plan is TSingle` `true` if the result is a single transaction plan result, `false` otherwise. ## Example ```ts const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, { signature }); if (isSingleTransactionPlanResult(result)) { console.log(result.status); // TypeScript knows this is a SingleTransactionPlanResult. } ``` ## See * [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) * [assertIsSingleTransactionPlanResult](/api/functions/assertIsSingleTransactionPlanResult) # isSolanaError (/api/functions/isSolanaError) ## Call Signature ```ts function isSolanaError( e, code, ): e is SolanaErrorWithDeprecatedCause; ``` A type guard that returns `true` if the input is a [SolanaError](/api/classes/SolanaError), optionally with a particular error code. When the `code` argument is supplied and the input is a [SolanaError](/api/classes/SolanaError), TypeScript will refine the error's [\`context\`](/api/classes/SolanaError#property-context) property to the type associated with that error code. You can use that context to render useful error messages, or to make context-aware decisions that help your application to recover from the error. ### Type Parameters | Type Parameter | | -------------------------------- | | `TErrorCode` *extends* `7618003` | ### Parameters | Parameter | Type | | --------- | ------------ | | `e` | `unknown` | | `code` | `TErrorCode` | ### Returns `e is SolanaErrorWithDeprecatedCause` ### Example ```ts import { SOLANA_ERROR__TRANSACTION__MISSING_SIGNATURE, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING, isSolanaError, } from '@solana/errors'; import { assertIsFullySignedTransaction, getSignatureFromTransaction } from '@solana/transactions'; try { const transactionSignature = getSignatureFromTransaction(tx); assertIsFullySignedTransaction(tx); /* ... */ } catch (e) { if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) { displayError( "We can't send this transaction without signatures for these addresses:\n- %s", // The type of the `context` object is now refined to contain `addresses`. e.context.addresses.join('\n- '), ); return; } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING)) { if (!tx.feePayer) { displayError('Choose a fee payer for this transaction before sending it'); } else { displayError('The fee payer still needs to sign for this transaction'); } return; } throw e; } ``` ## Call Signature ```ts function isSolanaError( e, code?, ): e is SolanaError; ``` A type guard that returns `true` if the input is a [SolanaError](/api/classes/SolanaError), optionally with a particular error code. When the `code` argument is supplied and the input is a [SolanaError](/api/classes/SolanaError), TypeScript will refine the error's [\`context\`](/api/classes/SolanaError#property-context) property to the type associated with that error code. You can use that context to render useful error messages, or to make context-aware decisions that help your application to recover from the error. ### Type Parameters | Type Parameter | | ----------------------------------------------------------------------------- | | `TErrorCode` *extends* [`SolanaErrorCode`](/api/type-aliases/SolanaErrorCode) | ### Parameters | Parameter | Type | | --------- | ------------ | | `e` | `unknown` | | `code?` | `TErrorCode` | ### Returns `e is SolanaError` ### Example ```ts import { SOLANA_ERROR__TRANSACTION__MISSING_SIGNATURE, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING, isSolanaError, } from '@solana/errors'; import { assertIsFullySignedTransaction, getSignatureFromTransaction } from '@solana/transactions'; try { const transactionSignature = getSignatureFromTransaction(tx); assertIsFullySignedTransaction(tx); /* ... */ } catch (e) { if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) { displayError( "We can't send this transaction without signatures for these addresses:\n- %s", // The type of the `context` object is now refined to contain `addresses`. e.context.addresses.join('\n- '), ); return; } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING)) { if (!tx.feePayer) { displayError('Choose a fee payer for this transaction before sending it'); } else { displayError('The fee payer still needs to sign for this transaction'); } return; } throw e; } ``` # isSolanaRpcResponse (/api/functions/isSolanaRpcResponse) ```ts function isSolanaRpcResponse( notification, ): notification is Readonly<{ context: Readonly<{ slot: Slot }>; value: UnwrapRpcResponse; }>; ``` Type-guards a notification as a [SolanaRpcResponse](/api/type-aliases/SolanaRpcResponse) envelope. Validates the shape by duck-typing for `context.slot: bigint` and the presence of `value`. The narrowed type is `SolanaRpcResponse>`. In the false branch, `notification` retains its original type. ## Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------------------------------------------- | | `T` | The notification shape, which may be a raw value, an envelope, or a union of the two. | ## Parameters | Parameter | Type | Description | | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | | `notification` | \| `T` \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `context`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `slot`: [`Slot`](/api/type-aliases/Slot); }>; `value`: [`UnwrapRpcResponse`](/api/type-aliases/UnwrapRpcResponse); }> | The value to test. | ## Returns `notification is Readonly<{ context: Readonly<{ slot: Slot }>; value: UnwrapRpcResponse }>` `true` when `notification` is a `SolanaRpcResponse` envelope, narrowing accordingly. ## Example ```ts if (isSolanaRpcResponse(notification)) { return { slot: notification.context.slot, value: notification.value }; } ``` # isSome (/api/functions/isSome) ```ts function isSome( option, ): option is Readonly<{ __option: 'Some'; value: T }>; ``` Checks whether the given [Option](/api/type-aliases/Option) contains a value. This function acts as a type guard, ensuring the value is a [Some](/api/type-aliases/Some). ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------ | ------------------------------------------------ | | `option` | [`Option`](/api/type-aliases/Option)\<`T`> | The [Option](/api/type-aliases/Option) to check. | ## Returns `option is Readonly<{ __option: "Some"; value: T }>` `true` if the option is a [Some](/api/type-aliases/Some), `false` otherwise. ## Example Checking for `Some` values. ```ts isSome(some(42)); // true isSome(none()); // false ``` ## See * [Option](/api/type-aliases/Option) * [Some](/api/type-aliases/Some) # isStringifiedBigInt (/api/functions/isStringifiedBigInt) ```ts function isStringifiedBigInt( putativeBigInt, ): putativeBigInt is StringifiedBigInt; ``` A type guard that returns `true` if the input string parses as a `BigInt`, and refines its type for use in your program. ## Parameters | Parameter | Type | | ---------------- | -------- | | `putativeBigInt` | `string` | ## Returns `putativeBigInt is StringifiedBigInt` ## Example ```ts import { isStringifiedBigInt } from '@solana/rpc-types'; if (isStringifiedBigInt(bigintString)) { // At this point, `bigintString` has been refined to a `StringifiedBigInt` bigintString satisfies StringifiedBigInt; // OK } else { setError(`${bigintString} does not represent a BigInt`); } ``` # isStringifiedNumber (/api/functions/isStringifiedNumber) ```ts function isStringifiedNumber( putativeNumber, ): putativeNumber is StringifiedNumber; ``` A type guard that returns `true` if the input string parses as a `Number`, and refines its type for use in your program. ## Parameters | Parameter | Type | | ---------------- | -------- | | `putativeNumber` | `string` | ## Returns `putativeNumber is StringifiedNumber` ## Example ```ts import { isStringifiedNumber } from '@solana/rpc-types'; if (isStringifiedNumber(numericString)) { // At this point, `numericString` has been refined to a `StringifiedNumber` numericString satisfies StringifiedNumber; // OK } else { setError(`${numericString} does not represent a number`); } ``` # isSuccessfulSingleTransactionPlanResult (/api/functions/isSuccessfulSingleTransactionPlanResult) ```ts function isSuccessfulSingleTransactionPlanResult< TContext, TTransactionMessage, >( plan, ): plan is SuccessfulSingleTransactionPlanResult< TContext, TTransactionMessage >; ``` Checks if the given transaction plan result is a successful [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult). ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result to check. | ## Returns `plan is SuccessfulSingleTransactionPlanResult` `true` if the result is a successful single transaction plan result, `false` otherwise. ## Example ```ts const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, { signature }); if (isSuccessfulSingleTransactionPlanResult(result)) { console.log(result.context.signature); // TypeScript knows this is a successful result. } ``` ## See * [SuccessfulSingleTransactionPlanResult](/api/type-aliases/SuccessfulSingleTransactionPlanResult) * [assertIsSuccessfulSingleTransactionPlanResult](/api/functions/assertIsSuccessfulSingleTransactionPlanResult) # isSuccessfulTransactionPlanResult (/api/functions/isSuccessfulTransactionPlanResult) ```ts function isSuccessfulTransactionPlanResult< TContext, TTransactionMessage, >( plan, ): plan is SuccessfulTransactionPlanResult< TContext, TTransactionMessage >; ``` Checks if the given transaction plan result is a [SuccessfulTransactionPlanResult](/api/type-aliases/SuccessfulTransactionPlanResult). This function verifies that the entire transaction plan result tree contains only successful single transaction results. It recursively checks all nested results to ensure every [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) has a 'successful' status. Note: This is different from [isSuccessfulSingleTransactionPlanResult](/api/functions/isSuccessfulSingleTransactionPlanResult) which checks if a single result is successful. This function checks that the entire plan result tree (including all nested parallel/sequential structures) contains only successful transactions. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------- | | `plan` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result to check. | ## Returns `plan is SuccessfulTransactionPlanResult` `true` if all single transaction results in the tree are successful, `false` otherwise. ## Example ```ts const result: TransactionPlanResult = parallelTransactionPlanResult([ successfulSingleTransactionPlanResult(messageA, { signature: signatureA }), successfulSingleTransactionPlanResult(messageB, { signature: signatureB }), ]); if (isSuccessfulTransactionPlanResult(result)) { // All transactions were successful. result satisfies SuccessfulTransactionPlanResult; } ``` ## See * [SuccessfulTransactionPlanResult](/api/type-aliases/SuccessfulTransactionPlanResult) * [assertIsSuccessfulTransactionPlanResult](/api/functions/assertIsSuccessfulTransactionPlanResult) * [isSuccessfulSingleTransactionPlanResult](/api/functions/isSuccessfulSingleTransactionPlanResult) # isTransactionMessageWithBlockhashLifetime (/api/functions/isTransactionMessageWithBlockhashLifetime) ```ts function isTransactionMessageWithBlockhashLifetime( transactionMessage, ): transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime; ``` A type guard that returns `true` if the transaction message conforms to the [TransactionMessageWithBlockhashLifetime](/api/interfaces/TransactionMessageWithBlockhashLifetime) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `transactionMessage` | \| [`TransactionMessage`](/api/type-aliases/TransactionMessage) \| TransactionMessage & TransactionMessageWithBlockhashLifetime | ## Returns `transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime` ## Example ```ts import { isTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages'; if (isTransactionMessageWithBlockhashLifetime(message)) { // At this point, `message` has been refined to a `TransactionMessageWithBlockhashLifetime`. const { blockhash } = message.lifetimeConstraint; const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send(); setBlockhashIsValid(blockhashIsValid); } else { setError( `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`, ); } ``` # isTransactionMessageWithDurableNonceLifetime (/api/functions/isTransactionMessageWithDurableNonceLifetime) ```ts function isTransactionMessageWithDurableNonceLifetime( transactionMessage, ): transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime; ``` A type guard that returns `true` if the transaction message conforms to the [TransactionMessageWithDurableNonceLifetime](/api/interfaces/TransactionMessageWithDurableNonceLifetime) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `transactionMessage` | \| [`TransactionMessage`](/api/type-aliases/TransactionMessage) \| TransactionMessage & TransactionMessageWithDurableNonceLifetime\ | ## Returns `transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime` ## Example ```ts import { isTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages'; import { fetchNonce } from "@solana-program/system"; if (isTransactionMessageWithDurableNonceLifetime(message)) { // At this point, `message` has been refined to a // `TransactionMessageWithDurableNonceLifetime`. const { nonce, nonceAccountAddress } = message.lifetimeConstraint; const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress); setNonceIsValid(nonce === actualNonce); } else { setError( `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`, ); } ``` # isTransactionMessageWithSingleSendingSigner (/api/functions/isTransactionMessageWithSingleSendingSigner) ```ts function isTransactionMessageWithSingleSendingSigner< TTransactionMessage, >( transaction, ): transaction is NominalType< 'brand', 'TransactionMessageWithSingleSendingSigner' > & Partial< Pick< | TransactionMessageWithFeePayerSigner< string, TransactionSigner > | Readonly<{ feePayer: Readonly<{ address: Address }> & Readonly<{ modifyAndSignTransactions?: undefined; signAndSendTransactions?: undefined; signTransactions?: undefined; }>; }>, 'feePayer' > > & Readonly<{ instructions: readonly (Instruction< string, readonly ( | AccountLookupMeta | AccountMeta )[] > & InstructionWithSigners< TransactionSigner, readonly AccountMetaWithSigner< TransactionSigner >[] >)[]; }> & TTransactionMessage; ``` Checks whether the provided transaction has exactly one [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner). This can be useful when using [signAndSendTransactionMessageWithSigners](/api/functions/signAndSendTransactionMessageWithSigners) to provide a fallback strategy in case the transaction message cannot be send using this function. ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | | `TTransactionMessage` *extends* `TransactionMessage` & `TransactionMessageWithFeePayer`\<`string`> | The inferred type of the transaction message provided. | ## Parameters | Parameter | Type | | ------------- | --------------------- | | `transaction` | `TTransactionMessage` | ## Returns transaction is NominalType\<"brand", "TransactionMessageWithSingleSendingSigner"> & Partial\> | Readonly\<\{ feePayer: Readonly\<\{ address: Address\ }> & Readonly\<\{ modifyAndSignTransactions?: undefined; signAndSendTransactions?: undefined; signTransactions?: undefined }> }>, "feePayer">> & Readonly\<\{ instructions: readonly (Instruction\ | AccountMeta\)\[]> & InstructionWithSigners\, readonly AccountMetaWithSigner\>\[]>)\[] }> & TTransactionMessage ## Example ```ts import { isTransactionMessageWithSingleSendingSigner, signAndSendTransactionMessageWithSigners, signTransactionMessageWithSigners, } from '@solana/signers'; import { getBase64EncodedWireTransaction } from '@solana/transactions'; let transactionSignature: SignatureBytes; if (isTransactionMessageWithSingleSendingSigner(transactionMessage)) { transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage); } else { const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); const encodedTransaction = getBase64EncodedWireTransaction(signedTransaction); transactionSignature = await rpc.sendTransaction(encodedTransaction).send(); } ``` ## See * [signAndSendTransactionMessageWithSigners](/api/functions/signAndSendTransactionMessageWithSigners) * [assertIsTransactionMessageWithSingleSendingSigner](/api/functions/assertIsTransactionMessageWithSingleSendingSigner) # isTransactionMessageWithinSizeLimit (/api/functions/isTransactionMessageWithinSizeLimit) ```ts function isTransactionMessageWithinSizeLimit( transactionMessage, ): transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage; ``` Checks if a transaction message is within the size limit when compiled into a transaction. ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------------- | ------------------------------------------ | | `TTransactionMessage` *extends* `TransactionMessage` & `TransactionMessageWithFeePayer`\<`string`> | The type of the given transaction message. | ## Parameters | Parameter | Type | | -------------------- | --------------------- | | `transactionMessage` | `TTransactionMessage` | ## Returns `transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage` ## Example ```ts if (isTransactionMessageWithinSizeLimit(transactionMessage)) { transactionMessage satisfies TransactionMessageWithinSizeLimit; } ``` # isTransactionModifyingSigner (/api/functions/isTransactionModifyingSigner) ```ts function isTransactionModifyingSigner( value, ): value is Readonly<{ address: Address; modifyAndSignTransactions: any; }> & TValue; ``` Checks whether the provided value implements the [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `value is Readonly<{ address: Address; modifyAndSignTransactions: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { isTransactionModifyingSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; isTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // true isTransactionModifyingSigner({ address }); // false ``` ## See [assertIsTransactionModifyingSigner](/api/functions/assertIsTransactionModifyingSigner) # isTransactionPartialSigner (/api/functions/isTransactionPartialSigner) ```ts function isTransactionPartialSigner( value, ): value is Readonly<{ address: Address; signTransactions: any; }> & TValue; ``` Checks whether the provided value implements the [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `value is Readonly<{ address: Address; signTransactions: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { isTransactionPartialSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; isTransactionPartialSigner({ address, signTransactions: async () => {} }); // true isTransactionPartialSigner({ address }); // false ``` ## See [assertIsTransactionPartialSigner](/api/functions/assertIsTransactionPartialSigner) # isTransactionPlan (/api/functions/isTransactionPlan) ```ts function isTransactionPlan(value): value is TransactionPlan; ``` Checks if the given value is a [TransactionPlan](/api/type-aliases/TransactionPlan). This type guard checks the `planType` property to determine if the value is a transaction plan. This is useful when you have a value that could be an [InstructionPlan](/api/type-aliases/InstructionPlan), [TransactionPlan](/api/type-aliases/TransactionPlan), or [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) and need to narrow the type. ## Parameters | Parameter | Type | Description | | --------- | --------- | ------------------- | | `value` | `unknown` | The value to check. | ## Returns `value is TransactionPlan` `true` if the value is a transaction plan, `false` otherwise. ## Example ```ts function processItem(item: InstructionPlan | TransactionPlan | TransactionPlanResult) { if (isTransactionPlan(item)) { // item is narrowed to TransactionPlan console.log(item.kind); } } ``` ## See * [TransactionPlan](/api/type-aliases/TransactionPlan) * [isInstructionPlan](/api/functions/isInstructionPlan) * [isTransactionPlanResult](/api/functions/isTransactionPlanResult) # isTransactionPlanResult (/api/functions/isTransactionPlanResult) ```ts function isTransactionPlanResult( value, ): value is TransactionPlanResult< TransactionPlanResultContextWithSignature, TransactionMessage & TransactionMessageWithFeePayer, SingleTransactionPlanResult< TransactionPlanResultContextWithSignature, TransactionMessage & TransactionMessageWithFeePayer > >; ``` Checks if the given value is a [TransactionPlanResult](/api/type-aliases/TransactionPlanResult). This type guard checks the `planType` property to determine if the value is a transaction plan result. This is useful when you have a value that could be an [InstructionPlan](/api/type-aliases/InstructionPlan), [TransactionPlan](/api/type-aliases/TransactionPlan), or [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) and need to narrow the type. ## Parameters | Parameter | Type | Description | | --------- | --------- | ------------------- | | `value` | `unknown` | The value to check. | ## Returns `value is TransactionPlanResult, SingleTransactionPlanResult>>` `true` if the value is a transaction plan result, `false` otherwise. ## Example ```ts function processItem(item: InstructionPlan | TransactionPlan | TransactionPlanResult) { if (isTransactionPlanResult(item)) { // item is narrowed to TransactionPlanResult console.log(item.kind); } } ``` ## See * [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) * [isInstructionPlan](/api/functions/isInstructionPlan) * [isTransactionPlan](/api/functions/isTransactionPlan) # isTransactionSendingSigner (/api/functions/isTransactionSendingSigner) ```ts function isTransactionSendingSigner( value, ): value is Readonly<{ address: Address; signAndSendTransactions: any; }> & TValue; ``` Checks whether the provided value implements the [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `value is Readonly<{ address: Address; signAndSendTransactions: any }> & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { isTransactionSendingSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; isTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // true isTransactionSendingSigner({ address }); // false ``` ## See [assertIsTransactionSendingSigner](/api/functions/assertIsTransactionSendingSigner) # isTransactionSigner (/api/functions/isTransactionSigner) ```ts function isTransactionSigner( value, ): value is TransactionSigner & TValue; ``` Checks whether the provided value implements the [TransactionSigner](/api/type-aliases/TransactionSigner) interface. ## Type Parameters | Type Parameter | Description | | ----------------------------- | ------------------------------------------ | | `TAddress` *extends* `string` | The inferred type of the address provided. | | `TValue` *extends* `object` | - | ## Parameters | Parameter | Type | | --------- | -------- | | `value` | `TValue` | ## Returns `value is TransactionSigner & TValue` ## Example ```ts import { Address } from '@solana/addresses'; import { isTransactionSigner } from '@solana/signers'; const address = '1234..5678' as Address<'1234..5678'>; isTransactionSigner({ address, signTransactions: async () => {} }); // true isTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // true isTransactionSigner({ address, signAndSendTransactions: async () => {} }); // true isTransactionSigner({ address }); // false ``` ## See [assertIsTransactionSigner](/api/functions/assertIsTransactionSigner) # isTransactionWithBlockhashLifetime (/api/functions/isTransactionWithBlockhashLifetime) ```ts function isTransactionWithBlockhashLifetime( transaction, ): transaction is Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> & TransactionWithBlockhashLifetime; ``` A type guard that returns `true` if the transaction conforms to the [TransactionWithBlockhashLifetime](/api/type-aliases/TransactionWithBlockhashLifetime) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `transaction` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> & [`TransactionWithLifetime`](/api/type-aliases/TransactionWithLifetime) | ## Returns `transaction is Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap }> & TransactionWithBlockhashLifetime` ## Example ```ts import { isTransactionWithBlockhashLifetime } from '@solana/transactions'; if (isTransactionWithBlockhashLifetime(transaction)) { // At this point, `transaction` has been refined to a `TransactionWithBlockhashLifetime`. const { blockhash } = transaction.lifetimeConstraint; const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send(); setBlockhashIsValid(blockhashIsValid); } else { setError( `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`, ); } ``` # isTransactionWithDurableNonceLifetime (/api/functions/isTransactionWithDurableNonceLifetime) ```ts function isTransactionWithDurableNonceLifetime( transaction, ): transaction is Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> & TransactionWithDurableNonceLifetime; ``` A type guard that returns `true` if the transaction conforms to the [TransactionWithDurableNonceLifetime](/api/type-aliases/TransactionWithDurableNonceLifetime) type, and refines its type for use in your program. ## Parameters | Parameter | Type | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `transaction` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> & [`TransactionWithLifetime`](/api/type-aliases/TransactionWithLifetime) | ## Returns `transaction is Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap }> & TransactionWithDurableNonceLifetime` ## Example ```ts import { isTransactionWithDurableNonceLifetime } from '@solana/transactions'; import { fetchNonce } from "@solana-program/system"; if (isTransactionWithDurableNonceLifetime(transaction)) { // At this point, `transaction` has been refined to a // `TransactionWithDurableNonceLifetime`. const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint; const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress); setNonceIsValid(nonce === actualNonce); } else { setError( `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`, ); } ``` # isTransactionWithinSizeLimit (/api/functions/isTransactionWithinSizeLimit) ```ts function isTransactionWithinSizeLimit( transaction, ): transaction is TransactionWithinSizeLimit & TTransaction; ``` Checks if a transaction is within the size limit. ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------- | | `TTransaction` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> | The type of the given transaction. | ## Parameters | Parameter | Type | | ------------- | -------------- | | `transaction` | `TTransaction` | ## Returns `transaction is TransactionWithinSizeLimit & TTransaction` ## Example ```ts if (isTransactionWithinSizeLimit(transaction)) { transaction satisfies TransactionWithinSizeLimit; } ``` # isUnixTimestamp (/api/functions/isUnixTimestamp) ```ts function isUnixTimestamp( putativeTimestamp, ): putativeTimestamp is UnixTimestamp; ``` This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer conforms to the [UnixTimestamp](/api/type-aliases/UnixTimestamp) type and will refine the type for use in your program. ## Parameters | Parameter | Type | | ------------------- | -------- | | `putativeTimestamp` | `bigint` | ## Returns `putativeTimestamp is UnixTimestamp` ## Example ```ts import { isUnixTimestamp } from '@solana/rpc-types'; if (isUnixTimestamp(timestamp)) { // At this point, `timestamp` has been refined to a // `UnixTimestamp` that can be used anywhere timestamps are expected. timestamp satisfies UnixTimestamp; } else { setError(`${timestamp} is not a Unix timestamp`); } ``` # isV1ConfigEmpty (/api/functions/isV1ConfigEmpty) ```ts function isV1ConfigEmpty(config): boolean; ``` Determines whether a transaction config has no fields set. ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------- | ---------------------- | | `config` | [`V1TransactionConfig`](/api/type-aliases/V1TransactionConfig) | The config to inspect. | ## Returns `boolean` `true` if every field of the config is `undefined`, `false` otherwise. # isVariableSize (/api/functions/isVariableSize) ## Call Signature ```ts function isVariableSize( encoder, ): encoder is VariableSizeEncoder; ``` Determines whether the given codec, encoder, or decoder is variable-size. A variable-size object is identified by the absence of a `fixedSize` property. If this property is missing, the object is considered a [VariableSizeCodec](/api/interfaces/VariableSizeCodec), [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder), or [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | ### Parameters | Parameter | Type | | --------- | ------------------------------------------------ | | `encoder` | [`Encoder`](/api/type-aliases/Encoder)\<`TFrom`> | ### Returns `encoder is VariableSizeEncoder` `true` if the object is variable-size, `false` otherwise. ### Examples Checking a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); isVariableSize(encoder); // true ``` Checking a fixed-size encoder. ```ts const encoder = getU32Encoder(); isVariableSize(encoder); // false ``` ### Remarks This function is the inverse of [isFixedSize](/api/functions/isFixedSize). ### See * [isFixedSize](/api/functions/isFixedSize) * [assertIsVariableSize](/api/functions/assertIsVariableSize) ## Call Signature ```ts function isVariableSize( decoder, ): decoder is VariableSizeDecoder; ``` Determines whether the given codec, encoder, or decoder is variable-size. A variable-size object is identified by the absence of a `fixedSize` property. If this property is missing, the object is considered a [VariableSizeCodec](/api/interfaces/VariableSizeCodec), [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder), or [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------ | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TTo`> | ### Returns `decoder is VariableSizeDecoder` `true` if the object is variable-size, `false` otherwise. ### Examples Checking a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); isVariableSize(encoder); // true ``` Checking a fixed-size encoder. ```ts const encoder = getU32Encoder(); isVariableSize(encoder); // false ``` ### Remarks This function is the inverse of [isFixedSize](/api/functions/isFixedSize). ### See * [isFixedSize](/api/functions/isFixedSize) * [assertIsVariableSize](/api/functions/assertIsVariableSize) ## Call Signature ```ts function isVariableSize( codec, ): codec is VariableSizeCodec; ``` Determines whether the given codec, encoder, or decoder is variable-size. A variable-size object is identified by the absence of a `fixedSize` property. If this property is missing, the object is considered a [VariableSizeCodec](/api/interfaces/VariableSizeCodec), [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder), or [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | ### Parameters | Parameter | Type | | --------- | --------------------------------------------------- | | `codec` | [`Codec`](/api/type-aliases/Codec)\<`TFrom`, `TTo`> | ### Returns `codec is VariableSizeCodec` `true` if the object is variable-size, `false` otherwise. ### Examples Checking a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); isVariableSize(encoder); // true ``` Checking a fixed-size encoder. ```ts const encoder = getU32Encoder(); isVariableSize(encoder); // false ``` ### Remarks This function is the inverse of [isFixedSize](/api/functions/isFixedSize). ### See * [isFixedSize](/api/functions/isFixedSize) * [assertIsVariableSize](/api/functions/assertIsVariableSize) ## Call Signature ```ts function isVariableSize(codec): codec is { maxSize?: number }; ``` Determines whether the given codec, encoder, or decoder is variable-size. A variable-size object is identified by the absence of a `fixedSize` property. If this property is missing, the object is considered a [VariableSizeCodec](/api/interfaces/VariableSizeCodec), [VariableSizeEncoder](/api/interfaces/VariableSizeEncoder), or [VariableSizeDecoder](/api/interfaces/VariableSizeDecoder). ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------ | | `codec` | \| \{ `fixedSize`: `number`; } \| \{ `maxSize?`: `number`; } | ### Returns `codec is { maxSize?: number }` `true` if the object is variable-size, `false` otherwise. ### Examples Checking a variable-size encoder. ```ts const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()); isVariableSize(encoder); // true ``` Checking a fixed-size encoder. ```ts const encoder = getU32Encoder(); isVariableSize(encoder); // false ``` ### Remarks This function is the inverse of [isFixedSize](/api/functions/isFixedSize). ### See * [isFixedSize](/api/functions/isFixedSize) * [assertIsVariableSize](/api/functions/assertIsVariableSize) # isWritableRole (/api/functions/isWritableRole) ```ts function isWritableRole(role): role is WRITABLE_SIGNER | WRITABLE; ``` Returns `true` if the [AccountRole](/api/enumerations/AccountRole) given represents that of a writable account. Also refines the TypeScript type of the supplied role. ## Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `role` | [`AccountRole`](/api/enumerations/AccountRole) | ## Returns role is WRITABLE\_SIGNER | WRITABLE # lamports (/api/functions/lamports) ```ts function lamports(putativeLamports): Lamports; ``` This helper combines *asserting* that a number is a possible number of [Lamports](/api/type-aliases/Lamports) with *coercing* it to the [Lamports](/api/type-aliases/Lamports) type. It's best used with untrusted input. ## Parameters | Parameter | Type | | ------------------ | -------- | | `putativeLamports` | `bigint` | ## Returns [`Lamports`](/api/type-aliases/Lamports) ## Example ```ts import { lamports } from '@solana/rpc-types'; await transfer(address(fromAddress), address(toAddress), lamports(100000n)); ``` # lamportsToSol (/api/functions/lamportsToSol) ```ts function lamportsToSol(value): Sol; ``` Converts a [Lamports](/api/type-aliases/Lamports) bigint to its equivalent [Sol](/api/type-aliases/Sol) fixed-point value. This conversion is exact. ## Parameters | Parameter | Type | | --------- | ---------------------------------------- | | `value` | [`Lamports`](/api/type-aliases/Lamports) | ## Returns [`Sol`](/api/type-aliases/Sol) ## Example ```ts lamportsToSol(lamports(1_500_000_000n)); // represents 1.5 SOL ``` ## See * [solToLamports](/api/functions/solToLamports) * [sol](/api/functions/sol) # ltBinaryFixedPoint (/api/functions/ltBinaryFixedPoint) ```ts function ltBinaryFixedPoint(a, b): boolean; ``` Returns `true` when `a` is strictly less than `b`. See [cmpBinaryFixedPoint](/api/functions/cmpBinaryFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TFractionalBits`> | | `b` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TFractionalBits`>> | ## Returns `boolean` # ltDecimalFixedPoint (/api/functions/ltDecimalFixedPoint) ```ts function ltDecimalFixedPoint(a, b): boolean; ``` Returns `true` when `a` is strictly less than `b`. See [cmpDecimalFixedPoint](/api/functions/cmpDecimalFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------ | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TDecimals`> | | `b` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TDecimals`>> | ## Returns `boolean` # lteBinaryFixedPoint (/api/functions/lteBinaryFixedPoint) ```ts function lteBinaryFixedPoint(a, b): boolean; ``` Returns `true` when `a` is less than or equal to `b`. See [cmpBinaryFixedPoint](/api/functions/cmpBinaryFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TFractionalBits`> | | `b` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TFractionalBits`>> | ## Returns `boolean` # lteDecimalFixedPoint (/api/functions/lteDecimalFixedPoint) ```ts function lteDecimalFixedPoint(a, b): boolean; ``` Returns `true` when `a` is less than or equal to `b`. See [cmpDecimalFixedPoint](/api/functions/cmpDecimalFixedPoint) for shape-matching rules. ## Type Parameters | Type Parameter | | ------------------------------ | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, `TDecimals`> | | `b` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `number`, [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TDecimals`>> | ## Returns `boolean` # mainnet (/api/functions/mainnet) ```ts function mainnet(putativeString): MainnetUrl; ``` Given a URL casts it to a type that is only accepted where mainnet URLs are expected. ## Parameters | Parameter | Type | | ---------------- | -------- | | `putativeString` | `string` | ## Returns [`MainnetUrl`](/api/type-aliases/MainnetUrl) # mergeBytes (/api/functions/mergeBytes) ```ts function mergeBytes(byteArrays): Uint8Array; ``` Concatenates an array of `Uint8Array`s into a single `Uint8Array`. Reuses the original byte array when applicable. ## Parameters | Parameter | Type | Description | | ------------ | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | `byteArrays` | [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`>\[] | The array of byte arrays to concatenate. | ## Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) ## Example ```ts const bytes1 = new Uint8Array([0x01, 0x02]); const bytes2 = new Uint8Array([]); const bytes3 = new Uint8Array([0x03, 0x04]); const bytes = mergeBytes([bytes1, bytes2, bytes3]); // ^ [0x01, 0x02, 0x03, 0x04] ``` # mergeRoles (/api/functions/mergeRoles) ## Call Signature ```ts function mergeRoles(roleA, roleB): WRITABLE_SIGNER; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `roleA` | [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) | | `roleB` | [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) | ### Returns [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` ## Call Signature ```ts function mergeRoles(roleA, roleB): WRITABLE_SIGNER; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `roleA` | [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) | | `roleB` | [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) | ### Returns [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` ## Call Signature ```ts function mergeRoles(roleA, roleB): WRITABLE_SIGNER; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `roleA` | [`AccountRole`](/api/enumerations/AccountRole) | | `roleB` | [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) | ### Returns [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` ## Call Signature ```ts function mergeRoles(roleA, roleB): WRITABLE_SIGNER; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `roleA` | [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) | | `roleB` | [`AccountRole`](/api/enumerations/AccountRole) | ### Returns [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` ## Call Signature ```ts function mergeRoles(roleA, roleB): READONLY_SIGNER; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `roleA` | [`AccountRole`](/api/enumerations/AccountRole) | | `roleB` | [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) | ### Returns [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` ## Call Signature ```ts function mergeRoles(roleA, roleB): READONLY_SIGNER; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `roleA` | [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) | | `roleB` | [`AccountRole`](/api/enumerations/AccountRole) | ### Returns [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` ## Call Signature ```ts function mergeRoles(roleA, roleB): WRITABLE; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `roleA` | [`AccountRole`](/api/enumerations/AccountRole) | | `roleB` | [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) | ### Returns [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` ## Call Signature ```ts function mergeRoles(roleA, roleB): WRITABLE; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `roleA` | [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) | | `roleB` | [`AccountRole`](/api/enumerations/AccountRole) | ### Returns [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` ## Call Signature ```ts function mergeRoles(roleA, roleB): READONLY; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `roleA` | [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) | | `roleB` | [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) | ### Returns [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` ## Call Signature ```ts function mergeRoles(roleA, roleB): AccountRole; ``` Given two [AccountRoles](/api/enumerations/AccountRole), will return the [AccountRole](/api/enumerations/AccountRole) that grants the highest privileges of both. ### Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `roleA` | [`AccountRole`](/api/enumerations/AccountRole) | | `roleB` | [`AccountRole`](/api/enumerations/AccountRole) | ### Returns [`AccountRole`](/api/enumerations/AccountRole) ### Example ```ts // Returns `AccountRole.WRITABLE_SIGNER` mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE); ``` # multiplyBinaryFixedPoint (/api/functions/multiplyBinaryFixedPoint) ```ts function multiplyBinaryFixedPoint< TSignedness, TTotalBits, TFractionalBits, >( a, b, rounding?, ): BinaryFixedPoint; ``` Multiplies a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) by a scalar. The second operand may be another [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) with the same signedness (any total bits or fractional bits) or a bare `bigint`. The result always has `a`'s shape. Multiplication by a same-kind fixed-point rescales the product back to `a`'s scale. When that rescaling is not exact, the optional [RoundingMode](/api/type-aliases/RoundingMode) is consulted; it defaults to `'strict'` and throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` in that case. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> | | `b` | \| `bigint` \| [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TSignedness`>, `number`, `number`> | | `rounding?` | [`RoundingMode`](/api/type-aliases/RoundingMode) | ## Returns [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> ## Example ```ts const audioSample = binaryFixedPoint('signed', 16, 15); multiplyBinaryFixedPoint(audioSample('0.6'), audioSample('0.8')); // represents 0.48 multiplyBinaryFixedPoint(audioSample('0.5'), 2n); // represents 1.0 (overflows Q1.15) ``` ## See [divideBinaryFixedPoint](/api/functions/divideBinaryFixedPoint) # multiplyDecimalFixedPoint (/api/functions/multiplyDecimalFixedPoint) ```ts function multiplyDecimalFixedPoint( a, b, rounding?, ): DecimalFixedPoint; ``` Multiplies a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) by a scalar. The second operand may be another [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) with the same signedness (any total bits or decimals) or a bare `bigint`. The result always has `a`'s shape. Multiplication by a same-kind fixed-point rescales the product back to `a`'s scale. When that rescaling is not exact, the optional [RoundingMode](/api/type-aliases/RoundingMode) is consulted; it defaults to `'strict'` and throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` in that case. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> | | `b` | \| `bigint` \| [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<`TSignedness`>, `number`, `number`> | | `rounding?` | [`RoundingMode`](/api/type-aliases/RoundingMode) | ## Returns [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> ## Example ```ts const usd = decimalFixedPoint('unsigned', 64, 2); const rate = decimalFixedPoint('unsigned', 64, 4); multiplyDecimalFixedPoint(usd('100'), rate('0.0025')); // represents 0.25 multiplyDecimalFixedPoint(usd('1.50'), 3n); // represents 4.50 ``` ## See [divideDecimalFixedPoint](/api/functions/divideDecimalFixedPoint) # negateBinaryFixedPoint (/api/functions/negateBinaryFixedPoint) ```ts function negateBinaryFixedPoint( a, ): BinaryFixedPoint<'signed', TTotalBits, TFractionalBits>; ``` Returns the additive inverse of a signed [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint). Unsigned values are rejected at the type level; they are also rejected at runtime with `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH` in case the type safety is bypassed. Negating the minimum representable value overflows and throws `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW`. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------ | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`"signed"`, `TTotalBits`, `TFractionalBits`> | ## Returns [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`"signed"`, `TTotalBits`, `TFractionalBits`> ## See [absoluteBinaryFixedPoint](/api/functions/absoluteBinaryFixedPoint) # negateDecimalFixedPoint (/api/functions/negateDecimalFixedPoint) ```ts function negateDecimalFixedPoint( a, ): DecimalFixedPoint<'signed', TTotalBits, TDecimals>; ``` Returns the additive inverse of a signed [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint). Unsigned values are rejected at the type level; they are also rejected at runtime with `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH` in case the type safety is bypassed. Negating the minimum representable value overflows and throws `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW`. ## Type Parameters | Type Parameter | | ------------------------------- | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------- | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`"signed"`, `TTotalBits`, `TDecimals`> | ## Returns [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`"signed"`, `TTotalBits`, `TDecimals`> ## See [absoluteDecimalFixedPoint](/api/functions/absoluteDecimalFixedPoint) # nonDivisibleSequentialInstructionPlan (/api/functions/nonDivisibleSequentialInstructionPlan) ```ts function nonDivisibleSequentialInstructionPlan(plans): Readonly<{ divisible: boolean; kind: 'sequential'; plans: InstructionPlan[]; planType: 'instructionPlan'; }> & object; ``` Creates a non-divisible [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) from an array of nested plans. It can accept [Instruction](/api/interfaces/Instruction) objects directly, which will be wrapped in [SingleInstructionPlans](/api/type-aliases/SingleInstructionPlan) automatically. ## Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `plans` | ( \| [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> \| [`InstructionPlan`](/api/type-aliases/InstructionPlan))\[] | ## Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `divisible`: `boolean`; `kind`: `"sequential"`; `plans`: [`InstructionPlan`](/api/type-aliases/InstructionPlan)\[]; `planType`: `"instructionPlan"`; }> & `object` ## Examples **Using explicit \{@link SingleInstructionPlan | SingleInstructionPlans}.** ```ts const plan = nonDivisibleSequentialInstructionPlan([ singleInstructionPlan(instructionA), singleInstructionPlan(instructionB), ]); ``` **Using \{@link Instruction | Instructions} directly.** ```ts const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]); ``` ## See [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) # nonDivisibleSequentialTransactionPlan (/api/functions/nonDivisibleSequentialTransactionPlan) ```ts function nonDivisibleSequentialTransactionPlan(plans): Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlan[]; planType: 'transactionPlan'; }> & object; ``` Creates a non-divisible [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) from an array of nested plans. It can accept [TransactionMessage](/api/type-aliases/TransactionMessage) objects directly, which will be wrapped in [SingleTransactionPlans](/api/type-aliases/SingleTransactionPlan) automatically. ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------- | | `plans` | ( \| TransactionMessage & TransactionMessageWithFeePayer\ \| [`TransactionPlan`](/api/type-aliases/TransactionPlan))\[] | ## Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `divisible`: `boolean`; `kind`: `"sequential"`; `plans`: [`TransactionPlan`](/api/type-aliases/TransactionPlan)\[]; `planType`: `"transactionPlan"`; }> & `object` ## Examples Using explicit [SingleTransactionPlans](/api/type-aliases/SingleTransactionPlan). ```ts const plan = nonDivisibleSequentialTransactionPlan([ singleTransactionPlan(messageA), singleTransactionPlan(messageB), ]); ``` Using [TransactionMessages](/api/type-aliases/TransactionMessage) directly. ```ts const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]); ``` ## See [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) # nonDivisibleSequentialTransactionPlanResult (/api/functions/nonDivisibleSequentialTransactionPlanResult) ```ts function nonDivisibleSequentialTransactionPlanResult( plans, ): Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlanResult< TContext, TransactionMessage & TransactionMessageWithFeePayer, SingleTransactionPlanResult< TContext, TransactionMessage & TransactionMessageWithFeePayer > >[]; planType: 'transactionPlanResult'; }> & object; ``` Creates a non-divisible [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) from an array of nested results. This function creates a sequential result with the `divisible` property set to `false`, indicating that the nested plans were executed sequentially and could not have been split into separate transactions or batches (e.g., they were executed as a transaction bundle). ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | | `plans` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>, [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>>>\[] | The child results that were executed sequentially | ## Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `divisible`: `boolean`; `kind`: `"sequential"`; `plans`: [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>, [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>>>\[]; `planType`: `"transactionPlanResult"`; }> & `object` ## Example ```ts const result = nonDivisibleSequentialTransactionPlanResult([ singleResultA, singleResultB, ]); result satisfies SequentialTransactionPlanResult & { divisible: false }; ``` ## See [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) # none (/api/functions/none) ```ts function none(): Option; ``` Creates a new [Option](/api/type-aliases/Option) that contains no value. This function explicitly represents an absent value. ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------------- | | `T` | The type of the expected absent value. | ## Returns [`Option`](/api/type-aliases/Option)\<`T`> An [Option](/api/type-aliases/Option) containing no value. ## Example Creating an empty `Option`. ```ts const empty = none(); isOption(empty); // true isSome(empty); // false isNone(empty); // true ``` ## See * [Option](/api/type-aliases/Option) * [None](/api/type-aliases/None) # offCurveAddress (/api/functions/offCurveAddress) ```ts function offCurveAddress( putativeOffCurveAddress, ): OffCurveAddress; ``` Combines *asserting* that an [Address](/api/type-aliases/Address) is off-curve with *coercing* it to the [OffCurveAddress](/api/type-aliases/OffCurveAddress) type. It's most useful with untrusted input. ## Type Parameters | Type Parameter | | ----------------------------------------------------------- | | `TAddress` *extends* [`Address`](/api/type-aliases/Address) | ## Parameters | Parameter | Type | | ------------------------- | ---------- | | `putativeOffCurveAddress` | `TAddress` | ## Returns [`OffCurveAddress`](/api/type-aliases/OffCurveAddress)\<`TAddress`> # offchainMessageApplicationDomain (/api/functions/offchainMessageApplicationDomain) ```ts function offchainMessageApplicationDomain( putativeApplicationDomain, ): OffchainMessageApplicationDomain; ``` Combines *asserting* that a string is an offchain message application domain with *coercing* it to the [OffchainMessageApplicationDomain](/api/type-aliases/OffchainMessageApplicationDomain) type. It's most useful with untrusted input. ## Parameters | Parameter | Type | | --------------------------- | -------- | | `putativeApplicationDomain` | `string` | ## Returns [`OffchainMessageApplicationDomain`](/api/type-aliases/OffchainMessageApplicationDomain) ## Example ```ts import { offchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages'; const offchainMessage: OffchainMessageV0 = { applicationDomain: offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'), // ... }; ``` > \[!TIP] > When starting from a known-good application domain as a string, it's more efficient to typecast > it rather than to use the offchainMessageApplicationDomain helper, because the helper > unconditionally performs validation on its input. > > ```ts > import { OffchainMessageApplicationDomain } from '@solana/offchain-messages'; > > const applicationDomain = > 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain; > ``` # offchainMessageContentRestrictedAsciiOf1232BytesMax (/api/functions/offchainMessageContentRestrictedAsciiOf1232BytesMax) ```ts function offchainMessageContentRestrictedAsciiOf1232BytesMax( text, ): OffchainMessageContentRestrictedAsciiOf1232BytesMax; ``` Combines *asserting* that the content of a v0 offchain message is restricted ASCII with *coercing* it to the [OffchainMessageContentRestrictedAsciiOf1232BytesMax](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax) type. It's most useful with untrusted input. ## Type Parameters | Type Parameter | | -------------------------- | | `TText` *extends* `string` | ## Parameters | Parameter | Type | | --------- | ------- | | `text` | `TText` | ## Returns [`OffchainMessageContentRestrictedAsciiOf1232BytesMax`](/api/type-aliases/OffchainMessageContentRestrictedAsciiOf1232BytesMax)\<`TText`> ## Example ```ts import { offchainMessageContentRestrictedAsciiOf1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages'; function handleSubmit() { // We know only that what the user typed conforms to the `string` type. const text: string = textInput.value; try { const offchainMessage: OffchainMessageV0 = { content: offchainMessageContentRestrictedAsciiOf1232BytesMax(text), // ... }; } catch (e) { // `text` turned out not to conform to // `OffchainMessageContentRestrictedAsciiOf1232BytesMax` } } ``` > \[!TIP] > When starting from known-good ASCII content as a string, it's more efficient to typecast it > rather than to use the offchainMessageContentRestrictedAsciiOf1232BytesMax helper, > because the helper unconditionally performs validation on its input. > > ```ts > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages'; > > const offchainMessage: OffchainMessageV0 = { > /* ... */ > content: Object.freeze({ > format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX, > text: 'Hello world', > } as OffchainMessageContentRestrictedAsciiOf1232BytesMax<'Hello world'>), > }; > ``` # offchainMessageContentUtf8Of1232BytesMax (/api/functions/offchainMessageContentUtf8Of1232BytesMax) ```ts function offchainMessageContentUtf8Of1232BytesMax( text, ): OffchainMessageContentUtf8Of1232BytesMax; ``` Combines *asserting* that the content of a v0 offchain message is UTF-8 of up to 1232 characters with *coercing* it to the [OffchainMessageContentUtf8Of1232BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of1232BytesMax) type. It's most useful with untrusted input. ## Type Parameters | Type Parameter | | -------------------------- | | `TText` *extends* `string` | ## Parameters | Parameter | Type | | --------- | ------- | | `text` | `TText` | ## Returns [`OffchainMessageContentUtf8Of1232BytesMax`](/api/type-aliases/OffchainMessageContentUtf8Of1232BytesMax)\<`TText`> ## Example ```ts import { OffchainMessageContentUtf8Of1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages'; function handleSubmit() { // We know only that what the user typed conforms to the `string` type. const text: string = textInput.value; try { const offchainMessage: OffchainMessageV0 = { content: OffchainMessageContentUtf8Of1232BytesMax(text), // ... }; } catch (e) { // `text` turned out not to conform to // `OffchainMessageContentUtf8Of1232BytesMax` } } ``` > \[!TIP] > When starting from known-good UTF-8 content as a string up to 1232 bytes, it's more efficient > to typecast it rather than to use the offchainMessageContentUtf8Of1232BytesMax helper, > because the helper unconditionally performs validation on its input. > > ```ts > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages'; > > const offchainMessage: OffchainMessageV0 = { > /* ... */ > content: Object.freeze({ > format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX, > text: '✌🏿cool', > } as OffchainMessageContentUtf8Of1232BytesMax<'✌🏿cool'>), > }; > ``` # offchainMessageContentUtf8Of65535BytesMax (/api/functions/offchainMessageContentUtf8Of65535BytesMax) ```ts function offchainMessageContentUtf8Of65535BytesMax( text, ): OffchainMessageContentUtf8Of65535BytesMax; ``` Combines *asserting* that the content of a v0 offchain message is UTF-8 of up to 65535 characters with *coercing* it to the [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) type. It's most useful with untrusted input. ## Type Parameters | Type Parameter | | -------------------------- | | `TText` *extends* `string` | ## Parameters | Parameter | Type | | --------- | ------- | | `text` | `TText` | ## Returns [`OffchainMessageContentUtf8Of65535BytesMax`](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax)\<`TText`> ## Example ```ts import { OffchainMessageContentUtf8Of65535BytesMax, OffchainMessageV0 } from '@solana/offchain-messages'; function handleSubmit() { // We know only that what the user typed conforms to the `string` type. const text: string = textInput.value; try { const offchainMessage: OffchainMessageV0 = { content: OffchainMessageContentUtf8Of65535BytesMax(text), // ... }; } catch (e) { // `text` turned out not to conform to // `OffchainMessageContentUtf8Of65535BytesMax` } } ``` > \[!TIP] > When starting from known-good UTF-8 content as a string up to 65535 bytes, it's more efficient > to typecast it rather than to use the [OffchainMessageContentUtf8Of65535BytesMax](/api/type-aliases/OffchainMessageContentUtf8Of65535BytesMax) helper, > because the helper unconditionally performs validation on its input. > > ```ts > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages'; > > const offchainMessage: OffchainMessageV0 = { > /* ... */ > content: Object.freeze({ > format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX, > text: '✌🏿cool', > } as OffchainMessageContentUtf8Of65535BytesMax<'✌🏿cool'>), > }; > ``` # offsetCodec (/api/functions/offsetCodec) ```ts function offsetCodec(codec, config): TCodec; ``` Moves the offset of a given codec before and/or after encoding and decoding. This function allows a codec to encode and decode values at custom offsets within a byte array. It modifies both the **pre-offset** (where encoding/decoding starts) and the **post-offset** (where the next operation should continue). This is particularly useful when working with structured binary formats that require skipping reserved bytes, inserting padding, or aligning fields at specific locations. ## Type Parameters | Type Parameter | | ----------------------------- | | `TCodec` *extends* `AnyCodec` | ## Parameters | Parameter | Type | Description | | --------- | -------------- | ------------------------------------------------------- | | `codec` | `TCodec` | The codec to adjust. | | `config` | `OffsetConfig` | An object specifying how the offset should be modified. | ## Returns `TCodec` A new codec with adjusted offsets. ## Examples Moving the pre-offset forward by 2 bytes when encoding and decoding. ```ts const codec = offsetCodec(getU32Codec(), { preOffset: ({ preOffset }) => preOffset + 2, }); const bytes = new Uint8Array(10); codec.write(42, bytes, 0); // Actually written at offset 2 codec.read(bytes, 0); // Actually read from offset 2 ``` Moving the post-offset forward by 2 bytes when encoding and decoding. ```ts const codec = offsetCodec(getU32Codec(), { postOffset: ({ postOffset }) => postOffset + 2, }); const bytes = new Uint8Array(10); codec.write(42, bytes, 0); // Next encoding starts at offset 6 instead of 4 codec.read(bytes, 0); // Next decoding starts at offset 6 instead of 4 ``` Using `wrapBytes` to loop around negative offsets. ```ts const codec = offsetCodec(getU32Codec(), { preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes }); const bytes = new Uint8Array(10); codec.write(42, bytes, 0); // Writes at bytes.length - 4 codec.read(bytes, 0); // Reads from bytes.length - 4 ``` ## Remarks If you only need to adjust offsets for encoding, use [offsetEncoder](/api/functions/offsetEncoder). If you only need to adjust offsets for decoding, use [offsetDecoder](/api/functions/offsetDecoder). ```ts const bytes = new Uint8Array(10); offsetEncoder(getU32Encoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).write(42, bytes, 0); const [value] = offsetDecoder(getU32Decoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).read(bytes, 0); ``` ## See * [offsetEncoder](/api/functions/offsetEncoder) * [offsetDecoder](/api/functions/offsetDecoder) # offsetDecoder (/api/functions/offsetDecoder) ```ts function offsetDecoder(decoder, config): TDecoder; ``` Moves the offset of a given decoder before and/or after decoding. This function allows a decoder to read its input from a different offset than the one originally provided. It supports both pre-offset adjustments (before decoding) and post-offset adjustments (after decoding). The pre-offset function determines where decoding should start, while the post-offset function adjusts where the next decoder should continue reading. For more details, see [offsetCodec](/api/functions/offsetCodec). ## Type Parameters | Type Parameter | | --------------------------------- | | `TDecoder` *extends* `AnyDecoder` | ## Parameters | Parameter | Type | Description | | --------- | -------------- | ------------------------------------------------------- | | `decoder` | `TDecoder` | The decoder to adjust. | | `config` | `OffsetConfig` | An object specifying how the offset should be modified. | ## Returns `TDecoder` A new decoder with adjusted offsets. ## Examples Moving the pre-offset forward by 2 bytes. ```ts const decoder = offsetDecoder(getU32Decoder(), { preOffset: ({ preOffset }) => preOffset + 2, }); const bytes = new Uint8Array([0, 0, 42, 0]); // Value starts at offset 2 decoder.read(bytes, 0); // Actually reads from offset 2 ``` Moving the post-offset forward by 2 bytes. ```ts const decoder = offsetDecoder(getU32Decoder(), { postOffset: ({ postOffset }) => postOffset + 2, }); const bytes = new Uint8Array([42, 0, 0, 0]); const [value, nextOffset] = decoder.read(bytes, 0); // Next decoder starts at offset 6 instead of 4 ``` Using `wrapBytes` to read from the last 4 bytes of an array. ```ts const decoder = offsetDecoder(getU32Decoder(), { preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array }); const bytes = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 42]); // Value stored at the last 4 bytes decoder.read(bytes, 0); // Reads from bytes.length - 4 ``` ## Remarks If you need both encoding and decoding offsets to be adjusted, use [offsetCodec](/api/functions/offsetCodec). ## See * [offsetCodec](/api/functions/offsetCodec) * [offsetEncoder](/api/functions/offsetEncoder) # offsetEncoder (/api/functions/offsetEncoder) ```ts function offsetEncoder(encoder, config): TEncoder; ``` Moves the offset of a given encoder before and/or after encoding. This function allows an encoder to write its encoded value at a different offset than the one originally provided. It supports both pre-offset adjustments (before encoding) and post-offset adjustments (after encoding). The pre-offset function determines where encoding should start, while the post-offset function adjusts where the next encoder should continue writing. For more details, see [offsetCodec](/api/functions/offsetCodec). ## Type Parameters | Type Parameter | | --------------------------------- | | `TEncoder` *extends* `AnyEncoder` | ## Parameters | Parameter | Type | Description | | --------- | -------------- | ------------------------------------------------------- | | `encoder` | `TEncoder` | The encoder to adjust. | | `config` | `OffsetConfig` | An object specifying how the offset should be modified. | ## Returns `TEncoder` A new encoder with adjusted offsets. ## Examples Moving the pre-offset forward by 2 bytes. ```ts const encoder = offsetEncoder(getU32Encoder(), { preOffset: ({ preOffset }) => preOffset + 2, }); const bytes = new Uint8Array(10); encoder.write(42, bytes, 0); // Actually written at offset 2 ``` Moving the post-offset forward by 2 bytes. ```ts const encoder = offsetEncoder(getU32Encoder(), { postOffset: ({ postOffset }) => postOffset + 2, }); const bytes = new Uint8Array(10); const nextOffset = encoder.write(42, bytes, 0); // Next encoder starts at offset 6 instead of 4 ``` Using `wrapBytes` to ensure an offset wraps around the byte array length. ```ts const encoder = offsetEncoder(getU32Encoder(), { preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array }); const bytes = new Uint8Array(10); encoder.write(42, bytes, 0); // Writes at bytes.length - 4 ``` ## Remarks If you need both encoding and decoding offsets to be adjusted, use [offsetCodec](/api/functions/offsetCodec). ## See * [offsetCodec](/api/functions/offsetCodec) * [offsetDecoder](/api/functions/offsetDecoder) # padBytes (/api/functions/padBytes) ## Call Signature ```ts function padBytes(bytes, length): Uint8Array; ``` Pads a `Uint8Array` with zeroes to the specified length. If the array is longer than the specified length, it is returned as-is. ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------- | | `bytes` | [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | The byte array to pad. | | `length` | `number` | The desired length of the byte array. | ### Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) ### Examples Adds zeroes to the end of the byte array to reach the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02]); const paddedBytes = padBytes(bytes, 4); // ^ [0x01, 0x02, 0x00, 0x00] ``` Returns the original byte array if it is already at the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02]); const paddedBytes = padBytes(bytes, 2); // bytes === paddedBytes ``` ## Call Signature ```ts function padBytes(bytes, length): ReadonlyUint8Array; ``` Pads a `Uint8Array` with zeroes to the specified length. If the array is longer than the specified length, it is returned as-is. ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ------------------------------------- | | `bytes` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | The byte array to pad. | | `length` | `number` | The desired length of the byte array. | ### Returns [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) ### Examples Adds zeroes to the end of the byte array to reach the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02]); const paddedBytes = padBytes(bytes, 4); // ^ [0x01, 0x02, 0x00, 0x00] ``` Returns the original byte array if it is already at the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02]); const paddedBytes = padBytes(bytes, 2); // bytes === paddedBytes ``` # padLeftCodec (/api/functions/padLeftCodec) ```ts function padLeftCodec(codec, offset): TCodec; ``` Adds left padding to the given codec, shifting the encoding and decoding positions forward by `offset` bytes whilst increasing the size of the codec accordingly. This ensures that values are read and written at a later position in the byte array, while the padding bytes remain unused. ## Type Parameters | Type Parameter | | ----------------------------- | | `TCodec` *extends* `AnyCodec` | ## Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------------------------------------------------- | | `codec` | `TCodec` | The codec to pad. | | `offset` | `number` | The number of padding bytes to add before encoding and decoding. | ## Returns `TCodec` A new codec with left padding applied. ## Example ```ts const codec = padLeftCodec(getU16Codec(), 2); const bytes = codec.encode(0xffff); // 0x0000ffff (0xffff written at offset 2) const value = codec.decode(bytes); // 0xffff (reads from offset 2) ``` ## Remarks If you only need to apply padding for encoding, use [padLeftEncoder](/api/functions/padLeftEncoder). If you only need to apply padding for decoding, use [padLeftDecoder](/api/functions/padLeftDecoder). ```ts const bytes = padLeftEncoder(getU16Encoder(), 2).encode(0xffff); const value = padLeftDecoder(getU16Decoder(), 2).decode(bytes); ``` ## See * [padLeftEncoder](/api/functions/padLeftEncoder) * [padLeftDecoder](/api/functions/padLeftDecoder) # padLeftDecoder (/api/functions/padLeftDecoder) ```ts function padLeftDecoder(decoder, offset): TDecoder; ``` Adds left padding to the given decoder, shifting the decoding position forward by `offset` bytes whilst increasing the size of the decoder accordingly. For more details, see [padLeftCodec](/api/functions/padLeftCodec). ## Type Parameters | Type Parameter | | --------------------------------- | | `TDecoder` *extends* `AnyDecoder` | ## Parameters | Parameter | Type | Description | | --------- | ---------- | ---------------------------------------------------- | | `decoder` | `TDecoder` | The decoder to pad. | | `offset` | `number` | The number of padding bytes to skip before decoding. | ## Returns `TDecoder` A new decoder with left padding applied. ## Example ```ts const decoder = padLeftDecoder(getU16Decoder(), 2); const value = decoder.decode(new Uint8Array([0, 0, 0x12, 0x34])); // 0xffff (reads from offset 2) ``` ## See * [padLeftCodec](/api/functions/padLeftCodec) * [padLeftEncoder](/api/functions/padLeftEncoder) # padLeftEncoder (/api/functions/padLeftEncoder) ```ts function padLeftEncoder(encoder, offset): TEncoder; ``` Adds left padding to the given encoder, shifting the encoded value forward by `offset` bytes whilst increasing the size of the encoder accordingly. For more details, see [padLeftCodec](/api/functions/padLeftCodec). ## Type Parameters | Type Parameter | | --------------------------------- | | `TEncoder` *extends* `AnyEncoder` | ## Parameters | Parameter | Type | Description | | --------- | ---------- | --------------------------------------------------- | | `encoder` | `TEncoder` | The encoder to pad. | | `offset` | `number` | The number of padding bytes to add before encoding. | ## Returns `TEncoder` A new encoder with left padding applied. ## Example ```ts const encoder = padLeftEncoder(getU16Encoder(), 2); const bytes = encoder.encode(0xffff); // 0x0000ffff (0xffff written at offset 2) ``` ## See * [padLeftCodec](/api/functions/padLeftCodec) * [padLeftDecoder](/api/functions/padLeftDecoder) # padNullCharacters (/api/functions/padNullCharacters) ```ts function padNullCharacters(value, chars): string; ``` Pads a string with null characters (`\u0000`) at the end to reach a fixed length. If the input string is shorter than the specified length, it is padded with null characters until it reaches the desired size. If it is already long enough, it remains unchanged. ## Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------ | | `value` | `string` | The string to pad. | | `chars` | `number` | The total length of the resulting string, including padding. | ## Returns `string` The input string padded with null characters up to the specified length. ## Example Padding a string with null characters. ```ts padNullCharacters('hello', 8); // "hello\u0000\u0000\u0000" ``` # padRightCodec (/api/functions/padRightCodec) ```ts function padRightCodec(codec, offset): TCodec; ``` Adds right padding to the given codec, extending the encoded and decoded value by `offset` bytes whilst increasing the size of the codec accordingly. The extra bytes remain unused, ensuring that the next operation starts further along the byte array. ## Type Parameters | Type Parameter | | ----------------------------- | | `TCodec` *extends* `AnyCodec` | ## Parameters | Parameter | Type | Description | | --------- | -------- | --------------------------------------------------------------- | | `codec` | `TCodec` | The codec to pad. | | `offset` | `number` | The number of padding bytes to add after encoding and decoding. | ## Returns `TCodec` A new codec with right padding applied. ## Example ```ts const codec = padRightCodec(getU16Codec(), 2); const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added) const value = codec.decode(bytes); // 0xffff (ignores padding bytes) ``` ## Remarks If you only need to apply padding for encoding, use [padRightEncoder](/api/functions/padRightEncoder). If you only need to apply padding for decoding, use [padRightDecoder](/api/functions/padRightDecoder). ```ts const bytes = padRightEncoder(getU16Encoder(), 2).encode(0xffff); const value = padRightDecoder(getU16Decoder(), 2).decode(bytes); ``` ## See * [padRightEncoder](/api/functions/padRightEncoder) * [padRightDecoder](/api/functions/padRightDecoder) # padRightDecoder (/api/functions/padRightDecoder) ```ts function padRightDecoder(decoder, offset): TDecoder; ``` Adds right padding to the given decoder, extending the post-offset by `offset` bytes whilst increasing the size of the decoder accordingly. For more details, see [padRightCodec](/api/functions/padRightCodec). ## Type Parameters | Type Parameter | | --------------------------------- | | `TDecoder` *extends* `AnyDecoder` | ## Parameters | Parameter | Type | Description | | --------- | ---------- | --------------------------------------------------- | | `decoder` | `TDecoder` | The decoder to pad. | | `offset` | `number` | The number of padding bytes to skip after decoding. | ## Returns `TDecoder` A new decoder with right padding applied. ## Example ```ts const decoder = padRightDecoder(getU16Decoder(), 2); const value = decoder.decode(new Uint8Array([0x12, 0x34, 0, 0])); // 0xffff (ignores trailing bytes) ``` ## See * [padRightCodec](/api/functions/padRightCodec) * [padRightEncoder](/api/functions/padRightEncoder) # padRightEncoder (/api/functions/padRightEncoder) ```ts function padRightEncoder(encoder, offset): TEncoder; ``` Adds right padding to the given encoder, extending the encoded value by `offset` bytes whilst increasing the size of the encoder accordingly. For more details, see [padRightCodec](/api/functions/padRightCodec). ## Type Parameters | Type Parameter | | --------------------------------- | | `TEncoder` *extends* `AnyEncoder` | ## Parameters | Parameter | Type | Description | | --------- | ---------- | -------------------------------------------------- | | `encoder` | `TEncoder` | The encoder to pad. | | `offset` | `number` | The number of padding bytes to add after encoding. | ## Returns `TEncoder` A new encoder with right padding applied. ## Example ```ts const encoder = padRightEncoder(getU16Encoder(), 2); const bytes = encoder.encode(0xffff); // 0xffff0000 (two extra bytes added at the end) ``` ## See * [padRightCodec](/api/functions/padRightCodec) * [padRightDecoder](/api/functions/padRightDecoder) # parallelInstructionPlan (/api/functions/parallelInstructionPlan) ```ts function parallelInstructionPlan(plans): ParallelInstructionPlan; ``` Creates a [ParallelInstructionPlan](/api/type-aliases/ParallelInstructionPlan) from an array of nested plans. It can accept [Instruction](/api/interfaces/Instruction) objects directly, which will be wrapped in [SingleInstructionPlans](/api/type-aliases/SingleInstructionPlan) automatically. ## Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `plans` | ( \| [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> \| [`InstructionPlan`](/api/type-aliases/InstructionPlan))\[] | ## Returns [`ParallelInstructionPlan`](/api/type-aliases/ParallelInstructionPlan) ## Examples **Using explicit \{@link SingleInstructionPlan | SingleInstructionPlans}.** ```ts const plan = parallelInstructionPlan([ singleInstructionPlan(instructionA), singleInstructionPlan(instructionB), ]); ``` **Using \{@link Instruction | Instructions} directly.** ```ts const plan = parallelInstructionPlan([instructionA, instructionB]); ``` ## See [ParallelInstructionPlan](/api/type-aliases/ParallelInstructionPlan) # parallelTransactionPlan (/api/functions/parallelTransactionPlan) ```ts function parallelTransactionPlan(plans): ParallelTransactionPlan; ``` Creates a [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan) from an array of nested plans. It can accept [TransactionMessage](/api/type-aliases/TransactionMessage) objects directly, which will be wrapped in [SingleTransactionPlans](/api/type-aliases/SingleTransactionPlan) automatically. ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------- | | `plans` | ( \| TransactionMessage & TransactionMessageWithFeePayer\ \| [`TransactionPlan`](/api/type-aliases/TransactionPlan))\[] | ## Returns [`ParallelTransactionPlan`](/api/type-aliases/ParallelTransactionPlan) ## Examples Using explicit [SingleTransactionPlans](/api/type-aliases/SingleTransactionPlan). ```ts const plan = parallelTransactionPlan([ singleTransactionPlan(messageA), singleTransactionPlan(messageB), ]); ``` Using [TransactionMessages](/api/type-aliases/TransactionMessage) directly. ```ts const plan = parallelTransactionPlan([messageA, messageB]); ``` ## See [ParallelTransactionPlan](/api/type-aliases/ParallelTransactionPlan) # parallelTransactionPlanResult (/api/functions/parallelTransactionPlanResult) ```ts function parallelTransactionPlanResult( plans, ): ParallelTransactionPlanResult; ``` Creates a [ParallelTransactionPlanResult](/api/type-aliases/ParallelTransactionPlanResult) from an array of nested results. This function creates a parallel result indicating that the nested plans were executed in parallel. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | | `plans` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>, [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>>>\[] | The child results that were executed in parallel | ## Returns [`ParallelTransactionPlanResult`](/api/type-aliases/ParallelTransactionPlanResult)\<`TContext`> ## Example ```ts const result = parallelTransactionPlanResult([ singleResultA, singleResultB, ]); result satisfies ParallelTransactionPlanResult; ``` ## See [ParallelTransactionPlanResult](/api/type-aliases/ParallelTransactionPlanResult) # parseBase58RpcAccount (/api/functions/parseBase58RpcAccount) ## Call Signature ```ts function parseBase58RpcAccount( address, rpcAccount, ): EncodedAccount; ``` Parses a base58-encoded account provided by the RPC client into an [EncodedAccount](/api/interfaces/EncodedAccount) type or a [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount) type if the raw data can be set to `null`. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | ------------ | --------------------------------------------------- | | `address` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `rpcAccount` | `Base58EncodedRpcAccount` | ### Returns [`EncodedAccount`](/api/interfaces/EncodedAccount)\<`TAddress`> ### Example ```ts const myAddress = address('1234..5678'); const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base58' }).send(); const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase58RpcAccount(myRpcAccount); ``` ## Call Signature ```ts function parseBase58RpcAccount( address, rpcAccount, ): MaybeEncodedAccount; ``` Parses a base58-encoded account provided by the RPC client into an [EncodedAccount](/api/interfaces/EncodedAccount) type or a [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount) type if the raw data can be set to `null`. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | ------------ | --------------------------------------------------- | | `address` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `rpcAccount` | `Base58EncodedRpcAccount` \| `null` | ### Returns [`MaybeEncodedAccount`](/api/type-aliases/MaybeEncodedAccount)\<`TAddress`> ### Example ```ts const myAddress = address('1234..5678'); const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base58' }).send(); const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase58RpcAccount(myRpcAccount); ``` # parseBase64RpcAccount (/api/functions/parseBase64RpcAccount) ## Call Signature ```ts function parseBase64RpcAccount( address, rpcAccount, ): EncodedAccount; ``` Parses a base64-encoded account provided by the RPC client into an [EncodedAccount](/api/interfaces/EncodedAccount) type or a [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount) type if the raw data can be set to `null`. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | ------------ | --------------------------------------------------- | | `address` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `rpcAccount` | `Base64EncodedRpcAccount` | ### Returns [`EncodedAccount`](/api/interfaces/EncodedAccount)\<`TAddress`> ### Example ```ts const myAddress = address('1234..5678'); const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base64' }).send(); const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase64RpcAccount(myRpcAccount); ``` ## Call Signature ```ts function parseBase64RpcAccount( address, rpcAccount, ): MaybeEncodedAccount; ``` Parses a base64-encoded account provided by the RPC client into an [EncodedAccount](/api/interfaces/EncodedAccount) type or a [MaybeEncodedAccount](/api/type-aliases/MaybeEncodedAccount) type if the raw data can be set to `null`. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | ------------ | --------------------------------------------------- | | `address` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `rpcAccount` | `Base64EncodedRpcAccount` \| `null` | ### Returns [`MaybeEncodedAccount`](/api/type-aliases/MaybeEncodedAccount)\<`TAddress`> ### Example ```ts const myAddress = address('1234..5678'); const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base64' }).send(); const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase64RpcAccount(myRpcAccount); ``` # parseInstructionOrTransactionPlanInput (/api/functions/parseInstructionOrTransactionPlanInput) ```ts function parseInstructionOrTransactionPlanInput( input, ): InstructionPlan | TransactionPlan; ``` Parses an [InstructionPlanInput](/api/type-aliases/InstructionPlanInput) or [TransactionPlanInput](/api/type-aliases/TransactionPlanInput) and returns the appropriate plan type. This function automatically detects whether the input represents instructions or transactions and delegates to the appropriate parser: * If the input is a transaction message or transaction plan, it delegates to [parseTransactionPlanInput](/api/functions/parseTransactionPlanInput). * Otherwise, it delegates to [parseInstructionPlanInput](/api/functions/parseInstructionPlanInput). ## Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | `input` | \| [`InstructionPlanInput`](/api/type-aliases/InstructionPlanInput) \| [`TransactionPlanInput`](/api/type-aliases/TransactionPlanInput) | The input to parse, which can be either an instruction-based or transaction-based input. | ## Returns \| [`InstructionPlan`](/api/type-aliases/InstructionPlan) \| [`TransactionPlan`](/api/type-aliases/TransactionPlan) The parsed plan, either an [InstructionPlan](/api/type-aliases/InstructionPlan) or a [TransactionPlan](/api/type-aliases/TransactionPlan). ## Examples Parsing an instruction input. ```ts const plan = parseInstructionOrTransactionPlanInput(myInstruction); // Returns an InstructionPlan ``` Parsing a transaction message input. ```ts const plan = parseInstructionOrTransactionPlanInput(myTransactionMessage); // Returns a TransactionPlan ``` ## See * [parseInstructionPlanInput](/api/functions/parseInstructionPlanInput) * [parseTransactionPlanInput](/api/functions/parseTransactionPlanInput) * [InstructionPlanInput](/api/type-aliases/InstructionPlanInput) * [TransactionPlanInput](/api/type-aliases/TransactionPlanInput) # parseInstructionPlanInput (/api/functions/parseInstructionPlanInput) ```ts function parseInstructionPlanInput(input): InstructionPlan; ``` Parses an [InstructionPlanInput](/api/type-aliases/InstructionPlanInput) and returns an [InstructionPlan](/api/type-aliases/InstructionPlan). This function handles the following input types: * A single [Instruction](/api/interfaces/Instruction) is wrapped in a [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan). * An existing [InstructionPlan](/api/type-aliases/InstructionPlan) is returned as-is. * An array with a single element is unwrapped and parsed recursively. * An array with multiple elements is wrapped in a divisible [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------- | -------------------------------------------- | | `input` | [`InstructionPlanInput`](/api/type-aliases/InstructionPlanInput) | The input to parse into an instruction plan. | ## Returns [`InstructionPlan`](/api/type-aliases/InstructionPlan) The parsed instruction plan. ## Examples Parsing a single instruction. ```ts const plan = parseInstructionPlanInput(myInstruction); // Equivalent to: singleInstructionPlan(myInstruction) ``` Parsing an array of instructions. ```ts const plan = parseInstructionPlanInput([instructionA, instructionB]); // Equivalent to: sequentialInstructionPlan([instructionA, instructionB]) ``` Parsing a mixed array with nested plans. ```ts const plan = parseInstructionPlanInput([ instructionA, parallelInstructionPlan([instructionB, instructionC]), ]); // Returns a sequential plan containing: // - A single instruction plan for instructionA. // - The parallel plan for instructionB and instructionC. ``` Single-element arrays are unwrapped. ```ts const plan = parseInstructionPlanInput([myInstruction]); // Equivalent to: singleInstructionPlan(myInstruction) ``` ## See * [InstructionPlanInput](/api/type-aliases/InstructionPlanInput) * [InstructionPlan](/api/type-aliases/InstructionPlan) # parseJsonRpcAccount (/api/functions/parseJsonRpcAccount) ## Call Signature ```ts function parseJsonRpcAccount( address, rpcAccount, ): Account, TAddress>; ``` Parses an arbitrary `jsonParsed` account provided by the RPC client into an [Account](/api/interfaces/Account) type or a [MaybeAccount](/api/type-aliases/MaybeAccount) type if the raw data can be set to `null`. The expected data type should be explicitly provided as the first type parameter. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TData` *extends* `object` | - | The expected type of this account's data. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | ------------ | --------------------------------------------------- | | `address` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `rpcAccount` | `JsonParsedRpcAccount` | ### Returns [`Account`](/api/interfaces/Account)\<`JsonParsedAccountData`\<`TData`>, `TAddress`> ### Example ```ts const myAccount: Account = parseJsonRpcAccount(myJsonRpcAccount); ``` ## Call Signature ```ts function parseJsonRpcAccount( address, rpcAccount, ): MaybeAccount, TAddress>; ``` Parses an arbitrary `jsonParsed` account provided by the RPC client into an [Account](/api/interfaces/Account) type or a [MaybeAccount](/api/type-aliases/MaybeAccount) type if the raw data can be set to `null`. The expected data type should be explicitly provided as the first type parameter. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------- | ------------ | ------------------------------------------------------------------------- | | `TData` *extends* `object` | - | The expected type of this account's data. | | `TAddress` *extends* `string` | `string` | Supply a string literal to define an account having a particular address. | ### Parameters | Parameter | Type | | ------------ | --------------------------------------------------- | | `address` | [`Address`](/api/type-aliases/Address)\<`TAddress`> | | `rpcAccount` | `JsonParsedRpcAccount` \| `null` | ### Returns [`MaybeAccount`](/api/type-aliases/MaybeAccount)\<`JsonParsedAccountData`\<`TData`>, `TAddress`> ### Example ```ts const myAccount: Account = parseJsonRpcAccount(myJsonRpcAccount); ``` # parseJsonWithBigInts (/api/functions/parseJsonWithBigInts) ```ts function parseJsonWithBigInts(json): unknown; ``` This function is a replacement for `JSON.parse` that can handle large unsafe integers by parsing them as BigInts. It transforms every numerical value into a BigInt without loss of precision. ## Parameters | Parameter | Type | | --------- | -------- | | `json` | `string` | ## Returns `unknown` # parseTransactionPlanInput (/api/functions/parseTransactionPlanInput) ```ts function parseTransactionPlanInput(input): TransactionPlan; ``` Parses a [TransactionPlanInput](/api/type-aliases/TransactionPlanInput) and returns a [TransactionPlan](/api/type-aliases/TransactionPlan). This function handles the following input types: * A single [TransactionMessage](/api/type-aliases/TransactionMessage) is wrapped in a [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan). * An existing [TransactionPlan](/api/type-aliases/TransactionPlan) is returned as-is. * An array with a single element is unwrapped and parsed recursively. * An array with multiple elements is wrapped in a divisible [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------- | ------------------------------------------- | | `input` | [`TransactionPlanInput`](/api/type-aliases/TransactionPlanInput) | The input to parse into a transaction plan. | ## Returns [`TransactionPlan`](/api/type-aliases/TransactionPlan) The parsed transaction plan. ## Examples Parsing a single transaction message. ```ts const plan = parseTransactionPlanInput(myTransactionMessage); // Equivalent to: singleTransactionPlan(myTransactionMessage) ``` Parsing an array of transaction messages. ```ts const plan = parseTransactionPlanInput([messageA, messageB]); // Equivalent to: sequentialTransactionPlan([messageA, messageB]) ``` Parsing a mixed array with nested plans. ```ts const plan = parseTransactionPlanInput([ messageA, parallelTransactionPlan([messageB, messageC]), ]); // Returns a sequential plan containing: // - A single transaction plan for messageA. // - The parallel plan for messageB and messageC. ``` Single-element arrays are unwrapped. ```ts const plan = parseTransactionPlanInput([myTransactionMessage]); // Equivalent to: singleTransactionPlan(myTransactionMessage) ``` ## See * [TransactionPlanInput](/api/type-aliases/TransactionPlanInput) * [TransactionPlan](/api/type-aliases/TransactionPlan) # partiallySignOffchainMessageEnvelope (/api/functions/partiallySignOffchainMessageEnvelope) ```ts function partiallySignOffchainMessageEnvelope( keyPairs, offchainMessageEnvelope, ): Promise; ``` Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are required to sign an offchain message, this method will return a new signed offchain message envelope of type [OffchainMessageEnvelope](/api/interfaces/OffchainMessageEnvelope). Though the resulting message might be signed by all required signers, this function will not assert that it is. A partially signed message is not complete, but can be serialized and deserialized. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------------------------------- | | `TOffchainMessageEnvelope` *extends* [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope) | ## Parameters | Parameter | Type | | ------------------------- | -------------------------- | | `keyPairs` | `CryptoKeyPair`\[] | | `offchainMessageEnvelope` | `TOffchainMessageEnvelope` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TOffchainMessageEnvelope`> ## Example ```ts import { generateKeyPair } from '@solana/keys'; import { partiallySignOffchainMessageEnvelope } from '@solana/offchain-messages'; const partiallySignedOffchainMessage = await partiallySignOffchainMessageEnvelope( [myPrivateKey], offchainMessageEnvelope, ); ``` ## See [signOffchainMessageEnvelope](/api/functions/signOffchainMessageEnvelope) if you want to assert that the message is signed by all its required signers after signing. # partiallySignOffchainMessageWithSigners (/api/functions/partiallySignOffchainMessageWithSigners) ```ts function partiallySignOffchainMessageWithSigners( offchainMessage, config?, ): Promise; ``` Extracts all [MessageSigners](/api/type-aliases/MessageSigner) inside the provided offchain message and uses them to return a signed offchain message envelope. It first uses all [MessageModifyingSigners](/api/type-aliases/MessageModifyingSigner) sequentially before using all [MessagePartialSigners](/api/type-aliases/MessagePartialSigner) in parallel. If a composite signer implements both interfaces, it will be used as a [MessageModifyingSigner](/api/type-aliases/MessageModifyingSigner) if no other signer implements that interface. Otherwise, it will be used as a [MessagePartialSigner](/api/type-aliases/MessagePartialSigner). ## Parameters | Parameter | Type | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `offchainMessage` | `OffchainMessageWithRequiredSignatories`\< \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; }> \| [`OffchainMessageSignatorySigner`](/api/type-aliases/OffchainMessageSignatorySigner)> & [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`OffchainMessage`, `"requiredSignatories"`> | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `abortSignal?`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); }> | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`OffchainMessageEnvelope`> ## Example ```ts const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage); ``` It also accepts an optional [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal) that will be propagated to all signers. ```ts const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, { abortSignal: myAbortController.signal, }); ``` ## See [signOffchainMessageWithSigners](/api/functions/signOffchainMessageWithSigners) # partiallySignTransaction (/api/functions/partiallySignTransaction) ```ts function partiallySignTransaction( keyPairs, transaction, ): Promise; ``` Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are required to sign a transaction, this method will return a new signed transaction of type [Transaction](/api/type-aliases/Transaction). Though the resulting transaction might have every signature it needs to land on the network, this function will not assert that it does. A partially signed transaction cannot be landed on the network, but can be serialized and deserialized. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TTransaction` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> | ## Parameters | Parameter | Type | | ------------- | ------------------ | | `keyPairs` | `CryptoKeyPair`\[] | | `transaction` | `TTransaction` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TTransaction`> ## Example ```ts import { generateKeyPair } from '@solana/keys'; import { partiallySignTransaction } from '@solana/transactions'; const partiallySignedTransaction = await partiallySignTransaction([myPrivateKey], tx); ``` ## See [signTransaction](/api/functions/signTransaction) if you want to assert that the transaction has all of its required signatures after signing. # partiallySignTransactionMessageWithSigners (/api/functions/partiallySignTransactionMessageWithSigners) ```ts function partiallySignTransactionMessageWithSigners( transactionMessage, config?, ): Promise< Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> & TransactionWithinSizeLimit & TransactionWithLifetime >; ``` Extracts all [TransactionSigners](/api/type-aliases/TransactionSigner) inside the provided transaction message and uses them to return a signed transaction. It first uses all [TransactionModifyingSigners](/api/type-aliases/TransactionModifyingSigner) sequentially before using all [TransactionPartialSigners](/api/type-aliases/TransactionPartialSigner) in parallel. If a composite signer implements both interfaces, it will be used as a [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) if no other signer implements that interface. Otherwise, it will be used as a [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner). ## Parameters | Parameter | Type | | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `transactionMessage` | TransactionMessage & TransactionMessageWithFeePayer\ & [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Pick`](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)\< \| [`TransactionMessageWithFeePayerSigner`](/api/interfaces/TransactionMessageWithFeePayerSigner)\<`string`, [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `feePayer`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `modifyAndSignTransactions?`: `undefined`; `signAndSendTransactions?`: `undefined`; `signTransactions?`: `undefined`; }>; }>, `"feePayer"`>> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `instructions`: readonly `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]> & [`InstructionWithSigners`](/api/interfaces/InstructionWithSigners)\<[`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>, readonly `AccountMetaWithSigner`\<[`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>>\[]>\[]; }> | | `config?` | [`BaseTransactionSignerConfig`](/api/interfaces/BaseTransactionSignerConfig) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: `TransactionMessageBytes`; `signatures`: `SignaturesMap`; }> & `TransactionWithinSizeLimit` & `TransactionWithLifetime`> ## Example ```ts const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage); ``` It also accepts an optional [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal) that will be propagated to all signers. ```ts const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, { abortSignal: myAbortController.signal, }); ``` ## Remarks Finally, note that this function ignores [TransactionSendingSigners](/api/type-aliases/TransactionSendingSigner) as it does not send the transaction. Check out the [signAndSendTransactionMessageWithSigners](/api/functions/signAndSendTransactionMessageWithSigners) function for more details on how to use sending signers. ## See * [partiallySignTransactionWithSigners](/api/functions/partiallySignTransactionWithSigners) * [signTransactionMessageWithSigners](/api/functions/signTransactionMessageWithSigners) * [signAndSendTransactionMessageWithSigners](/api/functions/signAndSendTransactionMessageWithSigners) # partiallySignTransactionWithSigners (/api/functions/partiallySignTransactionWithSigners) ```ts function partiallySignTransactionWithSigners( signers, transaction, config?, ): Promise< Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> & TransactionWithinSizeLimit & TransactionWithLifetime >; ``` Signs a transaction using the provided [TransactionModifyingSigners](/api/type-aliases/TransactionModifyingSigner) and [TransactionPartialSigners](/api/type-aliases/TransactionPartialSigner). It first uses all [TransactionModifyingSigners](/api/type-aliases/TransactionModifyingSigner) sequentially before using all [TransactionPartialSigners](/api/type-aliases/TransactionPartialSigner) in parallel. If a composite signer implements both interfaces, it will be used as a [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) if no other signer implements that interface. Otherwise, it will be used as a [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner). ## Parameters | Parameter | Type | Description | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `signers` | readonly ( \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; `modifyAndSignTransactions`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\ & `TransactionWithinSizeLimit` & `TransactionWithLifetime`\[]>; }> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; `signTransactions`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\>\[]>; }>)\[] | The signers to use. Only [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) and [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner) interfaces are accepted. | | `transaction` | `Transaction` | The compiled transaction to sign. | | `config?` | [`BaseTransactionSignerConfig`](/api/interfaces/BaseTransactionSignerConfig) | Optional configuration including an [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal). | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: `TransactionMessageBytes`; `signatures`: `SignaturesMap`; }> & `TransactionWithinSizeLimit` & `TransactionWithLifetime`> The signed transaction. ## Example ```ts const signedTransaction = await partiallySignTransactionWithSigners(mySigners, compiledTransaction); ``` It also accepts an optional [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal) that will be propagated to all signers. ```ts const signedTransaction = await partiallySignTransactionWithSigners(mySigners, compiledTransaction, { abortSignal: myAbortController.signal, }); ``` ## See * [signTransactionWithSigners](/api/functions/signTransactionWithSigners) * [signAndSendTransactionWithSigners](/api/functions/signAndSendTransactionWithSigners) * [partiallySignTransactionMessageWithSigners](/api/functions/partiallySignTransactionMessageWithSigners) # passthroughFailedTransactionPlanExecution (/api/functions/passthroughFailedTransactionPlanExecution) ## Call Signature ```ts function passthroughFailedTransactionPlanExecution( promise, ): Promise>; ``` Wraps a transaction plan execution promise to return a [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) even on execution failure. When a transaction plan executor throws a [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_FAILED\_TO\_EXECUTE\_TRANSACTION\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN) error, this helper catches it and returns the `TransactionPlanResult` from the error context instead of throwing. This allows us to handle the result of an execution in a single unified way instead of using try/catch and examine the `TransactionPlanResult` in both success and failure cases. Any other errors are re-thrown as normal. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object attached to the results. Any context is accepted, since this helper never reads from it. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | `promise` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`>> | A promise returned by a transaction plan executor. | ### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`>> A promise that resolves to the transaction plan result, even if some transactions failed. ### Example Handling failures using a single result object: ```ts const result = await passthroughFailedTransactionPlanExecution( transactionPlanExecutor(transactionPlan) ); const summary = summarizeTransactionPlanResult(result); if (summary.successful) { console.log('All transactions executed successfully'); } else { console.log(`${summary.successfulTransactions.length} succeeded`); console.log(`${summary.failedTransactions.length} failed`); console.log(`${summary.canceledTransactions.length} canceled`); } ``` ### See * [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) * [createTransactionPlanExecutor](/api/functions/createTransactionPlanExecutor) * [summarizeTransactionPlanResult](/api/functions/summarizeTransactionPlanResult) ## Call Signature ```ts function passthroughFailedTransactionPlanExecution( promise, ): Promise>; ``` Wraps a transaction plan execution promise to return a [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) even on execution failure. When a transaction plan executor throws a [SOLANA\_ERROR\_\_INSTRUCTION\_PLANS\_\_FAILED\_TO\_EXECUTE\_TRANSACTION\_PLAN](/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN) error, this helper catches it and returns the `TransactionPlanResult` from the error context instead of throwing. This allows us to handle the result of an execution in a single unified way instead of using try/catch and examine the `TransactionPlanResult` in both success and failure cases. Any other errors are re-thrown as normal. ### Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object attached to the results. Any context is accepted, since this helper never reads from it. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | `promise` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`>> | A promise returned by a transaction plan executor. | ### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`>> A promise that resolves to the transaction plan result, even if some transactions failed. ### Example Handling failures using a single result object: ```ts const result = await passthroughFailedTransactionPlanExecution( transactionPlanExecutor(transactionPlan) ); const summary = summarizeTransactionPlanResult(result); if (summary.successful) { console.log('All transactions executed successfully'); } else { console.log(`${summary.successfulTransactions.length} succeeded`); console.log(`${summary.failedTransactions.length} failed`); console.log(`${summary.canceledTransactions.length} canceled`); } ``` ### See * [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) * [createTransactionPlanExecutor](/api/functions/createTransactionPlanExecutor) * [summarizeTransactionPlanResult](/api/functions/summarizeTransactionPlanResult) # pipe (/api/functions/pipe) ## Call Signature ```ts function pipe(init): TInitial; ``` A pipeline is a solution that allows you to perform successive transforms of a value using functions. This is useful when building up a transaction message. Until the [pipeline operator](https://github.com/tc39/proposal-pipeline-operator) becomes part of JavaScript you can use this utility to create pipelines. Following common implementations of pipe functions that use TypeScript, this function supports a maximum arity of 10 for type safety. Note you can use nested pipes to extend this limitation, like so: ```ts const myValue = pipe( pipe( 1, (x) => x + 1, (x) => x * 2, (x) => x - 1, ), (y) => y / 3, (y) => y + 1, ); ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | ### Parameters | Parameter | Type | Description | | --------- | ---------- | ----------------- | | `init` | `TInitial` | The initial value | ### Returns `TInitial` The initial value ### See * [https://github.com/ramda/ramda/blob/master/source/pipe.js](https://github.com/ramda/ramda/blob/master/source/pipe.js) * [https://github.com/darky/rocket-pipes/blob/master/index.ts](https://github.com/darky/rocket-pipes/blob/master/index.ts) ### Examples **Basic** ```ts const add = (a, b) => a + b; const add10 = x => add(x, 10); const add100 = x => add(x, 100); const sum = pipe(1, add10, add100); sum === 111; // true ``` **Building a Solana transaction message** ```ts const transferTransactionMessage = pipe( // The result of the first expression... createTransactionMessage({ version: 0 }), // ...gets passed as the sole argument to the next function in the pipeline. tx => setTransactionMessageFeePayer(myAddress, tx), // The return value of that function gets passed to the next... tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), // ...and so on. tx => appendTransactionMessageInstruction(createTransferInstruction(myAddress, toAddress, amountInLamports), tx), ); ``` ## Call Signature ```ts function pipe(init, init_r1): R1; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | ------------------------------------------------------ | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | ### Returns `R1` The return value of the final transform function ## Call Signature ```ts function pipe(init, init_r1, r1_r2): R2; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | | `R2` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | | `r1_r2` | (`r1`) => `R2` | The function with which to transform the return value of the prior function | ### Returns `R2` The return value of the final transform function ## Call Signature ```ts function pipe(init, init_r1, r1_r2, r2_r3): R3; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | | `R2` | | `R3` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | | `r1_r2` | (`r1`) => `R2` | The function with which to transform the return value of the prior function | | `r2_r3` | (`r2`) => `R3` | The function with which to transform the return value of the prior function | ### Returns `R3` The return value of the final transform function ## Call Signature ```ts function pipe( init, init_r1, r1_r2, r2_r3, r3_r4, ): R4; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | | `R2` | | `R3` | | `R4` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | | `r1_r2` | (`r1`) => `R2` | The function with which to transform the return value of the prior function | | `r2_r3` | (`r2`) => `R3` | The function with which to transform the return value of the prior function | | `r3_r4` | (`r3`) => `R4` | The function with which to transform the return value of the prior function | ### Returns `R4` The return value of the final transform function ## Call Signature ```ts function pipe( init, init_r1, r1_r2, r2_r3, r3_r4, r4_r5, ): R5; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | | `R2` | | `R3` | | `R4` | | `R5` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | | `r1_r2` | (`r1`) => `R2` | The function with which to transform the return value of the prior function | | `r2_r3` | (`r2`) => `R3` | The function with which to transform the return value of the prior function | | `r3_r4` | (`r3`) => `R4` | The function with which to transform the return value of the prior function | | `r4_r5` | (`r4`) => `R5` | The function with which to transform the return value of the prior function | ### Returns `R5` The return value of the final transform function ## Call Signature ```ts function pipe( init, init_r1, r1_r2, r2_r3, r3_r4, r4_r5, r5_r6, ): R6; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | | `R2` | | `R3` | | `R4` | | `R5` | | `R6` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | | `r1_r2` | (`r1`) => `R2` | The function with which to transform the return value of the prior function | | `r2_r3` | (`r2`) => `R3` | The function with which to transform the return value of the prior function | | `r3_r4` | (`r3`) => `R4` | The function with which to transform the return value of the prior function | | `r4_r5` | (`r4`) => `R5` | The function with which to transform the return value of the prior function | | `r5_r6` | (`r5`) => `R6` | The function with which to transform the return value of the prior function | ### Returns `R6` The return value of the final transform function ## Call Signature ```ts function pipe( init, init_r1, r1_r2, r2_r3, r3_r4, r4_r5, r5_r6, r6_r7, ): R7; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | | `R2` | | `R3` | | `R4` | | `R5` | | `R6` | | `R7` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | | `r1_r2` | (`r1`) => `R2` | The function with which to transform the return value of the prior function | | `r2_r3` | (`r2`) => `R3` | The function with which to transform the return value of the prior function | | `r3_r4` | (`r3`) => `R4` | The function with which to transform the return value of the prior function | | `r4_r5` | (`r4`) => `R5` | The function with which to transform the return value of the prior function | | `r5_r6` | (`r5`) => `R6` | The function with which to transform the return value of the prior function | | `r6_r7` | (`r6`) => `R7` | The function with which to transform the return value of the prior function | ### Returns `R7` The return value of the final transform function ## Call Signature ```ts function pipe( init, init_r1, r1_r2, r2_r3, r3_r4, r4_r5, r5_r6, r6_r7, r7_r8, ): R8; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | | `R2` | | `R3` | | `R4` | | `R5` | | `R6` | | `R7` | | `R8` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | | `r1_r2` | (`r1`) => `R2` | The function with which to transform the return value of the prior function | | `r2_r3` | (`r2`) => `R3` | The function with which to transform the return value of the prior function | | `r3_r4` | (`r3`) => `R4` | The function with which to transform the return value of the prior function | | `r4_r5` | (`r4`) => `R5` | The function with which to transform the return value of the prior function | | `r5_r6` | (`r5`) => `R6` | The function with which to transform the return value of the prior function | | `r6_r7` | (`r6`) => `R7` | The function with which to transform the return value of the prior function | | `r7_r8` | (`r7`) => `R8` | The function with which to transform the return value of the prior function | ### Returns `R8` The return value of the final transform function ## Call Signature ```ts function pipe( init, init_r1, r1_r2, r2_r3, r3_r4, r4_r5, r5_r6, r6_r7, r7_r8, r8_r9, ): R9; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | | `R2` | | `R3` | | `R4` | | `R5` | | `R6` | | `R7` | | `R8` | | `R9` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | | `r1_r2` | (`r1`) => `R2` | The function with which to transform the return value of the prior function | | `r2_r3` | (`r2`) => `R3` | The function with which to transform the return value of the prior function | | `r3_r4` | (`r3`) => `R4` | The function with which to transform the return value of the prior function | | `r4_r5` | (`r4`) => `R5` | The function with which to transform the return value of the prior function | | `r5_r6` | (`r5`) => `R6` | The function with which to transform the return value of the prior function | | `r6_r7` | (`r6`) => `R7` | The function with which to transform the return value of the prior function | | `r7_r8` | (`r7`) => `R8` | The function with which to transform the return value of the prior function | | `r8_r9` | (`r8`) => `R9` | The function with which to transform the return value of the prior function | ### Returns `R9` The return value of the final transform function ## Call Signature ```ts function pipe( init, init_r1, r1_r2, r2_r3, r3_r4, r4_r5, r5_r6, r6_r7, r7_r8, r8_r9, r9_r10, ): R10; ``` ### Type Parameters | Type Parameter | | -------------- | | `TInitial` | | `R1` | | `R2` | | `R3` | | `R4` | | `R5` | | `R6` | | `R7` | | `R8` | | `R9` | | `R10` | ### Parameters | Parameter | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `init` | `TInitial` | The initial value | | `init_r1` | (`init`) => `R1` | The function with which to transform the initial value | | `r1_r2` | (`r1`) => `R2` | The function with which to transform the return value of the prior function | | `r2_r3` | (`r2`) => `R3` | The function with which to transform the return value of the prior function | | `r3_r4` | (`r3`) => `R4` | The function with which to transform the return value of the prior function | | `r4_r5` | (`r4`) => `R5` | The function with which to transform the return value of the prior function | | `r5_r6` | (`r5`) => `R6` | The function with which to transform the return value of the prior function | | `r6_r7` | (`r6`) => `R7` | The function with which to transform the return value of the prior function | | `r7_r8` | (`r7`) => `R8` | The function with which to transform the return value of the prior function | | `r8_r9` | (`r8`) => `R9` | The function with which to transform the return value of the prior function | | `r9_r10` | (`r9`) => `R10` | The function with which to transform the return value of the prior function | ### Returns `R10` The return value of the final transform function # prependTransactionMessageInstruction (/api/functions/prependTransactionMessageInstruction) ```ts function prependTransactionMessageInstruction< TTransactionMessage, TInstruction, >( instruction, transactionMessage, ): PrependTransactionMessageInstructions< TTransactionMessage, [TInstruction] >; ``` Given an instruction, this method will return a new transaction message with that instruction having been added to the beginning of the list of existing instructions. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | | `TInstruction` *extends* `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]> | ## Parameters | Parameter | Type | | -------------------- | --------------------- | | `instruction` | `TInstruction` | | `transactionMessage` | `TTransactionMessage` | ## Returns `PrependTransactionMessageInstructions`\<`TTransactionMessage`, \[`TInstruction`]> ## See prependTransactionInstructions if you need to prepend multiple instructions to a transaction message. ## Example ```ts import { address } from '@solana/addresses'; import { prependTransactionMessageInstruction } from '@solana/transaction-messages'; const memoTransaction = prependTransactionMessageInstruction( { data: new TextEncoder().encode('Hello world!'), programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), }, tx, ); ``` # prependTransactionMessageInstructions (/api/functions/prependTransactionMessageInstructions) ```ts function prependTransactionMessageInstructions< TTransactionMessage, TInstructions, >( instructions, transactionMessage, ): PrependTransactionMessageInstructions< TTransactionMessage, TInstructions >; ``` Given an array of instructions, this method will return a new transaction message with those instructions having been added to the beginning of the list of existing instructions. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | | `TInstructions` *extends* readonly `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]>\[] | ## Parameters | Parameter | Type | | -------------------- | --------------------- | | `instructions` | `TInstructions` | | `transactionMessage` | `TTransactionMessage` | ## Returns `PrependTransactionMessageInstructions`\<`TTransactionMessage`, `TInstructions`> ## See prependTransactionInstruction if you only need to prepend one instruction to a transaction message. ## Example ```ts import { address } from '@solana/addresses'; import { prependTransactionMessageInstructions } from '@solana/transaction-messages'; const memoTransaction = prependTransactionMessageInstructions( [ { data: new TextEncoder().encode('Hello world!'), programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), }, { data: new TextEncoder().encode('How are you?'), programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), }, ], tx, ); ``` # ratioBinaryFixedPoint (/api/functions/ratioBinaryFixedPoint) ```ts function ratioBinaryFixedPoint< TSignedness, TTotalBits, TFractionalBits, >( signedness, totalBits, fractionalBits, ): ( numerator, denominator, rounding?, ) => BinaryFixedPoint; ``` Returns a factory that constructs [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) values from a rational `numerator / denominator`. The outer call validates the shape parameters once and the returned factory can be called many times to construct values of that shape. If the ratio cannot be exactly represented at the target `fractionalBits`, the returned factory throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` under the default `'strict'` rounding mode. Pass a different [RoundingMode](/api/type-aliases/RoundingMode) to allow a rounded result. Zero denominators always throw `SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO`. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | ---------------- | ----------------- | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `fractionalBits` | `TFractionalBits` | ## Returns (`numerator`, `denominator`, `rounding?`) => [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> ## Example ```ts const probability = ratioBinaryFixedPoint('signed', 16, 15); probability(1n, 4n); // raw === 8192n (0.25, exact) probability(1n, 3n); // throws under 'strict' probability(1n, 3n, 'floor'); // raw === 10922n ``` ## See * [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) * [binaryFixedPoint](/api/functions/binaryFixedPoint) * [rawBinaryFixedPoint](/api/functions/rawBinaryFixedPoint) # ratioDecimalFixedPoint (/api/functions/ratioDecimalFixedPoint) ```ts function ratioDecimalFixedPoint( signedness, totalBits, decimals, ): ( numerator, denominator, rounding?, ) => DecimalFixedPoint; ``` Returns a factory that constructs [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) values from a rational `numerator / denominator`. The outer call validates the shape parameters once and the returned factory can be called many times to construct values of that shape. If the ratio cannot be exactly represented at the target `decimals`, the returned factory throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` under the default `'strict'` rounding mode. Pass a different [RoundingMode](/api/type-aliases/RoundingMode) to allow a rounded result. Zero denominators always throw `SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO`. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | ------------ | ------------- | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `decimals` | `TDecimals` | ## Returns (`numerator`, `denominator`, `rounding?`) => [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> ## Example ```ts const probability = ratioDecimalFixedPoint('unsigned', 64, 4); probability(1n, 4n); // raw === 2500n (0.2500) probability(1n, 3n); // throws under 'strict' probability(1n, 3n, 'floor'); // raw === 3333n ``` ## See * [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) * [decimalFixedPoint](/api/functions/decimalFixedPoint) * [rawDecimalFixedPoint](/api/functions/rawDecimalFixedPoint) # rawBinaryFixedPoint (/api/functions/rawBinaryFixedPoint) ```ts function rawBinaryFixedPoint( signedness, totalBits, fractionalBits, ): (raw) => BinaryFixedPoint; ``` Returns a factory that constructs [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) values from a raw bigint in the smallest representable unit (i.e. already scaled by `2 ** fractionalBits`). The outer call validates the shape parameters once and the returned factory can be called many times to construct values of that shape. The raw value is range-checked against the claimed `totalBits` and `signedness`; no rounding is ever required. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | ---------------- | ----------------- | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `fractionalBits` | `TFractionalBits` | ## Returns (`raw`) => [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> ## Example ```ts const q1_15 = rawBinaryFixedPoint('signed', 16, 15); q1_15(16384n); // Represents 0.5 ``` ## See * [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) * [binaryFixedPoint](/api/functions/binaryFixedPoint) * [ratioBinaryFixedPoint](/api/functions/ratioBinaryFixedPoint) # rawDecimalFixedPoint (/api/functions/rawDecimalFixedPoint) ```ts function rawDecimalFixedPoint( signedness, totalBits, decimals, ): (raw) => DecimalFixedPoint; ``` Returns a factory that constructs [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) values from a raw bigint in the smallest representable unit (i.e. already scaled by `10 ** decimals`). The outer call validates the shape parameters once and the returned factory can be called many times to construct values of that shape. The raw value is range-checked against the claimed `totalBits` and `signedness`; no rounding is ever required. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | ------------ | ------------- | | `signedness` | `TSignedness` | | `totalBits` | `TTotalBits` | | `decimals` | `TDecimals` | ## Returns (`raw`) => [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> ## Example ```ts const cents = rawDecimalFixedPoint('unsigned', 16, 2); cents(425n); // Represents 4.25 ``` ## See * [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) * [decimalFixedPoint](/api/functions/decimalFixedPoint) * [ratioDecimalFixedPoint](/api/functions/ratioDecimalFixedPoint) # removeNullCharacters (/api/functions/removeNullCharacters) ```ts function removeNullCharacters(value): string; ``` Removes all null characters (`\u0000`) from a string. This function cleans a string by stripping out any null characters, which are often used as padding in fixed-size string encodings. ## Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------- | | `value` | `string` | The string to process. | ## Returns `string` The input string with all null characters removed. ## Example Removing null characters from a string. ```ts removeNullCharacters('hello\u0000\u0000'); // "hello" ``` # rescaleBinaryFixedPoint (/api/functions/rescaleBinaryFixedPoint) ```ts function rescaleBinaryFixedPoint< TSignedness, TNewTotalBits, TNewFractionalBits, >( value, newTotalBits, newFractionalBits, rounding?, ): BinaryFixedPoint; ``` Returns a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) with the same signedness as `value` but a new `totalBits` and `fractionalBits`. If the requested shape matches the input shape, the same reference is returned. Scale-up (higher `fractionalBits`) is always exact. Scale-down (lower `fractionalBits`) is potentially lossy; the optional [RoundingMode](/api/type-aliases/RoundingMode) is consulted on inexact results and defaults to `'strict'`, which throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS`. Throws `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW` when the rescaled raw value does not fit the new `totalBits`. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TNewTotalBits` *extends* `number` | | `TNewFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | ------------------- | -------------------------------------------------------------------------------------------- | | `value` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `number`, `number`> | | `newTotalBits` | `TNewTotalBits` | | `newFractionalBits` | `TNewFractionalBits` | | `rounding?` | [`RoundingMode`](/api/type-aliases/RoundingMode) | ## Returns [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TNewTotalBits`, `TNewFractionalBits`> ## Example ```ts const q1_15 = binaryFixedPoint('signed', 16, 15); rescaleBinaryFixedPoint(q1_15('0.5'), 32, 30); // wider, higher precision rescaleBinaryFixedPoint(q1_15('0.5'), 16, 8, 'floor'); // lower precision, explicit rounding ``` ## See * [toSignedBinaryFixedPoint](/api/functions/toSignedBinaryFixedPoint) * [toUnsignedBinaryFixedPoint](/api/functions/toUnsignedBinaryFixedPoint) # rescaleDecimalFixedPoint (/api/functions/rescaleDecimalFixedPoint) ```ts function rescaleDecimalFixedPoint< TSignedness, TNewTotalBits, TNewDecimals, >( value, newTotalBits, newDecimals, rounding?, ): DecimalFixedPoint; ``` Returns a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) with the same signedness as `value` but a new `totalBits` and `decimals`. If the requested shape matches the input shape, the same reference is returned. Scale-up (higher `decimals`) is always exact. Scale-down (lower `decimals`) is potentially lossy; the optional [RoundingMode](/api/type-aliases/RoundingMode) is consulted on inexact results and defaults to `'strict'`, which throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS`. Throws `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW` when the rescaled raw value does not fit the new `totalBits`. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TNewTotalBits` *extends* `number` | | `TNewDecimals` *extends* `number` | ## Parameters | Parameter | Type | | -------------- | ---------------------------------------------------------------------------------------------- | | `value` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `number`, `number`> | | `newTotalBits` | `TNewTotalBits` | | `newDecimals` | `TNewDecimals` | | `rounding?` | [`RoundingMode`](/api/type-aliases/RoundingMode) | ## Returns [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TNewTotalBits`, `TNewDecimals`> ## Example ```ts // Bridge EVM USDC (u128 d18) down to SPL USDC (u64 d6). const evmUsdc = decimalFixedPoint('unsigned', 128, 18); rescaleDecimalFixedPoint(evmUsdc('100.123456789012345678'), 64, 6, 'floor'); // represents 100.123456 ``` ## See * [toSignedDecimalFixedPoint](/api/functions/toSignedDecimalFixedPoint) * [toUnsignedDecimalFixedPoint](/api/functions/toUnsignedDecimalFixedPoint) # resizeCodec (/api/functions/resizeCodec) ## Call Signature ```ts function resizeCodec( codec, resize, ): FixedSizeCodec; ``` Updates the size of a given codec. This function modifies the size of both the codec using a provided transformation function. It is useful for adjusting the allocated byte size for encoding and decoding without altering the underlying data structure. If the new size is negative, an error will be thrown. ### Type Parameters | Type Parameter | Description | | ----------------------------- | ----------------------------------------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The original fixed size of the encoded/decoded value (for fixed-size codecs). | | `TNewSize` *extends* `number` | The new fixed size after resizing (for fixed-size codecs). | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `codec` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`> | The codec whose size will be updated. | | `resize` | (`size`) => `TNewSize` | A function that takes the current size and returns the new size. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TNewSize`> A new codec with the updated size. ### Examples Expanding a `u16` codec from 2 to 4 bytes. ```ts const codec = resizeCodec(getU16Codec(), size => size + 2); const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added) const value = codec.decode(bytes); // 0xffff (reads original two bytes) ``` Shrinking a `u32` codec to only use 2 bytes. ```ts const codec = resizeCodec(getU32Codec(), () => 2); codec.fixedSize; // 2 ``` ### Remarks If you only need to resize an encoder, use [resizeEncoder](/api/functions/resizeEncoder). If you only need to resize a decoder, use [resizeDecoder](/api/functions/resizeDecoder). ```ts const bytes = resizeEncoder(getU32Encoder(), (size) => size + 2).encode(0xffff); const value = resizeDecoder(getU32Decoder(), (size) => size + 2).decode(bytes); ``` ### See * [resizeEncoder](/api/functions/resizeEncoder) * [resizeDecoder](/api/functions/resizeDecoder) ## Call Signature ```ts function resizeCodec(codec, resize): TCodec; ``` Updates the size of a given codec. This function modifies the size of both the codec using a provided transformation function. It is useful for adjusting the allocated byte size for encoding and decoding without altering the underlying data structure. If the new size is negative, an error will be thrown. ### Type Parameters | Type Parameter | | ----------------------------- | | `TCodec` *extends* `AnyCodec` | ### Parameters | Parameter | Type | Description | | --------- | -------------------- | ---------------------------------------------------------------- | | `codec` | `TCodec` | The codec whose size will be updated. | | `resize` | (`size`) => `number` | A function that takes the current size and returns the new size. | ### Returns `TCodec` A new codec with the updated size. ### Examples Expanding a `u16` codec from 2 to 4 bytes. ```ts const codec = resizeCodec(getU16Codec(), size => size + 2); const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added) const value = codec.decode(bytes); // 0xffff (reads original two bytes) ``` Shrinking a `u32` codec to only use 2 bytes. ```ts const codec = resizeCodec(getU32Codec(), () => 2); codec.fixedSize; // 2 ``` ### Remarks If you only need to resize an encoder, use [resizeEncoder](/api/functions/resizeEncoder). If you only need to resize a decoder, use [resizeDecoder](/api/functions/resizeDecoder). ```ts const bytes = resizeEncoder(getU32Encoder(), (size) => size + 2).encode(0xffff); const value = resizeDecoder(getU32Decoder(), (size) => size + 2).decode(bytes); ``` ### See * [resizeEncoder](/api/functions/resizeEncoder) * [resizeDecoder](/api/functions/resizeDecoder) # resizeDecoder (/api/functions/resizeDecoder) ## Call Signature ```ts function resizeDecoder( decoder, resize, ): FixedSizeDecoder; ``` Updates the size of a given decoder. This function modifies the size of a decoder using a provided transformation function. For fixed-size decoders, it updates the `fixedSize` property to reflect the new size. Variable-size decoders remain unchanged, as their size is determined dynamically. If the new size is negative, an error will be thrown. For more details, see [resizeCodec](/api/functions/resizeCodec). ### Type Parameters | Type Parameter | Description | | ----------------------------- | --------------------------------------------- | | `TFrom` | - | | `TSize` *extends* `number` | The original fixed size of the decoded value. | | `TNewSize` *extends* `number` | The new fixed size after resizing. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `decoder` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TFrom`, `TSize`> | The decoder whose size will be updated. | | `resize` | (`size`) => `TNewSize` | A function that takes the current size and returns the new size. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TFrom`, `TNewSize`> A new decoder with the updated size. ### Examples Expanding a `u16` decoder to read 4 bytes instead of 2. ```ts const decoder = resizeDecoder(getU16Decoder(), size => size + 2); decoder.fixedSize; // 4 ``` Shrinking a `u32` decoder to only read 2 bytes. ```ts const decoder = resizeDecoder(getU32Decoder(), () => 2); decoder.fixedSize; // 2 ``` ### See * [resizeCodec](/api/functions/resizeCodec) * [resizeEncoder](/api/functions/resizeEncoder) ## Call Signature ```ts function resizeDecoder(decoder, resize): TDecoder; ``` Updates the size of a given decoder. This function modifies the size of a decoder using a provided transformation function. For fixed-size decoders, it updates the `fixedSize` property to reflect the new size. Variable-size decoders remain unchanged, as their size is determined dynamically. If the new size is negative, an error will be thrown. For more details, see [resizeCodec](/api/functions/resizeCodec). ### Type Parameters | Type Parameter | | --------------------------------- | | `TDecoder` *extends* `AnyDecoder` | ### Parameters | Parameter | Type | Description | | --------- | -------------------- | ---------------------------------------------------------------- | | `decoder` | `TDecoder` | The decoder whose size will be updated. | | `resize` | (`size`) => `number` | A function that takes the current size and returns the new size. | ### Returns `TDecoder` A new decoder with the updated size. ### Examples Expanding a `u16` decoder to read 4 bytes instead of 2. ```ts const decoder = resizeDecoder(getU16Decoder(), size => size + 2); decoder.fixedSize; // 4 ``` Shrinking a `u32` decoder to only read 2 bytes. ```ts const decoder = resizeDecoder(getU32Decoder(), () => 2); decoder.fixedSize; // 2 ``` ### See * [resizeCodec](/api/functions/resizeCodec) * [resizeEncoder](/api/functions/resizeEncoder) # resizeEncoder (/api/functions/resizeEncoder) ## Call Signature ```ts function resizeEncoder( encoder, resize, ): FixedSizeEncoder; ``` Updates the size of a given encoder. This function modifies the size of an encoder using a provided transformation function. For fixed-size encoders, it updates the `fixedSize` property, and for variable-size encoders, it adjusts the size calculation based on the encoded value. If the new size is negative, an error will be thrown. For more details, see [resizeCodec](/api/functions/resizeCodec). ### Type Parameters | Type Parameter | Description | | ----------------------------- | --------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TSize` *extends* `number` | The original fixed size of the encoded value. | | `TNewSize` *extends* `number` | The new fixed size after resizing. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `encoder` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`> | The encoder whose size will be updated. | | `resize` | (`size`) => `TNewSize` | A function that takes the current size and returns the new size. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TNewSize`> A new encoder with the updated size. ### Examples Increasing the size of a `u16` encoder by 2 bytes. ```ts const encoder = resizeEncoder(getU16Encoder(), size => size + 2); encoder.encode(0xffff); // 0xffff0000 (two extra bytes added) ``` Shrinking a `u32` encoder to only use 2 bytes. ```ts const encoder = resizeEncoder(getU32Encoder(), () => 2); encoder.fixedSize; // 2 ``` ### See * [resizeCodec](/api/functions/resizeCodec) * [resizeDecoder](/api/functions/resizeDecoder) ## Call Signature ```ts function resizeEncoder(encoder, resize): TEncoder; ``` Updates the size of a given encoder. This function modifies the size of an encoder using a provided transformation function. For fixed-size encoders, it updates the `fixedSize` property, and for variable-size encoders, it adjusts the size calculation based on the encoded value. If the new size is negative, an error will be thrown. For more details, see [resizeCodec](/api/functions/resizeCodec). ### Type Parameters | Type Parameter | | --------------------------------- | | `TEncoder` *extends* `AnyEncoder` | ### Parameters | Parameter | Type | Description | | --------- | -------------------- | ---------------------------------------------------------------- | | `encoder` | `TEncoder` | The encoder whose size will be updated. | | `resize` | (`size`) => `number` | A function that takes the current size and returns the new size. | ### Returns `TEncoder` A new encoder with the updated size. ### Examples Increasing the size of a `u16` encoder by 2 bytes. ```ts const encoder = resizeEncoder(getU16Encoder(), size => size + 2); encoder.encode(0xffff); // 0xffff0000 (two extra bytes added) ``` Shrinking a `u32` encoder to only use 2 bytes. ```ts const encoder = resizeEncoder(getU32Encoder(), () => 2); encoder.fixedSize; // 2 ``` ### See * [resizeCodec](/api/functions/resizeCodec) * [resizeDecoder](/api/functions/resizeDecoder) # reverseCodec (/api/functions/reverseCodec) ```ts function reverseCodec( codec, ): FixedSizeCodec; ``` Reverses the bytes of a fixed-size codec. Given a `FixedSizeCodec`, this function returns a new `FixedSizeCodec` that reverses the bytes within the fixed-size byte array during encoding and decoding. This can be useful to modify endianness or for other byte-order transformations. ## Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the encoded/decoded value in bytes. | ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------- | -------------------------------- | | `codec` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`> | The fixed-size codec to reverse. | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TFrom`, `TTo`, `TSize`> A new codec that encodes and decodes bytes in reverse order. ## Example Reversing a `u16` codec. ```ts const codec = reverseCodec(getU16Codec({ endian: Endian.Big })); const bytes = codec.encode(0x1234); // 0x3412 (bytes are flipped) const value = codec.decode(bytes); // 0x1234 (bytes are flipped back) ``` ## Remarks If you only need to reverse an encoder, use [reverseEncoder](/api/functions/reverseEncoder). If you only need to reverse a decoder, use [reverseDecoder](/api/functions/reverseDecoder). ```ts const bytes = reverseEncoder(getU16Encoder()).encode(0x1234); const value = reverseDecoder(getU16Decoder()).decode(bytes); ``` ## See * [reverseEncoder](/api/functions/reverseEncoder) * [reverseDecoder](/api/functions/reverseDecoder) # reverseDecoder (/api/functions/reverseDecoder) ```ts function reverseDecoder( decoder, ): FixedSizeDecoder; ``` Reverses the bytes of a fixed-size decoder. Given a `FixedSizeDecoder`, this function returns a new `FixedSizeDecoder` that reverses the bytes within the fixed-size byte array before decoding. This can be useful to modify endianness or for other byte-order transformations. For more details, see [reverseCodec](/api/functions/reverseCodec). ## Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TTo` | The type of the decoded value. | | `TSize` *extends* `number` | The fixed size of the decoded value in bytes. | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------- | ---------------------------------- | | `decoder` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `TSize`> | The fixed-size decoder to reverse. | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TTo`, `TSize`> A new decoder that reads bytes in reverse order. ## Example Decoding a reversed `u16` value. ```ts const decoder = reverseDecoder(getU16Decoder({ endian: Endian.Big })); const value = decoder.decode(new Uint8Array([0x34, 0x12])); // 0x1234 (bytes are flipped back) ``` ## See * [reverseCodec](/api/functions/reverseCodec) * [reverseEncoder](/api/functions/reverseEncoder) # reverseEncoder (/api/functions/reverseEncoder) ```ts function reverseEncoder( encoder, ): FixedSizeEncoder; ``` Reverses the bytes of a fixed-size encoder. Given a `FixedSizeEncoder`, this function returns a new `FixedSizeEncoder` that reverses the bytes within the fixed-size byte array when encoding. This can be useful to modify endianness or for other byte-order transformations. For more details, see [reverseCodec](/api/functions/reverseCodec). ## Type Parameters | Type Parameter | Description | | -------------------------- | --------------------------------------------- | | `TFrom` | The type of the value to encode. | | `TSize` *extends* `number` | The fixed size of the encoded value in bytes. | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------- | ---------------------------------- | | `encoder` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`> | The fixed-size encoder to reverse. | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TFrom`, `TSize`> A new encoder that writes bytes in reverse order. ## Example Encoding a `u16` value in reverse order. ```ts const encoder = reverseEncoder(getU16Encoder({ endian: Endian.Big })); const bytes = encoder.encode(0x1234); // 0x3412 (bytes are flipped) ``` ## See * [reverseCodec](/api/functions/reverseCodec) * [reverseDecoder](/api/functions/reverseDecoder) # safeCaptureStackTrace (/api/functions/safeCaptureStackTrace) ```ts function safeCaptureStackTrace(...args): void; ``` ## Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------- | | ...`args` | \[`object`, [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function)] | ## Returns `void` # safeRace (/api/functions/safeRace) ```ts function safeRace(contenders): Promise>; ``` An implementation of [`Promise.race`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) that causes all of the losing promises to settle. This allows them to be released and garbage collected, preventing memory leaks. Read more here: [https://github.com/nodejs/node/issues/17469](https://github.com/nodejs/node/issues/17469) ## Type Parameters | Type Parameter | | ------------------------------------------ | | `T` *extends* \[] \| readonly `unknown`\[] | ## Parameters | Parameter | Type | | ------------ | ---- | | `contenders` | `T` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Awaited`](https://www.typescriptlang.org/docs/handbook/utility-types.html#awaitedtype)\<`T`\[`number`]>> # sendAndConfirmDurableNonceTransactionFactory (/api/functions/sendAndConfirmDurableNonceTransactionFactory) ## Call Signature ```ts function sendAndConfirmDurableNonceTransactionFactory( config, ): SendAndConfirmDurableNonceTransactionFunction; ``` Returns a function that you can call to send a nonce-based transaction to the network and to wait until it has been confirmed. ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------- | ----------- | | `config` | `SendAndConfirmDurableNonceTransactionFactoryConfig`\<`"devnet"`> | - | ### Returns `SendAndConfirmDurableNonceTransactionFunction` ### Example ```ts import { isSolanaError, sendAndConfirmDurableNonceTransactionFactory, SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, } from '@solana/kit'; const sendAndConfirmNonceTransaction = sendAndConfirmDurableNonceTransactionFactory({ rpc, rpcSubscriptions }); try { await sendAndConfirmNonceTransaction(transaction, { commitment: 'confirmed' }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) { console.error( 'The lifetime specified by this transaction refers to a nonce account ' + `\`${e.context.nonceAccountAddress}\` that does not exist`, ); } else if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) { console.error('This transaction depends on a nonce that is no longer valid'); } else { throw e; } } ``` ## Call Signature ```ts function sendAndConfirmDurableNonceTransactionFactory( config, ): SendAndConfirmDurableNonceTransactionFunction; ``` Returns a function that you can call to send a nonce-based transaction to the network and to wait until it has been confirmed. ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------ | ----------- | | `config` | `SendAndConfirmDurableNonceTransactionFactoryConfig`\<`"testnet"`> | - | ### Returns `SendAndConfirmDurableNonceTransactionFunction` ### Example ```ts import { isSolanaError, sendAndConfirmDurableNonceTransactionFactory, SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, } from '@solana/kit'; const sendAndConfirmNonceTransaction = sendAndConfirmDurableNonceTransactionFactory({ rpc, rpcSubscriptions }); try { await sendAndConfirmNonceTransaction(transaction, { commitment: 'confirmed' }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) { console.error( 'The lifetime specified by this transaction refers to a nonce account ' + `\`${e.context.nonceAccountAddress}\` that does not exist`, ); } else if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) { console.error('This transaction depends on a nonce that is no longer valid'); } else { throw e; } } ``` ## Call Signature ```ts function sendAndConfirmDurableNonceTransactionFactory( config, ): SendAndConfirmDurableNonceTransactionFunction; ``` Returns a function that you can call to send a nonce-based transaction to the network and to wait until it has been confirmed. ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------ | ----------- | | `config` | `SendAndConfirmDurableNonceTransactionFactoryConfig`\<`"mainnet"`> | - | ### Returns `SendAndConfirmDurableNonceTransactionFunction` ### Example ```ts import { isSolanaError, sendAndConfirmDurableNonceTransactionFactory, SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, } from '@solana/kit'; const sendAndConfirmNonceTransaction = sendAndConfirmDurableNonceTransactionFactory({ rpc, rpcSubscriptions }); try { await sendAndConfirmNonceTransaction(transaction, { commitment: 'confirmed' }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) { console.error( 'The lifetime specified by this transaction refers to a nonce account ' + `\`${e.context.nonceAccountAddress}\` that does not exist`, ); } else if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) { console.error('This transaction depends on a nonce that is no longer valid'); } else { throw e; } } ``` # sendAndConfirmTransactionFactory (/api/functions/sendAndConfirmTransactionFactory) ## Call Signature ```ts function sendAndConfirmTransactionFactory( config, ): SendAndConfirmTransactionWithBlockhashLifetimeFunction; ``` Returns a function that you can call to send a blockhash-based transaction to the network and to wait until it has been confirmed. ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------- | ----------- | | `config` | `SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig`\<`"devnet"`> | - | ### Returns `SendAndConfirmTransactionWithBlockhashLifetimeFunction` ### Example ```ts import { isSolanaError, sendAndConfirmTransactionFactory, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED } from '@solana/kit'; const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); try { await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) { console.error('This transaction depends on a blockhash that has expired'); } else { throw e; } } ``` ## Call Signature ```ts function sendAndConfirmTransactionFactory( config, ): SendAndConfirmTransactionWithBlockhashLifetimeFunction; ``` Returns a function that you can call to send a blockhash-based transaction to the network and to wait until it has been confirmed. ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------- | ----------- | | `config` | `SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig`\<`"testnet"`> | - | ### Returns `SendAndConfirmTransactionWithBlockhashLifetimeFunction` ### Example ```ts import { isSolanaError, sendAndConfirmTransactionFactory, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED } from '@solana/kit'; const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); try { await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) { console.error('This transaction depends on a blockhash that has expired'); } else { throw e; } } ``` ## Call Signature ```ts function sendAndConfirmTransactionFactory( config, ): SendAndConfirmTransactionWithBlockhashLifetimeFunction; ``` Returns a function that you can call to send a blockhash-based transaction to the network and to wait until it has been confirmed. ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------- | ----------- | | `config` | `SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig`\<`"mainnet"`> | - | ### Returns `SendAndConfirmTransactionWithBlockhashLifetimeFunction` ### Example ```ts import { isSolanaError, sendAndConfirmTransactionFactory, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED } from '@solana/kit'; const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); try { await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) { console.error('This transaction depends on a blockhash that has expired'); } else { throw e; } } ``` # sendTransactionWithoutConfirmingFactory (/api/functions/sendTransactionWithoutConfirmingFactory) ```ts function sendTransactionWithoutConfirmingFactory( config, ): SendTransactionWithoutConfirmingFunction; ``` Returns a function that you can call to send a transaction with any kind of lifetime to the network without waiting for it to be confirmed. ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------- | ----------- | | `config` | `SendTransactionWithoutConfirmingFactoryConfig` | - | ## Returns `SendTransactionWithoutConfirmingFunction` ## Example ```ts import { sendTransactionWithoutConfirmingFactory, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, } from '@solana/kit'; const sendTransaction = sendTransactionWithoutConfirmingFactory({ rpc }); try { await sendTransaction(transaction, { commitment: 'confirmed' }); } catch (e) { if (isSolanaError(e, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE)) { console.error('The transaction failed in simulation', e.cause); } else { throw e; } } ``` # sequentialInstructionPlan (/api/functions/sequentialInstructionPlan) ```ts function sequentialInstructionPlan(plans): Readonly<{ divisible: boolean; kind: 'sequential'; plans: InstructionPlan[]; planType: 'instructionPlan'; }> & object; ``` Creates a divisible [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) from an array of nested plans. It can accept [Instruction](/api/interfaces/Instruction) objects directly, which will be wrapped in [SingleInstructionPlans](/api/type-aliases/SingleInstructionPlan) automatically. ## Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `plans` | ( \| [`Instruction`](/api/interfaces/Instruction)\<`string`, readonly ( \| [`AccountLookupMeta`](/api/interfaces/AccountLookupMeta)\<`string`, `string`> \| [`AccountMeta`](/api/interfaces/AccountMeta)\<`string`>)\[]> \| [`InstructionPlan`](/api/type-aliases/InstructionPlan))\[] | ## Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `divisible`: `boolean`; `kind`: `"sequential"`; `plans`: [`InstructionPlan`](/api/type-aliases/InstructionPlan)\[]; `planType`: `"instructionPlan"`; }> & `object` ## Examples **Using explicit \{@link SingleInstructionPlan | SingleInstructionPlans}.** ```ts const plan = sequentialInstructionPlan([ singleInstructionPlan(instructionA), singleInstructionPlan(instructionB), ]); ``` **Using \{@link Instruction | Instructions} directly.** ```ts const plan = sequentialInstructionPlan([instructionA, instructionB]); ``` ## See [SequentialInstructionPlan](/api/type-aliases/SequentialInstructionPlan) # sequentialTransactionPlan (/api/functions/sequentialTransactionPlan) ```ts function sequentialTransactionPlan(plans): Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlan[]; planType: 'transactionPlan'; }> & object; ``` Creates a divisible [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) from an array of nested plans. It can accept [TransactionMessage](/api/type-aliases/TransactionMessage) objects directly, which will be wrapped in [SingleTransactionPlans](/api/type-aliases/SingleTransactionPlan) automatically. ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------- | | `plans` | ( \| TransactionMessage & TransactionMessageWithFeePayer\ \| [`TransactionPlan`](/api/type-aliases/TransactionPlan))\[] | ## Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `divisible`: `boolean`; `kind`: `"sequential"`; `plans`: [`TransactionPlan`](/api/type-aliases/TransactionPlan)\[]; `planType`: `"transactionPlan"`; }> & `object` ## Examples Using explicit [SingleTransactionPlans](/api/type-aliases/SingleTransactionPlan). ```ts const plan = sequentialTransactionPlan([ singleTransactionPlan(messageA), singleTransactionPlan(messageB), ]); ``` Using [TransactionMessages](/api/type-aliases/TransactionMessage) directly. ```ts const plan = sequentialTransactionPlan([messageA, messageB]); ``` ## See [SequentialTransactionPlan](/api/type-aliases/SequentialTransactionPlan) # sequentialTransactionPlanResult (/api/functions/sequentialTransactionPlanResult) ```ts function sequentialTransactionPlanResult(plans): Readonly<{ divisible: boolean; kind: 'sequential'; plans: TransactionPlanResult< TContext, TransactionMessage & TransactionMessageWithFeePayer, SingleTransactionPlanResult< TContext, TransactionMessage & TransactionMessageWithFeePayer > >[]; planType: 'transactionPlanResult'; }> & object; ``` Creates a divisible [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) from an array of nested results. This function creates a sequential result with the `divisible` property set to `true`, indicating that the nested plans were executed sequentially but could have been split into separate transactions or batches. ## Type Parameters | Type Parameter | Default type | Description | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | ## Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | | `plans` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>, [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>>>\[] | The child results that were executed sequentially | ## Returns [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `divisible`: `boolean`; `kind`: `"sequential"`; `plans`: [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>, [`SingleTransactionPlanResult`](/api/type-aliases/SingleTransactionPlanResult)\<`TContext`, [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>>>\[]; `planType`: `"transactionPlanResult"`; }> & `object` ## Example ```ts const result = sequentialTransactionPlanResult([ singleResultA, singleResultB, ]); result satisfies SequentialTransactionPlanResult & { divisible: true }; ``` ## See [SequentialTransactionPlanResult](/api/type-aliases/SequentialTransactionPlanResult) # setTransactionMessageComputeUnitLimit (/api/functions/setTransactionMessageComputeUnitLimit) ```ts function setTransactionMessageComputeUnitLimit( computeUnitLimit, transactionMessage, ): TTransactionMessage; ``` Sets the compute unit limit for a transaction message. This function works with all transaction versions: * **V1**: Sets the `computeUnitLimit` field in the transaction message's config. * **Legacy / V0**: Appends (or replaces) a `SetComputeUnitLimit` instruction from the Compute Budget program. ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------- | ----------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | The transaction message type. | ## Parameters | Parameter | Type | Description | | -------------------- | ----------------------- | ---------------------------------------------------------------------------- | | `computeUnitLimit` | `number` \| `undefined` | The maximum compute units (CUs) allowed, or `undefined` to remove the limit. | | `transactionMessage` | `TTransactionMessage` | The transaction message to configure. | ## Returns `TTransactionMessage` A new transaction message with the compute unit limit set. ## Example ```ts const txMessage = setTransactionMessageComputeUnitLimit( 400_000, transactionMessage, ); ``` # setTransactionMessageComputeUnitPrice (/api/functions/setTransactionMessageComputeUnitPrice) ```ts function setTransactionMessageComputeUnitPrice( computeUnitPrice, transactionMessage, ): TTransactionMessage; ``` Sets the compute unit price for a legacy or v0 transaction message. The value represents the price in **micro-lamports per compute unit**. The actual priority fee paid is `computeUnitPrice Γ— computeUnitLimit`. This appends, replaces, or removes a `SetComputeUnitPrice` instruction from the Compute Budget program. The operation is idempotent: setting the same value returns the same reference, and setting `undefined` removes the instruction. ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------- | ----------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & `object` | The transaction message type. | ## Parameters | Parameter | Type | Description | | -------------------- | ----------------------- | --------------------------------------------------------------------------------------- | | `computeUnitPrice` | `bigint` \| `undefined` | The price in micro-lamports per compute unit, or `undefined` to remove the instruction. | | `transactionMessage` | `TTransactionMessage` | The legacy or v0 transaction message to configure. | ## Returns `TTransactionMessage` A new transaction message with the compute unit price set. ## Example ```ts const txMessage = setTransactionMessageComputeUnitPrice( 10_000n, transactionMessage, ); ``` ## See * [getTransactionMessageComputeUnitPrice](/api/functions/getTransactionMessageComputeUnitPrice) * [setTransactionMessagePriorityFeeLamports](/api/functions/setTransactionMessagePriorityFeeLamports) for v1 transactions. # setTransactionMessageConfig (/api/functions/setTransactionMessageConfig) ```ts function setTransactionMessageConfig( config, transactionMessage, ): TTransactionMessage; ``` Sets configuration options on a transaction message. This function merges the provided configuration with any existing configuration on the transaction message. Configuration values control resource limits and transaction prioritization. ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------- | ----------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & `object` | The transaction message type. | ## Parameters | Parameter | Type | Description | | -------------------- | -------------------------------------------------------------- | ------------------------------------- | | `config` | [`V1TransactionConfig`](/api/type-aliases/V1TransactionConfig) | The configuration options to apply. | | `transactionMessage` | `TTransactionMessage` | The transaction message to configure. | ## Returns `TTransactionMessage` A new transaction message with the merged configuration. ## Examples ```ts const configuredTx = setTransactionMessageConfig( { computeUnitLimit: 300_000, priorityFeeLamports: 50_000n, }, transactionMessage, ); ``` Incrementally adding configuration values. ```ts const txMessage = pipe( baseTransaction, tx => setTransactionMessageConfig({ computeUnitLimit: 300_000 }, tx), tx => setTransactionMessageConfig({ priorityFeeLamports: 50_000n }, tx), ); ``` Removing a configuration value. ```ts const txMessage = setTransactionMessageConfig({ computeUnitLimit: undefined }, tx); ``` ## See * [setTransactionMessageComputeUnitLimit](/api/functions/setTransactionMessageComputeUnitLimit) * [setTransactionMessagePriorityFeeLamports](/api/functions/setTransactionMessagePriorityFeeLamports) # setTransactionMessageFeePayer (/api/functions/setTransactionMessageFeePayer) ```ts function setTransactionMessageFeePayer< TFeePayerAddress, TTransactionMessage, >( feePayer, transactionMessage, ): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayer; ``` Given a base58-encoded address of a system account, this method will return a new transaction message having the same type as the one supplied plus the [TransactionMessageWithFeePayer](/api/interfaces/TransactionMessageWithFeePayer) type. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TFeePayerAddress` *extends* `string` | | `TTransactionMessage` *extends* [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`>> & [`TransactionMessage`](/api/type-aliases/TransactionMessage) | ## Parameters | Parameter | Type | | -------------------- | ------------------------------ | | `feePayer` | `Address`\<`TFeePayerAddress`> | | `transactionMessage` | `TTransactionMessage` | ## Returns `ExcludeTransactionMessageFeePayer`\<`TTransactionMessage`> & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`TFeePayerAddress`> ## Example ```ts import { address } from '@solana/addresses'; import { setTransactionMessageFeePayer } from '@solana/transaction-messages'; const myAddress = address('mpngsFd4tmbUfzDYJayjKZwZcaR7aWb2793J6grLsGu'); const txPaidByMe = setTransactionMessageFeePayer(myAddress, tx); ``` # setTransactionMessageFeePayerSigner (/api/functions/setTransactionMessageFeePayerSigner) ```ts function setTransactionMessageFeePayerSigner< TFeePayerAddress, TTransactionMessage, >( feePayer, transactionMessage, ): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayerSigner< TFeePayerAddress, TransactionSigner >; ``` Sets the fee payer of a TransactionMessage | transaction message using a [TransactionSigner](/api/type-aliases/TransactionSigner). ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | `TFeePayerAddress` *extends* `string` | Supply a string literal to define a fee payer having a particular address. | | `TTransactionMessage` *extends* [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\< \| `TransactionMessageWithFeePayer`\<`string`> \| [`TransactionMessageWithFeePayerSigner`](/api/interfaces/TransactionMessageWithFeePayerSigner)\<`string`, [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>>> & `TransactionMessage` | The inferred type of the transaction message provided. | ## Parameters | Parameter | Type | | -------------------- | ------------------------------------------------------------------------------- | | `feePayer` | [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TFeePayerAddress`> | | `transactionMessage` | `TTransactionMessage` | ## Returns `ExcludeTransactionMessageFeePayer`\<`TTransactionMessage`> & [`TransactionMessageWithFeePayerSigner`](/api/interfaces/TransactionMessageWithFeePayerSigner)\<`TFeePayerAddress`, [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`TFeePayerAddress`>> ## Example ```ts import { pipe } from '@solana/functional'; import { generateKeyPairSigner, setTransactionMessageFeePayerSigner } from '@solana/signers'; import { createTransactionMessage } from '@solana/transaction-messages'; const feePayer = await generateKeyPairSigner(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), message => setTransactionMessageFeePayerSigner(signer, message), ); ``` # setTransactionMessageHeapSize (/api/functions/setTransactionMessageHeapSize) ```ts function setTransactionMessageHeapSize( heapSize, transactionMessage, ): TTransactionMessage; ``` Sets the heap frame size for a transaction message. This function works with all transaction versions: * **V1**: Sets the `heapSize` field in the transaction message's config. * **Legacy / V0**: Appends (or replaces) a `RequestHeapFrame` instruction from the Compute Budget program. ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------- | ----------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | The transaction message type. | ## Parameters | Parameter | Type | Description | | -------------------- | ----------------------- | ----------------------------------------------------------------------------- | | `heapSize` | `number` \| `undefined` | The requested heap frame size in bytes, or `undefined` to remove the setting. | | `transactionMessage` | `TTransactionMessage` | The transaction message to configure. | ## Returns `TTransactionMessage` A new transaction message with the heap size set. ## Example ```ts const txMessage = setTransactionMessageHeapSize( 256_000, transactionMessage, ); ``` # setTransactionMessageLifetimeUsingBlockhash (/api/functions/setTransactionMessageLifetimeUsingBlockhash) ```ts function setTransactionMessageLifetimeUsingBlockhash< TTransactionMessage, >( blockhashLifetimeConstraint, transactionMessage, ): ExcludeTransactionMessageLifetime & TransactionMessageWithBlockhashLifetime; ``` Given a blockhash and the last block height at which that blockhash is considered usable to land transactions, this method will return a new transaction message having the same type as the one supplied plus the `TransactionMessageWithBlockhashLifetime` type. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TTransactionMessage` *extends* [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Pick`](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)\<[`TransactionMessageWithLifetime`](/api/type-aliases/TransactionMessageWithLifetime), `"lifetimeConstraint"`>> & [`TransactionMessage`](/api/type-aliases/TransactionMessage) | ## Parameters | Parameter | Type | | ----------------------------- | ------------------------------------------------------------------------------ | | `blockhashLifetimeConstraint` | [`BlockhashLifetimeConstraint`](/api/type-aliases/BlockhashLifetimeConstraint) | | `transactionMessage` | `TTransactionMessage` | ## Returns [`ExcludeTransactionMessageLifetime`](/api/type-aliases/ExcludeTransactionMessageLifetime)\<`TTransactionMessage`> & [`TransactionMessageWithBlockhashLifetime`](/api/interfaces/TransactionMessageWithBlockhashLifetime) ## Example ```ts import { setTransactionMessageLifetimeUsingBlockhash } from '@solana/transaction-messages'; const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const txMessageWithBlockhashLifetime = setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, txMessage); ``` # setTransactionMessageLifetimeUsingDurableNonce (/api/functions/setTransactionMessageLifetimeUsingDurableNonce) ```ts function setTransactionMessageLifetimeUsingDurableNonce< TTransactionMessage, TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue, >( config, transactionMessage, ): SetTransactionMessageWithDurableNonceLifetime< TTransactionMessage, TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue >; ``` Given a nonce, the account where the value of the nonce is stored, and the address of the account authorized to consume that nonce, this method will return a new transaction having the same type as the one supplied plus the [TransactionMessageWithDurableNonceLifetime](/api/interfaces/TransactionMessageWithDurableNonceLifetime) type. In particular, this method *prepends* an instruction to the transaction message designed to consume (or 'advance') the nonce in the same transaction whose lifetime is defined by it. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------- | ------------ | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | - | | `TNonceAccountAddress` *extends* `string` | `string` | | `TNonceAuthorityAddress` *extends* `string` | `string` | | `TNonceValue` *extends* `string` | `string` | ## Parameters | Parameter | Type | Description | | -------------------- | -------------------------------------------------------------------------------------- | ----------- | | `config` | `DurableNonceConfig`\<`TNonceAccountAddress`, `TNonceAuthorityAddress`, `TNonceValue`> | - | | `transactionMessage` | `TTransactionMessage` | - | ## Returns `SetTransactionMessageWithDurableNonceLifetime`\<`TTransactionMessage`, `TNonceAccountAddress`, `TNonceAuthorityAddress`, `TNonceValue`> ## Example ```ts import { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from '@solana/transaction-messages'; import { fetchNonce } from '@solana-program/system'; const nonceAccountAddress = address('EGtMh4yvXswwHhwVhyPxGrVV2TkLTgUqGodbATEPvojZ'); const nonceAuthorityAddress = address('4KD1Rdrd89NG7XbzW3xsX9Aqnx2EExJvExiNme6g9iAT'); const { data: { blockhash }, } = await fetchNonce(rpc, nonceAccountAddress); const nonce = blockhash as string as Nonce; const durableNonceTransactionMessage = setTransactionMessageLifetimeUsingDurableNonce( { nonce, nonceAccountAddress, nonceAuthorityAddress }, tx, ); ``` # setTransactionMessageLoadedAccountsDataSizeLimit (/api/functions/setTransactionMessageLoadedAccountsDataSizeLimit) ```ts function setTransactionMessageLoadedAccountsDataSizeLimit< TTransactionMessage, >(loadedAccountsDataSizeLimit, transactionMessage): TTransactionMessage; ``` Sets the loaded accounts data size limit for a transaction message. This function works with all transaction versions: * **V1**: Sets the `loadedAccountsDataSizeLimit` field in the transaction message's config. * **Legacy / V0**: Appends (or replaces) a `SetLoadedAccountsDataSizeLimit` instruction from the Compute Budget program. ## Type Parameters | Type Parameter | Description | | -------------------------------------------------------------------------------------------- | ----------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) | The transaction message type. | ## Parameters | Parameter | Type | Description | | ----------------------------- | ----------------------- | -------------------------------------------------------------------------------------- | | `loadedAccountsDataSizeLimit` | `number` \| `undefined` | The maximum size in bytes for loaded account data, or `undefined` to remove the limit. | | `transactionMessage` | `TTransactionMessage` | The transaction message to configure. | ## Returns `TTransactionMessage` A new transaction message with the loaded accounts data size limit set. ## Example ```ts const txMessage = setTransactionMessageLoadedAccountsDataSizeLimit( 64_000, transactionMessage, ); ``` # setTransactionMessagePriorityFeeLamports (/api/functions/setTransactionMessagePriorityFeeLamports) ```ts function setTransactionMessagePriorityFeeLamports( priorityFeeLamports, transactionMessage, ): TTransactionMessage; ``` Sets the total priority fee for a v1 transaction message. In v1 transactions, the priority fee is expressed as a total amount in lamports β€” what you set is what you pay, regardless of the compute unit limit. ## Type Parameters | Type Parameter | Description | | ------------------------------------------------------------------------------------------------------- | ----------------------------- | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & `object` | The transaction message type. | ## Parameters | Parameter | Type | Description | | --------------------- | ----------------------- | ---------------------------------------------------------------------- | | `priorityFeeLamports` | `bigint` \| `undefined` | The priority fee amount in lamports, or `undefined` to remove the fee. | | `transactionMessage` | `TTransactionMessage` | The v1 transaction message to configure. | ## Returns `TTransactionMessage` A new transaction message with the priority fee set. ## Example ```ts const txMessage = setTransactionMessagePriorityFeeLamports( 10_000n, transactionMessage, ); ``` ## See * [getTransactionMessagePriorityFeeLamports](/api/functions/getTransactionMessagePriorityFeeLamports) * [setTransactionMessageComputeUnitPrice](/api/functions/setTransactionMessageComputeUnitPrice) for legacy/v0 transactions. # signAndSendTransactionMessageWithSigners (/api/functions/signAndSendTransactionMessageWithSigners) ```ts function signAndSendTransactionMessageWithSigners( transaction, config?, ): Promise; ``` Extracts all [TransactionSigners](/api/type-aliases/TransactionSigner) inside the provided transaction message and uses them to sign it before sending it immediately to the blockchain. It returns the signature of the sent transaction (i.e. its identifier) as bytes. ## Parameters | Parameter | Type | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `transaction` | TransactionMessage & TransactionMessageWithFeePayer\ & [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Pick`](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)\< \| [`TransactionMessageWithFeePayerSigner`](/api/interfaces/TransactionMessageWithFeePayerSigner)\<`string`, [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `feePayer`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `modifyAndSignTransactions?`: `undefined`; `signAndSendTransactions?`: `undefined`; `signTransactions?`: `undefined`; }>; }>, `"feePayer"`>> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `instructions`: readonly `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]> & [`InstructionWithSigners`](/api/interfaces/InstructionWithSigners)\<[`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>, readonly `AccountMetaWithSigner`\<[`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>>\[]>\[]; }> | | `config?` | [`BaseTransactionSignerConfig`](/api/interfaces/BaseTransactionSignerConfig) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`SignatureBytes`> ## Example ```ts import { signAndSendTransactionMessageWithSigners } from '@solana/signers'; const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage); // With additional config. const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage, { abortSignal: myAbortController.signal, }); ``` ## Remarks Similarly to the [partiallySignTransactionMessageWithSigners](/api/functions/partiallySignTransactionMessageWithSigners) function, it first uses all [TransactionModifyingSigners](/api/type-aliases/TransactionModifyingSigner) sequentially before using all [TransactionPartialSigners](/api/type-aliases/TransactionPartialSigner) in parallel. It then sends the transaction using the [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) it identified. Composite transaction signers are treated such that at least one sending signer is used if any. When a [TransactionSigner](/api/type-aliases/TransactionSigner) implements more than one interface, we use it as a: * [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner), if no other [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) exists. * [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner), if no other [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) exists. * [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner), otherwise. The provided transaction must contain exactly one [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) inside its account metas. If more than one composite signers implement the [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) interface, one of them will be selected as the sending signer. Otherwise, if multiple [TransactionSendingSigners](/api/type-aliases/TransactionSendingSigner) must be selected, the function will throw an error. If you'd like to assert that a transaction makes use of exactly one [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) *before* calling this function, you may use the [assertIsTransactionMessageWithSingleSendingSigner](/api/functions/assertIsTransactionMessageWithSingleSendingSigner) function. Alternatively, you may use the [isTransactionMessageWithSingleSendingSigner](/api/functions/isTransactionMessageWithSingleSendingSigner) function to provide a fallback in case the transaction does not contain any sending signer. ## See * [signAndSendTransactionWithSigners](/api/functions/signAndSendTransactionWithSigners) * [assertIsTransactionMessageWithSingleSendingSigner](/api/functions/assertIsTransactionMessageWithSingleSendingSigner) * [isTransactionMessageWithSingleSendingSigner](/api/functions/isTransactionMessageWithSingleSendingSigner) * [partiallySignTransactionMessageWithSigners](/api/functions/partiallySignTransactionMessageWithSigners) * [signTransactionMessageWithSigners](/api/functions/signTransactionMessageWithSigners) # signAndSendTransactionWithSigners (/api/functions/signAndSendTransactionWithSigners) ```ts function signAndSendTransactionWithSigners( signers, transaction, config?, ): Promise; ``` Signs a transaction using the provided signers and sends it immediately to the blockchain. It returns the signature of the sent transaction (i.e. its identifier) as bytes. Similarly to [partiallySignTransactionWithSigners](/api/functions/partiallySignTransactionWithSigners), it first uses all [TransactionModifyingSigners](/api/type-aliases/TransactionModifyingSigner) sequentially before using all [TransactionPartialSigners](/api/type-aliases/TransactionPartialSigner) in parallel. It then sends the transaction using the [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) it identified. Composite transaction signers are treated such that at least one sending signer is used if any. When a [TransactionSigner](/api/type-aliases/TransactionSigner) implements more than one interface, we use it as a: * [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner), if no other [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) exists. * [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner), if no other [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) exists. * [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner), otherwise. The provided signers must contain exactly one [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) that can be unambiguously resolved. If more than one composite signers implement the [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner) interface, one of them will be selected as the sending signer. Otherwise, if multiple [TransactionSendingSigners](/api/type-aliases/TransactionSendingSigner) must be selected, the function will throw an error. ## Parameters | Parameter | Type | Description | | ------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `signers` | readonly [`TransactionSigner`](/api/type-aliases/TransactionSigner)\[] | The signers to use. Must contain at least one resolvable [TransactionSendingSigner](/api/type-aliases/TransactionSendingSigner). | | `transaction` | `Transaction` | The compiled transaction to sign and send. | | `config?` | [`BaseTransactionSignerConfig`](/api/interfaces/BaseTransactionSignerConfig) | Optional configuration including an [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal). | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`SignatureBytes`> The signature of the sent transaction as bytes. ## Example ```ts const transactionSignature = await signAndSendTransactionWithSigners(mySigners, compiledTransaction); // With additional config. const transactionSignature = await signAndSendTransactionWithSigners(mySigners, compiledTransaction, { abortSignal: myAbortController.signal, }); ``` ## See * [assertContainsResolvableTransactionSendingSigner](/api/functions/assertContainsResolvableTransactionSendingSigner) * [partiallySignTransactionWithSigners](/api/functions/partiallySignTransactionWithSigners) * [signTransactionWithSigners](/api/functions/signTransactionWithSigners) * [signAndSendTransactionMessageWithSigners](/api/functions/signAndSendTransactionMessageWithSigners) # signBytes (/api/functions/signBytes) ```ts function signBytes(key, data): Promise; ``` Given a private [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and a `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a `Uint8Array`. ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------- | | `key` | [`CryptoKey`](https://developer.mozilla.org/docs/Web/API/CryptoKey) | | `data` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`SignatureBytes`](/api/type-aliases/SignatureBytes)> ## Example ```ts import { signBytes } from '@solana/keys'; const data = new Uint8Array([1, 2, 3]); const signature = await signBytes(privateKey, data); ``` # signOffchainMessageEnvelope (/api/functions/signOffchainMessageEnvelope) ```ts function signOffchainMessageEnvelope( keyPairs, offchainMessageEnvelope, ): Promise< FullySignedOffchainMessageEnvelope & TOffchainMessageEnvelope >; ``` Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are required to sign an offchain message envelope, this method will return a new signed envelope of type [FullySignedOffchainMessageEnvelope](/api/type-aliases/FullySignedOffchainMessageEnvelope). This function will throw unless the resulting message is fully signed. ## Type Parameters | Type Parameter | | --------------------------------------------------------------------------------------------------------- | | `TOffchainMessageEnvelope` *extends* [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope) | ## Parameters | Parameter | Type | | ------------------------- | -------------------------- | | `keyPairs` | `CryptoKeyPair`\[] | | `offchainMessageEnvelope` | `TOffchainMessageEnvelope` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`FullySignedOffchainMessageEnvelope`](/api/type-aliases/FullySignedOffchainMessageEnvelope) & `TOffchainMessageEnvelope`> ## Example ```ts import { generateKeyPair } from '@solana/keys'; import { signOffchainMessageEnvelope } from '@solana/offchain-messages'; const signedOffchainMessage = await signOffchainMessageEnvelope( [myPrivateKey], offchainMessageEnvelope, ); ``` ## See [partiallySignOffchainMessageEnvelope](/api/functions/partiallySignOffchainMessageEnvelope) if you want to sign the message without asserting that the resulting message envelope is fully signed. # signOffchainMessageWithSigners (/api/functions/signOffchainMessageWithSigners) ```ts function signOffchainMessageWithSigners( offchainMessage, config?, ): Promise< FullySignedOffchainMessageEnvelope & OffchainMessageEnvelope >; ``` Extracts all [MessageSigners](/api/type-aliases/MessageSigner) inside the provided offchain message and uses them to return a signed offchain message envelope before asserting that all signatures required by the message are present. This function delegates to the [partiallySignOffchainMessageWithSigners](/api/functions/partiallySignOffchainMessageWithSigners) function in order to extract signers from the offchain message and sign it. ## Parameters | Parameter | Type | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `offchainMessage` | `OffchainMessageWithRequiredSignatories`\< \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; }> \| [`OffchainMessageSignatorySigner`](/api/type-aliases/OffchainMessageSignatorySigner)> & [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<`OffchainMessage`, `"requiredSignatories"`> | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `abortSignal?`: [`AbortSignal`](https://developer.mozilla.org/docs/Web/API/AbortSignal); }> | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`FullySignedOffchainMessageEnvelope` & `OffchainMessageEnvelope`> ## Example ```ts const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage); // With additional config. const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage, { abortSignal: myAbortController.signal, }); // We now know the offchain message is fully signed. mySignedOffchainMessageEnvelope satisfies FullySignedOffchainMessageEnvelope; ``` ## See [partiallySignOffchainMessageWithSigners](/api/functions/partiallySignOffchainMessageWithSigners) # signTransaction (/api/functions/signTransaction) ```ts function signTransaction( keyPairs, transaction, ): Promise; ``` Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are required to sign a transaction, this method will return a new signed transaction of type [FullySignedTransaction](/api/type-aliases/FullySignedTransaction). This function will throw unless the resulting transaction is fully signed. ## Type Parameters | Type Parameter | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TTransaction` *extends* [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: [`TransactionMessageBytes`](/api/type-aliases/TransactionMessageBytes); `signatures`: [`SignaturesMap`](/api/type-aliases/SignaturesMap); }> | ## Parameters | Parameter | Type | | ------------- | ------------------ | | `keyPairs` | `CryptoKeyPair`\[] | | `transaction` | `TTransaction` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`FullySignedTransaction`](/api/type-aliases/FullySignedTransaction) & `TTransaction`> ## Example ```ts import { generateKeyPair } from '@solana/keys'; import { signTransaction } from '@solana/transactions'; const signedTransaction = await signTransaction([myPrivateKey], tx); ``` ## See [partiallySignTransaction](/api/functions/partiallySignTransaction) if you want to sign the transaction without asserting that the resulting transaction is fully signed. # signTransactionMessageWithSigners (/api/functions/signTransactionMessageWithSigners) ```ts function signTransactionMessageWithSigners( transactionMessage, config?, ): Promise< FullySignedTransaction & TransactionWithinSizeLimit & Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> & TransactionWithLifetime >; ``` Extracts all [TransactionSigners](/api/type-aliases/TransactionSigner) inside the provided transaction message and uses them to return a signed transaction before asserting that all signatures required by the transaction are present. This function delegates to the [partiallySignTransactionMessageWithSigners](/api/functions/partiallySignTransactionMessageWithSigners) function in order to extract signers from the transaction message and sign the transaction. ## Parameters | Parameter | Type | | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `transactionMessage` | TransactionMessage & TransactionMessageWithFeePayer\ & [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Pick`](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)\< \| [`TransactionMessageWithFeePayerSigner`](/api/interfaces/TransactionMessageWithFeePayerSigner)\<`string`, [`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `feePayer`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; }> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `modifyAndSignTransactions?`: `undefined`; `signAndSendTransactions?`: `undefined`; `signTransactions?`: `undefined`; }>; }>, `"feePayer"`>> & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `instructions`: readonly `Instruction`\<`string`, readonly (`AccountLookupMeta`\<`string`, `string`> \| `AccountMeta`\<`string`>)\[]> & [`InstructionWithSigners`](/api/interfaces/InstructionWithSigners)\<[`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>, readonly `AccountMetaWithSigner`\<[`TransactionSigner`](/api/type-aliases/TransactionSigner)\<`string`>>\[]>\[]; }> | | `config?` | [`BaseTransactionSignerConfig`](/api/interfaces/BaseTransactionSignerConfig) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`FullySignedTransaction` & `TransactionWithinSizeLimit` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: `TransactionMessageBytes`; `signatures`: `SignaturesMap`; }> & `TransactionWithLifetime`> ## Example ```ts const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage); // With additional config. const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage, { abortSignal: myAbortController.signal, }); // We now know the transaction is fully signed. mySignedTransaction satisfies FullySignedTransaction; ``` ## See * [signTransactionWithSigners](/api/functions/signTransactionWithSigners) * [partiallySignTransactionMessageWithSigners](/api/functions/partiallySignTransactionMessageWithSigners) * [signAndSendTransactionMessageWithSigners](/api/functions/signAndSendTransactionMessageWithSigners) # signTransactionWithSigners (/api/functions/signTransactionWithSigners) ```ts function signTransactionWithSigners( signers, transaction, config?, ): Promise< FullySignedTransaction & TransactionWithinSizeLimit & Readonly<{ messageBytes: TransactionMessageBytes; signatures: SignaturesMap; }> & TransactionWithLifetime >; ``` Signs a transaction using the provided signers and asserts that all signatures required by the transaction are present. This function delegates to [partiallySignTransactionWithSigners](/api/functions/partiallySignTransactionWithSigners) to sign the transaction, then asserts it is fully signed before returning. ## Parameters | Parameter | Type | Description | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `signers` | readonly ( \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; `modifyAndSignTransactions`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\ & `TransactionWithinSizeLimit` & `TransactionWithLifetime`\[]>; }> \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `address`: `Address`\<`string`>; `signTransactions`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\>\[]>; }>)\[] | The signers to use. Only [TransactionModifyingSigner](/api/type-aliases/TransactionModifyingSigner) and [TransactionPartialSigner](/api/type-aliases/TransactionPartialSigner) interfaces are accepted. | | `transaction` | `Transaction` | The compiled transaction to sign. | | `config?` | [`BaseTransactionSignerConfig`](/api/interfaces/BaseTransactionSignerConfig) | Optional configuration including an [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal). | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`FullySignedTransaction` & `TransactionWithinSizeLimit` & [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `messageBytes`: `TransactionMessageBytes`; `signatures`: `SignaturesMap`; }> & `TransactionWithLifetime`> The fully signed transaction. ## Example ```ts const mySignedTransaction = await signTransactionWithSigners(mySigners, compiledTransaction); // With additional config. const mySignedTransaction = await signTransactionWithSigners(mySigners, compiledTransaction, { abortSignal: myAbortController.signal, }); // We now know the transaction is fully signed. mySignedTransaction satisfies FullySignedTransaction; ``` ## See * [partiallySignTransactionWithSigners](/api/functions/partiallySignTransactionWithSigners) * [signAndSendTransactionWithSigners](/api/functions/signAndSendTransactionWithSigners) * [signTransactionMessageWithSigners](/api/functions/signTransactionMessageWithSigners) # signature (/api/functions/signature) ```ts function signature(putativeSignature): Signature; ``` This helper combines *asserting* that a string is an Ed25519 signature with *coercing* it to the [Signature](/api/type-aliases/Signature) type. It's best used with untrusted input. ## Parameters | Parameter | Type | | ------------------- | -------- | | `putativeSignature` | `string` | ## Returns [`Signature`](/api/type-aliases/Signature) ## Example ```ts import { signature } from '@solana/keys'; const signature = signature(userSuppliedSignature); const { value: [status], } = await rpc.getSignatureStatuses([signature]).send(); ``` # signatureBytes (/api/functions/signatureBytes) ```ts function signatureBytes(putativeSignatureBytes): SignatureBytes; ``` This helper combines *asserting* that a `ReadonlyUint8Array` is an Ed25519 signature with *coercing* it to the [SignatureBytes](/api/type-aliases/SignatureBytes) type. It's best used with untrusted input. ## Parameters | Parameter | Type | | ------------------------ | ---------------------------------------------------------- | | `putativeSignatureBytes` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ## Returns [`SignatureBytes`](/api/type-aliases/SignatureBytes) ## Example ```ts import { signatureBytes } from '@solana/keys'; const signature = signatureBytes(userSuppliedSignatureBytes); if (!(await verifySignature(publicKey, signature, data))) { throw new Error('The data were *not* signed by the private key associated with `publicKey`'); } ``` # singleInstructionPlan (/api/functions/singleInstructionPlan) ```ts function singleInstructionPlan(instruction): SingleInstructionPlan; ``` Creates a [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan) from an [Instruction](/api/interfaces/Instruction) object. ## Parameters | Parameter | Type | | ------------- | -------------------------------------------- | | `instruction` | [`Instruction`](/api/interfaces/Instruction) | ## Returns [`SingleInstructionPlan`](/api/type-aliases/SingleInstructionPlan) ## Example ```ts const plan = singleInstructionPlan(instructionA); ``` ## See [SingleInstructionPlan](/api/type-aliases/SingleInstructionPlan) # singleTransactionPlan (/api/functions/singleTransactionPlan) ```ts function singleTransactionPlan( transactionMessage, ): SingleTransactionPlan; ``` Creates a [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan) from a [TransactionMessage](/api/type-aliases/TransactionMessage) object. ## Type Parameters | Type Parameter | Default type | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | ## Parameters | Parameter | Type | | -------------------- | --------------------- | | `transactionMessage` | `TTransactionMessage` | ## Returns [`SingleTransactionPlan`](/api/type-aliases/SingleTransactionPlan)\<`TTransactionMessage`> ## Example ```ts const plan = singleTransactionPlan(transactionMessage); plan satisfies SingleTransactionPlan; ``` ## See [SingleTransactionPlan](/api/type-aliases/SingleTransactionPlan) # sol (/api/functions/sol) ```ts function sol(value, rounding?): Sol; ``` Parses a decimal string as a [Sol](/api/type-aliases/Sol) fixed-point value. The default rounding mode is `'strict'`, which throws `SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS` when the input has more than 9 fractional digits. Pass another `RoundingMode` to accept a rounded result. ## Parameters | Parameter | Type | | ----------- | -------------- | | `value` | `string` | | `rounding?` | `RoundingMode` | ## Returns [`Sol`](/api/type-aliases/Sol) ## Example ```ts sol('1.5'); // represents 1.5 SOL (raw === 1_500_000_000n) sol('0.000000001'); // the smallest representable amount: 1 Lamport sol('1.1234567891', 'round'); // rounded to 9 decimals ``` ## See * [solToLamports](/api/functions/solToLamports) * [lamportsToSol](/api/functions/lamportsToSol) # solToLamports (/api/functions/solToLamports) ```ts function solToLamports(value): Lamports; ``` Converts a [Sol](/api/type-aliases/Sol) fixed-point value to its equivalent [Lamports](/api/type-aliases/Lamports) bigint. This conversion is exact β€” a `Sol` value's raw bigint is exactly the Lamports count. ## Parameters | Parameter | Type | | --------- | ------------------------------ | | `value` | [`Sol`](/api/type-aliases/Sol) | ## Returns [`Lamports`](/api/type-aliases/Lamports) ## Example ```ts solToLamports(sol('1.5')); // lamports(1_500_000_000n) ``` ## See * [lamportsToSol](/api/functions/lamportsToSol) * [sol](/api/functions/sol) # some (/api/functions/some) ```ts function some(value): Option; ``` Creates a new [Option](/api/type-aliases/Option) that contains a value. This function explicitly wraps a value in an [Option](/api/type-aliases/Option) type. ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ## Parameters | Parameter | Type | Description | | --------- | ---- | ----------------------------------------------------------- | | `value` | `T` | The value to wrap in an [Option](/api/type-aliases/Option). | ## Returns [`Option`](/api/type-aliases/Option)\<`T`> An [Option](/api/type-aliases/Option) containing the provided value. ## Example Wrapping a value in an `Option`. ```ts const option = some('Hello'); option.value; // "Hello" isOption(option); // true isSome(option); // true isNone(option); // false ``` ## See * [Option](/api/type-aliases/Option) * [Some](/api/type-aliases/Some) # stringifiedBigInt (/api/functions/stringifiedBigInt) ```ts function stringifiedBigInt(putativeBigInt): StringifiedBigInt; ``` This helper combines *asserting* that a string will parse as a `BigInt` with *coercing* it to the [StringifiedBigInt](/api/type-aliases/StringifiedBigInt) type. It's best used with untrusted input. ## Parameters | Parameter | Type | | ---------------- | -------- | | `putativeBigInt` | `string` | ## Returns [`StringifiedBigInt`](/api/type-aliases/StringifiedBigInt) ## Example ```ts import { stringifiedBigInt } from '@solana/rpc-types'; const supplyString = stringifiedBigInt('1000000000'); ``` # stringifiedNumber (/api/functions/stringifiedNumber) ```ts function stringifiedNumber(putativeNumber): StringifiedNumber; ``` This helper combines *asserting* that a string will parse as a `Number` with *coercing* it to the [StringifiedNumber](/api/type-aliases/StringifiedNumber) type. It's best used with untrusted input. ## Parameters | Parameter | Type | | ---------------- | -------- | | `putativeNumber` | `string` | ## Returns [`StringifiedNumber`](/api/type-aliases/StringifiedNumber) ## Example ```ts import { stringifiedNumber } from '@solana/rpc-types'; const decimalNumberString = stringifiedNumber('-42.1'); ``` # stringifyJsonWithBigInts (/api/functions/stringifyJsonWithBigInts) ```ts function stringifyJsonWithBigInts(value, space?): string; ``` Transforms a value into a JSON string, whilst rendering bigints as large unsafe integers. ## Parameters | Parameter | Type | | --------- | -------------------- | | `value` | `unknown` | | `space?` | `string` \| `number` | ## Returns `string` # subtractBinaryFixedPoint (/api/functions/subtractBinaryFixedPoint) ```ts function subtractBinaryFixedPoint< TSignedness, TTotalBits, TFractionalBits, >(a, b): BinaryFixedPoint; ``` Subtracts `b` from `a` where both are [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) values of the same shape, and returns the result at the same shape. Throws `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH` if the two operands differ in shape, and `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW` if the difference does not fit the target shape. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `a` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> | | `b` | [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<[`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`>> | ## Returns [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`TSignedness`, `TTotalBits`, `TFractionalBits`> ## See [addBinaryFixedPoint](/api/functions/addBinaryFixedPoint) # subtractDecimalFixedPoint (/api/functions/subtractDecimalFixedPoint) ```ts function subtractDecimalFixedPoint( a, b, ): DecimalFixedPoint; ``` Subtracts `b` from `a` where both are [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) values of the same shape, and returns the result at the same shape. Throws `SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH` if the two operands differ in shape, and `SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW` if the difference does not fit the target shape. ## Type Parameters | Type Parameter | | -------------------------------------------------------------------- | | `TSignedness` *extends* [`Signedness`](/api/type-aliases/Signedness) | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `a` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> | | `b` | [`NoInfer`](https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype)\<[`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`>> | ## Returns [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`TSignedness`, `TTotalBits`, `TDecimals`> ## See [addDecimalFixedPoint](/api/functions/addDecimalFixedPoint) # successfulSingleTransactionPlanResult (/api/functions/successfulSingleTransactionPlanResult) ```ts function successfulSingleTransactionPlanResult< TContext, TTransactionMessage, >( plannedMessage, context, ): SuccessfulSingleTransactionPlanResult; ``` Creates a successful [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) from a transaction message and context. This function creates a single result with a 'successful' status, indicating that the transaction was successfully executed. It also includes the original transaction message and a context object, which becomes the result's `context` as-is, typed as `TContext`. Passing a context containing a `signature` β€” the common case β€” yields the default [TransactionPlanResultContextWithSignature](/api/type-aliases/TransactionPlanResultContextWithSignature) shape; supply a different context shape when the transaction has no fee payer signature to report. ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | The type of the transaction message | ## Parameters | Parameter | Type | Description | | ---------------- | --------------------- | ---------------------------------------------------------------- | | `plannedMessage` | `TTransactionMessage` | The original transaction message | | `context` | `TContext` | The context object to be included with the result, as `TContext` | ## Returns [`SuccessfulSingleTransactionPlanResult`](/api/type-aliases/SuccessfulSingleTransactionPlanResult)\<`TContext`, `TTransactionMessage`> ## Example ```ts const result = successfulSingleTransactionPlanResult( transactionMessage, { signature }, ); result satisfies SingleTransactionPlanResult; ``` ## See [SingleTransactionPlanResult](/api/type-aliases/SingleTransactionPlanResult) # summarizeTransactionPlanResult (/api/functions/summarizeTransactionPlanResult) ```ts function summarizeTransactionPlanResult( result, ): TransactionPlanResultSummary; ``` Summarize a [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) into a [TransactionPlanResultSummary](/api/type-aliases/TransactionPlanResultSummary). ## Type Parameters | Type Parameter | Default type | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | | `TContext` *extends* [`TransactionPlanResultContext`](/api/type-aliases/TransactionPlanResultContext) | [`TransactionPlanResultContextWithSignature`](/api/type-aliases/TransactionPlanResultContextWithSignature) | The type of the context object that may be passed along with results | | `TTransactionMessage` *extends* [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | [`TransactionMessage`](/api/type-aliases/TransactionMessage) & [`TransactionMessageWithFeePayer`](/api/interfaces/TransactionMessageWithFeePayer)\<`string`> | The type of the transaction message | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | ---------------------------------------- | | `result` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult)\<`TContext`, `TTransactionMessage`> | The transaction plan result to summarize | ## Returns [`TransactionPlanResultSummary`](/api/type-aliases/TransactionPlanResultSummary)\<`TContext`, `TTransactionMessage`> A summary of the transaction plan result # testnet (/api/functions/testnet) ```ts function testnet(putativeString): TestnetUrl; ``` Given a URL casts it to a type that is only accepted where testnet URLs are expected. ## Parameters | Parameter | Type | | ---------------- | -------- | | `putativeString` | `string` | ## Returns [`TestnetUrl`](/api/type-aliases/TestnetUrl) # toArrayBuffer (/api/functions/toArrayBuffer) ```ts function toArrayBuffer(bytes, offset?, length?): ArrayBuffer; ``` Converts a `Uint8Array` to an `ArrayBuffer`. If the underlying buffer is a `SharedArrayBuffer`, it will be copied to a non-shared buffer, for safety. ## Parameters | Parameter | Type | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `bytes` | \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array)\<`ArrayBufferLike`> \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\<`ArrayBufferLike`> | | `offset?` | `number` | | `length?` | `number` | ## Returns [`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) ## Remarks Source: [https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer](https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer) # toSignedBinaryFixedPoint (/api/functions/toSignedBinaryFixedPoint) ```ts function toSignedBinaryFixedPoint( value, ): BinaryFixedPoint<'signed', TTotalBits, TFractionalBits>; ``` Converts a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) to its signed equivalent at the same `totalBits` and `fractionalBits`. Signed inputs are returned by reference unchanged; unsigned inputs are accepted as long as their raw value fits the signed range, i.e. `raw <= 2 ** (totalBits - 1) - 1`. Throws `SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE` when the input's raw value exceeds the maximum representable signed value at its `totalBits`. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `value` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `TTotalBits`, `TFractionalBits`> | ## Returns [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`"signed"`, `TTotalBits`, `TFractionalBits`> ## Example ```ts const unsigned = rawBinaryFixedPoint('unsigned', 8, 0); toSignedBinaryFixedPoint(unsigned(100n)); // signed, raw === 100n toSignedBinaryFixedPoint(unsigned(200n)); // throws (200 > 127) ``` ## See [toUnsignedBinaryFixedPoint](/api/functions/toUnsignedBinaryFixedPoint) # toSignedDecimalFixedPoint (/api/functions/toSignedDecimalFixedPoint) ```ts function toSignedDecimalFixedPoint( value, ): DecimalFixedPoint<'signed', TTotalBits, TDecimals>; ``` Converts a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) to its signed equivalent at the same `totalBits` and `decimals`. Signed inputs are returned by reference unchanged; unsigned inputs are accepted as long as their raw value fits the signed range, i.e. `raw <= 2 ** (totalBits - 1) - 1`. Throws `SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE` when the input's raw value exceeds the maximum representable signed value at its `totalBits`. ## Type Parameters | Type Parameter | | ------------------------------- | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `value` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `TTotalBits`, `TDecimals`> | ## Returns [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`"signed"`, `TTotalBits`, `TDecimals`> ## Example ```ts const unsigned = rawDecimalFixedPoint('unsigned', 8, 0); toSignedDecimalFixedPoint(unsigned(100n)); // signed, raw === 100n toSignedDecimalFixedPoint(unsigned(200n)); // throws (200 > 127) ``` ## See [toUnsignedDecimalFixedPoint](/api/functions/toUnsignedDecimalFixedPoint) # toUnsignedBinaryFixedPoint (/api/functions/toUnsignedBinaryFixedPoint) ```ts function toUnsignedBinaryFixedPoint( value, ): BinaryFixedPoint<'unsigned', TTotalBits, TFractionalBits>; ``` Converts a [BinaryFixedPoint](/api/type-aliases/BinaryFixedPoint) to its unsigned equivalent at the same `totalBits` and `fractionalBits`. Unsigned inputs are returned by reference unchanged; signed inputs are accepted as long as their raw value is non-negative. Throws `SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE` when the input represents a negative value that cannot be stored as unsigned. ## Type Parameters | Type Parameter | | ------------------------------------ | | `TTotalBits` *extends* `number` | | `TFractionalBits` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `value` | [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `TTotalBits`, `TFractionalBits`> | ## Returns [`BinaryFixedPoint`](/api/type-aliases/BinaryFixedPoint)\<`"unsigned"`, `TTotalBits`, `TFractionalBits`> ## Example ```ts const signedUsd = binaryFixedPoint('signed', 16, 8); toUnsignedBinaryFixedPoint(signedUsd('1.5')); // unsigned, raw unchanged toUnsignedBinaryFixedPoint(signedUsd('-1')); // throws ``` ## See [toSignedBinaryFixedPoint](/api/functions/toSignedBinaryFixedPoint) # toUnsignedDecimalFixedPoint (/api/functions/toUnsignedDecimalFixedPoint) ```ts function toUnsignedDecimalFixedPoint( value, ): DecimalFixedPoint<'unsigned', TTotalBits, TDecimals>; ``` Converts a [DecimalFixedPoint](/api/type-aliases/DecimalFixedPoint) to its unsigned equivalent at the same `totalBits` and `decimals`. Unsigned inputs are returned by reference unchanged; signed inputs are accepted as long as their raw value is non-negative. Throws `SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE` when the input represents a negative value that cannot be stored as unsigned. ## Type Parameters | Type Parameter | | ------------------------------- | | `TTotalBits` *extends* `number` | | `TDecimals` *extends* `number` | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `value` | [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<[`Signedness`](/api/type-aliases/Signedness), `TTotalBits`, `TDecimals`> | ## Returns [`DecimalFixedPoint`](/api/type-aliases/DecimalFixedPoint)\<`"unsigned"`, `TTotalBits`, `TDecimals`> ## Example ```ts const signedUsd = decimalFixedPoint('signed', 64, 2); toUnsignedDecimalFixedPoint(signedUsd('1.50')); // unsigned, raw unchanged toUnsignedDecimalFixedPoint(signedUsd('-1')); // throws ``` ## See [toSignedDecimalFixedPoint](/api/functions/toSignedDecimalFixedPoint) # transactionConfigMaskHasComputeUnitLimit (/api/functions/transactionConfigMaskHasComputeUnitLimit) ```ts function transactionConfigMaskHasComputeUnitLimit(mask): boolean; ``` Checks whether the transaction config mask indicates a compute unit limit is present. The compute unit limit uses bit 2 of the mask. ## Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------- | | `mask` | `number` | The transaction config mask to check. | ## Returns `boolean` `true` if the mask indicates a compute unit limit is present, `false` otherwise. ## Example ```ts const hasComputeUnitLimit = transactionConfigMaskHasComputeUnitLimit(0b100); // true (bit 2 is set) ``` # transactionConfigMaskHasHeapSize (/api/functions/transactionConfigMaskHasHeapSize) ```ts function transactionConfigMaskHasHeapSize(mask): boolean; ``` Checks whether the transaction config mask indicates a heap size is present. The heap size uses bit 4 of the mask. ## Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------- | | `mask` | `number` | The transaction config mask to check. | ## Returns `boolean` `true` if the mask indicates a heap size is present, `false` otherwise. ## Example ```ts const hasHeapSize = transactionConfigMaskHasHeapSize(0b10000); // true (bit 4 is set) ``` # transactionConfigMaskHasLoadedAccountsDataSizeLimit (/api/functions/transactionConfigMaskHasLoadedAccountsDataSizeLimit) ```ts function transactionConfigMaskHasLoadedAccountsDataSizeLimit( mask, ): boolean; ``` Checks whether the transaction config mask indicates a loaded accounts data size limit is present. The loaded accounts data size limit uses bit 3 of the mask. ## Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------- | | `mask` | `number` | The transaction config mask to check. | ## Returns `boolean` `true` if the mask indicates a loaded accounts data size limit is present, `false` otherwise. ## Example ```ts const hasLimit = transactionConfigMaskHasLoadedAccountsDataSizeLimit(0b1000); // true (bit 3 is set) ``` # transactionConfigMaskHasPriorityFee (/api/functions/transactionConfigMaskHasPriorityFee) ```ts function transactionConfigMaskHasPriorityFee(mask): boolean; ``` Checks whether the transaction config mask indicates a priority fee is present. The priority fee uses bits 0 and 1 of the mask. Both bits must be set or both must be unset β€” having only one bit set is invalid and will throw an error. ## Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------- | | `mask` | `number` | The transaction config mask to check. | ## Returns `boolean` `true` if the mask indicates a priority fee is present, `false` otherwise. ## Throws Throws `SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS` if only one of the two priority fee bits is set. ## Example Check if a mask has a priority fee. ```ts const hasPriorityFee = transactionConfigMaskHasPriorityFee(0b11); // true (both bits 0 and 1 are set) ``` # transformChannelInboundMessages (/api/functions/transformChannelInboundMessages) ```ts function transformChannelInboundMessages< TOutboundMessage, TNewInboundMessage, TInboundMessage, >( channel, transform, ): RpcSubscriptionsChannel; ``` Given a channel with inbound messages of type `T` and a function of type `T => U`, returns a new channel with inbound messages of type `U`. Note that this only affects messages of type `"message"` and thus, does not affect incoming error messages. ## Type Parameters | Type Parameter | | -------------------- | | `TOutboundMessage` | | `TNewInboundMessage` | | `TInboundMessage` | ## Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------------------ | | `channel` | [`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`TOutboundMessage`, `TInboundMessage`> | | `transform` | (`message`) => `TNewInboundMessage` | ## Returns [`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`TOutboundMessage`, `TNewInboundMessage`> ## Example **Parsing incoming JSON messages** ```ts const transformedChannel = transformChannelInboundMessages(channel, JSON.parse); ``` # transformChannelOutboundMessages (/api/functions/transformChannelOutboundMessages) ```ts function transformChannelOutboundMessages< TNewOutboundMessage, TOutboundMessage, TInboundMessage, >( channel, transform, ): RpcSubscriptionsChannel; ``` Given a channel with outbound messages of type `T` and a function of type `U => T`, returns a new channel with outbound messages of type `U`. ## Type Parameters | Type Parameter | | --------------------- | | `TNewOutboundMessage` | | `TOutboundMessage` | | `TInboundMessage` | ## Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------------------ | | `channel` | [`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`TOutboundMessage`, `TInboundMessage`> | | `transform` | (`message`) => `TOutboundMessage` | ## Returns [`RpcSubscriptionsChannel`](/api/interfaces/RpcSubscriptionsChannel)\<`TNewOutboundMessage`, `TInboundMessage`> ## Example **Stringifying JSON messages before sending them over the wire** ```ts const transformedChannel = transformChannelOutboundMessages(channel, JSON.stringify); ``` # transformCodec (/api/functions/transformCodec) ## Call Signature ```ts function transformCodec( codec, unmap, ): FixedSizeCodec; ``` Transforms a codec by mapping its input and output values. This function takes an existing `Codec` and returns a `Codec`, allowing: * Values of type `C` to be transformed into `A` before encoding. * Values of type `B` to be transformed into `D` after decoding. This is useful for adapting codecs to work with different representations, handling default values, or converting between primitive and structured types. ### Type Parameters | Type Parameter | Description | | -------------------------- | ------------------------------------------------------ | | `TOldFrom` | The original type expected by the codec. | | `TNewFrom` | The new type that will be transformed before encoding. | | `TTo` | - | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | `codec` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TOldFrom`, `TTo`, `TSize`> | The codec to transform. | | `unmap` | (`value`) => `TOldFrom` | A function that converts values of `TNewFrom` into `TOldFrom` before encoding. | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TNewFrom`, `TTo`, `TSize`> A new codec that encodes `TNewFrom` and decodes into `TNewTo`. ### Example Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters. ```ts const codec = transformCodec( getU32Codec(), (value: string) => value.length, // Encode string length (length) => 'x'.repeat(length) // Decode length into a string of 'x's ); const bytes = codec.encode("hello"); // 0x05000000 (stores length 5) const value = codec.decode(bytes); // "xxxxx" ``` ### Remarks If only input transformation is needed, use [transformEncoder](/api/functions/transformEncoder). If only output transformation is needed, use [transformDecoder](/api/functions/transformDecoder). ```ts const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode("hello"); const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes); ``` ### See * [transformEncoder](/api/functions/transformEncoder) * [transformDecoder](/api/functions/transformDecoder) ## Call Signature ```ts function transformCodec( codec, unmap, ): VariableSizeCodec; ``` Transforms a codec by mapping its input and output values. This function takes an existing `Codec` and returns a `Codec`, allowing: * Values of type `C` to be transformed into `A` before encoding. * Values of type `B` to be transformed into `D` after decoding. This is useful for adapting codecs to work with different representations, handling default values, or converting between primitive and structured types. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------------ | | `TOldFrom` | The original type expected by the codec. | | `TNewFrom` | The new type that will be transformed before encoding. | | `TTo` | - | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | `codec` | [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TOldFrom`, `TTo`> | The codec to transform. | | `unmap` | (`value`) => `TOldFrom` | A function that converts values of `TNewFrom` into `TOldFrom` before encoding. | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TNewFrom`, `TTo`> A new codec that encodes `TNewFrom` and decodes into `TNewTo`. ### Example Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters. ```ts const codec = transformCodec( getU32Codec(), (value: string) => value.length, // Encode string length (length) => 'x'.repeat(length) // Decode length into a string of 'x's ); const bytes = codec.encode("hello"); // 0x05000000 (stores length 5) const value = codec.decode(bytes); // "xxxxx" ``` ### Remarks If only input transformation is needed, use [transformEncoder](/api/functions/transformEncoder). If only output transformation is needed, use [transformDecoder](/api/functions/transformDecoder). ```ts const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode("hello"); const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes); ``` ### See * [transformEncoder](/api/functions/transformEncoder) * [transformDecoder](/api/functions/transformDecoder) ## Call Signature ```ts function transformCodec( codec, unmap, ): Codec; ``` Transforms a codec by mapping its input and output values. This function takes an existing `Codec` and returns a `Codec`, allowing: * Values of type `C` to be transformed into `A` before encoding. * Values of type `B` to be transformed into `D` after decoding. This is useful for adapting codecs to work with different representations, handling default values, or converting between primitive and structured types. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------------ | | `TOldFrom` | The original type expected by the codec. | | `TNewFrom` | The new type that will be transformed before encoding. | | `TTo` | - | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------ | ------------------------------------------------------------------------------ | | `codec` | [`Codec`](/api/type-aliases/Codec)\<`TOldFrom`, `TTo`> | The codec to transform. | | `unmap` | (`value`) => `TOldFrom` | A function that converts values of `TNewFrom` into `TOldFrom` before encoding. | ### Returns [`Codec`](/api/type-aliases/Codec)\<`TNewFrom`, `TTo`> A new codec that encodes `TNewFrom` and decodes into `TNewTo`. ### Example Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters. ```ts const codec = transformCodec( getU32Codec(), (value: string) => value.length, // Encode string length (length) => 'x'.repeat(length) // Decode length into a string of 'x's ); const bytes = codec.encode("hello"); // 0x05000000 (stores length 5) const value = codec.decode(bytes); // "xxxxx" ``` ### Remarks If only input transformation is needed, use [transformEncoder](/api/functions/transformEncoder). If only output transformation is needed, use [transformDecoder](/api/functions/transformDecoder). ```ts const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode("hello"); const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes); ``` ### See * [transformEncoder](/api/functions/transformEncoder) * [transformDecoder](/api/functions/transformDecoder) ## Call Signature ```ts function transformCodec( codec, unmap, map, ): FixedSizeCodec; ``` Transforms a codec by mapping its input and output values. This function takes an existing `Codec` and returns a `Codec`, allowing: * Values of type `C` to be transformed into `A` before encoding. * Values of type `B` to be transformed into `D` after decoding. This is useful for adapting codecs to work with different representations, handling default values, or converting between primitive and structured types. ### Type Parameters | Type Parameter | Description | | -------------------------- | ------------------------------------------------------ | | `TOldFrom` | The original type expected by the codec. | | `TNewFrom` | The new type that will be transformed before encoding. | | `TOldTo` | The original type returned by the codec. | | `TNewTo` | The new type that will be transformed after decoding. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | `codec` | [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TOldFrom`, `TOldTo`, `TSize`> | The codec to transform. | | `unmap` | (`value`) => `TOldFrom` | A function that converts values of `TNewFrom` into `TOldFrom` before encoding. | | `map` | (`value`, `bytes`, `offset`) => `TNewTo` | A function that converts values of `TOldTo` into `TNewTo` after decoding (optional). | ### Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`TNewFrom`, `TNewTo`, `TSize`> A new codec that encodes `TNewFrom` and decodes into `TNewTo`. ### Example Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters. ```ts const codec = transformCodec( getU32Codec(), (value: string) => value.length, // Encode string length (length) => 'x'.repeat(length) // Decode length into a string of 'x's ); const bytes = codec.encode("hello"); // 0x05000000 (stores length 5) const value = codec.decode(bytes); // "xxxxx" ``` ### Remarks If only input transformation is needed, use [transformEncoder](/api/functions/transformEncoder). If only output transformation is needed, use [transformDecoder](/api/functions/transformDecoder). ```ts const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode("hello"); const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes); ``` ### See * [transformEncoder](/api/functions/transformEncoder) * [transformDecoder](/api/functions/transformDecoder) ## Call Signature ```ts function transformCodec( codec, unmap, map, ): VariableSizeCodec; ``` Transforms a codec by mapping its input and output values. This function takes an existing `Codec` and returns a `Codec`, allowing: * Values of type `C` to be transformed into `A` before encoding. * Values of type `B` to be transformed into `D` after decoding. This is useful for adapting codecs to work with different representations, handling default values, or converting between primitive and structured types. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------------ | | `TOldFrom` | The original type expected by the codec. | | `TNewFrom` | The new type that will be transformed before encoding. | | `TOldTo` | The original type returned by the codec. | | `TNewTo` | The new type that will be transformed after decoding. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | `codec` | [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TOldFrom`, `TOldTo`> | The codec to transform. | | `unmap` | (`value`) => `TOldFrom` | A function that converts values of `TNewFrom` into `TOldFrom` before encoding. | | `map` | (`value`, `bytes`, `offset`) => `TNewTo` | A function that converts values of `TOldTo` into `TNewTo` after decoding (optional). | ### Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`TNewFrom`, `TNewTo`> A new codec that encodes `TNewFrom` and decodes into `TNewTo`. ### Example Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters. ```ts const codec = transformCodec( getU32Codec(), (value: string) => value.length, // Encode string length (length) => 'x'.repeat(length) // Decode length into a string of 'x's ); const bytes = codec.encode("hello"); // 0x05000000 (stores length 5) const value = codec.decode(bytes); // "xxxxx" ``` ### Remarks If only input transformation is needed, use [transformEncoder](/api/functions/transformEncoder). If only output transformation is needed, use [transformDecoder](/api/functions/transformDecoder). ```ts const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode("hello"); const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes); ``` ### See * [transformEncoder](/api/functions/transformEncoder) * [transformDecoder](/api/functions/transformDecoder) ## Call Signature ```ts function transformCodec( codec, unmap, map, ): Codec; ``` Transforms a codec by mapping its input and output values. This function takes an existing `Codec` and returns a `Codec`, allowing: * Values of type `C` to be transformed into `A` before encoding. * Values of type `B` to be transformed into `D` after decoding. This is useful for adapting codecs to work with different representations, handling default values, or converting between primitive and structured types. ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------------ | | `TOldFrom` | The original type expected by the codec. | | `TNewFrom` | The new type that will be transformed before encoding. | | `TOldTo` | The original type returned by the codec. | | `TNewTo` | The new type that will be transformed after decoding. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------ | | `codec` | [`Codec`](/api/type-aliases/Codec)\<`TOldFrom`, `TOldTo`> | The codec to transform. | | `unmap` | (`value`) => `TOldFrom` | A function that converts values of `TNewFrom` into `TOldFrom` before encoding. | | `map` | (`value`, `bytes`, `offset`) => `TNewTo` | A function that converts values of `TOldTo` into `TNewTo` after decoding (optional). | ### Returns [`Codec`](/api/type-aliases/Codec)\<`TNewFrom`, `TNewTo`> A new codec that encodes `TNewFrom` and decodes into `TNewTo`. ### Example Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters. ```ts const codec = transformCodec( getU32Codec(), (value: string) => value.length, // Encode string length (length) => 'x'.repeat(length) // Decode length into a string of 'x's ); const bytes = codec.encode("hello"); // 0x05000000 (stores length 5) const value = codec.decode(bytes); // "xxxxx" ``` ### Remarks If only input transformation is needed, use [transformEncoder](/api/functions/transformEncoder). If only output transformation is needed, use [transformDecoder](/api/functions/transformDecoder). ```ts const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode("hello"); const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes); ``` ### See * [transformEncoder](/api/functions/transformEncoder) * [transformDecoder](/api/functions/transformDecoder) # transformDecoder (/api/functions/transformDecoder) ## Call Signature ```ts function transformDecoder( decoder, map, ): FixedSizeDecoder; ``` Transforms a decoder by mapping its output values. This function takes an existing `Decoder` and returns a `Decoder`, allowing values of type `A` to be converted into values of type `B` after decoding. The transformation is applied via the `map` function. This is useful for post-processing, type conversions, or enriching decoded data. For more details, see [transformCodec](/api/functions/transformCodec). ### Type Parameters | Type Parameter | Description | | -------------------------- | ----------------------------------------------------- | | `TOldTo` | The original type returned by the decoder. | | `TNewTo` | The new type that will be transformed after decoding. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | `decoder` | [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TOldTo`, `TSize`> | The decoder to transform. | | `map` | (`value`, `bytes`, `offset`) => `TNewTo` | A function that converts values of `TOldTo` into `TNewTo` after decoding. | ### Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`TNewTo`, `TSize`> A new decoder that decodes into `TNewTo`. ### Example Decoding a stored `u32` length into a string of `'x'` characters. ```ts const decoder = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)); decoder.decode(new Uint8Array([0x05, 0x00, 0x00, 0x00])); // "xxxxx" ``` ### See * [transformCodec](/api/functions/transformCodec) * [transformEncoder](/api/functions/transformEncoder) ## Call Signature ```ts function transformDecoder( decoder, map, ): VariableSizeDecoder; ``` Transforms a decoder by mapping its output values. This function takes an existing `Decoder` and returns a `Decoder`, allowing values of type `A` to be converted into values of type `B` after decoding. The transformation is applied via the `map` function. This is useful for post-processing, type conversions, or enriching decoded data. For more details, see [transformCodec](/api/functions/transformCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------------------- | | `TOldTo` | The original type returned by the decoder. | | `TNewTo` | The new type that will be transformed after decoding. | ### Parameters | Parameter | Type | Description | | --------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------- | | `decoder` | [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TOldTo`> | The decoder to transform. | | `map` | (`value`, `bytes`, `offset`) => `TNewTo` | A function that converts values of `TOldTo` into `TNewTo` after decoding. | ### Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`TNewTo`> A new decoder that decodes into `TNewTo`. ### Example Decoding a stored `u32` length into a string of `'x'` characters. ```ts const decoder = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)); decoder.decode(new Uint8Array([0x05, 0x00, 0x00, 0x00])); // "xxxxx" ``` ### See * [transformCodec](/api/functions/transformCodec) * [transformEncoder](/api/functions/transformEncoder) ## Call Signature ```ts function transformDecoder( decoder, map, ): Decoder; ``` Transforms a decoder by mapping its output values. This function takes an existing `Decoder` and returns a `Decoder`, allowing values of type `A` to be converted into values of type `B` after decoding. The transformation is applied via the `map` function. This is useful for post-processing, type conversions, or enriching decoded data. For more details, see [transformCodec](/api/functions/transformCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------------------------- | | `TOldTo` | The original type returned by the decoder. | | `TNewTo` | The new type that will be transformed after decoding. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------- | ------------------------------------------------------------------------- | | `decoder` | [`Decoder`](/api/type-aliases/Decoder)\<`TOldTo`> | The decoder to transform. | | `map` | (`value`, `bytes`, `offset`) => `TNewTo` | A function that converts values of `TOldTo` into `TNewTo` after decoding. | ### Returns [`Decoder`](/api/type-aliases/Decoder)\<`TNewTo`> A new decoder that decodes into `TNewTo`. ### Example Decoding a stored `u32` length into a string of `'x'` characters. ```ts const decoder = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)); decoder.decode(new Uint8Array([0x05, 0x00, 0x00, 0x00])); // "xxxxx" ``` ### See * [transformCodec](/api/functions/transformCodec) * [transformEncoder](/api/functions/transformEncoder) # transformEncoder (/api/functions/transformEncoder) ## Call Signature ```ts function transformEncoder( encoder, unmap, ): FixedSizeEncoder; ``` Transforms an encoder by mapping its input values. This function takes an existing `Encoder` and returns an `Encoder`, allowing values of type `B` to be converted into values of type `A` before encoding. The transformation is applied via the `unmap` function. This is useful for handling type conversions, applying default values, or structuring data before encoding. For more details, see [transformCodec](/api/functions/transformCodec). ### Type Parameters | Type Parameter | Description | | -------------------------- | ------------------------------------------------------ | | `TOldFrom` | The original type expected by the encoder. | | `TNewFrom` | The new type that will be transformed before encoding. | | `TSize` *extends* `number` | - | ### Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | `encoder` | [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TOldFrom`, `TSize`> | The encoder to transform. | | `unmap` | (`value`) => `TOldFrom` | A function that converts values of `TNewFrom` into `TOldFrom` before encoding. | ### Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`TNewFrom`, `TSize`> A new encoder that accepts `TNewFrom` values and transforms them before encoding. ### Example Encoding a string by counting its characters and storing the length as a `u32`. ```ts const encoder = transformEncoder(getU32Encoder(), (value: string) => value.length); encoder.encode("hello"); // 0x05000000 (stores length 5) ``` ### See * [transformCodec](/api/functions/transformCodec) * [transformDecoder](/api/functions/transformDecoder) ## Call Signature ```ts function transformEncoder( encoder, unmap, ): VariableSizeEncoder; ``` Transforms an encoder by mapping its input values. This function takes an existing `Encoder` and returns an `Encoder`, allowing values of type `B` to be converted into values of type `A` before encoding. The transformation is applied via the `unmap` function. This is useful for handling type conversions, applying default values, or structuring data before encoding. For more details, see [transformCodec](/api/functions/transformCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------------ | | `TOldFrom` | The original type expected by the encoder. | | `TNewFrom` | The new type that will be transformed before encoding. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | `encoder` | [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TOldFrom`> | The encoder to transform. | | `unmap` | (`value`) => `TOldFrom` | A function that converts values of `TNewFrom` into `TOldFrom` before encoding. | ### Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`TNewFrom`> A new encoder that accepts `TNewFrom` values and transforms them before encoding. ### Example Encoding a string by counting its characters and storing the length as a `u32`. ```ts const encoder = transformEncoder(getU32Encoder(), (value: string) => value.length); encoder.encode("hello"); // 0x05000000 (stores length 5) ``` ### See * [transformCodec](/api/functions/transformCodec) * [transformDecoder](/api/functions/transformDecoder) ## Call Signature ```ts function transformEncoder( encoder, unmap, ): Encoder; ``` Transforms an encoder by mapping its input values. This function takes an existing `Encoder` and returns an `Encoder`, allowing values of type `B` to be converted into values of type `A` before encoding. The transformation is applied via the `unmap` function. This is useful for handling type conversions, applying default values, or structuring data before encoding. For more details, see [transformCodec](/api/functions/transformCodec). ### Type Parameters | Type Parameter | Description | | -------------- | ------------------------------------------------------ | | `TOldFrom` | The original type expected by the encoder. | | `TNewFrom` | The new type that will be transformed before encoding. | ### Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------- | ------------------------------------------------------------------------------ | | `encoder` | [`Encoder`](/api/type-aliases/Encoder)\<`TOldFrom`> | The encoder to transform. | | `unmap` | (`value`) => `TOldFrom` | A function that converts values of `TNewFrom` into `TOldFrom` before encoding. | ### Returns [`Encoder`](/api/type-aliases/Encoder)\<`TNewFrom`> A new encoder that accepts `TNewFrom` values and transforms them before encoding. ### Example Encoding a string by counting its characters and storing the length as a `u32`. ```ts const encoder = transformEncoder(getU32Encoder(), (value: string) => value.length); encoder.encode("hello"); // 0x05000000 (stores length 5) ``` ### See * [transformCodec](/api/functions/transformCodec) * [transformDecoder](/api/functions/transformDecoder) # transformInstructionPlan (/api/functions/transformInstructionPlan) ```ts function transformInstructionPlan(instructionPlan, fn): InstructionPlan; ``` Transforms an instruction plan tree using a bottom-up approach. This function recursively traverses the instruction plan tree, applying the transformation function to each plan. The transformation is applied bottom-up, meaning nested plans are transformed first, then the parent plans receive the already-transformed children before being transformed themselves. All transformed plans are frozen using `Object.freeze` to ensure immutability. ## Parameters | Parameter | Type | Description | | ----------------- | ------------------------------------------------------------------ | ------------------------------------------------------------ | | `instructionPlan` | [`InstructionPlan`](/api/type-aliases/InstructionPlan) | The instruction plan tree to transform. | | `fn` | (`plan`) => [`InstructionPlan`](/api/type-aliases/InstructionPlan) | A function that transforms each plan and returns a new plan. | ## Returns [`InstructionPlan`](/api/type-aliases/InstructionPlan) A new transformed instruction plan tree. ## Examples Making all sequential plans non-divisible to ensure atomicity. ```ts const plan = sequentialInstructionPlan([instructionA, instructionB]); const transformed = transformInstructionPlan(plan, (p) => { if (p.kind === 'sequential' && p.divisible) { return nonDivisibleSequentialInstructionPlan(p.plans); } return p; }); ``` Filtering out debug instructions before production execution. ```ts const plan = sequentialInstructionPlan([instructionA, debugInstruction, instructionB]); const transformed = transformInstructionPlan(plan, (p) => { if (p.kind === 'sequential' || p.kind === 'parallel') { return { ...p, plans: p.plans.filter((p) => !isDebugInstruction(p)) }; } return p; }); ``` ## See * [InstructionPlan](/api/type-aliases/InstructionPlan) * [findInstructionPlan](/api/functions/findInstructionPlan) * [everyInstructionPlan](/api/functions/everyInstructionPlan) * [flattenInstructionPlan](/api/functions/flattenInstructionPlan) # transformTransactionPlan (/api/functions/transformTransactionPlan) ```ts function transformTransactionPlan(transactionPlan, fn): TransactionPlan; ``` Transforms a transaction plan tree using a bottom-up approach. This function recursively traverses the transaction plan tree, applying the transformation function to each plan. The transformation is applied bottom-up, meaning nested plans are transformed first, then the parent plans receive the already-transformed children before being transformed themselves. All transformed plans are frozen using `Object.freeze` to ensure immutability. ## Parameters | Parameter | Type | Description | | ----------------- | ------------------------------------------------------------------ | ------------------------------------------------------------ | | `transactionPlan` | [`TransactionPlan`](/api/type-aliases/TransactionPlan) | The transaction plan tree to transform. | | `fn` | (`plan`) => [`TransactionPlan`](/api/type-aliases/TransactionPlan) | A function that transforms each plan and returns a new plan. | ## Returns [`TransactionPlan`](/api/type-aliases/TransactionPlan) A new transformed transaction plan tree. ## Examples Removing parallelism by converting parallel plans to sequential. ```ts const plan = parallelTransactionPlan([messageA, messageB, messageC]); const transformed = transformTransactionPlan(plan, (p) => { if (p.kind === 'parallel') { return sequentialTransactionPlan(p.plans); } return p; }); ``` Updating the fee payer on all transaction messages. ```ts const plan = parallelTransactionPlan([messageA, messageB]); const transformed = transformTransactionPlan(plan, (p) => { if (p.kind === 'single') { return singleTransactionPlan({ ...p.message, feePayer: newFeePayer }); } return p; }); ``` ## See * [TransactionPlan](/api/type-aliases/TransactionPlan) * [findTransactionPlan](/api/functions/findTransactionPlan) * [everyTransactionPlan](/api/functions/everyTransactionPlan) * [flattenTransactionPlan](/api/functions/flattenTransactionPlan) # transformTransactionPlanResult (/api/functions/transformTransactionPlanResult) ```ts function transformTransactionPlanResult( transactionPlanResult, fn, ): TransactionPlanResult; ``` Transforms a transaction plan result tree using a bottom-up approach. This function recursively traverses the transaction plan result tree, applying the transformation function to each result. The transformation is applied bottom-up, meaning nested results are transformed first, then the parent results receive the already-transformed children before being transformed themselves. All transformed results are frozen using `Object.freeze` to ensure immutability. ## Parameters | Parameter | Type | Description | | ----------------------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------- | | `transactionPlanResult` | [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult) | The transaction plan result tree to transform. | | `fn` | (`plan`) => [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult) | A function that transforms each result and returns a new result. | ## Returns [`TransactionPlanResult`](/api/type-aliases/TransactionPlanResult) A new transformed transaction plan result tree. ## Example Converting all canceled results to failed results. ```ts const result = parallelTransactionPlanResult([ successfulSingleTransactionPlanResult(messageA, { signature: signatureA }), canceledSingleTransactionPlanResult(messageB), ]); const transformed = transformTransactionPlanResult(result, (r) => { if (r.kind === 'single' && r.status === 'canceled') { return failedSingleTransactionPlanResult(r.plannedMessage, new Error('Execution canceled')); } return r; }); ``` ## See * [TransactionPlanResult](/api/type-aliases/TransactionPlanResult) * [findTransactionPlanResult](/api/functions/findTransactionPlanResult) * [everyTransactionPlanResult](/api/functions/everyTransactionPlanResult) * [flattenTransactionPlanResult](/api/functions/flattenTransactionPlanResult) # unixTimestamp (/api/functions/unixTimestamp) ```ts function unixTimestamp(putativeTimestamp): UnixTimestamp; ``` This helper combines *asserting* that a `bigint` represents a Unix timestamp with *coercing* it to the [UnixTimestamp](/api/type-aliases/UnixTimestamp) type. It's best used with untrusted input. ## Parameters | Parameter | Type | | ------------------- | -------- | | `putativeTimestamp` | `bigint` | ## Returns [`UnixTimestamp`](/api/type-aliases/UnixTimestamp) ## Example ```ts import { unixTimestamp } from '@solana/rpc-types'; const timestamp = unixTimestamp(-42n); // Wednesday, December 31, 1969 3:59:18 PM GMT-08:00 ``` # unwrapOption (/api/functions/unwrapOption) ## Call Signature ```ts function unwrapOption(option): T | null; ``` Unwraps the value of an [Option](/api/type-aliases/Option), returning its contained value or a fallback. This function extracts the value `T` from an `Option` type. * If the option is [Some](/api/type-aliases/Some), it returns the contained value `T`. * If the option is [None](/api/type-aliases/None), it returns the fallback value `U`, which defaults to `null`. ### Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ### Parameters | Parameter | Type | Description | | --------- | ------------------------------------------ | ------------------------------------------------- | | `option` | [`Option`](/api/type-aliases/Option)\<`T`> | The [Option](/api/type-aliases/Option) to unwrap. | ### Returns `T` | `null` The contained value if [Some](/api/type-aliases/Some), otherwise the fallback value. ### Examples Unwrapping an `Option` with no fallback. ```ts unwrapOption(some('Hello World')); // "Hello World" unwrapOption(none()); // null ``` Providing a custom fallback value. ```ts unwrapOption(some('Hello World'), () => 'Default'); // "Hello World" unwrapOption(none(), () => 'Default'); // "Default" ``` ### See * [Option](/api/type-aliases/Option) * [Some](/api/type-aliases/Some) * [None](/api/type-aliases/None) ## Call Signature ```ts function unwrapOption(option, fallback): T | U; ``` Unwraps the value of an [Option](/api/type-aliases/Option), returning its contained value or a fallback. This function extracts the value `T` from an `Option` type. * If the option is [Some](/api/type-aliases/Some), it returns the contained value `T`. * If the option is [None](/api/type-aliases/None), it returns the fallback value `U`, which defaults to `null`. ### Type Parameters | Type Parameter | Description | | -------------- | ---------------------------------------------------- | | `T` | The type of the contained value. | | `U` | The type of the fallback value (defaults to `null`). | ### Parameters | Parameter | Type | Description | | ---------- | ------------------------------------------ | ------------------------------------------------------------------------------------------ | | `option` | [`Option`](/api/type-aliases/Option)\<`T`> | The [Option](/api/type-aliases/Option) to unwrap. | | `fallback` | () => `U` | A function that provides a fallback value if the option is [None](/api/type-aliases/None). | ### Returns `T` | `U` The contained value if [Some](/api/type-aliases/Some), otherwise the fallback value. ### Examples Unwrapping an `Option` with no fallback. ```ts unwrapOption(some('Hello World')); // "Hello World" unwrapOption(none()); // null ``` Providing a custom fallback value. ```ts unwrapOption(some('Hello World'), () => 'Default'); // "Hello World" unwrapOption(none(), () => 'Default'); // "Default" ``` ### See * [Option](/api/type-aliases/Option) * [Some](/api/type-aliases/Some) * [None](/api/type-aliases/None) # unwrapOptionRecursively (/api/functions/unwrapOptionRecursively) ## Call Signature ```ts function unwrapOptionRecursively(input): UnwrappedOption; ``` Recursively unwraps all nested [Option](/api/type-aliases/Option) types within a value. This function traverses a given value and removes all instances of [Option](/api/type-aliases/Option), replacing them with their contained values. * If an [Option](/api/type-aliases/Option) is encountered, its value is extracted. * If an array or object is encountered, its elements are traversed recursively. * If `None` is encountered, it is replaced with the fallback value (default: `null`). ### Type Parameters | Type Parameter | Description | | -------------- | ---------------------------- | | `T` | The type of the input value. | ### Parameters | Parameter | Type | Description | | --------- | ---- | -------------------- | | `input` | `T` | The value to unwrap. | ### Returns [`UnwrappedOption`](/api/type-aliases/UnwrappedOption)\<`T`> The recursively unwrapped value. ### Examples Recursively unwrapping nested options. ```ts unwrapOptionRecursively(some(some('Hello World'))); // "Hello World" unwrapOptionRecursively(some(none())); // null ``` Recursively unwrapping options inside objects and arrays. ```ts unwrapOptionRecursively({ a: 'hello', b: none(), c: [{ c1: some(42) }, { c2: none() }], }); // { a: "hello", b: null, c: [{ c1: 42 }, { c2: null }] } ``` Using a fallback value for `None` options. ```ts unwrapOptionRecursively( { a: 'hello', b: none(), c: [{ c1: some(42) }, { c2: none() }], }, () => 'Default', ); // { a: "hello", b: "Default", c: [{ c1: 42 }, { c2: "Default" }] } ``` ### Remarks This function does not mutate objects or arrays. ### See * [Option](/api/type-aliases/Option) * [UnwrappedOption](/api/type-aliases/UnwrappedOption) ## Call Signature ```ts function unwrapOptionRecursively( input, fallback, ): UnwrappedOption; ``` Recursively unwraps all nested [Option](/api/type-aliases/Option) types within a value. This function traverses a given value and removes all instances of [Option](/api/type-aliases/Option), replacing them with their contained values. * If an [Option](/api/type-aliases/Option) is encountered, its value is extracted. * If an array or object is encountered, its elements are traversed recursively. * If `None` is encountered, it is replaced with the fallback value (default: `null`). ### Type Parameters | Type Parameter | Description | | -------------- | --------------------------------------------------------- | | `T` | The type of the input value. | | `U` | The fallback type for `None` values (defaults to `null`). | ### Parameters | Parameter | Type | Description | | ---------- | --------- | ------------------------------------------------------------- | | `input` | `T` | The value to unwrap. | | `fallback` | () => `U` | A function that provides a fallback value for `None` options. | ### Returns [`UnwrappedOption`](/api/type-aliases/UnwrappedOption)\<`T`, `U`> The recursively unwrapped value. ### Examples Recursively unwrapping nested options. ```ts unwrapOptionRecursively(some(some('Hello World'))); // "Hello World" unwrapOptionRecursively(some(none())); // null ``` Recursively unwrapping options inside objects and arrays. ```ts unwrapOptionRecursively({ a: 'hello', b: none(), c: [{ c1: some(42) }, { c2: none() }], }); // { a: "hello", b: null, c: [{ c1: 42 }, { c2: null }] } ``` Using a fallback value for `None` options. ```ts unwrapOptionRecursively( { a: 'hello', b: none(), c: [{ c1: some(42) }, { c2: none() }], }, () => 'Default', ); // { a: "hello", b: "Default", c: [{ c1: 42 }, { c2: "Default" }] } ``` ### Remarks This function does not mutate objects or arrays. ### See * [Option](/api/type-aliases/Option) * [UnwrappedOption](/api/type-aliases/UnwrappedOption) # unwrapSimulationError (/api/functions/unwrapSimulationError) ```ts function unwrapSimulationError(error): unknown; ``` Extracts the underlying cause from a simulation-related error. When a transaction simulation fails, the error is often wrapped in a simulation-specific [SolanaError](/api/classes/SolanaError). This function unwraps such errors by returning the `cause` property, giving you access to the actual error that triggered the simulation failure. If the provided error is not a simulation-related error, it is returned unchanged. The following error codes are considered simulation errors: * [SOLANA\_ERROR\_\_JSON\_RPC\_\_SERVER\_ERROR\_SEND\_TRANSACTION\_PREFLIGHT\_FAILURE](/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) * [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_WHEN\_SIMULATING\_TO\_ESTIMATE\_COMPUTE\_LIMIT](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT) * [SOLANA\_ERROR\_\_TRANSACTION\_\_FAILED\_WHEN\_SIMULATING\_TO\_ESTIMATE\_RESOURCE\_LIMITS](/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS) ## Parameters | Parameter | Type | Description | | --------- | --------- | -------------------- | | `error` | `unknown` | The error to unwrap. | ## Returns `unknown` The underlying cause if the error is a simulation error, otherwise the original error. ## Example Unwrapping a preflight failure to access the root cause. ```ts import { unwrapSimulationError } from '@solana/errors'; try { await sendTransaction(signedTransaction); } catch (e) { const cause = unwrapSimulationError(e); console.log('Send transaction failed due to:', cause); } ``` # upgradeRoleToSigner (/api/functions/upgradeRoleToSigner) ## Call Signature ```ts function upgradeRoleToSigner(role): READONLY_SIGNER; ``` ### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `role` | [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) | ### Returns [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) An [AccountRole](/api/enumerations/AccountRole) representing the signer variant of the supplied role. ## Call Signature ```ts function upgradeRoleToSigner(role): WRITABLE_SIGNER; ``` ### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `role` | [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) | ### Returns [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) An [AccountRole](/api/enumerations/AccountRole) representing the signer variant of the supplied role. ## Call Signature ```ts function upgradeRoleToSigner(role): AccountRole; ``` ### Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `role` | [`AccountRole`](/api/enumerations/AccountRole) | ### Returns [`AccountRole`](/api/enumerations/AccountRole) An [AccountRole](/api/enumerations/AccountRole) representing the signer variant of the supplied role. # upgradeRoleToWritable (/api/functions/upgradeRoleToWritable) ## Call Signature ```ts function upgradeRoleToWritable(role): WRITABLE; ``` ### Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------------- | | `role` | [`READONLY`](/api/enumerations/AccountRole#enumeration-member-readonly) | ### Returns [`WRITABLE`](/api/enumerations/AccountRole#enumeration-member-writable) An [AccountRole](/api/enumerations/AccountRole) representing the writable variant of the supplied role. ## Call Signature ```ts function upgradeRoleToWritable(role): WRITABLE_SIGNER; ``` ### Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------- | | `role` | [`READONLY_SIGNER`](/api/enumerations/AccountRole#enumeration-member-readonly_signer) | ### Returns [`WRITABLE_SIGNER`](/api/enumerations/AccountRole#enumeration-member-writable_signer) An [AccountRole](/api/enumerations/AccountRole) representing the writable variant of the supplied role. ## Call Signature ```ts function upgradeRoleToWritable(role): AccountRole; ``` ### Parameters | Parameter | Type | | --------- | ---------------------------------------------- | | `role` | [`AccountRole`](/api/enumerations/AccountRole) | ### Returns [`AccountRole`](/api/enumerations/AccountRole) An [AccountRole](/api/enumerations/AccountRole) representing the writable variant of the supplied role. # useAction (/api/functions/useAction) ```ts function useAction(fn): ActionResult; ``` Bridge an arbitrary async function into a reactive [ActionResult](/api/type-aliases/ActionResult). Each `dispatch(...)` call runs the function with a fresh [AbortSignal](https://developer.mozilla.org/docs/Web/API/AbortSignal) and tracks its lifecycle through React state; a second call while a first is in flight aborts the first. `fn` is held in a ref that always points at the latest closure β€” there is no `deps` array to maintain. Each `dispatch(...)` invokes the most recently rendered `fn`, so values captured inside (e.g. form state, route params) are always fresh without explicit dependency tracking. In-flight calls are unaffected β€” they continue with the closure they captured at dispatch time. ## Type Parameters | Type Parameter | Description | | --------------------------------------- | -------------------------------------------------------------------------------- | | `TArgs` *extends* readonly `unknown`\[] | The argument tuple `dispatch` accepts; forwarded to `fn` after the abort signal. | | `TResult` | The value `fn` resolves to on success. | ## Parameters | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `fn` | (`signal`, ...`args`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`TResult`> | ## Returns [`ActionResult`](/api/type-aliases/ActionResult)\<`TArgs`, `TResult`> ## Example ```tsx import { useAction } from '@solana/react'; function PostMessageButton({ url, body }: { url: string; body: string }) { const { dispatch, isRunning, error } = useAction(async (signal, content: string) => { const res = await fetch(url, { body: content, method: 'POST', signal }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json() as Promise<{ id: string }>; }); return ( ); } ``` ## See [ActionResult](/api/type-aliases/ActionResult) # useAirdrop (/api/functions/useAirdrop) ```ts function useAirdrop( client, ): ActionResult<[Address, Lamports], Signature | undefined>; ``` Requests an airdrop of SOL to an address, as a reactive action. Wraps `client.airdrop` with [useAction](/api/functions/useAction): each `dispatch(address, amount)` runs the airdrop with a fresh `AbortSignal` and tracks its lifecycle through React state. Calling `dispatch` again while a previous airdrop is in flight aborts the first. This is a great fit for a devnet or localnet "fund this account" button, where the `isRunning` / `data` / `error` tracking drives the UI directly. The airdrop capability is typically available on test networks (devnet, testnet) and local validators. Some implementations (e.g. LiteSVM) update balances directly without sending a transaction, in which case the resolved `data` is `undefined` rather than a Signature. ## Parameters | Parameter | Type | Description | | --------- | ------------------- | ---------------------------------------------------------------- | | `client` | `ClientWithAirdrop` | A client with an airdrop plugin installed (`ClientWithAirdrop`). | ## Returns [`ActionResult`](/api/type-aliases/ActionResult)\<\[`Address`, `Lamports`], `Signature` | `undefined`> An [ActionResult](/api/type-aliases/ActionResult) whose `dispatch`/`dispatchAsync` take the recipient `address` and the `amount` of lamports, and resolve with the transaction Signature, or `undefined` when the airdrop was performed without a transaction. ## Example ```tsx import { useAirdrop } from '@solana/react'; import { lamports } from '@solana/kit'; function AirdropButton({ client, address }) { const { dispatch, isRunning } = useAirdrop(client); return ( ); } ``` ## See * [ActionResult](/api/type-aliases/ActionResult) * [useAction](/api/functions/useAction) # useClient (/api/functions/useClient) ```ts function useClient(): Client; ``` Reads the Kit client published by the nearest [ClientProvider](/api/functions/ClientProvider). Throws a SolanaError with code SOLANA\_ERROR\_\_REACT\_\_MISSING\_PROVIDER if no provider is mounted in the ancestor tree. Pass the shape of your client through the generic (typically the `AppClient` type you export alongside the client) so every installed capability is typed at the call site. This is a pure cast with no runtime capability check, so reach for [useClientCapability](/api/functions/useClientCapability) when a missing plugin should fail loudly at mount instead of surfacing later as `undefined`. ## Type Parameters | Type Parameter | Description | | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TClient` *extends* `object` | The shape the client is expected to satisfy. Pure type assertion, so this must always be supplied β€” the hook can't infer it from its (absent) arguments. | ## Returns `Client`\<`TClient`> ## Example ```tsx import { ClientWithRpc, GetEpochInfoApi } from '@solana/kit'; import { useClient } from '@solana/react'; function ManualSend() { const client = useClient>(); return ; } ``` ## See * [ClientProvider](/api/functions/ClientProvider) * [useClientCapability](/api/functions/useClientCapability) # useClientCapability (/api/functions/useClientCapability) ```ts function useClientCapability( __namedParameters, ): Client; ``` Reads the client from the nearest [ClientProvider](/api/functions/ClientProvider) and asserts at mount that the requested capability is installed, narrowing the return type via the generic. Throws a SolanaError with code SOLANA\_ERROR\_\_REACT\_\_MISSING\_CAPABILITY when the capability is absent β€” including the calling `hookName` and a `providerHint` so users can fix the mistake without cross-referencing docs. Use this from the implementation of plugin-specific hooks. Apps that need ad-hoc access without a runtime check can reach for [useClient](/api/functions/useClient) directly and supply their own type narrowing. ## Type Parameters | Type Parameter | Description | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `TClient` *extends* `object` | The narrowed client shape returned once the capability assertion passes. Always pass this generic β€” the hook can't infer it from a string. | ## Parameters | Parameter | Type | | ------------------- | -------------------------------------------------------------------------- | | `__namedParameters` | [`UseClientCapabilityConfig`](/api/type-aliases/UseClientCapabilityConfig) | ## Returns `Client`\<`TClient`> ## Example ```ts import { ClientWithRpc, GetEpochInfoApi } from '@solana/kit'; import { useClientCapability } from '@solana/react'; function useRpc() { return useClientCapability>({ capability: 'rpc', hookName: 'useRpc', providerHint: 'Install `solanaRpc()` on the client.', }); } ``` ## See * [useClient](/api/functions/useClient) * [ClientProvider](/api/functions/ClientProvider) # useIdentity (/api/functions/useIdentity) ```ts function useIdentity(client): TransactionSigner | undefined; ``` Reads `client.identity` and re-renders whenever it changes, returning `undefined` while no identity is available. The identity is the TransactionSigner representing the wallet whose on-chain assets the application is acting upon. When the client advertises ClientWithSubscribeToIdentity, this hook subscribes via `client.subscribeToIdentity` so the returned value always reflects the latest identity. For a client whose identity is fixed for its lifetime, the hook falls back to a no-op subscription and simply reads the value once. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `client` | `ClientWithIdentity` & [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<`ClientWithSubscribeToIdentity`> | A client with an identity plugin installed. If it also advertises `subscribeToIdentity`, the hook tracks changes reactively. | ## Returns `TransactionSigner` | `undefined` The current `client.identity` signer, or `undefined` if no identity is currently available. ## Example ```tsx const identity = useIdentity(client); return {identity ? `Signed in as ${identity.address}` : 'Signed out'}; ``` ## See [usePayer](/api/functions/usePayer) # usePayer (/api/functions/usePayer) ```ts function usePayer(client): TransactionSigner | undefined; ``` Reads `client.payer` and re-renders whenever it changes, returning `undefined` while no payer is available. The payer is the TransactionSigner a client uses to sign and pay for transactions by default. When the client advertises ClientWithSubscribeToPayer, this hook subscribes via `client.subscribeToPayer` so the returned value always reflects the latest payer. For a client whose payer is fixed for its lifetime, the hook falls back to a no-op subscription and simply reads the value once. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | `client` | `ClientWithPayer` & [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<`ClientWithSubscribeToPayer`> | A client with a payer plugin installed. If it also advertises `subscribeToPayer`, the hook tracks changes reactively. | ## Returns `TransactionSigner` | `undefined` The current `client.payer` signer, or `undefined` if no payer is currently available. ## Example ```tsx const payer = usePayer(client); return {payer ? `Paying with ${payer.address}` : 'No payer'}; ``` ## See [useIdentity](/api/functions/useIdentity) # usePlanTransaction (/api/functions/usePlanTransaction) ```ts function usePlanTransaction( client, ): ActionResult< [InstructionPlanInput], TransactionMessage & TransactionMessageWithFeePayer >; ``` Plans a single transaction from an instruction input, as a reactive action. Wraps `client.planTransaction` with [useAction](/api/functions/useAction): each `dispatch(input)` runs the plan with a fresh `AbortSignal` and tracks its lifecycle through React state. Calling `dispatch` again while a previous plan is in flight aborts the first. Use this when you expect all instructions to fit in a single transaction; reach for [usePlanTransactions](/api/functions/usePlanTransactions) when they might need splitting. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------- | ------------------------------------------------------ | | `client` | `ClientWithTransactionPlanning` | A client with a transaction-planning plugin installed. | ## Returns [`ActionResult`](/api/type-aliases/ActionResult)\<\[`InstructionPlanInput`], `TransactionMessage` & `TransactionMessageWithFeePayer`\<`string`>> An [ActionResult](/api/type-aliases/ActionResult) whose `dispatch`/`dispatchAsync` take the InstructionPlanInput and resolve with the planned transaction message. ## Example ```tsx const { dispatch, data, isRunning } = usePlanTransaction(client); ``` ## See * [usePlanTransactions](/api/functions/usePlanTransactions) * [useSendTransaction](/api/functions/useSendTransaction) # usePlanTransactions (/api/functions/usePlanTransactions) ```ts function usePlanTransactions( client, ): ActionResult<[InstructionPlanInput], TransactionPlan>; ``` Plans one or more transactions from an instruction input, as a reactive action. Wraps `client.planTransactions` with [useAction](/api/functions/useAction): each `dispatch(input)` runs the plan with a fresh `AbortSignal` and tracks its lifecycle through React state. Calling `dispatch` again while a previous plan is in flight aborts the first. Use this when the instructions might be split across multiple transactions due to size limits; reach for [usePlanTransaction](/api/functions/usePlanTransaction) for the single- transaction case. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------- | ------------------------------------------------------ | | `client` | `ClientWithTransactionPlanning` | A client with a transaction-planning plugin installed. | ## Returns [`ActionResult`](/api/type-aliases/ActionResult)\<\[`InstructionPlanInput`], `TransactionPlan`> An [ActionResult](/api/type-aliases/ActionResult) whose `dispatch`/`dispatchAsync` take the InstructionPlanInput and resolve with the full TransactionPlan. ## Example ```tsx const { dispatch, data, isRunning } = usePlanTransactions(client); ``` ## See * [usePlanTransaction](/api/functions/usePlanTransaction) * [useSendTransactions](/api/functions/useSendTransactions) # useRequest (/api/functions/useRequest) ```ts function useRequest(source, options?): RequestResult; ``` Fire a one-shot request on mount and re-fire each time `source` changes identity or `refresh()` is called. Returns reactive state tracking the call's lifecycle. Two ways to pass the work: * A ReactiveActionSource β€” the `{ reactiveStore() }` duck-type satisfied by `PendingRpcRequest`. * An async function `(signal: AbortSignal) => Promise` β€” wrap any one-shot async source (a `fetch`, a third-party SDK call, etc). Most general shape. Pass `null` to disable; the result reports `status: 'disabled'`. Memoize the input (`useMemo` for a source, `useCallback` for a function) keyed on whatever inputs it depends on. ## Type Parameters | Type Parameter | Description | | -------------- | --------------------------------------------- | | `T` | The value the underlying request resolves to. | ## Parameters | Parameter | Type | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `source` | \| `ReactiveActionSource`\<`T`> \| ((`signal`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`T`>) \| `null` | | `options?` | [`UseRequestOptions`](/api/type-aliases/UseRequestOptions) | ## Returns [`RequestResult`](/api/type-aliases/RequestResult)\<`T`> ## Example ```tsx function LatestBlockhash() { const client = useClient>(); const source = useMemo(() => client.rpc.getLatestBlockhash(), [client]); const { data, error, refresh } = useRequest(source, { getAbortSignal: () => AbortSignal.timeout(5_000), }); if (error) return ; return

{data ? `Blockhash: ${data.value.blockhash}` : 'Loading…'}

; } // Function shape β€” wraps an arbitrary async call: function Profile({ userId }: { userId: string }) { const fetcher = useCallback( (signal: AbortSignal) => fetch(`/api/users/${userId}`, { signal }).then(r => r.json()), [userId], ); const { data, error, refresh } = useRequest(fetcher); if (error) return ; return

{data ? data.name : 'Loading…'}

; } ``` ## See * [RequestResult](/api/type-aliases/RequestResult) * [UseRequestOptions](/api/type-aliases/UseRequestOptions) # useSelectedWalletAccount (/api/functions/useSelectedWalletAccount) ```ts function useSelectedWalletAccount(): SelectedWalletAccountContextValue; ``` ## Returns [`SelectedWalletAccountContextValue`](/api/type-aliases/SelectedWalletAccountContextValue) # useSendTransaction (/api/functions/useSendTransaction) ```ts function useSendTransaction(client): ActionResult< [ | InstructionPlanInput | (TransactionMessage & TransactionMessageWithFeePayer) | Readonly<{ kind: 'single'; message: TransactionMessage & TransactionMessageWithFeePayer; planType: 'transactionPlan'; }>, ], SuccessfulSingleTransactionPlanResult >; ``` Sends a single transaction to the network, as a reactive action. Wraps `client.sendTransaction` with [useAction](/api/functions/useAction), which handles signing, submission, and confirmation. Each `dispatch(input)` runs with a fresh `AbortSignal` and tracks its lifecycle through React state; calling `dispatch` again while a previous send is in flight aborts the first. Accepts flexible input: instructions, an instruction plan, a single transaction message, or a single transaction plan. Use [useSendTransactions](/api/functions/useSendTransactions) when the work may span multiple transactions. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------ | ----------------------------------------------------- | | `client` | `ClientWithTransactionSending` | A client with a transaction-sending plugin installed. | ## Returns [`ActionResult`](/api/type-aliases/ActionResult)\<\[ \| `InstructionPlanInput` \| TransactionMessage & TransactionMessageWithFeePayer\ \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `kind`: `"single"`; `message`: TransactionMessage & TransactionMessageWithFeePayer\; `planType`: `"transactionPlan"`; }>], `SuccessfulSingleTransactionPlanResult`> An [ActionResult](/api/type-aliases/ActionResult) whose `dispatch`/`dispatchAsync` take the input and resolve with the SuccessfulSingleTransactionPlanResult. ## Example ```tsx const { dispatch, data, isRunning } = useSendTransaction(client); ``` ## See * [useSendTransactions](/api/functions/useSendTransactions) * [usePlanTransaction](/api/functions/usePlanTransaction) # useSendTransactions (/api/functions/useSendTransactions) ```ts function useSendTransactions( client, ): ActionResult< [InstructionPlanInput | TransactionPlanInput], TransactionPlanResult >; ``` Sends one or more transactions to the network, as a reactive action. Wraps `client.sendTransactions` with [useAction](/api/functions/useAction), which handles signing, submission, and confirmation. Each `dispatch(input)` runs with a fresh `AbortSignal` and tracks its lifecycle through React state; calling `dispatch` again while a previous send is in flight aborts the first. Accepts flexible input: instructions, an instruction plan, or a transaction plan. Use [useSendTransaction](/api/functions/useSendTransaction) for the single-transaction case. ## Parameters | Parameter | Type | Description | | --------- | ------------------------------ | ----------------------------------------------------- | | `client` | `ClientWithTransactionSending` | A client with a transaction-sending plugin installed. | ## Returns [`ActionResult`](/api/type-aliases/ActionResult)\<\[`InstructionPlanInput` | `TransactionPlanInput`], `TransactionPlanResult`> An [ActionResult](/api/type-aliases/ActionResult) whose `dispatch`/`dispatchAsync` take the input and resolve with the TransactionPlanResult for all transactions. ## Example ```tsx const { dispatch, data, isRunning } = useSendTransactions(client); ``` ## See * [useSendTransaction](/api/functions/useSendTransaction) * [usePlanTransactions](/api/functions/usePlanTransactions) # useSignAndSendTransaction (/api/functions/useSignAndSendTransaction) ## Call Signature ```ts function useSignAndSendTransaction( uiWalletAccount, chain, ): (input) => Promise; ``` Use this to get a function capable of signing a serialized transaction with the private key of a UiWalletAccount and sending it to the network for processing. ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | Description | | ----------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | - | | `chain` | `OnlySolanaChains`\<`TWalletAccount`\[`"chains"`]> | The identifier of the chain the transaction is destined for. Wallets may use this to simulate the transaction for the user. | ### Returns (`input`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`SolanaSignAndSendTransactionOutput`> ### Example ```tsx import { getBase58Decoder } from '@solana/codecs-strings'; import { useSignAndSendTransaction } from '@solana/react'; function SignAndSendTransactionButton({ account, transactionBytes }) { const signAndSendTransaction = useSignAndSendTransaction(account, 'solana:devnet'); return ( ); } ``` ## Call Signature ```ts function useSignAndSendTransaction( uiWalletAccount, chain, ): (input) => Promise; ``` Use this to get a function capable of signing a serialized transaction with the private key of a UiWalletAccount and sending it to the network for processing. ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | Description | | ----------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | - | | `chain` | `` `solana:${string}` `` | The identifier of the chain the transaction is destined for. Wallets may use this to simulate the transaction for the user. | ### Returns (`input`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`SolanaSignAndSendTransactionOutput`> ### Example ```tsx import { getBase58Decoder } from '@solana/codecs-strings'; import { useSignAndSendTransaction } from '@solana/react'; function SignAndSendTransactionButton({ account, transactionBytes }) { const signAndSendTransaction = useSignAndSendTransaction(account, 'solana:devnet'); return ( ); } ``` # useSignAndSendTransactions (/api/functions/useSignAndSendTransactions) ## Call Signature ```ts function useSignAndSendTransactions( uiWalletAccount, chain, ): ( ...inputs ) => Promise; ``` Use this to get a function capable of signing one or more serialized transactions with the private key of a UiWalletAccount and sending them to the network for processing. This supports wallets that allow batching multiple transactions in a single request. ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | | ----------------- | -------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | | `chain` | `OnlySolanaChains`\<`TWalletAccount`\[`"chains"`]> | ### Returns (...`inputs`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\ ### Example ```tsx import { useSignAndSendTransactions } from '@solana/react'; function SignAndSendTransactionsButton({ account, transactionBytes1, transactionBytes2 }) { const signAndSendTransactions = useSignAndSendTransactions(account, 'solana:devnet'); return ( ); } ``` ## Call Signature ```ts function useSignAndSendTransactions( uiWalletAccount, chain, ): ( ...inputs ) => Promise; ``` Use this to get a function capable of signing one or more serialized transactions with the private key of a UiWalletAccount and sending them to the network for processing. This supports wallets that allow batching multiple transactions in a single request. ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | | ----------------- | ------------------------ | | `uiWalletAccount` | `TWalletAccount` | | `chain` | `` `solana:${string}` `` | ### Returns (...`inputs`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\ ### Example ```tsx import { useSignAndSendTransactions } from '@solana/react'; function SignAndSendTransactionsButton({ account, transactionBytes1, transactionBytes2 }) { const signAndSendTransactions = useSignAndSendTransactions(account, 'solana:devnet'); return ( ); } ``` # useSignIn (/api/functions/useSignIn) ## Call Signature ```ts function useSignIn(uiWalletAccount): (input?) => Promise; ``` Use the ['Sign In With Solana'](https://phantom.app/learn/developers/sign-in-with-solana) feature of a UiWallet or UiWalletAccount. ### Parameters | Parameter | Type | | ----------------- | ----------------- | | `uiWalletAccount` | `UiWalletAccount` | ### Returns A function that you can call to sign in with the particular wallet and address specified by the supplied UiWalletAccount (`input?`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`Output`> ### Example ```tsx import { useSignIn } from '@solana/react'; function SignInButton({ wallet }) { const csrfToken = useCsrfToken(); const signIn = useSignIn(wallet); return ( ); } ``` ## Call Signature ```ts function useSignIn(uiWallet): (input?) => Promise; ``` ### Parameters | Parameter | Type | | ---------- | ---------- | | `uiWallet` | `UiWallet` | ### Returns A function that you can call to sign in with the supplied UiWallet (`input?`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`Output`> # useSignMessage (/api/functions/useSignMessage) ```ts function useSignMessage( ...config ): (input) => Promise; ``` Use this to get a function capable of signing a message with the private key of a UiWalletAccount ## Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ## Parameters | Parameter | Type | | ----------- | ------------------- | | ...`config` | \[`TWalletAccount`] | ## Returns (`input`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`Output`> ## Example ```tsx import { useSignMessage } from '@solana/react'; function SignMessageButton({ account, messageBytes }) { const signMessage = useSignMessage(account); return ( ); } ``` # useSignTransaction (/api/functions/useSignTransaction) ## Call Signature ```ts function useSignTransaction( uiWalletAccount, chain, ): (input) => Promise; ``` Use this to get a function capable of signing a serialized transaction with the private key of a UiWalletAccount ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | Description | | ----------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | - | | `chain` | `OnlySolanaChains`\<`TWalletAccount`\[`"chains"`]> | The identifier of the chain the transaction is destined for. Wallets may use this to simulate the transaction for the user. | ### Returns (`input`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`SolanaSignTransactionOutput`> ### Example ```tsx import { useSignTransaction } from '@solana/react'; function SignTransactionButton({ account, transactionBytes }) { const signTransaction = useSignTransaction(account, 'solana:devnet'); return ( ); } ``` ## Call Signature ```ts function useSignTransaction( uiWalletAccount, chain, ): (input) => Promise; ``` Use this to get a function capable of signing a serialized transaction with the private key of a UiWalletAccount ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | Description | | ----------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | - | | `chain` | `` `solana:${string}` `` | The identifier of the chain the transaction is destined for. Wallets may use this to simulate the transaction for the user. | ### Returns (`input`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`SolanaSignTransactionOutput`> ### Example ```tsx import { useSignTransaction } from '@solana/react'; function SignTransactionButton({ account, transactionBytes }) { const signTransaction = useSignTransaction(account, 'solana:devnet'); return ( ); } ``` # useSignTransactions (/api/functions/useSignTransactions) ## Call Signature ```ts function useSignTransactions( uiWalletAccount, chain, ): (...inputs) => Promise; ``` Use this to get a function capable of signing one or more serialized transactions with the private key of a UiWalletAccount. This supports batching multiple transactions in a single wallet prompt when the wallet implementation allows it. ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | | ----------------- | -------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | | `chain` | `OnlySolanaChains`\<`TWalletAccount`\[`"chains"`]> | ### Returns (...`inputs`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\ ### Example ```tsx import { useSignTransactions } from '@solana/react'; function SignTransactionsButton({ account, transactionBytes1, transactionBytes2 }) { const signTransactions = useSignTransactions(account, 'solana:devnet'); return ( ); } ``` ## Call Signature ```ts function useSignTransactions( uiWalletAccount, chain, ): (...inputs) => Promise; ``` Use this to get a function capable of signing one or more serialized transactions with the private key of a UiWalletAccount. This supports batching multiple transactions in a single wallet prompt when the wallet implementation allows it. ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | | ----------------- | ------------------------ | | `uiWalletAccount` | `TWalletAccount` | | `chain` | `` `solana:${string}` `` | ### Returns (...`inputs`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\ ### Example ```tsx import { useSignTransactions } from '@solana/react'; function SignTransactionsButton({ account, transactionBytes1, transactionBytes2 }) { const signTransactions = useSignTransactions(account, 'solana:devnet'); return ( ); } ``` # useSubscription (/api/functions/useSubscription) ```ts function useSubscription(source, options?): SubscriptionResult; ``` Subscribe to a stream-store source and surface the latest notification as reactive state. The subscription opens on mount, re-opens whenever `source` changes identity, and tears down on unmount. Accepts any ReactiveStreamSource β€” the `{ reactiveStore() }` duck-type satisfied by `PendingRpcSubscriptionsRequest` (e.g. `client.rpcSubscriptions.accountNotifications(addr)`) and any plugin-authored stream object that follows the same convention. Pass `null` to disable; the result reports `status: 'disabled'`. Memoize the source with `useMemo` keyed on whatever inputs it depends on; stable identity is how the hook knows when to tear down and re-open. SSR-safe β€” on the server the connect effect doesn't run, so the store stays `idle` and the hook reports `status: 'loading'`. The first client render hydrates from that same `loading` paint, then commits the connect effect. ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------------------- | | `T` | The notification type emitted by the source. | ## Parameters | Parameter | Type | | ---------- | -------------------------------------------------------------------- | | `source` | `ReactiveStreamSource`\<`T`> \| `null` | | `options?` | [`UseSubscriptionOptions`](/api/type-aliases/UseSubscriptionOptions) | ## Returns [`SubscriptionResult`](/api/type-aliases/SubscriptionResult)\<`T`> ## Example ```tsx function AccountBalance({ address }: { address: Address }) { const client = useClient>(); const source = useMemo(() => client.rpcSubscriptions.accountNotifications(address), [client, address]); const { data, error, reconnect } = useSubscription(source); if (error) return ; return

{data ? `${data.value.lamports} lamports at slot ${data.context.slot}` : 'Connecting…'}

; } ``` ## See * [SubscriptionResult](/api/type-aliases/SubscriptionResult) * [UseSubscriptionOptions](/api/type-aliases/UseSubscriptionOptions) # useTrackedData (/api/functions/useTrackedData) ```ts function useTrackedData( spec, options?, ): TrackedDataResult; ``` Render reactive state for an RPC subscription seeded by a one-shot RPC fetch, slot-deduped. The subscription (e.g. `accountNotifications`) is the primary source of live updates; the initial fetch (e.g. `getBalance`) provides a value to surface as soon as it resolves β€” typically before the first subscription notification arrives β€” so the `loading` paint is shorter than subscription-only would give you. The underlying store slot-dedupes between the two sources β€” out-of-order arrivals never regress the surfaced value. Pass a memoized [TrackedDataSpec](/api/type-aliases/TrackedDataSpec) keyed on whatever inputs it depends on; stable identity is how the hook knows when to tear down and re-run. Pass `null` to gate the work off β€” the result reports `status: 'disabled'`. SSR-safe β€” on the server the connect effect doesn't run, so the store stays `idle` and the hook reports `status: 'loading'`. The first client render hydrates from that same `loading` paint, then commits the connect effect. ## Type Parameters | Type Parameter | Description | | --------------- | --------------------------------------------------------------------------- | | `TInitialValue` | The value inside the initial RPC `SolanaRpcResponse` envelope. | | `TStreamValue` | The value inside subscription `SolanaRpcResponse` notifications. | | `TItem` | The unified item type produced by the two mappers and stored in the result. | ## Parameters | Parameter | Type | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `spec` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `initialValueMapper`: (`value`) => `TItem`; `initialValueSource`: `ReactiveActionSource`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `context`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `slot`: `Slot`; }>; `value`: `TInitialValue`; }>>; `streamSource`: `ReactiveStreamSource`\<[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `context`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `slot`: `Slot`; }>; `value`: `TStreamValue`; }>>; `streamValueMapper`: (`value`) => `TItem`; }> \| `null` | | `options?` | [`UseTrackedDataOptions`](/api/type-aliases/UseTrackedDataOptions) | ## Returns [`TrackedDataResult`](/api/type-aliases/TrackedDataResult)\<`TItem`> ## Example ```tsx function AccountBalance({ address }: { address: Address }) { const client = useClient & ClientWithRpcSubscriptions>(); const spec = useMemo(() => ({ initialValueSource: client.rpc.getBalance(address), initialValueMapper: (lamports: bigint) => lamports, streamSource: client.rpcSubscriptions.accountNotifications(address), streamValueMapper: ({ lamports }: { lamports: bigint }) => lamports, }), [client, address]); const { data, error, refresh } = useTrackedData(spec); if (error) return ; return

{data ? `${data.value} lamports at slot ${data.context.slot}` : 'Loading…'}

; } ``` ## See * [TrackedDataResult](/api/type-aliases/TrackedDataResult) * [UseTrackedDataOptions](/api/type-aliases/UseTrackedDataOptions) # useWalletAccountMessageSigner (/api/functions/useWalletAccountMessageSigner) ```ts function useWalletAccountMessageSigner( uiWalletAccount, ): MessageModifyingSigner; ``` Use this to get a MessageSigner capable of signing messages with the private key of a UiWalletAccount ## Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ## Parameters | Parameter | Type | | ----------------- | ---------------- | | `uiWalletAccount` | `TWalletAccount` | ## Returns `MessageModifyingSigner`\<`TWalletAccount`\[`"address"`]> A MessageModifyingSigner. This is a conservative assumption based on the fact that your application can not control whether or not the wallet will modify the message before signing it. Otherwise this method could more specifically return a MessageSigner or a MessagePartialSigner. ## Example ```tsx import { useWalletAccountMessageSigner } from '@solana/react'; import { createSignableMessage } from '@solana/kit'; function SignMessageButton({ account, text }) { const messageSigner = useWalletAccountMessageSigner(account); return ( ); } ``` # useWalletAccountTransactionSendingSigner (/api/functions/useWalletAccountTransactionSendingSigner) ## Call Signature ```ts function useWalletAccountTransactionSendingSigner( uiWalletAccount, chain, ): TransactionSendingSigner; ``` Use this to get a TransactionSendingSigner capable of signing a serialized transaction with the private key of a UiWalletAccount and sending it to the network for processing. ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | Description | | ----------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | - | | `chain` | `OnlySolanaChains`\<`TWalletAccount`\[`"chains"`]> | The identifier of the chain the transaction is destined for. Wallets may use this to simulate the transaction for the user. | ### Returns `TransactionSendingSigner`\<`TWalletAccount`\[`"address"`]> ### Example ```tsx import { useWalletAccountTransactionSendingSigner } from '@solana/react'; import { appendTransactionMessageInstruction, createSolanaRpc, getBase58Decoder, pipe, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, signAndSendTransactionMessageWithSigners, } from '@solana/kit'; function RecordMemoButton({ account, rpc, text }) { const signer = useWalletAccountTransactionSendingSigner(account, 'solana:devnet'); return ( ); } ``` ## Call Signature ```ts function useWalletAccountTransactionSendingSigner( uiWalletAccount, chain, ): TransactionSendingSigner; ``` Use this to get a TransactionSendingSigner capable of signing a serialized transaction with the private key of a UiWalletAccount and sending it to the network for processing. ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | Description | | ----------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | - | | `chain` | `` `solana:${string}` `` | The identifier of the chain the transaction is destined for. Wallets may use this to simulate the transaction for the user. | ### Returns `TransactionSendingSigner`\<`TWalletAccount`\[`"address"`]> ### Example ```tsx import { useWalletAccountTransactionSendingSigner } from '@solana/react'; import { appendTransactionMessageInstruction, createSolanaRpc, getBase58Decoder, pipe, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, signAndSendTransactionMessageWithSigners, } from '@solana/kit'; function RecordMemoButton({ account, rpc, text }) { const signer = useWalletAccountTransactionSendingSigner(account, 'solana:devnet'); return ( ); } ``` # useWalletAccountTransactionSigner (/api/functions/useWalletAccountTransactionSigner) ## Call Signature ```ts function useWalletAccountTransactionSigner( uiWalletAccount, chain, ): TransactionModifyingSigner; ``` Use this to get a TransactionSigner capable of signing serialized transactions with the private key of a UiWalletAccount ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | | ----------------- | -------------------------------------------------- | | `uiWalletAccount` | `TWalletAccount` | | `chain` | `OnlySolanaChains`\<`TWalletAccount`\[`"chains"`]> | ### Returns `TransactionModifyingSigner`\<`TWalletAccount`\[`"address"`]> A TransactionModifyingSigner. This is a conservative assumption based on the fact that your application can not control whether or not the wallet will modify the transaction before signing it (eg. to add guard instructions, or a priority fee budget). Otherwise this method could more specifically return a TransactionSigner or a TransactionPartialSigner. ### Example ```tsx import { useWalletAccountTransactionSigner } from '@solana/react'; function SignTransactionButton({ account, transaction }) { const transactionSigner = useWalletAccountTransactionSigner(account, 'solana:devnet'); return ( ); } ``` ## Call Signature ```ts function useWalletAccountTransactionSigner( uiWalletAccount, chain, ): TransactionModifyingSigner; ``` Use this to get a TransactionSigner capable of signing serialized transactions with the private key of a UiWalletAccount ### Type Parameters | Type Parameter | | -------------------------------------------- | | `TWalletAccount` *extends* `UiWalletAccount` | ### Parameters | Parameter | Type | | ----------------- | ------------------------ | | `uiWalletAccount` | `TWalletAccount` | | `chain` | `` `solana:${string}` `` | ### Returns `TransactionModifyingSigner`\<`TWalletAccount`\[`"address"`]> A TransactionModifyingSigner. This is a conservative assumption based on the fact that your application can not control whether or not the wallet will modify the transaction before signing it (eg. to add guard instructions, or a priority fee budget). Otherwise this method could more specifically return a TransactionSigner or a TransactionPartialSigner. ### Example ```tsx import { useWalletAccountTransactionSigner } from '@solana/react'; function SignTransactionButton({ account, transaction }) { const transactionSigner = useWalletAccountTransactionSigner(account, 'solana:devnet'); return ( ); } ``` # verifyOffchainMessageEnvelope (/api/functions/verifyOffchainMessageEnvelope) ```ts function verifyOffchainMessageEnvelope( offchainMessageEnvelope, ): Promise; ``` Asserts that there are signatures present for all of an offchain message's required signatories, and that those signatures are valid given the message. ## Parameters | Parameter | Type | | ------------------------- | -------------------------------------------------------------------- | | `offchainMessageEnvelope` | [`OffchainMessageEnvelope`](/api/interfaces/OffchainMessageEnvelope) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`> ## Example ```ts import { isSolanaError, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE } from '@solana/errors'; import { verifyOffchainMessageEnvelope } from '@solana/offchain-messages'; try { await verifyOffchainMessageEnvelope(offchainMessageEnvelope); // At this point the message is valid and signed by all of the required signatories. } catch (e) { if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE)) { if (e.context.signatoriesWithMissingSignatures.length) { console.error( 'Missing signatures for the following addresses', e.context.signatoriesWithMissingSignatures, ); } if (e.context.signatoriesWithInvalidSignatures.length) { console.error( 'Signatures for the following addresses are invalid', e.context.signatoriesWithInvalidSignatures, ); } } throw e; } ``` # verifySignature (/api/functions/verifySignature) ```ts function verifySignature(key, signature, data): Promise; ``` Given a public [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey), some [SignatureBytes](/api/type-aliases/SignatureBytes), and a `Uint8Array` of data, this method will return `true` if the signature was produced by signing the data using the private key associated with the public key, and `false` otherwise. ## Parameters | Parameter | Type | | ----------- | ------------------------------------------------------------------- | | `key` | [`CryptoKey`](https://developer.mozilla.org/docs/Web/API/CryptoKey) | | `signature` | [`SignatureBytes`](/api/type-aliases/SignatureBytes) | | `data` | [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`boolean`> ## Example ```ts import { verifySignature } from '@solana/keys'; const data = new Uint8Array([1, 2, 3]); if (!(await verifySignature(publicKey, signature, data))) { throw new Error('The data were *not* signed by the private key associated with `publicKey`'); } ``` # waitForDurableNonceTransactionConfirmation (/api/functions/waitForDurableNonceTransactionConfirmation) ```ts function waitForDurableNonceTransactionConfirmation( config, ): Promise; ``` Supply your own confirmation implementations to this function to create a custom nonce transaction confirmation strategy. ## Parameters | Parameter | Type | | --------- | -------------------------------------------------- | | `config` | `WaitForDurableNonceTransactionConfirmationConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`> ## Example ```ts import { waitForDurableNonceTransactionConfirmation } from '@solana/transaction-confirmation'; try { await waitForDurableNonceTransactionConfirmation({ getNonceInvalidationPromise({ abortSignal, commitment, currentNonceValue, nonceAccountAddress }) { // Return a promise that rejects when a nonce becomes invalid. }, getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) { // Return a promise that resolves when a transaction achieves confirmation }, }); } catch (e) { // Handle errors. } ``` # waitForRecentTransactionConfirmation (/api/functions/waitForRecentTransactionConfirmation) ```ts function waitForRecentTransactionConfirmation(config): Promise; ``` Supply your own confirmation implementations to this function to create a custom confirmation strategy for recently-landed transactions. ## Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------- | | `config` | `WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`> ## Example ```ts import { waitForRecentTransactionConfirmation } from '@solana/transaction-confirmation'; try { await waitForRecentTransactionConfirmation({ getBlockHeightExceedencePromise({ abortSignal, commitment, lastValidBlockHeight }) { // Return a promise that rejects when the blockhash's block height has been exceeded }, getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) { // Return a promise that resolves when a transaction achieves confirmation }, }); } catch (e) { // Handle errors. } ``` # waitForRecentTransactionConfirmationUntilTimeout (/api/functions/waitForRecentTransactionConfirmationUntilTimeout) ```ts function waitForRecentTransactionConfirmationUntilTimeout( config, ): Promise; ``` ## Parameters | Parameter | Type | | --------- | ----------------------------------------------------------------- | | `config` | `WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig` | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`> ## Deprecated # walkInstructions (/api/functions/walkInstructions) ```ts function walkInstructions(args): TracedInstruction[]; ``` Returns every instruction in a confirmed transaction as [TracedInstruction](/api/type-aliases/TracedInstruction)s, in the order an explorer displays them: each outer instruction followed immediately by the inner instructions its CPIs produced. Each returned instruction has its account indices resolved to AccountMetas and its data exposed as a `ReadonlyUint8Array` (omitted when empty), making it directly usable with the auto-generated `@solana-program/*` `identifyXInstruction` and `parseXInstruction` functions, and with `isInstructionForProgram` from `@solana/instructions`. If `meta` is omitted, only outer instructions are returned. If `loadedAddresses` is omitted, only static accounts are used to resolve indices β€” pass `meta?.loadedAddresses` for v0 transactions that load accounts from address lookup tables. ## Parameters | Parameter | Type | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `args` | \{ `compiledMessage`: `CompiledTransactionMessage`; `loadedAddresses?`: \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `readonly`: readonly `Address`\[]; `writable`: readonly `Address`\[]; }> \| `null`; `meta?`: \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions?`: \| readonly [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `index`: `number`; `instructions`: readonly `TransactionInstruction`\[]; }>\[] \| `null`; }> \| `null`; } | | `args.compiledMessage` | `CompiledTransactionMessage` | | `args.loadedAddresses?` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `readonly`: readonly `Address`\[]; `writable`: readonly `Address`\[]; }> \| `null` | | `args.meta?` | \| [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `innerInstructions?`: \| readonly [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `index`: `number`; `instructions`: readonly `TransactionInstruction`\[]; }>\[] \| `null`; }> \| `null` | ## Returns [`TracedInstruction`](/api/type-aliases/TracedInstruction)\[] ## Example ```ts import { isInstructionForProgram, isInstructionWithData } from '@solana/instructions'; import { TOKEN_PROGRAM_ADDRESS, identifyTokenInstruction, TokenInstruction } from '@solana-program/token'; const instructions = walkInstructions({ compiledMessage, meta, loadedAddresses }); for (const ix of instructions) { if (isInstructionForProgram(ix, TOKEN_PROGRAM_ADDRESS) && isInstructionWithData(ix) && identifyTokenInstruction(ix) === TokenInstruction.SyncNative) { console.log(ix.trace); } } ``` # withCleanup (/api/functions/withCleanup) ```ts function withCleanup( client, cleanup, ): { [K in string | number | symbol]: (Omit & Disposable)[K]; }; ``` Wraps a client with a cleanup function, making it Disposable. Plugin authors can use this to register teardown logic (e.g. closing connections or clearing timers) that runs when the client is disposed. If the client already implements `Symbol.dispose`, the existing dispose logic is chained so that it runs after the new `cleanup` function. Cleanups run in reverse order of registration, disposal is idempotent, and if more than one cleanup throws then the errors are aggregated into a `SuppressedError` chain. Runtimes that have not shipped explicit resource management are supported too, though a `using` declaration needs a `Symbol.dispose` polyfill there. The return type is an [ExtendedClient](/api/type-aliases/ExtendedClient), which flattens the merged shape into a single object literal so chained calls do not accumulate nested intersections in editor tooltips and error messages. ## Type Parameters | Type Parameter | Description | | ---------------------------- | -------------------------------- | | `TClient` *extends* `object` | The type of the original client. | ## Parameters | Parameter | Type | Description | | --------- | ------------ | -------------------------------------------------------- | | `client` | `TClient` | The client to wrap. | | `cleanup` | () => `void` | The cleanup function to run when the client is disposed. | ## Returns \{ \[K in string | number | symbol]: (Omit\ & Disposable)\[K] } A new client that extends `TClient` and implements `Disposable`. ## Examples Register a cleanup function in a plugin that opens a WebSocket connection. ```ts function myPlugin() { return (client: T) => { const socket = new WebSocket('wss://api.example.com'); return withCleanup( extendClient(client, { socket }), () => socket.close(), ); }; } // Build the client in the scope that should own it: using client = createClient().use(myPlugin()); // `socket.close()` is called automatically when `client` goes out of scope. ``` **Disposing without a using declaration** `using` requires explicit resource management, which Safari has not shipped as of Safari 27. Either dispose the client yourself, as below, or polyfill `Symbol.dispose` β€” installing the polyfill before any client is created, since a client registers its dispose method under whatever `Symbol.dispose` was at the time. ```ts const client = createClient().use(myPlugin()); // Later, when the client is no longer needed: client[Symbol.dispose](); // `socket.close()` has now been called. ``` ## See * [extendClient](/api/functions/extendClient) * [ExtendedClient](/api/type-aliases/ExtendedClient) ## Remarks See [https://caniuse.com/mdn-javascript\_builtins\_disposablestack](https://caniuse.com/mdn-javascript_builtins_disposablestack) for platform availability of `DisposableStack`. # wrapNullable (/api/functions/wrapNullable) ```ts function wrapNullable(nullable): Option; ``` Wraps a nullable value into an [Option](/api/type-aliases/Option). * If the input value is `null`, this function returns [None](/api/type-aliases/None). * Otherwise, it wraps the value in [Some](/api/type-aliases/Some). ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ## Parameters | Parameter | Type | Description | | ---------- | ------------- | --------------------------- | | `nullable` | `T` \| `null` | The nullable value to wrap. | ## Returns [`Option`](/api/type-aliases/Option)\<`T`> An [Option](/api/type-aliases/Option) wrapping the value. ## Example Wrapping nullable values. ```ts wrapNullable('Hello World'); // Option (Some) wrapNullable(null); // Option (None) ``` ## See * [Option](/api/type-aliases/Option) * [Some](/api/type-aliases/Some) * [None](/api/type-aliases/None) # writeKeyPair (/api/functions/writeKeyPair) ```ts function writeKeyPair(keyPair, path, config?): Promise; ``` Writes an extractable CryptoKeyPair to disk as a JSON array of 64 bytes, matching the format produced by `solana-keygen`. The first 32 bytes are the raw Ed25519 seed (private key) and the last 32 bytes are the raw public key. Any missing parent directories are created automatically. The written file uses mode `0600` (owner read/write only) to match `solana-keygen`. This helper requires a writable filesystem and will throw in environments that don't provide one (such as browsers or React Native). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | `keyPair` | `CryptoKeyPair` | An extractable CryptoKeyPair. Both the private and public keys must have been created with `extractable: true`. | | `path` | `string` | The destination path on disk. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `unsafelyOverwriteExistingKeyPair?`: `boolean`; }> | See [WriteKeyPairConfig](/api/type-aliases/WriteKeyPairConfig). | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`> ## Throws A [SolanaError](/api/classes/SolanaError) of code [\`SOLANA\_ERROR\_\_KEYS\_\_WRITE\_KEY\_PAIR\_UNSUPPORTED\_ENVIRONMENT\`](/api/variables/SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT) when called in an environment without a writable filesystem. ## Throws A [SolanaError](/api/classes/SolanaError) of code [\`SOLANA\_ERROR\_\_SUBTLE\_CRYPTO\_\_CANNOT\_EXPORT\_NON\_EXTRACTABLE\_KEY\`](/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY) when either the private or public key is not extractable. ## Examples ```ts import { generateKeyPair, writeKeyPair } from '@solana/keys'; // Generate an extractable key pair so its bytes can be persisted. const keyPair = await generateKeyPair(true); await writeKeyPair(keyPair, './my-keypair.json'); ``` Overwriting an existing file requires an explicit opt-in, because doing so permanently destroys the previous key and any funds controlled by it: ```ts import { writeKeyPair } from '@solana/keys'; await writeKeyPair(keyPair, './my-keypair.json', { unsafelyOverwriteExistingKeyPair: true, }); ``` ## See * [createKeyPairFromBytes](/api/functions/createKeyPairFromBytes) β€” the inverse helper that loads a key pair from a 64-byte buffer. * [writeKeyPairSigner](/api/functions/writeKeyPairSigner) β€” the signer-flavored variant from `@solana/signers`. # writeKeyPairSigner (/api/functions/writeKeyPairSigner) ```ts function writeKeyPairSigner(signer, path, config?): Promise; ``` Writes the CryptoKeyPair backing a [KeyPairSigner](/api/type-aliases/KeyPairSigner) to disk as a JSON array of 64 bytes, matching the format produced by `solana-keygen`. The first 32 bytes are the raw Ed25519 seed (private key) and the last 32 bytes are the raw public key. Any missing parent directories are created automatically. The written file uses mode `0600` (owner read/write only) to match `solana-keygen`. This helper requires a writable filesystem and will throw in environments that don't provide one (such as browsers or React Native). ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `signer` | [`KeyPairSigner`](/api/type-aliases/KeyPairSigner) | A [KeyPairSigner](/api/type-aliases/KeyPairSigner) whose underlying CryptoKeyPair is extractable (i.e. created via `generateKeyPairSigner(true)` or `createKeyPairSignerFromBytes(bytes, true)`). | | `path` | `string` | The destination path on disk. | | `config?` | [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)\<\{ `unsafelyOverwriteExistingKeyPair?`: `boolean`; }> | See [WriteKeyPairConfig](/api/type-aliases/WriteKeyPairConfig). | ## Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`> ## Throws A SolanaError of code `SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT` when called in an environment without a writable filesystem. ## Throws A SolanaError of code `SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY` when the signer's underlying key pair is not extractable. ## Examples ```ts import { generateKeyPairSigner, writeKeyPairSigner } from '@solana/signers'; // Generate an extractable signer so its bytes can be persisted. const signer = await generateKeyPairSigner(true); await writeKeyPairSigner(signer, './my-keypair.json'); ``` Overwriting an existing file requires an explicit opt-in, because doing so permanently destroys the previous key and any funds controlled by it: ```ts import { writeKeyPairSigner } from '@solana/signers'; await writeKeyPairSigner(signer, './my-keypair.json', { unsafelyOverwriteExistingKeyPair: true, }); ``` ## See * writeKeyPair β€” the lower-level helper from `@solana/keys` that operates on a raw CryptoKeyPair. * [createKeyPairSignerFromBytes](/api/functions/createKeyPairSignerFromBytes) β€” the inverse helper that loads a signer from a 64-byte buffer. # BASE_ACCOUNT_SIZE (/api/variables/BASE_ACCOUNT_SIZE) ```ts const BASE_ACCOUNT_SIZE: 128 = 128; ``` The number of bytes required to store the [BaseAccount](/api/interfaces/BaseAccount) information without its data. ## Example ```ts const myTotalAccountSize = myAccountDataSize + BASE_ACCOUNT_SIZE; ``` # ClientContext (/api/variables/ClientContext) ```ts const ClientContext: Context | null>; ``` The React context that holds the Kit client published by the nearest [ClientProvider](/api/functions/ClientProvider). Exported for advanced cases such as third-party providers that wrap and extend the client; most consumers should reach for [useClient](/api/functions/useClient) or one of the higher-level hooks instead. # DEFAULT_RPC_CONFIG (/api/variables/DEFAULT_RPC_CONFIG) ```ts const DEFAULT_RPC_CONFIG: Partial[0]>>; ``` When you create [Rpc](/api/type-aliases/Rpc) instances with custom transports but otherwise the default RPC API behaviours, use this. ## Example ```ts const myCustomRpc = createRpc({ api: createSolanaRpcApi(DEFAULT_RPC_CONFIG), transport: myCustomTransport, }); ``` # DEFAULT_RPC_SUBSCRIPTIONS_CONFIG (/api/variables/DEFAULT_RPC_SUBSCRIPTIONS_CONFIG) ```ts const DEFAULT_RPC_SUBSCRIPTIONS_CONFIG: Partial[0]>>; ``` # KEYPATH_WILDCARD (/api/variables/KEYPATH_WILDCARD) ```ts const KEYPATH_WILDCARD: KeyPathWildcard; ``` # MAX_SUPPORTED_TRANSACTION_VERSION (/api/variables/MAX_SUPPORTED_TRANSACTION_VERSION) ```ts const MAX_SUPPORTED_TRANSACTION_VERSION: 1 = 1; ``` # SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND (/api/variables/SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND) ```ts const SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND: 3230000 = 3230000; ``` # SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED (/api/variables/SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED) ```ts const SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED: 3230004 = 3230004; ``` # SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT (/api/variables/SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT) ```ts const SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT: 3230003 = 3230003; ``` # SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT (/api/variables/SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT) ```ts const SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT: 3230002 = 3230002; ``` # SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND (/api/variables/SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND) ```ts const SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND: 32300001 = 32300001; ``` # SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED (/api/variables/SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED) ```ts const SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED: 2800009 = 2800009; ``` # SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS (/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS) ```ts const SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS: 2800002 = 2800002; ``` # SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH (/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH) ```ts const SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH: 2800000 = 2800000; ``` # SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY (/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY) ```ts const SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY: 2800003 = 2800003; ``` # SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS (/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS) ```ts const SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS: 2800011 = 2800011; ``` # SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE (/api/variables/SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE) ```ts const SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE: 2800008 = 2800008; ``` # SOLANA_ERROR__ADDRESSES__MALFORMED_PDA (/api/variables/SOLANA_ERROR__ADDRESSES__MALFORMED_PDA) ```ts const SOLANA_ERROR__ADDRESSES__MALFORMED_PDA: 2800004 = 2800004; ``` # SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED (/api/variables/SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED) ```ts const SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED: 2800006 = 2800006; ``` # SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED (/api/variables/SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED) ```ts const SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED: 2800007 = 2800007; ``` # SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE) ```ts const SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE: 2800005 = 2800005; ``` # SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER (/api/variables/SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER) ```ts const SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER: 2800010 = 2800010; ``` # SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE) ```ts const SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE: 2800001 = 2800001; ``` # SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE) ```ts const SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE: 4 = 4; ``` # SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED (/api/variables/SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED) ```ts const SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED: 1 = 1; ``` # SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY (/api/variables/SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY) ```ts const SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY: 8078000 = 8078000; ``` # SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS (/api/variables/SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS) ```ts const SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS: 8078022 = 8078022; ``` # SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL (/api/variables/SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL) ```ts const SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL: 8078020 = 8078020; ``` # SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH (/api/variables/SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH) ```ts const SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH: 8078005 = 8078005; ``` # SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH (/api/variables/SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH) ```ts const SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH: 8078006 = 8078006; ``` # SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH (/api/variables/SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH) ```ts const SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH: 8078004 = 8078004; ``` # SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE) ```ts const SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE: 8078008 = 8078008; ``` # SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY (/api/variables/SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY) ```ts const SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY: 8078023 = 8078023; ``` # SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH (/api/variables/SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH) ```ts const SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH: 8078002 = 8078002; ``` # SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH (/api/variables/SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH) ```ts const SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH: 8078013 = 8078013; ``` # SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH (/api/variables/SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH) ```ts const SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH: 8078003 = 8078003; ``` # SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE (/api/variables/SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE) ```ts const SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE: 8078019 = 8078019; ``` # SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH (/api/variables/SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH) ```ts const SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH: 8078001 = 8078001; ``` # SOLANA_ERROR__CODECS__INVALID_CONSTANT (/api/variables/SOLANA_ERROR__CODECS__INVALID_CONSTANT) ```ts const SOLANA_ERROR__CODECS__INVALID_CONSTANT: 8078018 = 8078018; ``` # SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT (/api/variables/SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT) ```ts const SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT: 8078009 = 8078009; ``` # SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT (/api/variables/SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT) ```ts const SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT: 8078010 = 8078010; ``` # SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT (/api/variables/SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT) ```ts const SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT: 8078015 = 8078015; ``` # SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS (/api/variables/SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS) ```ts const SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS: 8078007 = 8078007; ``` # SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES (/api/variables/SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES) ```ts const SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES: 8078025 = 8078025; ``` # SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE (/api/variables/SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE) ```ts const SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE: 8078024 = 8078024; ``` # SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE (/api/variables/SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE) ```ts const SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE: 8078012 = 8078012; ``` # SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE) ```ts const SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE: 8078016 = 8078016; ``` # SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE) ```ts const SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE: 8078011 = 8078011; ``` # SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE) ```ts const SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE: 8078014 = 8078014; ``` # SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES (/api/variables/SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES) ```ts const SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES: 8078021 = 8078021; ``` # SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE) ```ts const SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE: 8078017 = 8078017; ``` # SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED (/api/variables/SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED) ```ts const SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED: 3611000 = 3611000; ``` # SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION (/api/variables/SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION) ```ts const SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION: 11 = 11; ``` # SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS (/api/variables/SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS) ```ts const SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS: 12 = 12; ``` # SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION (/api/variables/SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION) ```ts const SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION: 13 = 13; ``` # SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS (/api/variables/SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS) ```ts const SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS: 14 = 14; ``` # SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW (/api/variables/SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW) ```ts const SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW: 8090007 = 8090007; ``` # SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO (/api/variables/SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO) ```ts const SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO: 8090009 = 8090009; ``` # SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS (/api/variables/SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS) ```ts const SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS: 8090003 = 8090003; ``` # SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS (/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS) ```ts const SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS: 8090002 = 8090002; ``` # SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS (/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS) ```ts const SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS: 8090001 = 8090001; ``` # SOLANA_ERROR__FIXED_POINTS__INVALID_STRING (/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_STRING) ```ts const SOLANA_ERROR__FIXED_POINTS__INVALID_STRING: 8090005 = 8090005; ``` # SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS (/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS) ```ts const SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS: 8090000 = 8090000; ``` # SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO (/api/variables/SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO) ```ts const SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO: 8090006 = 8090006; ``` # SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE (/api/variables/SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE) ```ts const SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE: 8090011 = 8090011; ``` # SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH (/api/variables/SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH) ```ts const SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH: 8090008 = 8090008; ``` # SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS (/api/variables/SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS) ```ts const SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS: 8090010 = 8090010; ``` # SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED (/api/variables/SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED) ```ts const SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED: 8090012 = 8090012; ``` # SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE) ```ts const SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE: 8090004 = 8090004; ``` # SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT (/api/variables/SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT) ```ts const SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT: 3712000 = 3712000; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED: 4615009 = 4615009; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED: 4615023 = 4615023; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING: 4615024 = 4615024; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED: 4615021 = 4615021; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL: 4615005 = 4615005; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE: 4615022 = 4615022; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT: 4615046 = 4615046; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW: 4615048 = 4615048; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR: 4615045 = 4615045; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS: 4615054 = 4615054; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH: 4615032 = 4615032; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED: 4615038 = 4615038; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM: 4615026 = 4615026; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX: 4615017 = 4615017; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC: 4615025 = 4615025; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT: 4615030 = 4615030; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED: 4615028 = 4615028; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE: 4615029 = 4615029; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED: 4615018 = 4615018; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED: 4615014 = 4615014; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND: 4615013 = 4615013; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR: 4615001 = 4615001; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER: 4615050 = 4615050; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE: 4615043 = 4615043; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY: 4615044 = 4615044; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID: 4615007 = 4615007; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS: 4615006 = 4615006; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA: 4615004 = 4615004; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER: 4615047 = 4615047; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT: 4615002 = 4615002; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR: 4615027 = 4615027; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA: 4615003 = 4615003; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC: 4615037 = 4615037; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS: 4615036 = 4615036; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED: 4615051 = 4615051; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED: 4615052 = 4615052; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED: 4615053 = 4615053; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED: 4615035 = 4615035; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT: 4615033 = 4615033; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE: 4615008 = 4615008; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID: 4615012 = 4615012; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS: 4615020 = 4615020; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION: 4615039 = 4615039; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE: 4615040 = 4615040; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE: 4615042 = 4615042; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE: 4615041 = 4615041; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED: 4615016 = 4615016; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE: 4615015 = 4615015; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED: 4615034 = 4615034; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED: 4615019 = 4615019; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION: 4615011 = 4615011; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT: 4615010 = 4615010; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN: 4615000 = 4615000; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID: 4615031 = 4615031; ``` # SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR (/api/variables/SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR) ```ts const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR: 4615049 = 4615049; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN: 7618002 = 7618002; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT: 7618009 = 7618009; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND: 7618005 = 7618005; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN: 7618003 = 7618003; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION: 7618011 = 7618011; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED: 7618010 = 7618010; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN: 7618000 = 7618000; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE: 7618001 = 7618001; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED: 7618004 = 7618004; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN: 7618006 = 7618006; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN: 7618007 = 7618007; ``` # SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT (/api/variables/SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT) ```ts const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT: 7618008 = 7618008; ``` # SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS (/api/variables/SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS) ```ts const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS: 4128000 = 4128000; ``` # SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA (/api/variables/SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA) ```ts const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA: 4128001 = 4128001; ``` # SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH (/api/variables/SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH) ```ts const SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH: 4128002 = 4128002; ``` # SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH (/api/variables/SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH) ```ts const SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH: 5 = 5; ``` # SOLANA_ERROR__INVALID_NONCE (/api/variables/SOLANA_ERROR__INVALID_NONCE) ```ts const SOLANA_ERROR__INVALID_NONCE: 2 = 2; ``` # SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING (/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING) ```ts const SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING: 9900002 = 9900002; ``` # SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED (/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED) ```ts const SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED: 9900004 = 9900004; ``` # SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND (/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND) ```ts const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND: 9900005 = 9900005; ``` # SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND (/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND) ```ts const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND: 9900006 = 9900006; ``` # SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE (/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE) ```ts const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE: 9900001 = 9900001; ``` # SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING (/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING) ```ts const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING: 9900000 = 9900000; ``` # SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE (/api/variables/SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE) ```ts const SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE: 9900003 = 9900003; ``` # SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR (/api/variables/SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR) ```ts const SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR: -32603 = -32603; ``` # SOLANA_ERROR__JSON_RPC__INVALID_PARAMS (/api/variables/SOLANA_ERROR__JSON_RPC__INVALID_PARAMS) ```ts const SOLANA_ERROR__JSON_RPC__INVALID_PARAMS: -32602 = -32602; ``` # SOLANA_ERROR__JSON_RPC__INVALID_REQUEST (/api/variables/SOLANA_ERROR__JSON_RPC__INVALID_REQUEST) ```ts const SOLANA_ERROR__JSON_RPC__INVALID_REQUEST: -32600 = -32600; ``` # SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND (/api/variables/SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND) ```ts const SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND: -32601 = -32601; ``` # SOLANA_ERROR__JSON_RPC__PARSE_ERROR (/api/variables/SOLANA_ERROR__JSON_RPC__PARSE_ERROR) ```ts const SOLANA_ERROR__JSON_RPC__PARSE_ERROR: -32700 = -32700; ``` # SOLANA_ERROR__JSON_RPC__SCAN_ERROR (/api/variables/SOLANA_ERROR__JSON_RPC__SCAN_ERROR) ```ts const SOLANA_ERROR__JSON_RPC__SCAN_ERROR: -32012 = -32012; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP: -32001 = -32001; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004 = -32004; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014 = -32014; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE: -32017 = -32017; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND: -32020 = -32020; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010 = -32010; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009 = -32009; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE: -32019 = -32019; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016 = -32016; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY: -32005 = -32005; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY: -32021 = -32021; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT: -32008 = -32008; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002 = -32002; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY: -32018 = -32018; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED: -32007 = -32007; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011 = -32011; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006 = -32006; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013 = -32013; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003 = -32003; ``` # SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION (/api/variables/SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION) ```ts const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015 = -32015; ``` # SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX (/api/variables/SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX) ```ts const SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX: 3704005 = 3704005; ``` # SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH (/api/variables/SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH) ```ts const SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH: 3704000 = 3704000; ``` # SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH (/api/variables/SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH) ```ts const SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH: 3704001 = 3704001; ``` # SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH (/api/variables/SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH) ```ts const SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH: 3704002 = 3704002; ``` # SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY (/api/variables/SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY) ```ts const SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY: 3704004 = 3704004; ``` # SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE) ```ts const SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE: 3704003 = 3704003; ``` # SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT (/api/variables/SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT) ```ts const SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT: 3704006 = 3704006; ``` # SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE) ```ts const SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE: 6 = 6; ``` # SOLANA_ERROR__MALFORMED_BIGINT_STRING (/api/variables/SOLANA_ERROR__MALFORMED_BIGINT_STRING) ```ts const SOLANA_ERROR__MALFORMED_BIGINT_STRING: 7 = 7; ``` # SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR (/api/variables/SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR) ```ts const SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR: 10 = 10; ``` # SOLANA_ERROR__MALFORMED_NUMBER_STRING (/api/variables/SOLANA_ERROR__MALFORMED_NUMBER_STRING) ```ts const SOLANA_ERROR__MALFORMED_NUMBER_STRING: 8 = 8; ``` # SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND (/api/variables/SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND) ```ts const SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND: 3 = 3; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE: 5607013 = 5607013; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE: 5607002 = 5607002; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED: 5607018 = 5607018; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH: 5607012 = 5607012; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH: 5607003 = 5607003; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED: 5607000 = 5607000; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH: 5607007 = 5607007; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH: 5607008 = 5607008; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY: 5607009 = 5607009; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO: 5607010 = 5607010; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO: 5607005 = 5607005; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH: 5607004 = 5607004; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED: 5607019 = 5607019; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE: 5607001 = 5607001; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED: 5607015 = 5607015; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE: 5607016 = 5607016; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING: 5607011 = 5607011; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE: 5607017 = 5607017; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION: 5607014 = 5607014; ``` # SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED (/api/variables/SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED) ```ts const SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED: 5607006 = 5607006; ``` # SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT (/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT) ```ts const SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT: 8500006 = 8500006; ``` # SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION (/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION) ```ts const SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION: 8500002 = 8500002; ``` # SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS (/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS) ```ts const SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS: 8500000 = 8500000; ``` # SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL (/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL) ```ts const SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL: 8500004 = 8500004; ``` # SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE (/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE) ```ts const SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE: 8500003 = 8500003; ``` # SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE (/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE) ```ts const SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE: 8500005 = 8500005; ``` # SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE (/api/variables/SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE) ```ts const SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE: 8500001 = 8500001; ``` # SOLANA_ERROR__REACT__MISSING_CAPABILITY (/api/variables/SOLANA_ERROR__REACT__MISSING_CAPABILITY) ```ts const SOLANA_ERROR__REACT__MISSING_CAPABILITY: 9000001 = 9000001; ``` # SOLANA_ERROR__REACT__MISSING_PROVIDER (/api/variables/SOLANA_ERROR__REACT__MISSING_PROVIDER) ```ts const SOLANA_ERROR__REACT__MISSING_PROVIDER: 9000000 = 9000000; ``` # SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR (/api/variables/SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR) ```ts const SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR: 9000002 = 9000002; ``` # SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN (/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN) ```ts const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN: 8190000 = 8190000; ``` # SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED (/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED) ```ts const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED: 8190002 = 8190002; ``` # SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED (/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED) ```ts const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED: 8190003 = 8190003; ``` # SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT (/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT) ```ts const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT: 8190004 = 8190004; ``` # SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID (/api/variables/SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID) ```ts const SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID: 8190001 = 8190001; ``` # SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD (/api/variables/SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD) ```ts const SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD: 8100003 = 8100003; ``` # SOLANA_ERROR__RPC__INTEGER_OVERFLOW (/api/variables/SOLANA_ERROR__RPC__INTEGER_OVERFLOW) ```ts const SOLANA_ERROR__RPC__INTEGER_OVERFLOW: 8100000 = 8100000; ``` # SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR (/api/variables/SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) ```ts const SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR: 8100002 = 8100002; ``` # SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN (/api/variables/SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN) ```ts const SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN: 8100001 = 8100001; ``` # SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS (/api/variables/SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS) ```ts const SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS: 5508000 = 5508000; ``` # SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER (/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER) ```ts const SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER: 5508001 = 5508001; ``` # SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER (/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER) ```ts const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER: 5508003 = 5508003; ``` # SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER (/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER) ```ts const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER: 5508004 = 5508004; ``` # SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER (/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER) ```ts const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER: 5508002 = 5508002; ``` # SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER (/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER) ```ts const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER: 5508006 = 5508006; ``` # SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER (/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER) ```ts const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER: 5508007 = 5508007; ``` # SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER (/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER) ```ts const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER: 5508008 = 5508008; ``` # SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER (/api/variables/SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER) ```ts const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER: 5508005 = 5508005; ``` # SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS (/api/variables/SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS) ```ts const SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS: 5508009 = 5508009; ``` # SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING (/api/variables/SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING) ```ts const SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING: 5508010 = 5508010; ``` # SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION (/api/variables/SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION) ```ts const SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION: 5508012 = 5508012; ``` # SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED (/api/variables/SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED) ```ts const SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED: 5508011 = 5508011; ``` # SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED (/api/variables/SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED) ```ts const SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED: 8195000 = 8195000; ``` # SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR (/api/variables/SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR) ```ts const SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR: 8195001 = 8195001; ``` # SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY (/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY) ```ts const SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY: 3610007 = 3610007; ``` # SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED (/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED) ```ts const SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED: 3610001 = 3610001; ``` # SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT (/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT) ```ts const SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT: 3610000 = 3610000; ``` # SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED (/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED) ```ts const SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED: 3610002 = 3610002; ``` # SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED (/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED) ```ts const SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED: 3610003 = 3610003; ``` # SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED (/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED) ```ts const SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED: 3610004 = 3610004; ``` # SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED (/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED) ```ts const SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED: 3610005 = 3610005; ``` # SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED (/api/variables/SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED) ```ts const SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED: 3610006 = 3610006; ``` # SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE) ```ts const SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE: 9 = 9; ``` # SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING: 7050016 = 7050016; ``` # SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE: 7050001 = 7050001; ``` # SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE: 7050002 = 7050002; ``` # SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND: 7050003 = 7050003; ``` # SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND: 7050023 = 7050023; ``` # SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED: 7050007 = 7050007; ``` # SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND: 7050008 = 7050008; ``` # SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP: 7050009 = 7050009; ``` # SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE: 7050015 = 7050015; ``` # SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION: 7050030 = 7050030; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE: 7050005 = 7050005; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT: 7050031 = 7050031; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE: 7050006 = 7050006; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX: 7050011 = 7050011; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA: 7050025 = 7050025; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX: 7050026 = 7050026; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER: 7050024 = 7050024; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT: 7050033 = 7050033; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION: 7050013 = 7050013; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT: 7050027 = 7050027; ``` # SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT: 7050019 = 7050019; ``` # SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED: 7050032 = 7050032; ``` # SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE: 7050010 = 7050010; ``` # SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND: 7050004 = 7050004; ``` # SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED: 7050035 = 7050035; ``` # SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED: 7050034 = 7050034; ``` # SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE: 7050014 = 7050014; ``` # SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE: 7050012 = 7050012; ``` # SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS: 7050022 = 7050022; ``` # SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION: 7050036 = 7050036; ``` # SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN: 7050000 = 7050000; ``` # SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION: 7050018 = 7050018; ``` # SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT: 7050021 = 7050021; ``` # SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT: 7050029 = 7050029; ``` # SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT: 7050020 = 7050020; ``` # SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT: 7050017 = 7050017; ``` # SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT: 7050028 = 7050028; ``` # SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION (/api/variables/SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION) ```ts const SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION: 5664000 = 5664000; ``` # SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE (/api/variables/SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE) ```ts const SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE: 5664001 = 5664001; ``` # SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION (/api/variables/SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION) ```ts const SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION: 5663015 = 5663015; ``` # SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING (/api/variables/SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING) ```ts const SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING: 5663010 = 5663010; ``` # SOLANA_ERROR__TRANSACTION__CANNOT_DECODE_EMPTY_TRANSACTION_BYTES (/api/variables/SOLANA_ERROR__TRANSACTION__CANNOT_DECODE_EMPTY_TRANSACTION_BYTES) ```ts const SOLANA_ERROR__TRANSACTION__CANNOT_DECODE_EMPTY_TRANSACTION_BYTES: 5663025 = 5663025; ``` # SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES (/api/variables/SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES) ```ts const SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES: 5663024 = 5663024; ``` # SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES (/api/variables/SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES) ```ts const SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES: 5663016 = 5663016; ``` # SOLANA_ERROR__TRANSACTION__COMPUTE_UNIT_LIMIT_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__TRANSACTION__COMPUTE_UNIT_LIMIT_OUT_OF_RANGE) ```ts const SOLANA_ERROR__TRANSACTION__COMPUTE_UNIT_LIMIT_OUT_OF_RANGE: 5663039 = 5663039; ``` # SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT: 5663020 = 5663020; ``` # SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME (/api/variables/SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME) ```ts const SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME: 5663002 = 5663002; ``` # SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME (/api/variables/SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME) ```ts const SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME: 5663003 = 5663003; ``` # SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING (/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING) ```ts const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING: 5663005 = 5663005; ``` # SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE) ```ts const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE: 5663006 = 5663006; ``` # SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING (/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING) ```ts const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING: 5663008 = 5663008; ``` # SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE) ```ts const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE: 5663038 = 5663038; ``` # SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND (/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND) ```ts const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND: 5663007 = 5663007; ``` # SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT: 5663018 = 5663018; ``` # SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_LOADED_ACCOUNTS_DATA_SIZE_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_LOADED_ACCOUNTS_DATA_SIZE_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_LOADED_ACCOUNTS_DATA_SIZE_LIMIT: 5663036 = 5663036; ``` # SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT (/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT) ```ts const SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT: 5663019 = 5663019; ``` # SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS (/api/variables/SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS) ```ts const SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS: 5663037 = 5663037; ``` # SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING (/api/variables/SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING) ```ts const SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING: 5663011 = 5663011; ``` # SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING (/api/variables/SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING) ```ts const SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING: 5663012 = 5663012; ``` # SOLANA_ERROR__TRANSACTION__INSTRUCTION_HEADERS_PAYLOADS_MISMATCH (/api/variables/SOLANA_ERROR__TRANSACTION__INSTRUCTION_HEADERS_PAYLOADS_MISMATCH) ```ts const SOLANA_ERROR__TRANSACTION__INSTRUCTION_HEADERS_PAYLOADS_MISMATCH: 5663031 = 5663031; ``` # SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS (/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS) ```ts const SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS: 5663028 = 5663028; ``` # SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND (/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND) ```ts const SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND: 5663030 = 5663030; ``` # SOLANA_ERROR__TRANSACTION__INVALID_HEAP_SIZE (/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_HEAP_SIZE) ```ts const SOLANA_ERROR__TRANSACTION__INVALID_HEAP_SIZE: 5663040 = 5663040; ``` # SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX (/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX) ```ts const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX: 5663029 = 5663029; ``` # SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE (/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE) ```ts const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE: 5663014 = 5663014; ``` # SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING (/api/variables/SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING) ```ts const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING: 5663013 = 5663013; ``` # SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES (/api/variables/SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES) ```ts const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES: 5663000 = 5663000; ``` # SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE (/api/variables/SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE) ```ts const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE: 5663001 = 5663001; ``` # SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES (/api/variables/SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES) ```ts const SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES: 5663023 = 5663023; ``` # SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH (/api/variables/SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH) ```ts const SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH: 5663017 = 5663017; ``` # SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE (/api/variables/SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE) ```ts const SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE: 5663022 = 5663022; ``` # SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING (/api/variables/SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING) ```ts const SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING: 5663009 = 5663009; ``` # SOLANA_ERROR__TRANSACTION__SIGNATURE_COUNT_TOO_HIGH_FOR_TRANSACTION_BYTES (/api/variables/SOLANA_ERROR__TRANSACTION__SIGNATURE_COUNT_TOO_HIGH_FOR_TRANSACTION_BYTES) ```ts const SOLANA_ERROR__TRANSACTION__SIGNATURE_COUNT_TOO_HIGH_FOR_TRANSACTION_BYTES: 5663027 = 5663027; ``` # SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNTS_IN_INSTRUCTION (/api/variables/SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNTS_IN_INSTRUCTION) ```ts const SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNTS_IN_INSTRUCTION: 5663035 = 5663035; ``` # SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNT_ADDRESSES (/api/variables/SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNT_ADDRESSES) ```ts const SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNT_ADDRESSES: 5663033 = 5663033; ``` # SOLANA_ERROR__TRANSACTION__TOO_MANY_INSTRUCTIONS (/api/variables/SOLANA_ERROR__TRANSACTION__TOO_MANY_INSTRUCTIONS) ```ts const SOLANA_ERROR__TRANSACTION__TOO_MANY_INSTRUCTIONS: 5663034 = 5663034; ``` # SOLANA_ERROR__TRANSACTION__TOO_MANY_SIGNER_ADDRESSES (/api/variables/SOLANA_ERROR__TRANSACTION__TOO_MANY_SIGNER_ADDRESSES) ```ts const SOLANA_ERROR__TRANSACTION__TOO_MANY_SIGNER_ADDRESSES: 5663032 = 5663032; ``` # SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED (/api/variables/SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED) ```ts const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED: 5663021 = 5663021; ``` # SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE (/api/variables/SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE) ```ts const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE: 5663004 = 5663004; ``` # SOLANA_ERROR__TRANSACTION__VERSION_ZERO_MUST_BE_ENCODED_WITH_SIGNATURES_FIRST (/api/variables/SOLANA_ERROR__TRANSACTION__VERSION_ZERO_MUST_BE_ENCODED_WITH_SIGNATURES_FIRST) ```ts const SOLANA_ERROR__TRANSACTION__VERSION_ZERO_MUST_BE_ENCODED_WITH_SIGNATURES_FIRST: 5663026 = 5663026; ``` # SOLANA_ERROR__WALLET__ACCOUNT_NOT_AVAILABLE (/api/variables/SOLANA_ERROR__WALLET__ACCOUNT_NOT_AVAILABLE) ```ts const SOLANA_ERROR__WALLET__ACCOUNT_NOT_AVAILABLE: 8900003 = 8900003; ``` # SOLANA_ERROR__WALLET__NOT_CONNECTED (/api/variables/SOLANA_ERROR__WALLET__NOT_CONNECTED) ```ts const SOLANA_ERROR__WALLET__NOT_CONNECTED: 8900000 = 8900000; ``` # SOLANA_ERROR__WALLET__NO_SIGNER_CONNECTED (/api/variables/SOLANA_ERROR__WALLET__NO_SIGNER_CONNECTED) ```ts const SOLANA_ERROR__WALLET__NO_SIGNER_CONNECTED: 8900001 = 8900001; ``` # SOLANA_ERROR__WALLET__SIGNER_NOT_AVAILABLE (/api/variables/SOLANA_ERROR__WALLET__SIGNER_NOT_AVAILABLE) ```ts const SOLANA_ERROR__WALLET__SIGNER_NOT_AVAILABLE: 8900002 = 8900002; ``` # SYSVAR_CLOCK_ADDRESS (/api/variables/SYSVAR_CLOCK_ADDRESS) ```ts const SYSVAR_CLOCK_ADDRESS: Address<"SysvarC1ock11111111111111111111111111111111">; ``` # SYSVAR_EPOCH_REWARDS_ADDRESS (/api/variables/SYSVAR_EPOCH_REWARDS_ADDRESS) ```ts const SYSVAR_EPOCH_REWARDS_ADDRESS: Address<"SysvarEpochRewards1111111111111111111111111">; ``` # SYSVAR_EPOCH_SCHEDULE_ADDRESS (/api/variables/SYSVAR_EPOCH_SCHEDULE_ADDRESS) ```ts const SYSVAR_EPOCH_SCHEDULE_ADDRESS: Address<"SysvarEpochSchedu1e111111111111111111111111">; ``` # SYSVAR_INSTRUCTIONS_ADDRESS (/api/variables/SYSVAR_INSTRUCTIONS_ADDRESS) ```ts const SYSVAR_INSTRUCTIONS_ADDRESS: Address<"Sysvar1nstructions1111111111111111111111111">; ``` # SYSVAR_LAST_RESTART_SLOT_ADDRESS (/api/variables/SYSVAR_LAST_RESTART_SLOT_ADDRESS) ```ts const SYSVAR_LAST_RESTART_SLOT_ADDRESS: Address<"SysvarLastRestartS1ot1111111111111111111111">; ``` # SYSVAR_RECENT_BLOCKHASHES_ADDRESS (/api/variables/SYSVAR_RECENT_BLOCKHASHES_ADDRESS) ```ts const SYSVAR_RECENT_BLOCKHASHES_ADDRESS: Address<"SysvarRecentB1ockHashes11111111111111111111">; ``` # SYSVAR_RENT_ADDRESS (/api/variables/SYSVAR_RENT_ADDRESS) ```ts const SYSVAR_RENT_ADDRESS: Address<"SysvarRent111111111111111111111111111111111">; ``` # SYSVAR_SLOT_HASHES_ADDRESS (/api/variables/SYSVAR_SLOT_HASHES_ADDRESS) ```ts const SYSVAR_SLOT_HASHES_ADDRESS: Address<"SysvarS1otHashes111111111111111111111111111">; ``` # SYSVAR_SLOT_HISTORY_ADDRESS (/api/variables/SYSVAR_SLOT_HISTORY_ADDRESS) ```ts const SYSVAR_SLOT_HISTORY_ADDRESS: Address<"SysvarS1otHistory11111111111111111111111111">; ``` # SYSVAR_STAKE_HISTORY_ADDRESS (/api/variables/SYSVAR_STAKE_HISTORY_ADDRESS) ```ts const SYSVAR_STAKE_HISTORY_ADDRESS: Address<"SysvarStakeHistory1111111111111111111111111">; ``` # SelectedWalletAccountContext (/api/variables/SelectedWalletAccountContext) ```ts const SelectedWalletAccountContext: Context; ``` # TRANSACTION_CONFIG_COMPUTE_UNIT_LIMIT_BIT_MASK (/api/variables/TRANSACTION_CONFIG_COMPUTE_UNIT_LIMIT_BIT_MASK) ```ts const TRANSACTION_CONFIG_COMPUTE_UNIT_LIMIT_BIT_MASK: 4 = 0b100; ``` # TRANSACTION_CONFIG_HEAP_SIZE_BIT_MASK (/api/variables/TRANSACTION_CONFIG_HEAP_SIZE_BIT_MASK) ```ts const TRANSACTION_CONFIG_HEAP_SIZE_BIT_MASK: 16 = 0b10000; ``` # TRANSACTION_CONFIG_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_BIT_MASK (/api/variables/TRANSACTION_CONFIG_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_BIT_MASK) ```ts const TRANSACTION_CONFIG_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_BIT_MASK: 8 = 0b1000; ``` # TRANSACTION_CONFIG_PRIORITY_FEE_LAMPORTS_BIT_MASK (/api/variables/TRANSACTION_CONFIG_PRIORITY_FEE_LAMPORTS_BIT_MASK) ```ts const TRANSACTION_CONFIG_PRIORITY_FEE_LAMPORTS_BIT_MASK: 3 = 0b11; ``` # fixBytes (/api/variables/fixBytes) ```ts const fixBytes: (bytes, length) => | ReadonlyUint8Array | Uint8Array; ``` Fixes a `Uint8Array` to the specified length. If the array is longer than the specified length, it is truncated. If the array is shorter than the specified length, it is padded with zeroes. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | | `bytes` | \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | The byte array to truncate or pad. | | `length` | `number` | The desired length of the byte array. | ## Returns \| [`ReadonlyUint8Array`](/api/interfaces/ReadonlyUint8Array) \| [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) ## Examples Truncates the byte array to the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]); const fixedBytes = fixBytes(bytes, 2); // ^ [0x01, 0x02] ``` Adds zeroes to the end of the byte array to reach the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02]); const fixedBytes = fixBytes(bytes, 4); // ^ [0x01, 0x02, 0x00, 0x00] ``` Returns the original byte array if it is already at the desired length. ```ts const bytes = new Uint8Array([0x01, 0x02]); const fixedBytes = fixBytes(bytes, 2); // bytes === fixedBytes ``` # getBase10Codec (/api/variables/getBase10Codec) ```ts const getBase10Codec: () => VariableSizeCodec; ``` Returns a codec for encoding and decoding base-10 strings. This codec serializes strings using a base-10 encoding scheme. The output consists of bytes representing the numerical values of the input string. ## Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec) A `VariableSizeCodec` for encoding and decoding base-10 strings. ## Example Encoding and decoding a base-10 string. ```ts const codec = getBase10Codec(); const bytes = codec.encode('1024'); // 0x0400 const value = codec.decode(bytes); // "1024" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-10 codec, consider using [fixCodecSize](/api/functions/fixCodecSize). ```ts const codec = fixCodecSize(getBase10Codec(), 5); ``` If you need a size-prefixed base-10 codec, consider using [addCodecSizePrefix](/api/functions/addCodecSizePrefix). ```ts const codec = addCodecSizePrefix(getBase10Codec(), getU32Codec()); ``` Separate [getBase10Encoder](/api/variables/getBase10Encoder) and [getBase10Decoder](/api/variables/getBase10Decoder) functions are available. ```ts const bytes = getBase10Encoder().encode('1024'); const value = getBase10Decoder().decode(bytes); ``` ## See * [getBase10Encoder](/api/variables/getBase10Encoder) * [getBase10Decoder](/api/variables/getBase10Decoder) # getBase10Decoder (/api/variables/getBase10Decoder) ```ts const getBase10Decoder: () => VariableSizeDecoder; ``` Returns a decoder for base-10 strings. This decoder deserializes base-10 encoded strings from a byte array. For more details, see [getBase10Codec](/api/variables/getBase10Codec). ## Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder) A `VariableSizeDecoder` for decoding base-10 strings. ## Example Decoding a base-10 string. ```ts const decoder = getBase10Decoder(); const value = decoder.decode(new Uint8Array([0x04, 0x00])); // "1024" ``` ## See [getBase10Codec](/api/variables/getBase10Codec) # getBase10Encoder (/api/variables/getBase10Encoder) ```ts const getBase10Encoder: () => VariableSizeEncoder; ``` Returns an encoder for base-10 strings. This encoder serializes strings using a base-10 encoding scheme. The output consists of bytes representing the numerical values of the input string. For more details, see [getBase10Codec](/api/variables/getBase10Codec). ## Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder) A `VariableSizeEncoder` for encoding base-10 strings. ## Example Encoding a base-10 string. ```ts const encoder = getBase10Encoder(); const bytes = encoder.encode('1024'); // 0x0400 ``` ## See [getBase10Codec](/api/variables/getBase10Codec) # getBase16Codec (/api/variables/getBase16Codec) ```ts const getBase16Codec: () => VariableSizeCodec; ``` Returns a codec for encoding and decoding base-16 (hexadecimal) strings. This codec serializes strings using a base-16 encoding scheme. The output consists of bytes representing the hexadecimal values of the input string. ## Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`string`> A `VariableSizeCodec` for encoding and decoding base-16 strings. ## Example Encoding and decoding a base-16 string. ```ts const codec = getBase16Codec(); const bytes = codec.encode('deadface'); // 0xdeadface const value = codec.decode(bytes); // "deadface" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-16 codec, consider using [fixCodecSize](/api/functions/fixCodecSize). ```ts const codec = fixCodecSize(getBase16Codec(), 8); ``` If you need a size-prefixed base-16 codec, consider using [addCodecSizePrefix](/api/functions/addCodecSizePrefix). ```ts const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec()); ``` Separate [getBase16Encoder](/api/variables/getBase16Encoder) and [getBase16Decoder](/api/variables/getBase16Decoder) functions are available. ```ts const bytes = getBase16Encoder().encode('deadface'); const value = getBase16Decoder().decode(bytes); ``` ## See * [getBase16Encoder](/api/variables/getBase16Encoder) * [getBase16Decoder](/api/variables/getBase16Decoder) # getBase16Decoder (/api/variables/getBase16Decoder) ```ts const getBase16Decoder: () => VariableSizeDecoder; ``` Returns a decoder for base-16 (hexadecimal) strings. This decoder deserializes base-16 encoded strings from a byte array. For more details, see [getBase16Codec](/api/variables/getBase16Codec). ## Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`string`> A `VariableSizeDecoder` for decoding base-16 strings. ## Example Decoding a base-16 string. ```ts const decoder = getBase16Decoder(); const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // "deadface" ``` ## See [getBase16Codec](/api/variables/getBase16Codec) # getBase16Encoder (/api/variables/getBase16Encoder) ```ts const getBase16Encoder: () => VariableSizeEncoder; ``` Returns an encoder for base-16 (hexadecimal) strings. This encoder serializes strings using a base-16 encoding scheme. The output consists of bytes representing the hexadecimal values of the input string. For more details, see [getBase16Codec](/api/variables/getBase16Codec). ## Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`string`> A `VariableSizeEncoder` for encoding base-16 strings. ## Example Encoding a base-16 string. ```ts const encoder = getBase16Encoder(); const bytes = encoder.encode('deadface'); // 0xdeadface ``` ## See [getBase16Codec](/api/variables/getBase16Codec) # getBase58Codec (/api/variables/getBase58Codec) ```ts const getBase58Codec: () => VariableSizeCodec; ``` Returns a codec for encoding and decoding base-58 strings. This codec serializes strings using a base-58 encoding scheme, commonly used in cryptocurrency addresses and other compact representations. ## Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec) A `VariableSizeCodec` for encoding and decoding base-58 strings. ## Example Encoding and decoding a base-58 string. ```ts const codec = getBase58Codec(); const bytes = codec.encode('heLLo'); // 0x1b6a3070 const value = codec.decode(bytes); // "heLLo" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-58 codec, consider using [fixCodecSize](/api/functions/fixCodecSize). ```ts const codec = fixCodecSize(getBase58Codec(), 8); ``` If you need a size-prefixed base-58 codec, consider using [addCodecSizePrefix](/api/functions/addCodecSizePrefix). ```ts const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec()); ``` Separate [getBase58Encoder](/api/variables/getBase58Encoder) and [getBase58Decoder](/api/variables/getBase58Decoder) functions are available. ```ts const bytes = getBase58Encoder().encode('heLLo'); const value = getBase58Decoder().decode(bytes); ``` ## See * [getBase58Encoder](/api/variables/getBase58Encoder) * [getBase58Decoder](/api/variables/getBase58Decoder) # getBase58Decoder (/api/variables/getBase58Decoder) ```ts const getBase58Decoder: () => VariableSizeDecoder; ``` Returns a decoder for base-58 strings. This decoder deserializes base-58 encoded strings from a byte array. For more details, see [getBase58Codec](/api/variables/getBase58Codec). ## Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder) A `VariableSizeDecoder` for decoding base-58 strings. ## Example Decoding a base-58 string. ```ts const decoder = getBase58Decoder(); const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // "heLLo" ``` ## See [getBase58Codec](/api/variables/getBase58Codec) # getBase58Encoder (/api/variables/getBase58Encoder) ```ts const getBase58Encoder: () => VariableSizeEncoder; ``` Returns an encoder for base-58 strings. This encoder serializes strings using a base-58 encoding scheme, commonly used in cryptocurrency addresses and other compact representations. For more details, see [getBase58Codec](/api/variables/getBase58Codec). ## Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder) A `VariableSizeEncoder` for encoding base-58 strings. ## Example Encoding a base-58 string. ```ts const encoder = getBase58Encoder(); const bytes = encoder.encode('heLLo'); // 0x1b6a3070 ``` ## See [getBase58Codec](/api/variables/getBase58Codec) # getBase64Codec (/api/variables/getBase64Codec) ```ts const getBase64Codec: () => VariableSizeCodec; ``` Returns a codec for encoding and decoding base-64 strings. This codec serializes strings using a base-64 encoding scheme, commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding. ## Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`string`> A `VariableSizeCodec` for encoding and decoding base-64 strings. ## Example Encoding and decoding a base-64 string. ```ts const codec = getBase64Codec(); const bytes = codec.encode('hello+world'); // 0x85e965a3ec28ae57 const value = codec.decode(bytes); // "hello+world" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-64 codec, consider using [fixCodecSize](/api/functions/fixCodecSize). ```ts const codec = fixCodecSize(getBase64Codec(), 8); ``` If you need a size-prefixed base-64 codec, consider using [addCodecSizePrefix](/api/functions/addCodecSizePrefix). ```ts const codec = addCodecSizePrefix(getBase64Codec(), getU32Codec()); ``` Separate [getBase64Encoder](/api/variables/getBase64Encoder) and [getBase64Decoder](/api/variables/getBase64Decoder) functions are available. ```ts const bytes = getBase64Encoder().encode('hello+world'); const value = getBase64Decoder().decode(bytes); ``` ## See * [getBase64Encoder](/api/variables/getBase64Encoder) * [getBase64Decoder](/api/variables/getBase64Decoder) # getBase64Decoder (/api/variables/getBase64Decoder) ```ts const getBase64Decoder: () => VariableSizeDecoder; ``` Returns a decoder for base-64 strings. This decoder deserializes base-64 encoded strings from a byte array. For more details, see [getBase64Codec](/api/variables/getBase64Codec). ## Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`string`> A `VariableSizeDecoder` for decoding base-64 strings. ## Example Decoding a base-64 string. ```ts const decoder = getBase64Decoder(); const value = decoder.decode(new Uint8Array([0x85, 0xe9, 0x65, 0xa3, 0xec, 0x28, 0xae, 0x57])); // "hello+world" ``` ## See [getBase64Codec](/api/variables/getBase64Codec) # getBase64Encoder (/api/variables/getBase64Encoder) ```ts const getBase64Encoder: () => VariableSizeEncoder; ``` Returns an encoder for base-64 strings. This encoder serializes strings using a base-64 encoding scheme, commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding. For more details, see [getBase64Codec](/api/variables/getBase64Codec). ## Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`string`> A `VariableSizeEncoder` for encoding base-64 strings. ## Example Encoding a base-64 string. ```ts const encoder = getBase64Encoder(); const bytes = encoder.encode('hello+world'); // 0x85e965a3ec28ae57 ``` ## See [getBase64Codec](/api/variables/getBase64Codec) # getBaseXCodec (/api/variables/getBaseXCodec) ```ts const getBaseXCodec: (alphabet) => VariableSizeCodec; ``` Returns a codec for encoding and decoding base-X strings. This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base. The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes. The decoding process reverses this transformation to reconstruct the original string. This codec supports leading zeroes by treating the first character of the alphabet as the zero character. ## Parameters | Parameter | Type | Description | | ---------- | -------- | --------------------------------------------------- | | `alphabet` | `string` | The set of characters defining the base-X encoding. | ## Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`string`> A `VariableSizeCodec` for encoding and decoding base-X strings. ## Example Encoding and decoding a base-X string using a custom alphabet. ```ts const codec = getBaseXCodec('0123456789abcdef'); const bytes = codec.encode('deadface'); // 0xdeadface const value = codec.decode(bytes); // "deadface" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-X codec, consider using [fixCodecSize](/api/functions/fixCodecSize). ```ts const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8); ``` If you need a size-prefixed base-X codec, consider using [addCodecSizePrefix](/api/functions/addCodecSizePrefix). ```ts const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec()); ``` Separate [getBaseXEncoder](/api/variables/getBaseXEncoder) and [getBaseXDecoder](/api/variables/getBaseXDecoder) functions are available. ```ts const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface'); const value = getBaseXDecoder('0123456789abcdef').decode(bytes); ``` ## See * [getBaseXEncoder](/api/variables/getBaseXEncoder) * [getBaseXDecoder](/api/variables/getBaseXDecoder) # getBaseXDecoder (/api/variables/getBaseXDecoder) ```ts const getBaseXDecoder: (alphabet) => VariableSizeDecoder; ``` Returns a decoder for base-X encoded strings. This decoder deserializes base-X encoded strings from a byte array using a custom alphabet. The decoding process converts the byte array into a numeric value in base-10, then maps that value back to characters in the specified base-X alphabet. For more details, see [getBaseXCodec](/api/variables/getBaseXCodec). ## Parameters | Parameter | Type | Description | | ---------- | -------- | --------------------------------------------------- | | `alphabet` | `string` | The set of characters defining the base-X encoding. | ## Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`string`> A `VariableSizeDecoder` for decoding base-X strings. ## Example Decoding a base-X string using a custom alphabet. ```ts const decoder = getBaseXDecoder('0123456789abcdef'); const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // "deadface" ``` ## See [getBaseXCodec](/api/variables/getBaseXCodec) # getBaseXEncoder (/api/variables/getBaseXEncoder) ```ts const getBaseXEncoder: (alphabet) => VariableSizeEncoder; ``` Returns an encoder for base-X encoded strings. This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base. The encoding process involves converting the input string to a numeric value in base-X, then encoding that value into bytes while preserving leading zeroes. For more details, see [getBaseXCodec](/api/variables/getBaseXCodec). ## Parameters | Parameter | Type | Description | | ---------- | -------- | --------------------------------------------------- | | `alphabet` | `string` | The set of characters defining the base-X encoding. | ## Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`string`> A `VariableSizeEncoder` for encoding base-X strings. ## Example Encoding a base-X string using a custom alphabet. ```ts const encoder = getBaseXEncoder('0123456789abcdef'); const bytes = encoder.encode('deadface'); // 0xdeadface ``` ## See [getBaseXCodec](/api/variables/getBaseXCodec) # getBaseXResliceCodec (/api/variables/getBaseXResliceCodec) ```ts const getBaseXResliceCodec: (alphabet, bits) => VariableSizeCodec; ``` Returns a codec for encoding and decoding base-X strings using bit re-slicing. This codec serializes strings by dividing the input into custom-sized bit chunks, mapping them to a given alphabet, and encoding the result into bytes. It is particularly suited for encoding schemes where the alphabet's length is a power of 2, such as base-16 or base-64. ## Parameters | Parameter | Type | Description | | ---------- | -------- | ------------------------------------------------------------------------ | | `alphabet` | `string` | The set of characters defining the base-X encoding. | | `bits` | `number` | The number of bits per encoded chunk, typically `log2(alphabet.length)`. | ## Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`string`> A `VariableSizeCodec` for encoding and decoding base-X strings using bit re-slicing. ## Example Encoding and decoding a base-X string using bit re-slicing. ```ts const codec = getBaseXResliceCodec('elho', 2); const bytes = codec.encode('hellolol'); // 0x4aee const value = codec.decode(bytes); // "hellolol" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size base-X codec, consider using [fixCodecSize](/api/functions/fixCodecSize). ```ts const codec = fixCodecSize(getBaseXResliceCodec('elho', 2), 8); ``` If you need a size-prefixed base-X codec, consider using [addCodecSizePrefix](/api/functions/addCodecSizePrefix). ```ts const codec = addCodecSizePrefix(getBaseXResliceCodec('elho', 2), getU32Codec()); ``` Separate [getBaseXResliceEncoder](/api/variables/getBaseXResliceEncoder) and [getBaseXResliceDecoder](/api/variables/getBaseXResliceDecoder) functions are available. ```ts const bytes = getBaseXResliceEncoder('elho', 2).encode('hellolol'); const value = getBaseXResliceDecoder('elho', 2).decode(bytes); ``` ## See * [getBaseXResliceEncoder](/api/variables/getBaseXResliceEncoder) * [getBaseXResliceDecoder](/api/variables/getBaseXResliceDecoder) # getBaseXResliceDecoder (/api/variables/getBaseXResliceDecoder) ```ts const getBaseXResliceDecoder: (alphabet, bits) => VariableSizeDecoder; ``` Returns a decoder for base-X encoded strings using bit re-slicing. This decoder deserializes base-X encoded strings by re-slicing the bits of a byte array into custom-sized chunks and mapping them to a specified alphabet. This is typically used for encoding schemes where the alphabet's length is a power of 2, such as base-16 or base-64. For more details, see [getBaseXResliceCodec](/api/variables/getBaseXResliceCodec). ## Parameters | Parameter | Type | Description | | ---------- | -------- | ------------------------------------------------------------------------ | | `alphabet` | `string` | The set of characters defining the base-X encoding. | | `bits` | `number` | The number of bits per encoded chunk, typically `log2(alphabet.length)`. | ## Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`string`> A `VariableSizeDecoder` for decoding base-X strings using bit re-slicing. ## Example Decoding a base-X string using bit re-slicing. ```ts const decoder = getBaseXResliceDecoder('elho', 2); const value = decoder.decode(new Uint8Array([0x4a, 0xee])); // "hellolol" ``` ## See [getBaseXResliceCodec](/api/variables/getBaseXResliceCodec) # getBaseXResliceEncoder (/api/variables/getBaseXResliceEncoder) ```ts const getBaseXResliceEncoder: (alphabet, bits) => VariableSizeEncoder; ``` Returns an encoder for base-X encoded strings using bit re-slicing. This encoder serializes strings by dividing the input into custom-sized bit chunks, mapping them to an alphabet, and encoding the result into a byte array. This approach is commonly used for encoding schemes where the alphabet's length is a power of 2, such as base-16 or base-64. For more details, see [getBaseXResliceCodec](/api/variables/getBaseXResliceCodec). ## Parameters | Parameter | Type | Description | | ---------- | -------- | ------------------------------------------------------------------------ | | `alphabet` | `string` | The set of characters defining the base-X encoding. | | `bits` | `number` | The number of bits per encoded chunk, typically `log2(alphabet.length)`. | ## Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`string`> A `VariableSizeEncoder` for encoding base-X strings using bit re-slicing. ## Example Encoding a base-X string using bit re-slicing. ```ts const encoder = getBaseXResliceEncoder('elho', 2); const bytes = encoder.encode('hellolol'); // 0x4aee ``` ## See [getBaseXResliceCodec](/api/variables/getBaseXResliceCodec) # getF32Codec (/api/variables/getF32Codec) ```ts const getF32Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 32-bit floating-point numbers (`f32`). This codec serializes `f32` values using 4 bytes. Due to the IEEE 754 floating-point representation, some precision loss may occur. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `number`, `4`> A `FixedSizeCodec` for encoding and decoding `f32` values. ## Examples Encoding and decoding an `f32` value. ```ts const codec = getF32Codec(); const bytes = codec.encode(-1.5); // 0x0000c0bf const value = codec.decode(bytes); // -1.5 ``` Using big-endian encoding. ```ts const codec = getF32Codec({ endian: Endian.Big }); const bytes = codec.encode(-1.5); // 0xbfc00000 ``` ## Remarks `f32` values follow the IEEE 754 single-precision floating-point standard. Precision loss may occur for certain values. * If you need higher precision, consider using [getF64Codec](/api/variables/getF64Codec). * If you need integer values, consider using [getI32Codec](/api/variables/getI32Codec) or [getU32Codec](/api/variables/getU32Codec). Separate [getF32Encoder](/api/variables/getF32Encoder) and [getF32Decoder](/api/variables/getF32Decoder) functions are available. ```ts const bytes = getF32Encoder().encode(-1.5); const value = getF32Decoder().decode(bytes); ``` ## See * [getF32Encoder](/api/variables/getF32Encoder) * [getF32Decoder](/api/variables/getF32Decoder) # getF32Decoder (/api/variables/getF32Decoder) ```ts const getF32Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 32-bit floating-point numbers (`f32`). This decoder deserializes `f32` values from 4 bytes. Some precision may be lost during decoding due to floating-point representation. For more details, see [getF32Codec](/api/variables/getF32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`number`, `4`> A `FixedSizeDecoder` for decoding `f32` values. ## Example Decoding an `f32` value. ```ts const decoder = getF32Decoder(); const value = decoder.decode(new Uint8Array([0x00, 0x00, 0xc0, 0xbf])); // -1.5 ``` ## See [getF32Codec](/api/variables/getF32Codec) # getF32Encoder (/api/variables/getF32Encoder) ```ts const getF32Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 32-bit floating-point numbers (`f32`). This encoder serializes `f32` values using 4 bytes. Floating-point values may lose precision when encoded. For more details, see [getF32Codec](/api/variables/getF32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `4`> A `FixedSizeEncoder` for encoding `f32` values. ## Example Encoding an `f32` value. ```ts const encoder = getF32Encoder(); const bytes = encoder.encode(-1.5); // 0x0000c0bf ``` ## See [getF32Codec](/api/variables/getF32Codec) # getF64Codec (/api/variables/getF64Codec) ```ts const getF64Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 64-bit floating-point numbers (`f64`). This codec serializes `f64` values using 8 bytes. Due to the IEEE 754 floating-point representation, some precision loss may occur. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `number`, `8`> A `FixedSizeCodec` for encoding and decoding `f64` values. ## Examples Encoding and decoding an `f64` value. ```ts const codec = getF64Codec(); const bytes = codec.encode(-1.5); // 0x000000000000f8bf const value = codec.decode(bytes); // -1.5 ``` Using big-endian encoding. ```ts const codec = getF64Codec({ endian: Endian.Big }); const bytes = codec.encode(-1.5); // 0xbff8000000000000 ``` ## Remarks `f64` values follow the IEEE 754 double-precision floating-point standard. Precision loss may still occur but is significantly lower than `f32`. * If you need smaller floating-point values, consider using [getF32Codec](/api/variables/getF32Codec). * If you need integer values, consider using [getI64Codec](/api/variables/getI64Codec) or [getU64Codec](/api/variables/getU64Codec). Separate [getF64Encoder](/api/variables/getF64Encoder) and [getF64Decoder](/api/variables/getF64Decoder) functions are available. ```ts const bytes = getF64Encoder().encode(-1.5); const value = getF64Decoder().decode(bytes); ``` ## See * [getF64Encoder](/api/variables/getF64Encoder) * [getF64Decoder](/api/variables/getF64Decoder) # getF64Decoder (/api/variables/getF64Decoder) ```ts const getF64Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 64-bit floating-point numbers (`f64`). This decoder deserializes `f64` values from 8 bytes. Some precision may be lost during decoding due to floating-point representation. For more details, see [getF64Codec](/api/variables/getF64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`number`, `8`> A `FixedSizeDecoder` for decoding `f64` values. ## Example Decoding an `f64` value. ```ts const decoder = getF64Decoder(); const value = decoder.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf])); // -1.5 ``` ## See [getF64Codec](/api/variables/getF64Codec) # getF64Encoder (/api/variables/getF64Encoder) ```ts const getF64Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 64-bit floating-point numbers (`f64`). This encoder serializes `f64` values using 8 bytes. Floating-point values may lose precision when encoded. For more details, see [getF64Codec](/api/variables/getF64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `8`> A `FixedSizeEncoder` for encoding `f64` values. ## Example Encoding an `f64` value. ```ts const encoder = getF64Encoder(); const bytes = encoder.encode(-1.5); // 0x000000000000f8bf ``` ## See [getF64Codec](/api/variables/getF64Codec) # getI128Codec (/api/variables/getI128Codec) ```ts const getI128Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 128-bit signed integers (`i128`). This codec serializes `i128` values using 16 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `bigint`, `16`> A `FixedSizeCodec` for encoding and decoding `i128` values. ## Examples Encoding and decoding an `i128` value. ```ts const codec = getI128Codec(); const bytes = codec.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff const value = codec.decode(bytes); // -42n ``` Using big-endian encoding. ```ts const codec = getI128Codec({ endian: Endian.Big }); const bytes = codec.encode(-42n); // 0xffffffffffffffffffffffffffffd6 ``` ## Remarks This codec supports values between `-2^127` and `2^127 - 1`. Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`. * If you need a smaller signed integer, consider using [getI64Codec](/api/variables/getI64Codec) or [getI32Codec](/api/variables/getI32Codec). * If you need a larger signed integer, consider using a custom codec. * If you need unsigned integers, consider using [getU128Codec](/api/variables/getU128Codec). Separate [getI128Encoder](/api/variables/getI128Encoder) and [getI128Decoder](/api/variables/getI128Decoder) functions are available. ```ts const bytes = getI128Encoder().encode(-42); const value = getI128Decoder().decode(bytes); ``` ## See * [getI128Encoder](/api/variables/getI128Encoder) * [getI128Decoder](/api/variables/getI128Decoder) # getI128Decoder (/api/variables/getI128Decoder) ```ts const getI128Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 128-bit signed integers (`i128`). This decoder deserializes `i128` values from 16 bytes. The decoded value is always a `bigint`. For more details, see [getI128Codec](/api/variables/getI128Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`bigint`, `16`> A `FixedSizeDecoder` for decoding `i128` values. ## Example Decoding an `i128` value. ```ts const decoder = getI128Decoder(); const value = decoder.decode(new Uint8Array([ 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ])); // -42n ``` ## See [getI128Codec](/api/variables/getI128Codec) # getI128Encoder (/api/variables/getI128Encoder) ```ts const getI128Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 128-bit signed integers (`i128`). This encoder serializes `i128` values using 16 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getI128Codec](/api/variables/getI128Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `16`> A `FixedSizeEncoder` for encoding `i128` values. ## Example Encoding an `i128` value. ```ts const encoder = getI128Encoder(); const bytes = encoder.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff ``` ## See [getI128Codec](/api/variables/getI128Codec) # getI16Codec (/api/variables/getI16Codec) ```ts const getI16Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 16-bit signed integers (`i16`). This codec serializes `i16` values using 2 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `number`, `2`> A `FixedSizeCodec` for encoding and decoding `i16` values. ## Examples Encoding and decoding an `i16` value. ```ts const codec = getI16Codec(); const bytes = codec.encode(-42); // 0xd6ff const value = codec.decode(bytes); // -42 ``` Using big-endian encoding. ```ts const codec = getI16Codec({ endian: Endian.Big }); const bytes = codec.encode(-42); // 0xffd6 ``` ## Remarks This codec supports values between `-2^15` (`-32,768`) and `2^15 - 1` (`32,767`). * If you need a smaller signed integer, consider using [getI8Codec](/api/variables/getI8Codec). * If you need a larger signed integer, consider using [getI32Codec](/api/variables/getI32Codec). * If you need unsigned integers, consider using [getU16Codec](/api/variables/getU16Codec). Separate [getI16Encoder](/api/variables/getI16Encoder) and [getI16Decoder](/api/variables/getI16Decoder) functions are available. ```ts const bytes = getI16Encoder().encode(-42); const value = getI16Decoder().decode(bytes); ``` ## See * [getI16Encoder](/api/variables/getI16Encoder) * [getI16Decoder](/api/variables/getI16Decoder) # getI16Decoder (/api/variables/getI16Decoder) ```ts const getI16Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 16-bit signed integers (`i16`). This decoder deserializes `i16` values from 2 bytes. The decoded value is always a `number`. For more details, see [getI16Codec](/api/variables/getI16Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`number`, `2`> A `FixedSizeDecoder` for decoding `i16` values. ## Example Decoding an `i16` value. ```ts const decoder = getI16Decoder(); const value = decoder.decode(new Uint8Array([0xd6, 0xff])); // -42 ``` ## See [getI16Codec](/api/variables/getI16Codec) # getI16Encoder (/api/variables/getI16Encoder) ```ts const getI16Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 16-bit signed integers (`i16`). This encoder serializes `i16` values using 2 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getI16Codec](/api/variables/getI16Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `2`> A `FixedSizeEncoder` for encoding `i16` values. ## Example Encoding an `i16` value. ```ts const encoder = getI16Encoder(); const bytes = encoder.encode(-42); // 0xd6ff ``` ## See [getI16Codec](/api/variables/getI16Codec) # getI32Codec (/api/variables/getI32Codec) ```ts const getI32Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 32-bit signed integers (`i32`). This codec serializes `i32` values using 4 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `number`, `4`> A `FixedSizeCodec` for encoding and decoding `i32` values. ## Examples Encoding and decoding an `i32` value. ```ts const codec = getI32Codec(); const bytes = codec.encode(-42); // 0xd6ffffff const value = codec.decode(bytes); // -42 ``` Using big-endian encoding. ```ts const codec = getI32Codec({ endian: Endian.Big }); const bytes = codec.encode(-42); // 0xffffffd6 ``` ## Remarks This codec supports values between `-2^31` (`-2,147,483,648`) and `2^31 - 1` (`2,147,483,647`). * If you need a smaller signed integer, consider using [getI16Codec](/api/variables/getI16Codec) or [getI8Codec](/api/variables/getI8Codec). * If you need a larger signed integer, consider using [getI64Codec](/api/variables/getI64Codec). * If you need unsigned integers, consider using [getU32Codec](/api/variables/getU32Codec). Separate [getI32Encoder](/api/variables/getI32Encoder) and [getI32Decoder](/api/variables/getI32Decoder) functions are available. ```ts const bytes = getI32Encoder().encode(-42); const value = getI32Decoder().decode(bytes); ``` ## See * [getI32Encoder](/api/variables/getI32Encoder) * [getI32Decoder](/api/variables/getI32Decoder) # getI32Decoder (/api/variables/getI32Decoder) ```ts const getI32Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 32-bit signed integers (`i32`). This decoder deserializes `i32` values from 4 bytes. The decoded value is always a `number`. For more details, see [getI32Codec](/api/variables/getI32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`number`, `4`> A `FixedSizeDecoder` for decoding `i32` values. ## Example Decoding an `i32` value. ```ts const decoder = getI32Decoder(); const value = decoder.decode(new Uint8Array([0xd6, 0xff, 0xff, 0xff])); // -42 ``` ## See [getI32Codec](/api/variables/getI32Codec) # getI32Encoder (/api/variables/getI32Encoder) ```ts const getI32Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 32-bit signed integers (`i32`). This encoder serializes `i32` values using 4 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getI32Codec](/api/variables/getI32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `4`> A `FixedSizeEncoder` for encoding `i32` values. ## Example Encoding an `i32` value. ```ts const encoder = getI32Encoder(); const bytes = encoder.encode(-42); // 0xd6ffffff ``` ## See [getI32Codec](/api/variables/getI32Codec) # getI64Codec (/api/variables/getI64Codec) ```ts const getI64Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 64-bit signed integers (`i64`). This codec serializes `i64` values using 8 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `bigint`, `8`> A `FixedSizeCodec` for encoding and decoding `i64` values. ## Examples Encoding and decoding an `i64` value. ```ts const codec = getI64Codec(); const bytes = codec.encode(-42n); // 0xd6ffffffffffffff const value = codec.decode(bytes); // -42n ``` Using big-endian encoding. ```ts const codec = getI64Codec({ endian: Endian.Big }); const bytes = codec.encode(-42n); // 0xffffffffffffffd6 ``` ## Remarks This codec supports values between `-2^63` and `2^63 - 1`. Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`. * If you need a smaller signed integer, consider using [getI32Codec](/api/variables/getI32Codec) or [getI16Codec](/api/variables/getI16Codec). * If you need a larger signed integer, consider using [getI128Codec](/api/variables/getI128Codec). * If you need unsigned integers, consider using [getU64Codec](/api/variables/getU64Codec). Separate [getI64Encoder](/api/variables/getI64Encoder) and [getI64Decoder](/api/variables/getI64Decoder) functions are available. ```ts const bytes = getI64Encoder().encode(-42); const value = getI64Decoder().decode(bytes); ``` ## See * [getI64Encoder](/api/variables/getI64Encoder) * [getI64Decoder](/api/variables/getI64Decoder) # getI64Decoder (/api/variables/getI64Decoder) ```ts const getI64Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 64-bit signed integers (`i64`). This decoder deserializes `i64` values from 8 bytes. The decoded value is always a `bigint`. For more details, see [getI64Codec](/api/variables/getI64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`bigint`, `8`> A `FixedSizeDecoder` for decoding `i64` values. ## Example Decoding an `i64` value. ```ts const decoder = getI64Decoder(); const value = decoder.decode(new Uint8Array([ 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ])); // -42n ``` ## See [getI64Codec](/api/variables/getI64Codec) # getI64Encoder (/api/variables/getI64Encoder) ```ts const getI64Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 64-bit signed integers (`i64`). This encoder serializes `i64` values using 8 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getI64Codec](/api/variables/getI64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `8`> A `FixedSizeEncoder` for encoding `i64` values. ## Example Encoding an `i64` value. ```ts const encoder = getI64Encoder(); const bytes = encoder.encode(-42n); // 0xd6ffffffffffffff ``` ## See [getI64Codec](/api/variables/getI64Codec) # getI8Codec (/api/variables/getI8Codec) ```ts const getI8Codec: () => FixedSizeCodec; ``` Returns a codec for encoding and decoding 8-bit signed integers (`i8`). This codec serializes `i8` values using 1 byte. Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`. ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `number`, `1`> A `FixedSizeCodec` for encoding and decoding `i8` values. ## Example Encoding and decoding an `i8` value. ```ts const codec = getI8Codec(); const bytes = codec.encode(-42); // 0xd6 const value = codec.decode(bytes); // -42 ``` ## Remarks This codec supports values between `-2^7` (`-128`) and `2^7 - 1` (`127`). * If you need a larger signed integer, consider using [getI16Codec](/api/variables/getI16Codec). * If you need an unsigned integer, consider using [getU8Codec](/api/variables/getU8Codec). Separate [getI8Encoder](/api/variables/getI8Encoder) and [getI8Decoder](/api/variables/getI8Decoder) functions are available. ```ts const bytes = getI8Encoder().encode(-42); const value = getI8Decoder().decode(bytes); ``` ## See * [getI8Encoder](/api/variables/getI8Encoder) * [getI8Decoder](/api/variables/getI8Decoder) # getI8Decoder (/api/variables/getI8Decoder) ```ts const getI8Decoder: () => FixedSizeDecoder; ``` Returns a decoder for 8-bit signed integers (`i8`). This decoder deserializes `i8` values from 1 byte. The decoded value is always a `number`. For more details, see [getI8Codec](/api/variables/getI8Codec). ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`number`, `1`> A `FixedSizeDecoder` for decoding `i8` values. ## Example Decoding an `i8` value. ```ts const decoder = getI8Decoder(); const value = decoder.decode(new Uint8Array([0xd6])); // -42 ``` ## See [getI8Codec](/api/variables/getI8Codec) # getI8Encoder (/api/variables/getI8Encoder) ```ts const getI8Encoder: () => FixedSizeEncoder; ``` Returns an encoder for 8-bit signed integers (`i8`). This encoder serializes `i8` values using 1 byte. Values can be provided as either `number` or `bigint`. For more details, see [getI8Codec](/api/variables/getI8Codec). ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `1`> A `FixedSizeEncoder` for encoding `i8` values. ## Example Encoding an `i8` value. ```ts const encoder = getI8Encoder(); const bytes = encoder.encode(-42); // 0xd6 ``` ## See [getI8Codec](/api/variables/getI8Codec) # getShortU16Codec (/api/variables/getShortU16Codec) ```ts const getShortU16Codec: () => VariableSizeCodec; ``` Returns a codec for encoding and decoding `shortU16` values. It serializes unsigned integers using **1 to 3 bytes** based on the encoded value. The larger the value, the more bytes it uses. * If the value is `<= 0x7f` (127), it is stored in a **single byte** and the first bit is set to `0` to indicate the end of the value. * Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern. * This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value. In other words, the encoding scheme follows this structure: ```txt 0XXXXXXX <- Values 0 to 127 (1 byte) 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes) 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes) ``` ## Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`bigint` | `number`, `number`> A `VariableSizeCodec` for encoding and decoding `shortU16` values. ## Example Encoding and decoding `shortU16` values. ```ts const codec = getShortU16Codec(); const bytes1 = codec.encode(42); // 0x2a const bytes2 = codec.encode(128); // 0x8001 const bytes3 = codec.encode(16384); // 0x808001 codec.decode(bytes1); // 42 codec.decode(bytes2); // 128 codec.decode(bytes3); // 16384 ``` ## Remarks This codec efficiently stores small numbers, making it useful for transactions and compact representations. If you need a fixed-size `u16` codec, consider using [getU16Codec](/api/variables/getU16Codec). Separate [getShortU16Encoder](/api/variables/getShortU16Encoder) and [getShortU16Decoder](/api/variables/getShortU16Decoder) functions are available. ```ts const bytes = getShortU16Encoder().encode(42); const value = getShortU16Decoder().decode(bytes); ``` ## See * [getShortU16Encoder](/api/variables/getShortU16Encoder) * [getShortU16Decoder](/api/variables/getShortU16Decoder) # getShortU16Decoder (/api/variables/getShortU16Decoder) ```ts const getShortU16Decoder: () => VariableSizeDecoder; ``` Returns a decoder for `shortU16` values. This decoder deserializes `shortU16` values from **1 to 3 bytes**. The number of bytes used depends on the encoded value. For more details, see [getShortU16Codec](/api/variables/getShortU16Codec). ## Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`number`> A `VariableSizeDecoder` for decoding `shortU16` values. ## Example Decoding a `shortU16` value. ```ts const decoder = getShortU16Decoder(); decoder.decode(new Uint8Array([0x2a])); // 42 decoder.decode(new Uint8Array([0x80, 0x01])); // 128 decoder.decode(new Uint8Array([0x80, 0x80, 0x01])); // 16384 ``` ## See [getShortU16Codec](/api/variables/getShortU16Codec) # getShortU16Encoder (/api/variables/getShortU16Encoder) ```ts const getShortU16Encoder: () => VariableSizeEncoder; ``` Returns an encoder for `shortU16` values. This encoder serializes `shortU16` values using **1 to 3 bytes**. Smaller values use fewer bytes, while larger values take up more space. For more details, see [getShortU16Codec](/api/variables/getShortU16Codec). ## Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`bigint` | `number`> A `VariableSizeEncoder` for encoding `shortU16` values. ## Example Encoding a `shortU16` value. ```ts const encoder = getShortU16Encoder(); encoder.encode(42); // 0x2a encoder.encode(128); // 0x8001 encoder.encode(16384); // 0x808001 ``` ## See [getShortU16Codec](/api/variables/getShortU16Codec) # getU128Codec (/api/variables/getU128Codec) ```ts const getU128Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 128-bit unsigned integers (`u128`). This codec serializes `u128` values using 16 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `bigint`, `16`> A `FixedSizeCodec` for encoding and decoding `u128` values. ## Examples Encoding and decoding a `u128` value. ```ts const codec = getU128Codec(); const bytes = codec.encode(42); // 0x2a000000000000000000000000000000 const value = codec.decode(bytes); // 42n ``` Using big-endian encoding. ```ts const codec = getU128Codec({ endian: Endian.Big }); const bytes = codec.encode(42); // 0x0000000000000000000000000000002a ``` ## Remarks This codec supports values between `0` and `2^128 - 1`. Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`. * If you need a smaller unsigned integer, consider using [getU64Codec](/api/variables/getU64Codec) or [getU32Codec](/api/variables/getU32Codec). * If you need signed integers, consider using [getI128Codec](/api/variables/getI128Codec). Separate [getU128Encoder](/api/variables/getU128Encoder) and [getU128Decoder](/api/variables/getU128Decoder) functions are available. ```ts const bytes = getU128Encoder().encode(42); const value = getU128Decoder().decode(bytes); ``` ## See * [getU128Encoder](/api/variables/getU128Encoder) * [getU128Decoder](/api/variables/getU128Decoder) # getU128Decoder (/api/variables/getU128Decoder) ```ts const getU128Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 128-bit unsigned integers (`u128`). This decoder deserializes `u128` values from sixteen bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU128Codec](/api/variables/getU128Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`bigint`, `16`> A `FixedSizeDecoder` for decoding `u128` values. ## Example Decoding a `u128` value. ```ts const decoder = getU128Decoder(); const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n ``` ## See [getU128Codec](/api/variables/getU128Codec) # getU128Encoder (/api/variables/getU128Encoder) ```ts const getU128Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 128-bit unsigned integers (`u128`). This encoder serializes `u128` values using sixteen bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU128Codec](/api/variables/getU128Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `16`> A `FixedSizeEncoder` for encoding `u128` values. ## Example Encoding a `u128` value. ```ts const encoder = getU128Encoder(); const bytes = encoder.encode(42n); // 0x2a000000000000000000000000000000 ``` ## See [getU128Codec](/api/variables/getU128Codec) # getU16Codec (/api/variables/getU16Codec) ```ts const getU16Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 16-bit unsigned integers (`u16`). This codec serializes `u16` values using two bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `number`, `2`> A `FixedSizeCodec` for encoding and decoding `u16` values. ## Examples Encoding and decoding a `u16` value. ```ts const codec = getU16Codec(); const bytes = codec.encode(42); // 0x2a00 (little-endian) const value = codec.decode(bytes); // 42 ``` Storing values in big-endian format. ```ts const codec = getU16Codec({ endian: Endian.Big }); const bytes = codec.encode(42); // 0x002a ``` ## Remarks This codec supports values between `0` and `2^16 - 1`. If you need a larger range, consider using [getU32Codec](/api/variables/getU32Codec) or [getU64Codec](/api/variables/getU64Codec). For signed integers, use [getI16Codec](/api/variables/getI16Codec). Separate [getU16Encoder](/api/variables/getU16Encoder) and [getU16Decoder](/api/variables/getU16Decoder) functions are available. ```ts const bytes = getU16Encoder().encode(42); const value = getU16Decoder().decode(bytes); ``` ## See * [getU16Encoder](/api/variables/getU16Encoder) * [getU16Decoder](/api/variables/getU16Decoder) # getU16Decoder (/api/variables/getU16Decoder) ```ts const getU16Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 16-bit unsigned integers (`u16`). This decoder deserializes `u16` values from two bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU16Codec](/api/variables/getU16Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`number`, `2`> A `FixedSizeDecoder` for decoding `u16` values. ## Example Decoding a `u16` value. ```ts const decoder = getU16Decoder(); const value = decoder.decode(new Uint8Array([0x2a, 0x00])); // 42 ``` ## See [getU16Codec](/api/variables/getU16Codec) # getU16Encoder (/api/variables/getU16Encoder) ```ts const getU16Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 16-bit unsigned integers (`u16`). This encoder serializes `u16` values using two bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU16Codec](/api/variables/getU16Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `2`> A `FixedSizeEncoder` for encoding `u16` values. ## Example Encoding a `u16` value. ```ts const encoder = getU16Encoder(); const bytes = encoder.encode(42); // 0x2a00 ``` ## See [getU16Codec](/api/variables/getU16Codec) # getU32Codec (/api/variables/getU32Codec) ```ts const getU32Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 32-bit unsigned integers (`u32`). This codec serializes `u32` values using four bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `number`, `4`> A `FixedSizeCodec` for encoding and decoding `u32` values. ## Examples Encoding and decoding a `u32` value. ```ts const codec = getU32Codec(); const bytes = codec.encode(42); // 0x2a000000 (little-endian) const value = codec.decode(bytes); // 42 ``` Storing values in big-endian format. ```ts const codec = getU32Codec({ endian: Endian.Big }); const bytes = codec.encode(42); // 0x0000002a ``` ## Remarks This codec only supports values between `0` and `2^32 - 1`. If you need a larger range, consider using [getU64Codec](/api/variables/getU64Codec) or [getU128Codec](/api/variables/getU128Codec). For signed integers, use [getI32Codec](/api/variables/getI32Codec). Separate [getU32Encoder](/api/variables/getU32Encoder) and [getU32Decoder](/api/variables/getU32Decoder) functions are available. ```ts const bytes = getU32Encoder().encode(42); const value = getU32Decoder().decode(bytes); ``` ## See * [getU32Encoder](/api/variables/getU32Encoder) * [getU32Decoder](/api/variables/getU32Decoder) # getU32Decoder (/api/variables/getU32Decoder) ```ts const getU32Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 32-bit unsigned integers (`u32`). This decoder deserializes `u32` values from four bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU32Codec](/api/variables/getU32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`number`, `4`> A `FixedSizeDecoder` for decoding `u32` values. ## Example Decoding a `u32` value. ```ts const decoder = getU32Decoder(); const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42 ``` ## See [getU32Codec](/api/variables/getU32Codec) # getU32Encoder (/api/variables/getU32Encoder) ```ts const getU32Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 32-bit unsigned integers (`u32`). This encoder serializes `u32` values using four bytes in little-endian format by default. You may specify big-endian storage using the `endian` option. For more details, see [getU32Codec](/api/variables/getU32Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | --------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional settings for endianness. | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `4`> A `FixedSizeEncoder` for encoding `u32` values. ## Example Encoding a `u32` value. ```ts const encoder = getU32Encoder(); const bytes = encoder.encode(42); // 0x2a000000 ``` ## See [getU32Codec](/api/variables/getU32Codec) # getU64Codec (/api/variables/getU64Codec) ```ts const getU64Codec: (config?) => FixedSizeCodec; ``` Returns a codec for encoding and decoding 64-bit unsigned integers (`u64`). This codec serializes `u64` values using 8 bytes. Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`. ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `bigint`, `8`> A `FixedSizeCodec` for encoding and decoding `u64` values. ## Examples Encoding and decoding a `u64` value. ```ts const codec = getU64Codec(); const bytes = codec.encode(42); // 0x2a00000000000000 const value = codec.decode(bytes); // 42n ``` Using big-endian encoding. ```ts const codec = getU64Codec({ endian: Endian.Big }); const bytes = codec.encode(42); // 0x000000000000002a ``` ## Remarks This codec supports values between `0` and `2^64 - 1`. Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`. * If you need a smaller unsigned integer, consider using [getU32Codec](/api/variables/getU32Codec) or [getU16Codec](/api/variables/getU16Codec). * If you need a larger unsigned integer, consider using [getU128Codec](/api/variables/getU128Codec). * If you need signed integers, consider using [getI64Codec](/api/variables/getI64Codec). Separate [getU64Encoder](/api/variables/getU64Encoder) and [getU64Decoder](/api/variables/getU64Decoder) functions are available. ```ts const bytes = getU64Encoder().encode(42); const value = getU64Decoder().decode(bytes); ``` ## See * [getU64Encoder](/api/variables/getU64Encoder) * [getU64Decoder](/api/variables/getU64Decoder) # getU64Decoder (/api/variables/getU64Decoder) ```ts const getU64Decoder: (config?) => FixedSizeDecoder; ``` Returns a decoder for 64-bit unsigned integers (`u64`). This decoder deserializes `u64` values from 8 bytes. The decoded value is always a `bigint`. For more details, see [getU64Codec](/api/variables/getU64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`bigint`, `8`> A `FixedSizeDecoder` for decoding `u64` values. ## Example Decoding a `u64` value. ```ts const decoder = getU64Decoder(); const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n ``` ## See [getU64Codec](/api/variables/getU64Codec) # getU64Encoder (/api/variables/getU64Encoder) ```ts const getU64Encoder: (config?) => FixedSizeEncoder; ``` Returns an encoder for 64-bit unsigned integers (`u64`). This encoder serializes `u64` values using 8 bytes. Values can be provided as either `number` or `bigint`. For more details, see [getU64Codec](/api/variables/getU64Codec). ## Parameters | Parameter | Type | Description | | --------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | `config?` | [`NumberCodecConfig`](/api/type-aliases/NumberCodecConfig) | Optional configuration to specify endianness (little by default). | ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `8`> A `FixedSizeEncoder` for encoding `u64` values. ## Example Encoding a `u64` value. ```ts const encoder = getU64Encoder(); const bytes = encoder.encode(42); // 0x2a00000000000000 ``` ## See [getU64Codec](/api/variables/getU64Codec) # getU8Codec (/api/variables/getU8Codec) ```ts const getU8Codec: () => FixedSizeCodec; ``` Returns a codec for encoding and decoding 8-bit unsigned integers (`u8`). This codec serializes `u8` values using a single byte. ## Returns [`FixedSizeCodec`](/api/interfaces/FixedSizeCodec)\<`bigint` | `number`, `number`, `1`> A `FixedSizeCodec` for encoding and decoding `u8` values. ## Example Encoding and decoding a `u8` value. ```ts const codec = getU8Codec(); const bytes = codec.encode(255); // 0xff const value = codec.decode(bytes); // 255 ``` ## Remarks This codec supports values between `0` and `2^8 - 1` (0 to 255). If you need larger integers, consider using [getU16Codec](/api/variables/getU16Codec), [getU32Codec](/api/variables/getU32Codec), or [getU64Codec](/api/variables/getU64Codec). For signed integers, use [getI8Codec](/api/variables/getI8Codec). Separate [getU8Encoder](/api/variables/getU8Encoder) and [getU8Decoder](/api/variables/getU8Decoder) functions are available. ```ts const bytes = getU8Encoder().encode(42); const value = getU8Decoder().decode(bytes); ``` ## See * [getU8Encoder](/api/variables/getU8Encoder) * [getU8Decoder](/api/variables/getU8Decoder) # getU8Decoder (/api/variables/getU8Decoder) ```ts const getU8Decoder: () => FixedSizeDecoder; ``` Returns a decoder for 8-bit unsigned integers (`u8`). This decoder deserializes `u8` values from a single byte. For more details, see [getU8Codec](/api/variables/getU8Codec). ## Returns [`FixedSizeDecoder`](/api/interfaces/FixedSizeDecoder)\<`number`, `1`> A `FixedSizeDecoder` for decoding `u8` values. ## Example Decoding a `u8` value. ```ts const decoder = getU8Decoder(); const value = decoder.decode(new Uint8Array([0xff])); // 255 ``` ## See [getU8Codec](/api/variables/getU8Codec) # getU8Encoder (/api/variables/getU8Encoder) ```ts const getU8Encoder: () => FixedSizeEncoder; ``` Returns an encoder for 8-bit unsigned integers (`u8`). This encoder serializes `u8` values using a single byte. For more details, see [getU8Codec](/api/variables/getU8Codec). ## Returns [`FixedSizeEncoder`](/api/interfaces/FixedSizeEncoder)\<`bigint` | `number`, `1`> A `FixedSizeEncoder` for encoding `u8` values. ## Example Encoding a `u8` value. ```ts const encoder = getU8Encoder(); const bytes = encoder.encode(42); // 0x2a ``` ## See [getU8Codec](/api/variables/getU8Codec) # getUtf8Codec (/api/variables/getUtf8Codec) ```ts const getUtf8Codec: () => VariableSizeCodec; ``` Returns a codec for encoding and decoding UTF-8 strings. This codec serializes strings using UTF-8 encoding. The encoded output contains as many bytes as needed to represent the string. ## Returns [`VariableSizeCodec`](/api/interfaces/VariableSizeCodec)\<`string`> A `VariableSizeCodec` for encoding and decoding UTF-8 strings. ## Example Encoding and decoding a UTF-8 string. ```ts const codec = getUtf8Codec(); const bytes = codec.encode('hello'); // 0x68656c6c6f const value = codec.decode(bytes); // "hello" ``` ## Remarks This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string. If you need a fixed-size UTF-8 codec, consider using [fixCodecSize](/api/functions/fixCodecSize). ```ts const codec = fixCodecSize(getUtf8Codec(), 5); ``` If you need a size-prefixed UTF-8 codec, consider using [addCodecSizePrefix](/api/functions/addCodecSizePrefix). ```ts const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec()); ``` Separate [getUtf8Encoder](/api/variables/getUtf8Encoder) and [getUtf8Decoder](/api/variables/getUtf8Decoder) functions are available. ```ts const bytes = getUtf8Encoder().encode('hello'); const value = getUtf8Decoder().decode(bytes); ``` ## See * [getUtf8Encoder](/api/variables/getUtf8Encoder) * [getUtf8Decoder](/api/variables/getUtf8Decoder) # getUtf8Decoder (/api/variables/getUtf8Decoder) ```ts const getUtf8Decoder: () => VariableSizeDecoder; ``` Returns a decoder for UTF-8 strings. This decoder deserializes UTF-8 encoded strings from a byte array. It reads all available bytes starting from the given offset. For more details, see [getUtf8Codec](/api/variables/getUtf8Codec). ## Returns [`VariableSizeDecoder`](/api/interfaces/VariableSizeDecoder)\<`string`> A `VariableSizeDecoder` for decoding UTF-8 strings. ## Example Decoding a UTF-8 string. ```ts const decoder = getUtf8Decoder(); const value = decoder.decode(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // "hello" ``` ## See [getUtf8Codec](/api/variables/getUtf8Codec) # getUtf8Encoder (/api/variables/getUtf8Encoder) ```ts const getUtf8Encoder: () => VariableSizeEncoder; ``` Returns an encoder for UTF-8 strings. This encoder serializes strings using UTF-8 encoding. The encoded output contains as many bytes as needed to represent the string. For more details, see [getUtf8Codec](/api/variables/getUtf8Codec). ## Returns [`VariableSizeEncoder`](/api/interfaces/VariableSizeEncoder)\<`string`> A `VariableSizeEncoder` for encoding UTF-8 strings. ## Example Encoding a UTF-8 string. ```ts const encoder = getUtf8Encoder(); const bytes = encoder.encode('hello'); // 0x68656c6c6f ``` ## See [getUtf8Codec](/api/variables/getUtf8Codec) # innerInstructionsConfigs (/api/variables/innerInstructionsConfigs) ```ts const innerInstructionsConfigs: (string | KeyPathWildcard)[][]; ``` # isNone (/api/variables/isNone) ```ts const isNone: (option) => option is None; ``` Checks whether the given [Option](/api/type-aliases/Option) contains no value. This function acts as a type guard, ensuring the value is a [None](/api/type-aliases/None). ## Type Parameters | Type Parameter | Description | | -------------- | ------------------------------- | | `T` | The type of the expected value. | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------ | ------------------------------------------------ | | `option` | [`Option`](/api/type-aliases/Option)\<`T`> | The [Option](/api/type-aliases/Option) to check. | ## Returns `option is None` `true` if the option is a [None](/api/type-aliases/None), `false` otherwise. ## Example Checking for `None` values. ```ts isNone(some(42)); // false isNone(none()); // true ``` ## See * [Option](/api/type-aliases/Option) * [None](/api/type-aliases/None) # isOption (/api/variables/isOption) ```ts const isOption: (input) => input is Option; ``` Checks whether the given value is an [Option](/api/type-aliases/Option). This function determines whether an input follows the `Option` structure. ## Type Parameters | Type Parameter | Default type | Description | | -------------- | ------------ | -------------------------------- | | `T` | `unknown` | The type of the contained value. | ## Parameters | Parameter | Type | Description | | --------- | --------- | ------------------- | | `input` | `unknown` | The value to check. | ## Returns `input is Option` `true` if the value is an [Option](/api/type-aliases/Option), `false` otherwise. ## Example Checking for `Option` values. ```ts isOption(some(42)); // true isOption(none()); // true isOption(42); // false isOption(null); // false isOption("anything else"); // false ``` ## See [Option](/api/type-aliases/Option) # isSome (/api/variables/isSome) ```ts const isSome: (option) => option is Some; ``` Checks whether the given [Option](/api/type-aliases/Option) contains a value. This function acts as a type guard, ensuring the value is a [Some](/api/type-aliases/Some). ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ## Parameters | Parameter | Type | Description | | --------- | ------------------------------------------ | ------------------------------------------------ | | `option` | [`Option`](/api/type-aliases/Option)\<`T`> | The [Option](/api/type-aliases/Option) to check. | ## Returns `option is Some` `true` if the option is a [Some](/api/type-aliases/Some), `false` otherwise. ## Example Checking for `Some` values. ```ts isSome(some(42)); // true isSome(none()); // false ``` ## See * [Option](/api/type-aliases/Option) * [Some](/api/type-aliases/Some) # jsonParsedAccountsConfigs (/api/variables/jsonParsedAccountsConfigs) ```ts const jsonParsedAccountsConfigs: (string | KeyPathWildcard)[][]; ``` # jsonParsedTokenAccountsConfigs (/api/variables/jsonParsedTokenAccountsConfigs) ```ts const jsonParsedTokenAccountsConfigs: (string | KeyPathWildcard)[][]; ``` # mergeBytes (/api/variables/mergeBytes) ```ts const mergeBytes: (byteArrays) => Uint8Array; ``` Concatenates an array of `Uint8Array`s into a single `Uint8Array`. Reuses the original byte array when applicable. ## Parameters | Parameter | Type | Description | | ------------ | -------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | `byteArrays` | [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\[] | The array of byte arrays to concatenate. | ## Returns [`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) ## Example ```ts const bytes1 = new Uint8Array([0x01, 0x02]); const bytes2 = new Uint8Array([]); const bytes3 = new Uint8Array([0x03, 0x04]); const bytes = mergeBytes([bytes1, bytes2, bytes3]); // ^ [0x01, 0x02, 0x03, 0x04] ``` # messageConfig (/api/variables/messageConfig) ```ts const messageConfig: readonly [readonly ["addressTableLookups", KeyPathWildcard, "writableIndexes", KeyPathWildcard], readonly ["addressTableLookups", KeyPathWildcard, "readonlyIndexes", KeyPathWildcard], readonly ["header", "numReadonlySignedAccounts"], readonly ["header", "numReadonlyUnsignedAccounts"], readonly ["header", "numRequiredSignatures"], readonly ["instructions", KeyPathWildcard, "accounts", KeyPathWildcard], readonly ["instructions", KeyPathWildcard, "programIdIndex"], readonly ["instructions", KeyPathWildcard, "stackHeight"], readonly ["transactionConfig", "computeUnitLimit"], readonly ["transactionConfig", "heapSize"], readonly ["transactionConfig", "loadedAccountsDataSizeLimit"]]; ``` # none (/api/variables/none) ```ts const none: () => Option; ``` Creates a new [Option](/api/type-aliases/Option) that contains no value. This function explicitly represents an absent value. ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------------- | | `T` | The type of the expected absent value. | ## Returns [`Option`](/api/type-aliases/Option)\<`T`> An [Option](/api/type-aliases/Option) containing no value. ## Example Creating an empty `Option`. ```ts const empty = none(); isOption(empty); // true isSome(empty); // false isNone(empty); // true ``` ## See * [Option](/api/type-aliases/Option) * [None](/api/type-aliases/None) # padNullCharacters (/api/variables/padNullCharacters) ```ts const padNullCharacters: (value, chars) => string; ``` Pads a string with null characters (`\u0000`) at the end to reach a fixed length. If the input string is shorter than the specified length, it is padded with null characters until it reaches the desired size. If it is already long enough, it remains unchanged. ## Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------ | | `value` | `string` | The string to pad. | | `chars` | `number` | The total length of the resulting string, including padding. | ## Returns `string` The input string padded with null characters up to the specified length. ## Example Padding a string with null characters. ```ts padNullCharacters('hello', 8); // "hello\u0000\u0000\u0000" ``` # removeNullCharacters (/api/variables/removeNullCharacters) ```ts const removeNullCharacters: (value) => string; ``` Removes all null characters (`\u0000`) from a string. This function cleans a string by stripping out any null characters, which are often used as padding in fixed-size string encodings. ## Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------- | | `value` | `string` | The string to process. | ## Returns `string` The input string with all null characters removed. ## Example Removing null characters from a string. ```ts removeNullCharacters('hello\u0000\u0000'); // "hello" ``` # some (/api/variables/some) ```ts const some: (value) => Option; ``` Creates a new [Option](/api/type-aliases/Option) that contains a value. This function explicitly wraps a value in an [Option](/api/type-aliases/Option) type. ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ## Parameters | Parameter | Type | Description | | --------- | ---- | ----------------------------------------------------------- | | `value` | `T` | The value to wrap in an [Option](/api/type-aliases/Option). | ## Returns [`Option`](/api/type-aliases/Option)\<`T`> An [Option](/api/type-aliases/Option) containing the provided value. ## Example Wrapping a value in an `Option`. ```ts const option = some('Hello'); option.value; // "Hello" isOption(option); // true isSome(option); // true isNone(option); // false ``` ## See * [Option](/api/type-aliases/Option) * [Some](/api/type-aliases/Some) # tokenBalancesConfigs (/api/variables/tokenBalancesConfigs) ```ts const tokenBalancesConfigs: readonly [readonly ["accountIndex"], readonly ["uiTokenAmount", "decimals"], readonly ["uiTokenAmount", "uiAmount"]]; ``` Keypaths, relative to a token balance, at the end of which you will find a numeric value that should not be upcast to a `bigint`. `accountIndex` and `decimals` are small bounded integers, and `uiAmount` is an `f64`. # wrapNullable (/api/variables/wrapNullable) ```ts const wrapNullable: (nullable) => Option; ``` Wraps a nullable value into an [Option](/api/type-aliases/Option). * If the input value is `null`, this function returns [None](/api/type-aliases/None). * Otherwise, it wraps the value in [Some](/api/type-aliases/Some). ## Type Parameters | Type Parameter | Description | | -------------- | -------------------------------- | | `T` | The type of the contained value. | ## Parameters | Parameter | Type | Description | | ---------- | ------------- | --------------------------- | | `nullable` | `T` \| `null` | The nullable value to wrap. | ## Returns [`Option`](/api/type-aliases/Option)\<`T`> An [Option](/api/type-aliases/Option) wrapping the value. ## Example Wrapping nullable values. ```ts wrapNullable('Hello World'); // Option (Some) wrapNullable(null); // Option (None) ``` ## See * [Option](/api/type-aliases/Option) * [Some](/api/type-aliases/Some) * [None](/api/type-aliases/None)