UNPKG

solana-kite

Version:

The modern Solana framework for TypeScript.

424 lines (410 loc) 25.9 kB
import * as _solana_kit from '@solana/kit'; import { KeyPairSigner, Address, createSolanaRpcFromTransport, sendAndConfirmTransactionFactory, IInstruction, Commitment, TransactionSendingSigner, Lamports, createSolanaRpcSubscriptions, Decoder, MessageModifyingSigner } from '@solana/kit'; import { createRecentSignatureConfirmationPromiseFactory } from '@solana/transaction-confirmation'; import * as _solana_program_token_2022 from '@solana-program/token-2022'; /** * Loads a wallet (KeyPairSigner) from a file. The file should be in the same format as files created by the solana-keygen command. * @param {string} [filepath] - Path to load keypair from file. Defaults to ~/.config/solana/id.json * @returns {Promise<KeyPairSigner>} The loaded wallet */ declare const loadWalletFromFile: (filepath?: string) => Promise<KeyPairSigner>; /** * Loads a wallet (KeyPairSigner) from an environment variable. The keypair should be in the same 'array of numbers' format as used by solana-keygen. * @param {string} variableName - Name of environment variable containing the keypair * @returns {KeyPairSigner} The loaded wallet */ declare const loadWalletFromEnvironment: (variableName: string) => Promise<KeyPairSigner<string>>; declare const checkAddressMatchesPrivateKey: (address: Address, privateKey: Uint8Array) => Promise<boolean>; interface ErrorWithTransaction extends Error { transaction: Awaited<ReturnType<ReturnType<typeof createSolanaRpcFromTransport>["getTransaction"]>>; context: { __code: number; code: number; index: number; }; } declare const signatureBytesToBase58String: (signatureBytes: Uint8Array) => string; declare const signatureBase58StringToBytes: (base58String: string) => Uint8Array; declare const sendTransactionFromInstructionsWithWalletAppFactory: (rpc: ReturnType<typeof createSolanaRpcFromTransport>) => ({ feePayer, instructions, abortSignal, }: { feePayer: TransactionSendingSigner; instructions: Array<IInstruction>; abortSignal?: AbortSignal | null; }) => Promise<string>; declare const sendTransactionFromInstructionsFactory: (rpc: ReturnType<typeof createSolanaRpcFromTransport>, needsPriorityFees: boolean, supportsGetPriorityFeeEstimate: boolean, enableClientSideRetries: boolean, sendAndConfirmTransaction: ReturnType<typeof sendAndConfirmTransactionFactory>) => ({ feePayer, instructions, commitment, skipPreflight, maximumClientSideRetries, abortSignal, }: { feePayer: KeyPairSigner; instructions: Array<IInstruction>; commitment?: Commitment; skipPreflight?: boolean; maximumClientSideRetries?: number; abortSignal?: AbortSignal | null; }) => Promise<_solana_kit.Signature>; declare const getLamportBalanceFactory: (rpc: ReturnType<typeof createSolanaRpcFromTransport>) => (address: string, commitment?: Commitment) => Promise<Lamports>; declare const airdropIfRequiredFactory: (rpc: ReturnType<typeof createSolanaRpcFromTransport>, rpcSubscriptions: ReturnType<typeof createSolanaRpcSubscriptions>) => (address: Address, airdropAmount: Lamports, minimumBalance: Lamports, commitment?: Commitment) => Promise<string | null>; declare const createWalletFactory: (airdropIfRequired: ReturnType<typeof airdropIfRequiredFactory>) => (options?: { prefix?: string | null; suffix?: string | null; envFileName?: string | null; envVariableName?: string; airdropAmount?: Lamports | null; }) => Promise<KeyPairSigner>; declare const createWalletsFactory: (createWallet: ReturnType<typeof createWalletFactory>) => (amount: number, options?: Parameters<ReturnType<typeof createWalletFactory>>[0]) => Promise<Array<KeyPairSigner>>; declare const transferLamportsFactory: (sendTransactionFromInstructions: ReturnType<typeof sendTransactionFromInstructionsFactory>) => ({ source, destination, amount, skipPreflight, maximumClientSideRetries, abortSignal, }: { source: KeyPairSigner; destination: Address; amount: Lamports; skipPreflight?: boolean; maximumClientSideRetries?: number; abortSignal?: AbortSignal | null; }) => Promise<_solana_kit.Signature>; declare const transferTokensFactory: (getMint: ReturnType<typeof getMintFactory>, sendTransactionFromInstructions: ReturnType<typeof sendTransactionFromInstructionsFactory>) => ({ sender, destination, mintAddress, amount, maximumClientSideRetries, abortSignal, }: { sender: KeyPairSigner; destination: Address; mintAddress: Address; amount: bigint; maximumClientSideRetries?: number; abortSignal?: AbortSignal | null; }) => Promise<_solana_kit.Signature>; /** * Gets the address where a wallet's tokens are stored. * Each wallet has a unique storage address for each type of token. * @param {Address} wallet - The wallet that owns the tokens * @param {Address} mint - The type of token * @param {boolean} [useTokenExtensions=false] - Use Token Extensions program instead of classic Token program * @returns {Promise<Address>} The token account address */ declare const getTokenAccountAddress: (wallet: Address, mint: Address, useTokenExtensions?: boolean) => Promise<Address<string>>; declare const getMintFactory: (rpc: ReturnType<typeof createSolanaRpcFromTransport>) => (mintAddress: Address, commitment?: Commitment) => Promise<_solana_kit.Account<_solana_program_token_2022.Mint, string>>; declare const getTokenAccountBalanceFactory: (rpc: ReturnType<typeof createSolanaRpcFromTransport>) => (options: { wallet?: Address; mint?: Address; tokenAccount?: Address; useTokenExtensions?: boolean; }) => Promise<{ amount: bigint; decimals: any; uiAmount: any; uiAmountString: any; }>; declare const checkTokenAccountIsClosedFactory: (getTokenAccountBalance: ReturnType<typeof getTokenAccountBalanceFactory>) => (options: { wallet?: Address; mint?: Address; tokenAccount?: Address; useTokenExtensions?: boolean; }) => Promise<boolean>; declare const getLogsFactory: (rpc: ReturnType<typeof createSolanaRpcFromTransport>) => (signature: string) => Promise<Array<string>>; declare const getExplorerLinkFactory: (clusterNameOrURL: string) => (linkType: "transaction" | "tx" | "address" | "block", id: string) => string; /** * Calculates a Program Derived Address (PDA) and its bump seed from a program address and seeds. * Handles encoding of different seed types: * - Strings: encoded as UTF-8 * - Addresses: encoded using the address encoder * - BigInts: encoded as 8-byte little-endian Uint8Array * - Uint8Array: used as-is * * @param {Address} programAddress - The program address to derive the PDA from * @param {Array<String | Address | BigInt | Uint8Array>} seeds - Array of seeds to derive the PDA * @returns {Promise<{pda: Address, bump: number}>} The derived PDA and its bump seed */ declare const getPDAAndBump: (programAddress: Address, seeds: Array<String | Address | BigInt | Uint8Array>) => Promise<{ pda: Address<string>; bump: _solana_kit.ProgramDerivedAddressBump; }>; declare const getAccountsFactoryFactory: (rpc: ReturnType<typeof createSolanaRpcFromTransport>) => <T extends object>(programAddress: Address, discriminator: Uint8Array, decoder: Decoder<T>) => () => Promise<_solana_kit.MaybeAccount<T, string>[]>; declare const signMessageFromWalletApp: (message: string, messageSigner: MessageModifyingSigner) => Promise<string>; /** * Creates a connection to a Solana cluster with all helper functions pre-configured. * @param {string | ReturnType<typeof createSolanaRpcFromTransport>} [clusterNameOrURLOrRpc="localnet"] - Either: * - A cluster name, from this list: * Public clusters (note these are rate limited, you should use a commercial RPCp provider for production apps) * "mainnet", "testnet", "devnet", "localnet" * QuickNode: * "quicknode-mainnet", "quicknode-devnet", "quicknode-testnet" * Helius: * "helius-mainnet" or "helius-devnet" (Helius does not have testnet) * - An HTTP URL * - A pre-configured RPC client * @param {string | ReturnType<typeof createSolanaRpcSubscriptions> | null} [clusterWebSocketURLOrRpcSubscriptions=null] - Either: * - WebSocket URL for subscriptions (required if using custom HTTP URL) * - A pre-configured RPC subscriptions client * @returns {Connection} Connection object with all helper functions configured * @throws {Error} If using Helius cluster without HELIUS_API_KEY environment variable set * @throws {Error} If using custom HTTP URL without WebSocket URL * @throws {Error} If cluster name is invalid */ declare const connect: (clusterNameOrURLOrRpc?: string | ReturnType<typeof createSolanaRpcFromTransport<RpcTransport>>, clusterWebSocketURLOrRpcSubscriptions?: string | ReturnType<typeof createSolanaRpcSubscriptions> | null) => Connection; interface Connection { /** * The core RPC client for making direct Solana API calls. Use this when you need * access to raw Solana JSON RPC methods not covered by helper functions. */ rpc: ReturnType<typeof createSolanaRpcFromTransport<RpcTransport>>; /** * The WebSocket client for real-time Solana event subscriptions like new blocks, * program logs, account changes etc. */ rpcSubscriptions: ReturnType<typeof createSolanaRpcSubscriptions>; /** * Submits a transaction and waits for it to be confirmed on the network. * @param {VersionedTransaction} transaction - The complete signed transaction to submit * @param {Object} [options] - Optional configuration * @param {Commitment} [options.commitment] - Confirmation level to wait for: * 'processed' = processed by current node, * 'confirmed' = confirmed by supermajority of the cluster, * 'finalized' = confirmed by supermajority and unlikely to revert * @param {boolean} [options.skipPreflight] - Skip pre-flight transaction checks to reduce latency * @returns {Promise<void>} */ sendAndConfirmTransaction: ReturnType<typeof sendAndConfirmTransactionFactory>; /** * Builds, signs and sends a transaction containing multiple instructions. * @param {Object} params - Transaction parameters * @param {KeyPairSigner} params.feePayer - Account that will pay the transaction fees * @param {Array<IInstruction>} params.instructions - List of instructions to execute in sequence * @param {Commitment} [params.commitment="confirmed"] - Confirmation level to wait for: * 'processed' = processed by current node, * 'confirmed' = confirmed by supermajority of the cluster, * 'finalized' = confirmed by supermajority and unlikely to revert * @param {boolean} [params.skipPreflight=true] - Skip pre-flight transaction checks to reduce latency * @param {number} [params.maximumClientSideRetries=0] - Number of times to retry if the transaction fails * @param {AbortSignal | null} [params.abortSignal=null] - Signal to cancel the transaction * @returns {Promise<string>} The transaction signature */ sendTransactionFromInstructions: ReturnType<typeof sendTransactionFromInstructionsFactory>; /** * Gets an account's SOL balance in lamports (1 SOL = 1,000,000,000 lamports). * @param {string} address - The account address to check * @param {Commitment} commitment - Confirmation level of data: * 'processed' = maybe outdated but fast, * 'confirmed' = confirmed by supermajority, * 'finalized' = definitely permanent but slower * @returns {Promise<Lamports>} The balance in lamports */ getLamportBalance: ReturnType<typeof getLamportBalanceFactory>; /** * Creates a URL to view any Solana entity on Solana Explorer. * Automatically configures the URL for the current network/cluster. * @param {("transaction" | "tx" | "address" | "block")} linkType - What type of entity to view * @param {string} id - Identifier (address, signature, or block number) * @returns {string} A properly configured Solana Explorer URL */ getExplorerLink: ReturnType<typeof getExplorerLinkFactory>; /** * Checks if a transaction has been confirmed on the network. * Useful for verifying that time-sensitive transactions have succeeded. * @param {string} signature - The unique transaction signature to verify * @returns {Promise<boolean>} True if the transaction is confirmed */ getRecentSignatureConfirmation: ReturnType<typeof createRecentSignatureConfirmationPromiseFactory>; /** * Checks if a token account is closed or doesn't exist. * A token account can be specified directly or derived from a wallet and mint address. * @param {Object} params - Parameters for checking token account * @param {Address} [params.tokenAccount] - Direct token account address to check * @param {Address} [params.wallet] - Wallet address (required if tokenAccount not provided) * @param {Address} [params.mint] - Token mint address (required if tokenAccount not provided) * @param {boolean} [params.useTokenExtensions=false] - Use Token Extensions program instead of classic Token program * @returns {Promise<boolean>} True if the token account is closed or doesn't exist, false if it exists and is open * @throws {Error} If neither tokenAccount nor both wallet and mint are provided * @throws {Error} If there's an error checking the account that isn't related to the account not existing */ checkTokenAccountIsClosed: ReturnType<typeof checkTokenAccountIsClosedFactory>; /** * Requests free test SOL from a faucet if an account's balance is too low. * Only works on test networks (devnet/testnet). * @param {Address} address - The account that needs SOL * @param {Lamports} airdropAmount - How much SOL to request (in lamports) * @param {Lamports} minimumBalance - Only request SOL if balance is below this amount * @param {Commitment} commitment - Confirmation level to wait for: * 'processed' = processed by current node, * 'confirmed' = confirmed by supermajority of the cluster, * 'finalized' = confirmed by supermajority and unlikely to revert * @returns {Promise<string | null>} Transaction signature if SOL was airdropped, null if no airdrop was needed */ airdropIfRequired: ReturnType<typeof airdropIfRequiredFactory>; /** * Creates a new Solana wallet with optional vanity address and automatic funding. * @param {Object} [options={}] - Configuration options * @param {string | null} [options.prefix] - Generate address starting with these characters * @param {string | null} [options.suffix] - Generate address ending with these characters * @param {string | null} [options.envFileName] - Save private key to this .env file * @param {string} [options.envVariableName] - Environment variable name to store the key * @param {Lamports | null} [options.airdropAmount] - Amount of test SOL to request from faucet * @returns {Promise<KeyPairSigner>} The new wallet, ready to use */ createWallet: ReturnType<typeof createWalletFactory>; /** * Creates multiple Solana wallets in parallel with identical configuration. * @param {number} amount - How many wallets to create * @param {Object} options - Same configuration options as createWallet * @returns {Promise<Array<KeyPairSigner>>} Array of new wallets */ createWallets: ReturnType<typeof createWalletsFactory>; /** * Retrieves the program output messages from a transaction. * Useful for debugging failed transactions or understanding program behavior. * @param {string} signature - Transaction signature to analyze * @returns {Promise<readonly Array<string>>} Program log messages in order of execution */ getLogs: ReturnType<typeof getLogsFactory>; /** * Transfers SOL from one account to another. * @param {Object} params - Transfer details * @param {KeyPairSigner} params.source - Account sending the SOL (must sign) * @param {Address} params.destination - Account receiving the SOL * @param {Lamports} params.amount - Amount of SOL to send (in lamports) * @param {boolean} [params.skipPreflight=true] - Skip pre-flight checks to reduce latency * @param {number} [params.maximumClientSideRetries=0] - Number of retry attempts if transfer fails * @param {AbortSignal | null} [params.abortSignal=null] - Signal to cancel the transfer * @returns {Promise<string>} Transaction signature */ transferLamports: ReturnType<typeof transferLamportsFactory>; /** * Creates a new SPL token with metadata and minting controls. * @param {Object} params - Token configuration * @param {KeyPairSigner} params.mintAuthority - Account that will have permission to mint tokens * @param {number} params.decimals - Number of decimal places (e.g. 9 decimals means 1 token = 1,000,000,000 base units) * @param {string} params.name - Display name of the token * @param {string} params.symbol - Short ticker symbol (e.g. "USDC") * @param {string} params.uri - URL to token metadata (image, description etc.) * @param {Record<string, string> | Map<string, string>} [params.additionalMetadata={}] - Extra metadata key-value pairs * @returns {Promise<Address>} Address of the new token mint */ createTokenMint: (params: { mintAuthority: KeyPairSigner; decimals: number; name: string; symbol: string; uri: string; additionalMetadata?: Record<string, string> | Map<string, string>; }) => Promise<Address>; /** * Creates new tokens from a token mint. * @param {Address} mintAddress - The token mint to create tokens from * @param {KeyPairSigner} mintAuthority - Account authorized to mint new tokens (must sign) * @param {bigint} amount - Number of base units to mint (adjusted for decimals) * @param {Address} destination - Account to receive the new tokens * @returns {Promise<string>} Transaction signature */ mintTokens: (mintAddress: Address, mintAuthority: KeyPairSigner, amount: bigint, destination: Address) => Promise<string>; /** * Transfers SPL tokens between accounts. * @param {Object} params - Transfer details * @param {KeyPairSigner} params.sender - Account sending the tokens (must sign) * @param {Address} params.destination - Account receiving the tokens * @param {Address} params.mintAddress - The type of token to transfer * @param {bigint} params.amount - Number of base units to transfer (adjusted for decimals) * @param {number} [params.maximumClientSideRetries=0] - Number of retry attempts if transfer fails * @param {AbortSignal | null} [params.abortSignal=null] - Signal to cancel the transfer * @returns {Promise<string>} Transaction signature */ transferTokens: ReturnType<typeof transferTokensFactory>; /** * Retrieves information about a token mint including supply and decimals. * @param {Address} mintAddress - Address of the token mint to query * @param {Commitment} [commitment="confirmed"] - Confirmation level of data: * 'processed' = maybe outdated but fast, * 'confirmed' = confirmed by supermajority, * 'finalized' = definitely permanent but slower * @returns {Promise<Mint | null>} Token information if found, null if not */ getMint: ReturnType<typeof getMintFactory>; /** * Gets the token balance for a specific account. You can either provide a token account address directly, or provide a wallet address and a mint address to derive the token account address. * @param {Object} params - Parameters for getting token balance * @param {Address} [params.tokenAccount] - Direct token account address to check balance for * @param {Address} [params.wallet] - Wallet address (required if tokenAccount not provided) * @param {Address} [params.mint] - Token mint address (required if tokenAccount not provided) * @param {boolean} [params.useTokenExtensions=false] - Use Token Extensions program instead of classic Token program * @returns {Promise<{amount: BigInt, decimals: number, uiAmount: number | null, uiAmountString: string}>} Balance information including amount and decimals * @throws {Error} If neither tokenAccount nor both wallet and mint are provided */ getTokenAccountBalance: (params: { tokenAccount?: Address; wallet?: Address; mint?: Address; useTokenExtensions?: boolean; }) => Promise<{ amount: BigInt; decimals: number; uiAmount: number | null; uiAmountString: string; }>; /** * Gets the address where a wallet's tokens are stored. * Each wallet has a unique storage address for each type of token. * @param {Address} wallet - The wallet that owns the tokens * @param {Address} mint - The type of token * @param {boolean} [useTokenExtensions=false] - Use Token Extensions program instead of classic Token program * @returns {Promise<Address>} The token account address */ getTokenAccountAddress: typeof getTokenAccountAddress; /** * Loads a wallet from a file containing a keypair. * Compatible with keypair files generated by 'solana-keygen'. * @param {string} [filepath] - Location of the keypair file (defaults to ~/.config/solana/id.json) * @returns {Promise<KeyPairSigner>} The loaded wallet */ loadWalletFromFile: typeof loadWalletFromFile; /** * Loads a wallet from an environment variable containing a keypair. * The keypair must be in the same format as 'solana-keygen' (array of numbers). * @param {string} variableName - Name of environment variable storing the keypair * @returns {KeyPairSigner} The loaded wallet */ loadWalletFromEnvironment: typeof loadWalletFromEnvironment; /** * Derives a Program Derived Address (PDA) and its bump seed. * PDAs are deterministic addresses that programs can sign for. * @param {Address} programAddress - The program that will control this PDA * @param {Array<String | Address | BigInt>} seeds - Values used to derive the PDA * @returns {Promise<{pda: Address, bump: number}>} The derived address and bump seed */ getPDAAndBump: typeof getPDAAndBump; /** * Creates a factory function for getting program accounts with a specific discriminator. */ getAccountsFactory: ReturnType<typeof getAccountsFactoryFactory>; /** * Converts signature bytes to a base58 string. * @param {Uint8Array} signatureBytes - The signature bytes to convert * @returns {string} The base58 encoded signature string */ signatureBytesToBase58String: typeof signatureBytesToBase58String; /** * Converts a base58 string to signature bytes. * @param {string} base58String - The base58 encoded signature string * @returns {Uint8Array} The signature bytes */ signatureBase58StringToBytes: typeof signatureBase58StringToBytes; /** * Builds, signs and sends a transaction containing multiple instructions using a wallet app. * @param {Object} params - Transaction parameters * @param {TransactionSendingSigner} params.feePayer - Account that will pay the transaction fees * @param {Array<IInstruction>} params.instructions - List of instructions to execute in sequence * @param {AbortSignal | null} [params.abortSignal=null] - Signal to cancel the transaction * @returns {Promise<string>} The transaction signature */ sendTransactionFromInstructionsWithWalletApp: ReturnType<typeof sendTransactionFromInstructionsWithWalletAppFactory>; /** * Signs a message using a wallet app. * @param {string} message - The message to sign * @param {MessageModifyingSigner} messageSigner - The signer that will sign the message * @returns {Promise<string>} The base58 encoded signature */ signMessageFromWalletApp: typeof signMessageFromWalletApp; /** * Verifies if a given private key corresponds to a specific Solana address. * This is useful for validating that a private key matches an expected address * without exposing the private key in the process. * * @param {Address} address - The Solana address to verify against * @param {Uint8Array} privateKey - The raw private key bytes to check * @returns {Promise<boolean>} True if the private key corresponds to the address, false otherwise */ checkAddressMatchesPrivateKey: typeof checkAddressMatchesPrivateKey; } declare const TOKEN_PROGRAM: _solana_kit.Address<"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA">; declare const TOKEN_EXTENSIONS_PROGRAM: _solana_kit.Address<"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb">; declare const ASSOCIATED_TOKEN_PROGRAM: _solana_kit.Address<"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL">; declare const SOL = 1000000000n; export { ASSOCIATED_TOKEN_PROGRAM, type Connection, type ErrorWithTransaction, SOL, TOKEN_EXTENSIONS_PROGRAM, TOKEN_PROGRAM, connect };