@solana/web3.js
Version:
Solana Javascript API
9,077 lines • 367 kB
JavaScript
import { assertDigestCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from "@solana/assertions";
import { AccountRole, BASE_ACCOUNT_SIZE, DEFAULT_RPC_CONFIG, DEFAULT_RPC_SUBSCRIPTIONS_CONFIG, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE, SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SolanaError, TRANSACTION_CONFIG_COMPUTE_UNIT_LIMIT_BIT_MASK, TRANSACTION_CONFIG_HEAP_SIZE_BIT_MASK, TRANSACTION_CONFIG_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_BIT_MASK, TRANSACTION_CONFIG_PRIORITY_FEE_LAMPORTS_BIT_MASK, addCodecSizePrefix, assertIsAddress, assertIsSignature, assertIsTransactionPartialSigner, assertIsTransactionWithinSizeLimit, blockhash, createAddressWithSeed, createDefaultRpcSubscriptionsTransport, createDefaultSolanaRpcSubscriptionsChannelCreator, createKeyPairFromBytes, createKeyPairSignerFromBytes, createKeyPairSignerFromPrivateKeyBytes, createNoopSigner, createRpc, createSolanaRpcApi, createSolanaRpcSubscriptionsApi, createSubscriptionRpc, decompileTransactionConfig, fixCodecSize, fixDecoderSize, fixEncoderSize, flattenInstructionPlan, getAddressCodec, getArrayCodec, getArrayDecoder, getArrayEncoder, getBase16Encoder, getBase58Codec, getBase58Decoder, getBase58Encoder, getBase64Codec, getBytesCodec, getBytesDecoder, getBytesEncoder, getCompiledTransactionMessageDecoder, getCompiledTransactionMessageEncoder, getI64Codec, getOptionCodec, getProgramDerivedAddress, getShortU16Decoder, getShortU16Encoder, getStructCodec, getStructDecoder, getStructEncoder, getTransactionConfigMask, getTransactionConfigValues, getTransactionLifetimeConstraintFromCompiledTransactionMessage, getU16Codec, getU16Encoder, getU32Codec, getU64Codec, getU64Encoder, getU8Codec, getU8Decoder, getU8Encoder, getUtf8Codec, isAddress, isInstructionPlan, isSignerRole, isSingleInstructionPlan, isSolanaError, isV1ConfigEmpty, isWritableRole, lamports, signBytes, signatureBytes, toArrayBuffer, transformCodec, unwrapOption, verifySignature } from "@solana/kit";
import { ed25519 } from "@noble/curves/ed25519";
import { NonceState, SYSTEM_PROGRAM_ADDRESS, SystemInstruction as SystemInstruction$1, getAdvanceNonceAccountInstruction, getAllocateInstruction, getAllocateWithSeedInstruction, getAssignInstruction, getAssignWithSeedInstruction, getAuthorizeNonceAccountInstruction, getCreateAccountInstruction, getCreateAccountWithSeedInstruction, getInitializeNonceAccountInstruction, getNonceDecoder, getNonceSize, getTransferSolInstruction, getTransferSolWithSeedInstruction, getWithdrawNonceAccountInstruction, identifySystemInstruction, parseSystemInstruction } from "@solana-program/system";
import { parseJsonWithBigInts, stringifyJsonWithBigInts } from "@solana/rpc-spec-types";
import fastStableStringify from "@solana/fast-stable-stringify";
import { ADDRESS_LOOKUP_TABLE_DISCRIMINATOR, ADDRESS_LOOKUP_TABLE_PROGRAM_ADDRESS, AddressLookupTableInstruction as AddressLookupTableInstruction$1, getAddressLookupTableDecoder, getCloseLookupTableInstruction, getCreateLookupTableInstruction, getDeactivateLookupTableInstruction, getExtendLookupTableInstruction, getExtendLookupTableInstructionDataDecoder, getExtendLookupTableInstructionDataEncoder, getFreezeLookupTableInstruction, identifyAddressLookupTableInstruction, parseAddressLookupTableInstruction } from "@solana-program/address-lookup-table";
import { COMPUTE_BUDGET_PROGRAM_ADDRESS, ComputeBudgetInstruction as ComputeBudgetInstruction$1, getRequestHeapFrameInstruction, getRequestUnitsInstruction, getSetComputeUnitLimitInstruction, getSetComputeUnitPriceInstruction, getSetLoadedAccountsDataSizeLimitInstruction, identifyComputeBudgetInstruction, parseComputeBudgetInstruction } from "@solana-program/compute-budget";
import { LOADER_V3_PROGRAM_ADDRESS, LoaderV3Instruction as LoaderV3Instruction$1, getCloseInstruction, getDeployWithMaxDataLenInstruction, getExtendProgramInstruction, getInitializeBufferInstruction, getSetAuthorityCheckedInstruction, getSetAuthorityInstruction, getUpgradeInstruction, getWriteInstruction, identifyLoaderV3Instruction, parseLoaderV3Instruction } from "@solana-program/loader-v3";
import { keccak_256 } from "@noble/hashes/sha3";
import { secp256k1 } from "@noble/curves/secp256k1";
import { STAKE_PROGRAM_ADDRESS, StakeInstruction as StakeInstruction$1, getAuthorizeCheckedInstruction, getAuthorizeCheckedWithSeedInstruction, getAuthorizeInstruction, getAuthorizeWithSeedInstruction, getDeactivateDelinquentInstruction, getDeactivateInstruction, getDelegateStakeInstruction, getGetMinimumDelegationInstruction, getInitializeCheckedInstruction, getInitializeInstruction, getMergeInstruction, getMoveLamportsInstruction, getMoveStakeInstruction, getSetLockupCheckedInstruction, getSetLockupInstruction, getSplitInstruction, getStakeStateAccountDecoder, getWithdrawInstruction, identifyStakeInstruction, parseStakeInstruction } from "@solana-program/stake";
// src/utils/assert.ts
function assert_default(condition, message) {
if (!condition) throw new Error(message || "Assertion failed");
}
// src/utils/typed-array.ts
/**
* Convert common byte containers into a Uint8Array view when possible.
*
* Note: For sliced views, this preserves the original backing buffer and
* byte offsets. For `Array<number>`, this creates a copy because arrays do
* not have an `ArrayBuffer` backing store.
*
* Use `toPackedUint8Array` when a tightly packed buffer is required.
*/
const toUint8ArrayView = (arr) => {
return Array.isArray(arr) ? new Uint8Array(arr) : new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
};
/**
* Ensure byte-like input is tightly packed and only includes the intended bytes.
*
* This copies when the input is a view into a larger backing store so callers
* like signing/verifying cannot observe unrelated bytes.
*/
const toPackedUint8Array = (arr) => {
if (Array.isArray(arr)) return new Uint8Array(arr);
if (arr.byteOffset === 0 && arr.byteLength === arr.buffer.byteLength) return arr instanceof Uint8Array ? arr : new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
return Uint8Array.from(arr);
};
/**
* Concatenate byte sequences into a newly allocated Uint8Array.
*/
const concatUint8Arrays = (arrays) => {
const totalLength = arrays.reduce((sum, array) => sum + array.length, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
for (const array of arrays) {
result.set(array, offset);
offset += array.length;
}
return result;
};
// src/utils/ed25519.ts
function isOnCurve(publicKey) {
try {
ed25519.ExtendedPoint.fromHex(publicKey);
return true;
} catch {
return false;
}
}
async function sign(message, secretKey) {
const keyPair = await createKeyPairFromBytes(Uint8Array.from(secretKey));
return await signBytes(keyPair.privateKey, toPackedUint8Array(message));
}
async function verify(signature, message, publicKey) {
const signatureSnapshot = Uint8Array.from(signature);
const messageSnapshot = Uint8Array.from(message);
const cryptoKey = await globalThis.crypto.subtle.importKey("raw", Uint8Array.from(publicKey), { name: "Ed25519" }, true, ["verify"]);
return await verifySignature(cryptoKey, signatureBytes(signatureSnapshot), messageSnapshot);
}
// src/utils/sha256.ts
/**
* Calculate the SHA-256 hash of the input data using the Web Crypto API.
*
* @param data The input data to hash.
* @returns A promise that resolves to the SHA-256 hash of the input data.
*/
async function sha256(data) {
assertDigestCapabilityIsAvailable();
const normalizedData = toPackedUint8Array(data);
const digest = await globalThis.crypto.subtle.digest("SHA-256", toArrayBuffer(normalizedData));
return new Uint8Array(digest);
}
// src/publickey.ts
/**
* Maximum length of derived pubkey seed
*/
const MAX_SEED_LENGTH = 32;
/**
* Maximum number of seeds used to derive a program address.
*/
const MAX_SEEDS = 16;
/**
* Size of public key in bytes
*/
const PUBLIC_KEY_LENGTH = 32;
const ERROR__INVALID_PUBLIC_KEY_INPUT = "Invalid public key input";
const ADDRESS_CODEC = getAddressCodec();
const PDA_MARKER_BYTES = new TextEncoder().encode("ProgramDerivedAddress");
/**
* A Solana address
*/
var PublicKey = class PublicKey {
_publicKeyBytes;
/**
* Create a new PublicKey object
* @param value ed25519 public key as bytes or base-58 encoded string
*/
constructor(value) {
if (typeof value === "string") this._publicKeyBytes = bytesFromAddressString(value);
else if (isUint8ArrayLike(value)) this._publicKeyBytes = bytesFromUint8Array(new Uint8Array(value));
else if (Array.isArray(value)) this._publicKeyBytes = bytesFromNumberArray(value);
else if (value instanceof PublicKey) this._publicKeyBytes = value.toBytes();
else if (typeof value === "number") this._publicKeyBytes = bytesFromNumber(value);
else if (typeof value === "bigint") this._publicKeyBytes = bytesFromBigInt(value);
else assertUnreachablePublicKeyInput(value);
}
/**
* Default public key value. The base58-encoded string representation is all ones (as seen below)
* The underlying number is 32 bytes that are all zeros
*/
static default = new PublicKey("11111111111111111111111111111111");
/**
* Checks if two publicKeys are equal
*/
equals(address) {
if (this === address) return true;
const left = this._publicKeyBytes;
const right = address._publicKeyBytes;
for (let index = 0; index < 32; index += 1) if (left[index] !== right[index]) return false;
return true;
}
/**
* The base-58 representation of the public key as a Kit `Address` branded
* string. Satisfies Kit's
* [`HasAddress`](https://www.solanakit.com/api/type-aliases/HasAddress)
* interface so a `PublicKey` can be passed anywhere Kit accepts an
* address-bearing object.
*/
get address() {
return this.toBase58();
}
/**
* Return the base-58 representation of the public key as a Kit `Address`
* branded string, suitable for passing to `@solana/kit` APIs or generated
* program clients that expect an `Address`.
*/
toBase58() {
return ADDRESS_CODEC.decode(this._publicKeyBytes);
}
toJSON() {
return this.toBase58();
}
/**
* Return the byte array representation of the public key in big endian
*/
toBytes() {
return new Uint8Array(this._publicKeyBytes);
}
/**
* Verify a signature for the provided message with this public key.
* @since 2.0.0
*/
async verifySignature(signature, message) {
assertVerificationCapabilityIsAvailable();
const publicKeyBytes = Uint8Array.from(this._publicKeyBytes);
const signatureSnapshot = Uint8Array.from(signature);
const messageSnapshot = Uint8Array.from(message);
const publicKeyCryptoKey = await globalThis.crypto.subtle.importKey("raw", publicKeyBytes, { name: "Ed25519" }, true, ["verify"]);
return await verifySignature(publicKeyCryptoKey, signatureBytes(signatureSnapshot), messageSnapshot);
}
/**
* Borsh-compatible encoding (little-endian)
*/
encode() {
return Uint8Array.from(this._publicKeyBytes).reverse();
}
/**
* Borsh-compatible decoding (little-endian)
*/
static decode(data) {
const encoded = toUint8ArrayView(data);
assert_default(encoded.length === 32, ERROR__INVALID_PUBLIC_KEY_INPUT);
return new PublicKey(reverseCopyLittleEndianPublicKeyBytes(encoded));
}
/**
* Borsh-compatible unchecked decoding (little-endian)
*/
static decodeUnchecked(data) {
const encoded = toUint8ArrayView(data);
assert_default(encoded.length >= 32, ERROR__INVALID_PUBLIC_KEY_INPUT);
const firstField = encoded.subarray(0, 32);
return new PublicKey(reverseCopyLittleEndianPublicKeyBytes(firstField));
}
get [Symbol.toStringTag]() {
return `PublicKey(${this.toString()})`;
}
/**
* Return the base-58 representation of the public key
*/
toString() {
return this.toBase58();
}
/**
* Derive a public key from another key, a seed, and a program ID.
* The program ID will also serve as the owner of the public key, giving
* it permission to write data to the account.
*
* @throws `SolanaError` with
* `SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED` from
* `@solana/errors` if the seed exceeds 32 bytes.
* @throws `SolanaError` with
* `SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER` from
* `@solana/errors` if the program address ends with the PDA marker bytes.
*/
static async createWithSeed(fromPublicKey, seed, programId) {
const derivedAddress = await createAddressWithSeed({
baseAddress: fromPublicKey.toBase58(),
programAddress: programId.toBase58(),
seed
});
return new PublicKey(derivedAddress);
}
/**
* Derive a program address from seeds and a program ID.
*
* @throws `SolanaError` with
* `SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED` from
* `@solana/errors` if `crypto.subtle.digest()` is unavailable.
* @throws `SolanaError` with
* `SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED` from
* `@solana/errors` if the supplied seeds exceed the PDA count limit.
* @throws `SolanaError` with
* `SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED` from
* `@solana/errors` if any supplied seed exceeds the PDA seed-length limit.
* @throws `SolanaError` with
* `SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE` from
* `@solana/errors` if the derived address falls on the Ed25519 curve.
*/
static async createProgramAddress(seeds, programId) {
if (seeds.length > MAX_SEEDS) throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {
actual: seeds.length,
maxSeeds: MAX_SEEDS
});
for (const [index, seed] of seeds.entries()) if (seed.length > 32) throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {
actual: seed.length,
index,
maxSeedLength: 32
});
const publicKeyBytes = await sha256(concatUint8Arrays([
...seeds,
programId.toBytes(),
PDA_MARKER_BYTES
]));
if (isOnCurve(publicKeyBytes)) throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);
return new PublicKey(publicKeyBytes);
}
/**
* Find a valid program address
*
* Valid program addresses must fall off the ed25519 curve. This function
* iterates a nonce until it finds one that when combined with the seeds
* results in a valid program address.
*
* @throws `SolanaError` with
* `SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED` from
* `@solana/errors` if the supplied seeds exceed the PDA count limit.
* @throws `SolanaError` with
* `SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED` from
* `@solana/errors` if any supplied seed exceeds the PDA seed-length limit.
* @throws `SolanaError` with
* `SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED` from
* `@solana/errors` if no viable bump seed exists.
*/
static async findProgramAddress(seeds, programId) {
const [derivedAddress, nonce] = await getProgramDerivedAddress({
programAddress: programId.toBase58(),
seeds
});
return [new PublicKey(derivedAddress), nonce];
}
/**
* Check that a pubkey is on the ed25519 curve.
*/
static isOnCurve(addressData) {
return isOnCurve(new PublicKey(addressData).toBytes());
}
};
function isUint8ArrayLike(value) {
return value instanceof Uint8Array;
}
function assertUnreachablePublicKeyInput(_value) {
throw new Error(ERROR__INVALID_PUBLIC_KEY_INPUT);
}
function reverseCopyLittleEndianPublicKeyBytes(bytes) {
const reversedBytes = /* @__PURE__ */ new Uint8Array(32);
for (let index = 0; index < 32; index++) reversedBytes[index] = bytes[31 - index];
return reversedBytes;
}
/**
* Normalize constructor Uint8Array input into a canonical 32-byte public key byte array.
* @internal
*/
function bytesFromUint8Array(bytes) {
assert_default(bytes.length <= 32, ERROR__INVALID_PUBLIC_KEY_INPUT);
if (bytes.length === 32) return new Uint8Array(bytes);
const padded = /* @__PURE__ */ new Uint8Array(32);
padded.set(bytes, 32 - bytes.length);
return padded;
}
/**
* Convert constructor number input into a canonical 32-byte public key byte array.
* @internal
*/
function bytesFromNumber(value) {
assert_default(Number.isSafeInteger(value) && value >= 0, ERROR__INVALID_PUBLIC_KEY_INPUT);
return bytesFromBigInt(BigInt(value));
}
/**
* Convert constructor bigint input into a canonical 32-byte public key byte array.
* @internal
*/
function bytesFromBigInt(value) {
assert_default(value >= 0n && value <= 115792089237316195423570985008687907853269984665640564039457584007913129639935n, ERROR__INVALID_PUBLIC_KEY_INPUT);
const out = /* @__PURE__ */ new Uint8Array(32);
let remainder = value;
for (let index = 31; index >= 0 && remainder > 0n; index -= 1) {
out[index] = Number(remainder & 255n);
remainder >>= 8n;
}
return out;
}
/**
* Convert constructor address-string input into a public key byte array.
* @internal
*/
function bytesFromAddressString(value) {
assertIsAddress(value);
return new Uint8Array(ADDRESS_CODEC.encode(value));
}
/**
* Convert constructor number-array input into a canonical 32-byte public key byte array.
* @internal
*/
function bytesFromNumberArray(value) {
const parsed = new Uint8Array(value.length);
for (let index = 0; index < value.length; index += 1) {
const byteValue = value[index];
assert_default(Number.isInteger(byteValue) && byteValue >= 0 && byteValue <= 255, ERROR__INVALID_PUBLIC_KEY_INPUT);
parsed[index] = byteValue;
}
return bytesFromUint8Array(parsed);
}
// src/bpf-loader-deprecated.ts
const BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey("BPFLoader1111111111111111111111111111111111");
// src/kit-adapters/instruction-fields.ts
/** @internal */
function toLegacyInstructionFields(instruction) {
return {
keys: (instruction.accounts ?? []).map((accountMeta) => ({
pubkey: new PublicKey(accountMeta.address),
isSigner: isSignerRole(accountMeta.role),
isWritable: isWritableRole(accountMeta.role)
})),
programId: new PublicKey(instruction.programAddress),
data: Uint8Array.from(instruction.data ?? [])
};
}
// src/kit-adapters/instruction-guard.ts
/**
* Determines whether a value has the shape of a Kit `Instruction`, so that
* callers accepting either instruction format can route appropriately.
*
* @throws If the value carries both Kit (`programAddress`/`accounts`) and
* legacy (`programId`/`keys`) fields.
*/
function isKitInstruction(value) {
if (typeof value !== "object" || value === null) return false;
const { accounts, data, keys, programAddress, programId } = value;
if ((programAddress !== void 0 || accounts !== void 0) && (programId !== void 0 || keys !== void 0)) throw new Error("Ambiguous instruction: an object must not carry both Kit (`programAddress`/`accounts`) and legacy (`programId`/`keys`) fields.");
if (typeof programAddress !== "string" || !isAddress(programAddress)) return false;
if (accounts !== void 0) {
if (!Array.isArray(accounts)) return false;
for (const accountMeta of accounts) {
if (typeof accountMeta !== "object" || accountMeta === null) return false;
const { address, role } = accountMeta;
if (typeof address !== "string" || !isAddress(address) || !isAccountRole(role)) return false;
}
}
if (data !== void 0 && !(data instanceof Uint8Array)) return false;
return true;
}
function isAccountRole(value) {
if (typeof value !== "number" || !Number.isInteger(value)) return false;
switch (value) {
case AccountRole.READONLY:
case AccountRole.WRITABLE:
case AccountRole.READONLY_SIGNER:
case AccountRole.WRITABLE_SIGNER: return true;
default: return false;
}
}
// src/kit-adapters/instruction-plan.ts
/**
* Flatten any `InstructionPlan` items in `items` into their underlying
* `Instruction`s, leaving non-plan items untouched. `MessagePackerInstructionPlan`
* leaves are rejected — they are designed to span multiple transactions and
* cannot be honored inside a single transaction / message.
*/
function expandInstructionPlans(items) {
const out = [];
for (const item of items) if (isInstructionPlan(item)) for (const leaf of flattenInstructionPlan(item)) {
if (!isSingleInstructionPlan(leaf)) throw new Error(`Unsupported InstructionPlan leaf kind "${leaf.kind}". This plan type cannot be honored inside a single transaction.`);
out.push(leaf.instruction);
}
else out.push(item);
return out;
}
// src/transaction/constants.ts
/**
* Maximum over-the-wire size of a Transaction
*
* 1280 is IPv6 minimum MTU
* 40 bytes is the size of the IPv6 header
* 8 bytes is the size of the fragment header
*/
const PACKET_DATA_SIZE = 1232;
const VERSION_PREFIX_MASK = 127;
/** Version byte that opens the serialization of a v1 message (SIMD-0385). */
const V1_MESSAGE_PREFIX = 129;
/** Maximum number of top-level instructions a v1 message can carry (SIMD-0385). */
const V1_MAX_INSTRUCTIONS = 64;
const SIGNATURE_LENGTH_IN_BYTES = 64;
// src/kit-adapters/brand.ts
/**
* `TransactionMessageBytes` is a branded `ReadonlyUint8Array<ArrayBuffer>`.
* We produce raw bytes from our legacy `Message` serializer and need to brand
* them for Kit consumption. Centralized here so the brand bypass is auditable.
* @internal
*/
function asTransactionMessageBytes(bytes) {
return bytes;
}
// src/kit-adapters/signing.ts
const COMPILED_TRANSACTION_MESSAGE_DECODER = getCompiledTransactionMessageDecoder();
/**
* Sign the serialized bytes of a legacy or versioned transaction message by
* calling `signTransactions` on each `TransactionPartialSigner` directly.
*
* Partial signers are used exclusively (rather than
* `partiallySignTransactionWithSigners`) so that a signer which also
* implements `TransactionModifyingSigner` can never alter the message and
* produce signatures over bytes other than the ones supplied.
*
* The lifetime is derived from the compiled message itself (durable nonce or
* blockhash). A blockhash lifetime's `lastValidBlockHeight` can be supplied by
* the caller; otherwise Kit's maximum-height default applies.
*
* `requiredSignatures` seeds the signature dictionary with the
* signatures the caller already holds, so signers can observe them.
*
* Returns the signatures present after signing, keyed by base58 signer
* address. Addresses that remain unsigned are absent from the result.
*
* @internal
*/
async function signTransactionBytesWithSigners(signers, messageBytes, requiredSignatures, lastValidBlockHeight) {
signers.forEach((signer) => assertIsTransactionPartialSigner(signer));
const dedupedSigners = dedupeSignersByAddress(signers);
const packedMessageBytes = toPackedUint8Array(messageBytes);
const signatures = {};
for (const { publicKey, signature } of requiredSignatures) signatures[publicKey.toBase58()] = signature != null && !isAllZeroSignature(signature) ? signatureBytes(signature) : null;
const transaction = {
lifetimeConstraint: await getLifetimeConstraint(packedMessageBytes, lastValidBlockHeight),
messageBytes: asTransactionMessageBytes(packedMessageBytes),
signatures
};
assertIsTransactionWithinSizeLimit(transaction);
const signedSignatures = (await Promise.all(dedupedSigners.map(async (signer) => {
const [dictionary] = await signer.signTransactions([transaction]);
return dictionary;
}))).reduce((merged, dictionary) => ({
...merged,
...dictionary
}), signatures);
const result = {};
for (const [address, signature] of Object.entries(signedSignatures)) {
if (signature == null) continue;
assert_default(signature.byteLength === 64, "Signature must be 64 bytes long");
result[address] = Uint8Array.from(signature);
}
return result;
}
/**
* Keep the first signer supplied for each address so that callers may pass
*/
function dedupeSignersByAddress(signers) {
const seen = /* @__PURE__ */ new Set();
return signers.filter((signer) => {
if (seen.has(signer.address)) return false;
seen.add(signer.address);
return true;
});
}
async function getLifetimeConstraint(messageBytes, lastValidBlockHeight) {
const lifetimeConstraint = await getTransactionLifetimeConstraintFromCompiledTransactionMessage(COMPILED_TRANSACTION_MESSAGE_DECODER.decode(messageBytes));
if ("blockhash" in lifetimeConstraint && lastValidBlockHeight != null) return {
...lifetimeConstraint,
lastValidBlockHeight
};
return lifetimeConstraint;
}
function isAllZeroSignature(signature) {
return signature.every((byte) => byte === 0);
}
// src/message/account-keys.ts
var MessageAccountKeys = class {
staticAccountKeys;
accountKeysFromLookups;
constructor(staticAccountKeys, accountKeysFromLookups) {
this.staticAccountKeys = staticAccountKeys;
this.accountKeysFromLookups = accountKeysFromLookups;
}
keySegments() {
const keySegments = [this.staticAccountKeys];
if (this.accountKeysFromLookups) {
keySegments.push(this.accountKeysFromLookups.writable);
keySegments.push(this.accountKeysFromLookups.readonly);
}
return keySegments;
}
get(index) {
for (const keySegment of this.keySegments()) if (index < keySegment.length) return keySegment[index];
else index -= keySegment.length;
}
get length() {
return this.keySegments().flat().length;
}
compileInstructions(instructions) {
if (this.length > 256) throw new Error("Account index overflow encountered during compilation");
const keyIndexMap = /* @__PURE__ */ new Map();
this.keySegments().flat().forEach((key, index) => {
keyIndexMap.set(key.toBase58(), index);
});
const findKeyIndex = (key) => {
const keyIndex = keyIndexMap.get(key.toBase58());
if (keyIndex === void 0) throw new Error("Encountered an unknown instruction account key during compilation");
return keyIndex;
};
return instructions.map((instruction) => {
return {
programIdIndex: findKeyIndex(instruction.programId),
accountKeyIndexes: instruction.keys.map((meta) => findKeyIndex(meta.pubkey)),
data: instruction.data
};
});
}
};
// src/message/compiled-keys.ts
var CompiledKeys = class CompiledKeys {
payer;
keyMetaMap;
constructor(payer, keyMetaMap) {
this.payer = payer;
this.keyMetaMap = keyMetaMap;
}
static compile(instructions, payer) {
const keyMetaMap = /* @__PURE__ */ new Map();
const getOrInsertDefault = (pubkey) => {
const address = pubkey.toBase58();
let keyMeta = keyMetaMap.get(address);
if (keyMeta === void 0) {
keyMeta = {
isSigner: false,
isWritable: false,
isInvoked: false
};
keyMetaMap.set(address, keyMeta);
}
return keyMeta;
};
const payerKeyMeta = getOrInsertDefault(payer);
payerKeyMeta.isSigner = true;
payerKeyMeta.isWritable = true;
for (const ix of instructions) {
getOrInsertDefault(ix.programId).isInvoked = true;
for (const accountMeta of ix.keys) {
const keyMeta = getOrInsertDefault(accountMeta.pubkey);
keyMeta.isSigner ||= accountMeta.isSigner;
keyMeta.isWritable ||= accountMeta.isWritable;
}
}
return new CompiledKeys(payer, keyMetaMap);
}
getMessageComponents() {
const mapEntries = [...this.keyMetaMap.entries()];
assert_default(mapEntries.length <= 256, "Max static account keys length exceeded");
const writableSigners = mapEntries.filter(([, meta]) => meta.isSigner && meta.isWritable);
const readonlySigners = mapEntries.filter(([, meta]) => meta.isSigner && !meta.isWritable);
const writableNonSigners = mapEntries.filter(([, meta]) => !meta.isSigner && meta.isWritable);
const readonlyNonSigners = mapEntries.filter(([, meta]) => !meta.isSigner && !meta.isWritable);
const header = {
numRequiredSignatures: writableSigners.length + readonlySigners.length,
numReadonlySignedAccounts: readonlySigners.length,
numReadonlyUnsignedAccounts: readonlyNonSigners.length
};
{
assert_default(writableSigners.length > 0, "Expected at least one writable signer key");
const [payerAddress] = writableSigners[0];
assert_default(payerAddress === this.payer.toBase58(), "Expected first writable signer key to be the fee payer");
}
return [header, [
...writableSigners.map(([address]) => new PublicKey(address)),
...readonlySigners.map(([address]) => new PublicKey(address)),
...writableNonSigners.map(([address]) => new PublicKey(address)),
...readonlyNonSigners.map(([address]) => new PublicKey(address))
]];
}
extractTableLookup(lookupTable) {
const [writableIndexes, drainedWritableKeys] = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, (keyMeta) => !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable);
const [readonlyIndexes, drainedReadonlyKeys] = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, (keyMeta) => !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable);
if (writableIndexes.length === 0 && readonlyIndexes.length === 0) return;
return [{
accountKey: lookupTable.key,
writableIndexes,
readonlyIndexes
}, {
writable: drainedWritableKeys,
readonly: drainedReadonlyKeys
}];
}
/** @internal */
drainKeysFoundInLookupTable(lookupTableEntries, keyMetaFilter) {
const lookupTableIndexes = new Array();
const drainedKeys = new Array();
for (const [address, keyMeta] of this.keyMetaMap.entries()) if (keyMetaFilter(keyMeta)) {
const key = new PublicKey(address);
const lookupTableIndex = lookupTableEntries.findIndex((entry) => entry.equals(key));
if (lookupTableIndex >= 0) {
assert_default(lookupTableIndex < 256, "Max lookup table index exceeded");
lookupTableIndexes.push(lookupTableIndex);
drainedKeys.push(key);
this.keyMetaMap.delete(address);
}
}
return [lookupTableIndexes, drainedKeys];
}
};
// src/message/legacy.ts
const BASE58_ENCODER$4 = getBase58Encoder();
const BASE58_DECODER = getBase58Decoder();
const MESSAGE_ENCODER$2 = getCompiledTransactionMessageEncoder();
const MESSAGE_DECODER$3 = getCompiledTransactionMessageDecoder();
/**
* List of instructions to be processed atomically
*/
var Message = class Message {
header;
accountKeys;
recentBlockhash;
instructions;
indexToProgramIds = /* @__PURE__ */ new Map();
constructor(args) {
this.header = Object.freeze({ ...args.header });
this.accountKeys = args.accountKeys.map((account) => new PublicKey(account));
this.recentBlockhash = args.recentBlockhash;
this.instructions = args.instructions;
this.instructions.forEach((ix) => this.indexToProgramIds.set(ix.programIdIndex, this.accountKeys[ix.programIdIndex]));
}
get version() {
return "legacy";
}
get staticAccountKeys() {
return this.accountKeys;
}
get compiledInstructions() {
return this.instructions.map((ix) => ({
programIdIndex: ix.programIdIndex,
accountKeyIndexes: ix.accounts,
data: Uint8Array.from(BASE58_ENCODER$4.encode(ix.data))
}));
}
get addressTableLookups() {
return [];
}
getAccountKeys() {
return new MessageAccountKeys(this.staticAccountKeys);
}
static compile(args) {
const instructions = expandInstructionPlans(args.instructions).map((instruction) => isKitInstruction(instruction) ? toLegacyInstructionFields(instruction) : instruction);
const [header, staticAccountKeys] = CompiledKeys.compile(instructions, args.payerKey).getMessageComponents();
const compiledInstructions = new MessageAccountKeys(staticAccountKeys).compileInstructions(instructions).map((ix) => ({
programIdIndex: ix.programIdIndex,
accounts: ix.accountKeyIndexes,
data: BASE58_DECODER.decode(ix.data)
}));
return new Message({
header,
accountKeys: staticAccountKeys,
recentBlockhash: args.recentBlockhash,
instructions: compiledInstructions
});
}
isAccountSigner(index) {
return index < this.header.numRequiredSignatures;
}
isAccountWritable(index) {
const numSignedAccounts = this.header.numRequiredSignatures;
if (index >= this.header.numRequiredSignatures) return index - numSignedAccounts < this.accountKeys.length - numSignedAccounts - this.header.numReadonlyUnsignedAccounts;
else return index < numSignedAccounts - this.header.numReadonlySignedAccounts;
}
isProgramId(index) {
return this.indexToProgramIds.has(index);
}
programIds() {
return [...this.indexToProgramIds.values()];
}
nonProgramIds() {
return this.accountKeys.filter((_, index) => !this.isProgramId(index));
}
serialize() {
const encoded = MESSAGE_ENCODER$2.encode({
version: "legacy",
header: {
numSignerAccounts: this.header.numRequiredSignatures,
numReadonlySignerAccounts: this.header.numReadonlySignedAccounts,
numReadonlyNonSignerAccounts: this.header.numReadonlyUnsignedAccounts
},
staticAccounts: this.accountKeys.map((key) => key.toBase58()),
lifetimeToken: this.recentBlockhash,
instructions: this.instructions.map((ix) => ({
programAddressIndex: ix.programIdIndex,
accountIndices: ix.accounts,
data: Uint8Array.from(BASE58_ENCODER$4.encode(ix.data))
}))
});
return toPackedUint8Array(encoded);
}
/** @internal Construct a {@link Message} from a kit-decoded compiled message. */
static fromCompiledMessage(decoded) {
return new Message({
header: {
numRequiredSignatures: decoded.header.numSignerAccounts,
numReadonlySignedAccounts: decoded.header.numReadonlySignerAccounts,
numReadonlyUnsignedAccounts: decoded.header.numReadonlyNonSignerAccounts
},
accountKeys: decoded.staticAccounts.map((addr) => new PublicKey(addr)),
recentBlockhash: decoded.lifetimeToken,
instructions: decoded.instructions.map((ix) => ({
programIdIndex: ix.programAddressIndex,
accounts: [...ix.accountIndices ?? []],
data: BASE58_DECODER.decode(ix.data ?? /* @__PURE__ */ new Uint8Array(0))
}))
});
}
/**
* Decode a compiled message into a Message object.
*/
static from(buffer) {
const decoded = MESSAGE_DECODER$3.decode(toUint8ArrayView(buffer));
if (decoded.version !== "legacy") throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");
return Message.fromCompiledMessage(decoded);
}
};
// src/message/v0.ts
const MESSAGE_ENCODER$1 = getCompiledTransactionMessageEncoder();
const MESSAGE_DECODER$2 = getCompiledTransactionMessageDecoder();
var MessageV0 = class MessageV0 {
header;
staticAccountKeys;
recentBlockhash;
compiledInstructions;
addressTableLookups;
constructor(args) {
this.header = Object.freeze({ ...args.header });
this.staticAccountKeys = args.staticAccountKeys;
this.recentBlockhash = args.recentBlockhash;
this.compiledInstructions = args.compiledInstructions;
this.addressTableLookups = args.addressTableLookups;
}
get version() {
return 0;
}
get numAccountKeysFromLookups() {
let count = 0;
for (const lookup of this.addressTableLookups) count += lookup.readonlyIndexes.length + lookup.writableIndexes.length;
return count;
}
getAccountKeys(args) {
let accountKeysFromLookups;
if (args && "accountKeysFromLookups" in args && args.accountKeysFromLookups) {
if (this.numAccountKeysFromLookups != args.accountKeysFromLookups.writable.length + args.accountKeysFromLookups.readonly.length) throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");
accountKeysFromLookups = args.accountKeysFromLookups;
} else if (args && "addressLookupTableAccounts" in args && args.addressLookupTableAccounts) accountKeysFromLookups = this.resolveAddressTableLookups(args.addressLookupTableAccounts);
else if (this.addressTableLookups.length > 0) throw new Error("Failed to get account keys because address table lookups were not resolved");
return new MessageAccountKeys(this.staticAccountKeys, accountKeysFromLookups);
}
isAccountSigner(index) {
return index < this.header.numRequiredSignatures;
}
isAccountWritable(index) {
const numSignedAccounts = this.header.numRequiredSignatures;
const numStaticAccountKeys = this.staticAccountKeys.length;
if (index >= numStaticAccountKeys) return index - numStaticAccountKeys < this.addressTableLookups.reduce((count, lookup) => count + lookup.writableIndexes.length, 0);
else if (index >= this.header.numRequiredSignatures) return index - numSignedAccounts < numStaticAccountKeys - numSignedAccounts - this.header.numReadonlyUnsignedAccounts;
else return index < numSignedAccounts - this.header.numReadonlySignedAccounts;
}
resolveAddressTableLookups(addressLookupTableAccounts) {
const accountKeysFromLookups = {
writable: [],
readonly: []
};
for (const tableLookup of this.addressTableLookups) {
const tableAccount = addressLookupTableAccounts.find((account) => account.key.equals(tableLookup.accountKey));
if (!tableAccount) throw new Error(`Failed to find address lookup table account for table key ${tableLookup.accountKey.toBase58()}`);
for (const index of tableLookup.writableIndexes) if (index < tableAccount.state.addresses.length) accountKeysFromLookups.writable.push(tableAccount.state.addresses[index]);
else throw new Error(`Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`);
for (const index of tableLookup.readonlyIndexes) if (index < tableAccount.state.addresses.length) accountKeysFromLookups.readonly.push(tableAccount.state.addresses[index]);
else throw new Error(`Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`);
}
return accountKeysFromLookups;
}
static compile(args) {
const instructions = expandInstructionPlans(args.instructions).map((instruction) => isKitInstruction(instruction) ? toLegacyInstructionFields(instruction) : instruction);
const compiledKeys = CompiledKeys.compile(instructions, args.payerKey);
const addressTableLookups = new Array();
const accountKeysFromLookups = {
writable: new Array(),
readonly: new Array()
};
const lookupTableAccounts = args.addressLookupTableAccounts || [];
for (const lookupTable of lookupTableAccounts) {
const extractResult = compiledKeys.extractTableLookup(lookupTable);
if (extractResult !== void 0) {
const [addressTableLookup, { writable, readonly }] = extractResult;
addressTableLookups.push(addressTableLookup);
accountKeysFromLookups.writable.push(...writable);
accountKeysFromLookups.readonly.push(...readonly);
}
}
const [header, staticAccountKeys] = compiledKeys.getMessageComponents();
const compiledInstructions = new MessageAccountKeys(staticAccountKeys, accountKeysFromLookups).compileInstructions(instructions);
return new MessageV0({
header,
staticAccountKeys,
recentBlockhash: args.recentBlockhash,
compiledInstructions,
addressTableLookups
});
}
serialize() {
const encoded = MESSAGE_ENCODER$1.encode({
version: 0,
header: {
numSignerAccounts: this.header.numRequiredSignatures,
numReadonlySignerAccounts: this.header.numReadonlySignedAccounts,
numReadonlyNonSignerAccounts: this.header.numReadonlyUnsignedAccounts
},
staticAccounts: this.staticAccountKeys.map((key) => key.toBase58()),
lifetimeToken: this.recentBlockhash,
instructions: this.compiledInstructions.map((ix) => ({
programAddressIndex: ix.programIdIndex,
accountIndices: ix.accountKeyIndexes,
data: ix.data
})),
addressTableLookups: this.addressTableLookups.map((lookup) => ({
lookupTableAddress: lookup.accountKey.toBase58(),
writableIndexes: lookup.writableIndexes,
readonlyIndexes: lookup.readonlyIndexes
}))
});
return toPackedUint8Array(encoded);
}
/** @internal Construct a {@link MessageV0} from a kit-decoded compiled message. */
static fromCompiledMessage(decoded) {
return new MessageV0({
header: {
numRequiredSignatures: decoded.header.numSignerAccounts,
numReadonlySignedAccounts: decoded.header.numReadonlySignerAccounts,
numReadonlyUnsignedAccounts: decoded.header.numReadonlyNonSignerAccounts
},
staticAccountKeys: decoded.staticAccounts.map((addr) => new PublicKey(addr)),
recentBlockhash: decoded.lifetimeToken,
compiledInstructions: decoded.instructions.map((ix) => ({
programIdIndex: ix.programAddressIndex,
accountKeyIndexes: [...ix.accountIndices ?? []],
data: ix.data ? Uint8Array.from(ix.data) : /* @__PURE__ */ new Uint8Array(0)
})),
addressTableLookups: (decoded.addressTableLookups ?? []).map((lookup) => ({
accountKey: new PublicKey(lookup.lookupTableAddress),
writableIndexes: [...lookup.writableIndexes],
readonlyIndexes: [...lookup.readonlyIndexes]
}))
});
}
static deserialize(serializedMessage) {
const prefix = serializedMessage[0];
const maskedPrefix = prefix & 127;
if (prefix === maskedPrefix) throw new Error("Expected versioned message but received legacy message");
if (maskedPrefix !== 0) throw new Error(`Expected versioned message with version 0 but found version ${maskedPrefix}`);
const decoded = MESSAGE_DECODER$2.decode(toUint8ArrayView(serializedMessage));
if (decoded.version !== 0) throw new Error(`Expected versioned message with version 0 but found version ${decoded.version}`);
return MessageV0.fromCompiledMessage(decoded);
}
};
// src/message/v1.ts
const MESSAGE_ENCODER = getCompiledTransactionMessageEncoder();
const MESSAGE_DECODER$1 = getCompiledTransactionMessageDecoder();
const TRANSACTION_CONFIG_KNOWN_BIT_MASK = TRANSACTION_CONFIG_PRIORITY_FEE_LAMPORTS_BIT_MASK | TRANSACTION_CONFIG_COMPUTE_UNIT_LIMIT_BIT_MASK | TRANSACTION_CONFIG_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_BIT_MASK | TRANSACTION_CONFIG_HEAP_SIZE_BIT_MASK;
/**
* A v1 transaction message (SIMD-0385).
*
* Compared to v0, a v1 message:
* - carries resource limits and prioritization in a message-level
* {@link V1TransactionConfig} instead of Compute Budget program instructions
* (which are no-ops inside a v1 transaction),
* - does not support address lookup tables,
* - may be up to 4096 bytes when serialized as a transaction (vs. 1232), and
* - uses a message-first wire envelope when framed as a transaction.
*
* Fetching v1 transactions over RPC requires passing
* `maxSupportedTransactionVersion: 1` to `getTransaction`/`getBlock`.
*/
var MessageV1 = class MessageV1 {
header;
staticAccountKeys;
recentBlockhash;
compiledInstructions;
/** Message-level resource limits and prioritization; `undefined` when no config values are set */
transactionConfig;
constructor(args) {
this.header = Object.freeze({ ...args.header });
this.staticAccountKeys = args.staticAccountKeys;
this.recentBlockhash = args.recentBlockhash;
this.compiledInstructions = args.compiledInstructions;
this.transactionConfig = args.transactionConfig;
}
get version() {
return 1;
}
getAccountKeys() {
return new MessageAccountKeys(this.staticAccountKeys);
}
isAccountSigner(index) {
return index < this.header.numRequiredSignatures;
}
isAccountWritable(index) {
const numSigners = this.header.numRequiredSignatures;
const numWritableSignedAccounts = numSigners - this.header.numReadonlySignedAccounts;
const numWritableUnsignedAccounts = this.staticAccountKeys.length - numSigners - this.header.numReadonlyUnsignedAccounts;
return index < numWritableSignedAccounts || index >= numSigners && index < numSigners + numWritableUnsignedAccounts;
}
static compile(args) {
const instructions = expandInstructionPlans(args.instructions).map((instruction) => isKitInstruction(instruction) ? toLegacyInstructionFields(instruction) : instruction);
if (instructions.length > 64) throw new Error(`Version 1 messages support at most 64 instructions but found ${instructions.length}`);
const [header, staticAccountKeys] = CompiledKeys.compile(instructions, args.payerKey).getMessageComponents();
const compiledInstructions = new MessageAccountKeys(staticAccountKeys).compileInstructions(instructions);
return new MessageV1({
header,
staticAccountKeys,
recentBlockhash: args.recentBlockhash,
compiledInstructions,
transactionConfig: args.transactionConfig
});
}
serialize() {
const transactionConfig = this.transactionConfig ?? {};
const encoded = MESSAGE_ENCODER.encode({
version: 1,
configMask: getTransactionConfigMask(transactionConfig),
configValues: getTransactionConfigValues(transactionConfig),
header: {
numSignerAccounts: this.header.numRequiredSignatures,
numReadonlySignerAccounts: this.header.numReadonlySignedAccounts,
numReadonlyNonSignerAccounts: this.header.numReadonlyUnsignedAccounts
},
numStaticAccounts: this.staticAccountKeys.length,
staticAccounts: this.staticAccountKeys.map((key) => key.toBase58()),
lifetimeToken: this.recentBlockhash,
numInstructions: this.compiledInstructions.length,
instructionHeaders: this.compiledInstructions.map((ix) => ({
programAccountIndex: ix.programIdIndex,
numInstructionAccounts: ix.accountKeyIndexes.length,
numInstructionDataBytes: ix.data.byteLength
})),
instructionPayloads: this.compiledInstructions.map((ix) => ({
instructionAccountIndices: ix.accountKeyIndexes,
instructionData: ix.data
}))
});
return toPackedUint8Array(encoded);
}
/** @internal Construct a {@link MessageV1} from a kit-decoded compiled message. */
static fromCompiledMessage(decoded) {
const compiledInstructions = decoded.instructionHeaders.map((instructionHeader, i) => {
const payload = decoded.instructionPayloads[i];
return {
programIdIndex: instructionHeader.programAccountIndex,
accountKeyIndexes: [...payload.instructionAccountIndices ?? []],
data: payload.instructionData ? Uint8Array.from(payload.instructionData) : /* @__PURE__ */ new Uint8Array(0)
};
});
if ((decoded.configMask & ~TRANSACTION_CONFIG_KNOWN_BIT_MASK) !== 0) throw new Error("Unexpected bits set in the transaction config mask");
const decompiledConfig = decompileTransactionConfig(decoded.configMask, decoded.configValues);
const transactionConfig = isV1ConfigEmpty(decompiledConfig) ? void 0 : decompiledConfig;
return new MessageV1({
header: {
numRequiredSignatures: decoded.header.numSignerAccounts,
numReadonlySignedAccounts: decoded.header.numReadonlySignerAccounts,
numReadonlyUnsignedAccounts: decoded.header.numReadonlyNonSignerAccounts
},
staticAccountKeys: decoded.staticAccounts.map((addr) => new PublicKey(addr)),
recentBlockhash: decoded.lifetimeToken,
compiledInstructions,
transactionConfig
});
}
static deserialize(serializedMessage) {
const decoded = MESSAGE_DECODER$1.decode(toUint8ArrayView(serializedMessage));
if (decoded.version !== 1) throw new Error(decoded.version === "legacy" ? "Expected versioned message but received legacy message" : `Expected versioned message with version 1 but found version ${decoded.version}`);
return MessageV1.fromCompiledMessage(decoded);
}
};
// src/message/versioned.ts
const MESSAGE_DECODER = getCompiledTransactionMessageDecoder();
const VersionedMessage = {
deserializeMessageVersion(serializedMessage) {
const prefix = serializedMessage[0];
const maskedPrefix = prefix & 127;
if (maskedPrefix === prefix) return "legacy";
return maskedPrefix;
},
deserialize: (serializedMessage) => {
const version = VersionedMessage.deserializeMessageVersion(serializedMessage);
if (version !== "legacy" && version !== 0 && version !== 1) throw new Error(`Transaction message version ${version} deserialization is not supported`);
const decoded = MESSAGE_DECODER.decode(toUint8ArrayView(serializedMessage));
if (decoded.version === "legacy") return Message.fromCompiledMessage(decoded);
if (decoded.version === 0) return MessageV0.fromCompiledMessage(decoded);
return MessageV1.fromCompiledMessage(decoded);
}
};
// src/transaction/legacy.ts
let TransactionStatus = /* @__PURE__ */ function(TransactionStatus) {
TransactionStatus[TransactionStatus["BLOCKHEIGHT_EXCEEDED"] = 0] = "BLOCKHEIGHT_EXCEEDED";
TransactionStatus[TransactionStatus["PROCESSED"] = 1] = "PROCESSED";
TransactionStatus[TransactionStatus["TIMED_OUT"] = 2] = "TIMED_OUT";
TransactionStatus[TransactionStatus["NONCE_INVALID"] = 3] = "NONCE_INVALID";
return TransactionStatus;
}({});
/**
* Default (empty) signature
*/
const DEFAULT_SIGNATURE = /* @__PURE__ */ new Uint8Array(64);
const BASE58_CODEC = getBase58Codec();
const SHORT_U16_ENCODER = getShortU16Encoder();
const SHORT_U16_DECODER$1 = getShortU16Decoder();
const SIGNATURE_DECODER$1 = fixDecoderSize(getBytesDecoder(), 64);
const TRANSACTION_WIRE_DECODER = getStructDecoder([["signatures", getArrayDecoder(SIGNATURE_DECODER$1, { size: SHORT_U16_DECODER$1 })], ["messageBytes", getBytesDecoder()]]);
/**
* Transaction Instruction class
*/
var TransactionInstruction = class {
/**
* Public keys to include in this transaction
* Boolean represents whether this pubkey needs to sign the transaction
*/
keys;
/**
* Program Id to execute
*/
programId;
/**
* Program input
*/
_data = /* @__PURE__ */ new Uint8Array(0);
get data() {
return this._data;
}
set data(data) {
this._data = Object.getPrototypeOf(data) === Uint8Array.prototype ? data : Uint8Array.from(data);
}
constructor(opts) {
this.programId = opts.programId;
this.keys = opts.keys;
if (opts.data) this.data = opts.data;
}
/**
* @internal
*/
toJSON() {
return {
keys: this.keys.map(({ pubkey, isSigner, isWritable }) => ({
pubkey: pubkey.toJSON(),
isSigner,
isWritable
})),
programId: this.programId.toJSON(),
data: [...this.data]
};
}
};
/**
* Transaction class
*/
var Transaction = class Transaction {
/**
* Signatures for the transaction. Typically created by invoking the
* `sign()` method
*/
signatures = [];
/**
* The first (payer) Transaction signature
*
* @returns {Uint8Array | null} The payer's signature bytes
*/
get signature() {
if (this.signatures.length > 0) return this.signatures[0].signature;
return null;
}
/**
* The transaction fee payer
*/
feePayer;
/**
* The instructions to atomically execute
*/
instructions = [];
/**
* A recent transaction id. Must be populated by the caller
*/
recentBlockhash;
/**
* the last block chain can advance to before tx is declared expired
* */
lastValidBlockHeight;
/**
* Optional Nonce information. If populated, transaction will use a durable
* Nonce hash instead of a recentBlockhash. Must be populated by the caller
*/
nonceInfo;
/**
* If this is a nonce transaction this represents the minimum slot from which
* to evaluate if the nonce has advanced when attempting to confirm the
* transaction. This protects against a case where the transaction confirmation
* logic loads the nonce account from an old slot and assumes the mismatch in
* nonce value implies that the nonce has been advanced.
*/
minNonceContextSlot;
/**
* @internal
*/
_message;
/**
* @internal
*/
_json;
/**
* Construct an empty Transaction
*/
constructor(opts) {
if (!opts) return;
if (opts.feePayer) this.feePayer = opts.feePayer;
if (opts.signatures) this.signatures = opts.signatures.map(({ publicKey, signature }) => ({
publicKey,
signature: signature == null ? null : Uint8Array.from(signature)
}));
if (Object.prototype.hasOwnProperty.call(opts, "nonceInfo")) {
const { minContextSlot, nonceInfo } = opts;
this.minNonceContextSlot = minContextSlot;
this.nonceInfo = nonceInfo;
} else if (Object.prototype.hasOwnProperty.call(opts, "lastValidBlockHeight")) {
const { blockhash, lastValidBlockHeight } = opts;
this.recentBlockhash = blockhash;
this.lastValidBlockHeight = lastValidBlockHeight;
} else {
const { recentBlockhash, nonceInfo } = opts;
if (nonceInfo) this.nonceInfo = nonceInfo;
this.recentBlockhash = recentBlockhash;
}
}
/**
* @internal
*/
toJSON() {
return {
recentBlockhash: this.recentBlockhash || null,
feePayer: this.feePayer ? this.feePayer.toJSON() : null,
nonceInfo: this.nonceInfo ? {
nonce: this.nonceInfo.nonce,
nonceInstruction: this.nonceInfo.nonceInstruction.toJSON()
} : null,
instructions: this.instructions.map((instruction) => instruction.toJSON()),
signers: this.signatures.map(({ publicKey }) => {
return publicKey.toJSON();
})
};
}
/**
* Add one or more instructions to this Transaction.
*
* `InstructionPlan` inputs are flattened in order and each leaf instruction
* is appended. Parallel sub-trees collapse to sequential order in the
* single-transaction context. `MessagePackerInstructionPlan` leaves are
* rejected at runtime — they are designed to span multiple transactions and
* cannot be honored inside a single legacy `Transaction`.
*
* @param {Array< Transaction | TransactionInstructionCtorFields | InstructionInput >} items - Instructions or plans to add to the Transaction
*/
add(...items) {
const expanded = expandInstructionPlans(items);
if (expanded.length === 0) throw new Error("No instructions");
expanded.forEach((item) => {
if (item instanceof Transaction) this.instructions = this.instructions.concat(item.instructions);
else if (isKitInstruction(item)) this.instructions.push(new TransactionInstruction(toLegacyInstructionFields(item)));
else if (item instanceof TransactionInstruction) this.instructions.push(item);
else this.instructions.push(new TransactionInstruction(item));
});
return this;
}
/**
* Compile transaction data
*/
compileMessage() {
if (this._message && JSON.stringify(this.toJSON()) === JSON.stringify(this._json)) return this._message;
let recentBlockhash;
let instructions;
if (this.nonceInfo) {
recentBlockhash = this.nonceInfo.nonce;
if (this.instructions[0] != this.nonceInfo.nonceInstruction) instructions = [this.nonceInfo.nonceInstruction, ...this.instructions];
else instructions = this.instructions;
} else {
recentBlockhash = this.recentBlockhash;
instructions = this.instructions;
}
if (!recentBlockhash) throw new Error("Transaction recentBlockhash required");
if (instructions.length < 1) console.warn("No instructions provided");
let feePayer;
if (this.feePayer) feePayer = this.feePayer;
else if (this.signatures.length > 0 && this.signatures[0].publicKey) feePayer = this.signatures[0].publicKey;
else throw new Error("Transaction fee payer required");
for (let i = 0; i < instructions.length; i++) if (instructions[i].programId === void 0) throw new Error(`Transaction instruction index ${i} has undefined program id`);
const programIds = [];
const accountMetas = [];
instructions.forEach((instruction) => {
instruction.keys.forEach((accountMeta) => {
accountMetas.push({ ...accountMeta });
});
const programId = instruction.programId.toString();
if (!programIds.includes(programId)) programIds.push(programId);
});
programIds.forEach((programId) => {
accountMetas.push({
pubkey: new PublicKey(programId),
isSigner: false,
isWritable: false
});
});
const uniqueMetas = [];
accountMetas.forEach((accountMeta) => {
const pubkeyString = accountMeta.pubkey.toString();
const uniqueIndex = uniqueMetas.findIndex((x) => {
return x.pubkey.toString() === pubkeyString;
});
if (uniqueIndex > -1) {
uniqueMetas[uniqueIndex].isWritable = uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable;
uniqueMetas[uniqueIndex].isSigner = uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner;
} else uniqueMetas.push(accountMeta);
});
uniqueMetas.sort(function(x, y) {
if (x.isSigner !== y.isSigner) return x.isSigner ? -1 : 1;
if (x.isWritable !== y.isWritable) return x.isWritable ? -1 : 1;
return x.pubkey.toBase58().localeCompare(y.pubkey.toBase58(), "en", {
localeMatcher: "best fit",
usage: "sort",
sensitivity: "variant",
ignorePunctuation: false,
numeric: false,
caseFirst: "lower"
});
});
const feePayerIndex = uniqueMetas.findIndex((x) => {
return x.pubkey.equals(feePayer);
});
if (feePayerIndex > -1) {
const [payerMeta] = uniqueMetas.splice(feePayerIndex, 1);
payerMeta.isSigner = true;
payerMeta.isWritable = true;
uniqueMetas.unshift(payerMeta);
} else uniqueMetas.unshift({
pubkey: feePayer,
isSigner: true,
isWritable: true
});
for (const signature of this.signatures) {
const uniqueIndex = uniqueMetas.findIndex((x) => {
return x.pubkey.equals(signature.publicKey);
});
if (uniqueIndex > -1) {
if (!uniqueMetas[uniqueIndex].isSigner) {
uniqueMetas[uniqueIndex].isSigner = true;
console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release.");
}
} else throw new Error(`unknown signer: ${signature.publicKey.toString()}`);
}
let numRequiredSignatures = 0;
let numReadonlySignedAccounts = 0;
let numReadonlyUnsignedAccounts = 0;
const signedKeys = [];
const unsignedKeys = [];
uniqueMetas.forEach(({ pubkey, isSigner, isWritable }) => {
if (isSigner) {
signedKeys.push(pubkey.toString());
numRequiredSignatures += 1;
if (!isWritable) numReadonlySignedAccounts += 1;
} else {
unsignedKeys.push(pubkey.toString());
if (!isWritable) numReadonlyUnsignedAccounts += 1;
}
});
const accountKeys = signedKeys.concat(unsignedKeys);
const compiledInstructions = instructions.map((instruction) => {
const { data, programId } = instruction;
return {
programIdIndex: accountKeys.indexOf(programId.toString()),
accounts: instruction.keys.map((meta) => accountKeys.indexOf(meta.pubkey.toString())),
data: BASE58_CODEC.decode(data)
};
});
compiledInstructions.forEach((instruction) => {
assert_default(instruction.programIdIndex >= 0);
instruction.accounts.forEach((keyIndex) => assert_default(keyIndex >= 0));
});
return new Message({
header: {
numRequiredSignatures,
numReadonlySignedAccounts,
numReadonlyUnsignedAccounts
},
accountKeys,
recentBlockhash,
instructions: compiledInstructions
});
}
/**
* @internal
*/
_compile() {
const message = this.compileMessage();
const signedKeys = message.accountKeys.slice(0, message.header.numRequiredSignatures);
if (this.signatures.length === signedKeys.length) {
if (this.signatures.every((pair, index) => {
return signedKeys[index].equals(pair.publicKey);
})) return message;
}
this.signatures = signedKeys.map((publicKey) => ({
signature: null,
publicKey
}));
return message;
}
/**
* Get the Transaction data that need to be covered by signatures
*/
serializeMessage() {
return this._compile().serialize();
}
/**
* Get the estimated fee associated with a transaction
*
* @param {Connection} connection Connection to RPC Endpoint.
*
* @returns {Promise<bigint | null>} The estimated fee for the transaction
*/
async getEstimatedFee(connection) {
return (await connection.getFeeForMessage(this.compileMessage())).value;
}
/**
* Specify the public keys which will be used to sign the Transaction.
* The first signer will be used as the transaction fee payer account.
*
* Signatures can be added with either `partialSign` or `addSignature`
*
* @deprecated Deprecated since v0.84.0. Only the fee payer needs to be
* specified and it can be set in the Transaction constructor or with the
* `feePayer` property.
*/
setSigners(...signers) {
if (signers.length === 0) throw new Error("No signers");
const seen = /* @__PURE__ */ new Set();
this.signatures = signers.filter((publicKey) => {
const key = publicKey.toString();
if (seen.has(key)) return false;
else {
seen.add(key);
return true;
}
}).map((publicKey) => ({
signature: null,
publicKey
}));
}
/**
* Sign the Transaction with the specified signers. Multiple signatures may
* be applied to a Transaction. The first signature is considered "primary"
* and is used identify and confirm transactions.
*
* If the Transaction `feePayer` is not set, the first signer will be used
* as the transaction fee payer account.
*
* Transaction fields should not be modified after the first call to `sign`,
* as doing so may invalidate the signature and cause the Transaction to be
* rejected.
*
* The Transaction must be assigned a valid `recentBlockhash` before invoking this method
*/
async sign(...signers) {
if (signers.length === 0) throw new Error("No signers");
const resolved = this._resolveSigners(signers);
this.signatures = resolved.map(({ publicKey }) => ({
signature: null,
publicKey
}));
const message = this._compile();
await this._partialSign(message, resolved);
}
/**
* Partially sign a transaction with the specified accounts. All accounts must
* correspond to either the fee payer or a signer account in the transaction
* instructions.
*
* All the caveats from the `sign` method apply to `partialSign`
*/
async partialSign(...signers) {
if (signers.length === 0) throw new Error("No signers");
const resolved = this._resolveSigners(signers);
const message = this._compile();
await this._partialSign(message, resolved);
}
/**
* @internal
*/
async _partialSign(message, signers) {
for (const { publicKey } of signers) if (!this.signatures.some((pair) => publicKey.equals(pair.publicKey))) throw new Error(`unknown signer: ${publicKey.toString()}`);
const signatures = await signTransactionBytesWithSigners(signers.map(({ signer }) => signer), message.serialize(), this.signatures, this.lastValidBlockHeight === void 0 ? void 0 : BigInt(this.lastValidBlockHeight));
for (const { publicKey } of this.signatures) {
const signature = signatures[publicKey.toBase58()];
if (signature != null) this._addSignature(publicKey, signature);
}
}
_resolveSigners(signers) {
const seen = /* @__PURE__ */ new Set();
const resolved = [];
for (const signer of signers) {
const publicKey = new PublicKey(signer.address);
const key = publicKey.toString();
if (seen.has(key)) continue;
seen.add(key);
resolved.push({
signer,
publicKey
});
}
return resolved;
}
/**
* Add an externally created signature to a transaction. The public key
* must correspond to either the fee payer or a signer account in the transaction
* instructions.
*
* @param {PublicKey} pubkey Public key that will be added to the transaction.
* @param {Uint8Array} signature An externally created signature to add to the transaction.
*/
addSignature(pubkey, signature) {
this._compile();
this._addSignature(pubkey, signature);
}
/**
* @internal
*/
_addSignature(pubkey, signature) {
assert_default(signature.length === 64);
const index = this.signatures.findIndex((sigpair) => pubkey.equals(sigpair.publicKey));
if (index < 0) throw new Error(`unknown signer: ${pubkey.toString()}`);
this.signatures[index].signature = Uint8Array.from(signature);
}
/**
* Verify signatures of a Transaction
* Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one.
* If no boolean is provided, we expect a fully signed Transaction by default.
*
* @param {boolean} [requireAllSignatures=true] Require a fully signed Transaction
*/
async verifySignatures(requireAllSignatures = true) {
return !await this._getMessageSignednessErrors(this.serializeMessage(), requireAllSignatures);
}
/**
* @internal
*/
async _getMessageSignednessErrors(message, requireAllSignatures) {
const errors = {};
for (const { signature, publicKey } of this.signatures) if (signature === null) {
if (requireAllSignatures) (errors.missing ||= []).push(publicKey);
} else if (!await verify(signature, message, publicKey.toBytes())) (errors.invalid ||= []).push(publicKey);
return errors.invalid || errors.missing ? errors : void 0;
}
/**
* Serialize the Transaction in the wire format.
*
* @param {SerializeConfig} [config] Config of transaction.
*
* @returns {Uint8Array} Signature of transaction in wire format.
*/
async serialize(config) {
const { requireAllSignatures, verifySignatures } = Object.assign({
requireAllSignatures: true,
verifySignatures: true
}, config);
const signData = this.serializeMessage();
if (verifySignatures) {
const sigErrors = await this._getMessageSignednessErrors(signData, requireAllSignatures);
if (sigErrors) {
let errorMessage = "Signature verification failed.";
if (sigErrors.invalid) errorMessage += `\nInvalid signature for public key${sigErrors.invalid.length === 1 ? "" : "(s)"} [\`${sigErrors.invalid.map((p) => p.toBase58()).join("`, `")}\`].`;
if (sigErrors.missing) errorMessage += `\nMissing signature for public key${sigErrors.missing.length === 1 ? "" : "(s)"} [\`${sigErrors.missing.map((p) => p.toBase58()).join("`, `")}\`].`;
throw new Error(errorMessage);
}
}
return this._serialize(signData);
}
/**
* @internal
*/
_serialize(signData) {
const { signatures } = this;
const signatureCount = SHORT_U16_ENCODER.encode(signatures.length);
const transactionLength = signatureCount.length + signatures.length * 64 + signData.length;
const wireTransaction = new Uint8Array(transactionLength);
assert_default(signatures.length < 256);
wireTransaction.set(signatureCount, 0);
signatures.forEach(({ signature }, index) => {
if (signature !== null) {
assert_default(signature.length === 64, `signature has invalid length`);
wireTransaction.set(signature, signatureCount.length + index * 64);
}
});
wireTransaction.set(signData, signatureCount.length + signatures.length * 64);
assert_default(wireTransaction.length <= PACKET_DATA_SIZE, `Transaction too large: ${wireTransaction.length} > ${PACKET_DATA_SIZE}`);
return wireTransaction;
}
/**
* Deprecated method
* @internal
*/
get keys() {
assert_default(this.instructions.length === 1);
return this.instructions[0].keys.map((keyObj) => keyObj.pubkey);
}
/**
* Deprecated method
* @internal
*/
get programId() {
assert_default(this.instructions.length === 1);
return this.instructions[0].programId;
}
/**
* Deprecated method
* @internal
*/
get data() {
assert_default(this.instructions.length === 1);
return this.instructions[0].data;
}
/**
* Parse a wire transaction into a Transaction object.
*
* @param {Uint8Array | Array<number>} buffer Signature of wire Transaction
*
* @returns {Transaction} Transaction associated with the signature
*/
static from(buffer) {
const { signatures: decodedSignatures, messageBytes } = TRANSACTION_WIRE_DECODER.decode(toUint8ArrayView(buffer));
const signatures = decodedSignatures.map((signature) => BASE58_CODEC.decode(signature));
return Transaction.populate(Message.from(toUint8ArrayView(messageBytes)), signatures);
}
/**
* Populate Transaction object from message and signatures
*
* @param {Message} message Message of transaction
* @param {Array<string>} signatures List of signatures to assign to the transaction
*
* @returns {Transaction} The populated Transaction
*/
static populate(message, signatures = []) {
const transaction = new Transaction();
transaction.recentBlockhash = message.recentBlockhash;
if (message.header.numRequiredSignatures > 0) transaction.feePayer = message.accountKeys[0];
signatures.forEach((signature, index) => {
const sigPubkeyPair = {
signature: signature == BASE58_CODEC.decode(DEFAULT_SIGNATURE) ? null : Uint8Array.from(BASE58_CODEC.encode(signature)),
publicKey: message.accountKeys[index]
};
transaction.signatures.push(sigPubkeyPair);
});
message.instructions.forEach((instruction) => {
const keys = instruction.accounts.map((account) => {
const pubkey = message.accountKeys[account];
return {
pubkey,
isSigner: transaction.signatures.some((keyObj) => keyObj.publicKey.toString() === pubkey.toString()) || message.isAccountSigner(account),
isWritable: message.isAccountWritable(account)
};
});
transaction.instructions.push(new TransactionInstruction({
keys,
programId: message.accountKeys[instruction.programIdIndex],
data: Uint8Array.from(BASE58_CODEC.encode(instruction.data))
}));
});
transaction._message = new Message({
accountKeys: message.accountKeys,
header: message.header,
instructions: message.instructions.map((instruction) => ({
...instruction,
accounts: [...instruction.accounts]
})),
recentBlockhash: message.recentBlockhash
});
transaction._json = transaction.toJSON();
return transaction;
}
};
// src/kit-adapters/instruction.ts
function toKitInstruction(instruction) {
const accounts = instruction.keys.map((accountMeta) => Object.freeze({
address: accountMeta.pubkey.toBase58(),
role: toRole(accountMeta.isSigner, accountMeta.isWritable)
}));
return Object.freeze({
accounts: Object.freeze(accounts),
data: Uint8Array.from(instruction.data),
programAddress: instruction.programId.toBase58()
});
}
function fromKitInstruction(instruction) {
return new TransactionInstruction(toLegacyInstructionFields(instruction));
}
function toRole(isSigner, isWritable) {
if (isSigner && isWritable) return AccountRole.WRITABLE_SIGNER;
if (isSigner) return AccountRole.READONLY_SIGNER;
if (isWritable) return AccountRole.WRITABLE;
return AccountRole.READONLY;
}
// src/nonce-account.ts
const NONCE_ACCOUNT_DECODER = getNonceDecoder();
const NONCE_ACCOUNT_LENGTH = getNonceSize();
/**
* NonceAccount class
*
* Durable nonces are planned for deprecation on Solana. They remain valid on
* mainnet today and no removal date is set. See
* {@link https://solana.com/upgrades/durable-nonce-deprecation} for the
* timeline and migration guidance.
*/
var NonceAccount = class NonceAccount {
authorizedPubkey;
nonce;
feeCalculator;
/**
* @internal
*/
constructor(args) {
this.authorizedPubkey = args.authorizedPubkey;
this.nonce = args.nonce;
this.feeCalculator = args.feeCalculator;
}
/**
* Deserialize NonceAccount from the account data.
*
* @param buffer account data
* @return NonceAccount
*/
static fromAccountData(buffer) {
const nonceAccount = NONCE_ACCOUNT_DECODER.decode(toUint8ArrayView(buffer));
assert_default(nonceAccount.state === NonceState.Initialized, "nonce account is not initialized");
assert_default(nonceAccount.lamportsPerSignature <= BigInt(Number.MAX_SAFE_INTEGER), "lamportsPerSignature exceeds safe integer range");
return new NonceAccount({
authorizedPubkey: new PublicKey(nonceAccount.authority),
nonce: blockhash(nonceAccount.blockhash),
feeCalculator: { lamportsPerSignature: Number(nonceAccount.lamportsPerSignature) }
});
}
};
// src/sysvar.ts
const SYSVAR_CLOCK_PUBKEY = new PublicKey("SysvarC1ock11111111111111111111111111111111");
const SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey("SysvarEpochSchedu1e111111111111111111111111");
const SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey("Sysvar1nstructions1111111111111111111111111");
const SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey("SysvarRecentB1ockHashes11111111111111111111");
const SYSVAR_RENT_PUBKEY = new PublicKey("SysvarRent111111111111111111111111111111111");
const SYSVAR_REWARDS_PUBKEY = new PublicKey("SysvarRewards111111111111111111111111111111");
const SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey("SysvarS1otHashes111111111111111111111111111");
const SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey("SysvarS1otHistory11111111111111111111111111");
const SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey("SysvarStakeHistory1111111111111111111111111");
// src/transaction/expiry-custom-errors.ts
var TransactionExpiredBlockheightExceededError = class extends Error {
signature;
constructor(signature) {
super(`Signature ${signature} has expired: block height exceeded.`);
this.signature = signature;
}
};
Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype, "name", { value: "TransactionExpiredBlockheightExceededError" });
var TransactionExpiredTimeoutError = class extends Error {
signature;
constructor(signature, timeoutSeconds) {
super(`Transaction was not confirmed in ${timeoutSeconds.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`);
this.signature = signature;
}
};
Object.defineProperty(TransactionExpiredTimeoutError.prototype, "name", { value: "TransactionExpiredTimeoutError" });
var TransactionExpiredNonceInvalidError = class extends Error {
signature;
constructor(signature) {
super(`Signature ${signature} has expired: the nonce is no longer valid.`);
this.signature = signature;
}
};
Object.defineProperty(TransactionExpiredNonceInvalidError.prototype, "name", { value: "TransactionExpiredNonceInvalidError" });
// src/transaction/message.ts
var TransactionMessage = class TransactionMessage {
payerKey;
instructions;
recentBlockhash;
transactionConfig;
constructor(args) {
this.payerKey = args.payerKey;
this.instructions = expandInstructionPlans(args.instructions).map((instruction) => isKitInstruction(instruction) ? fromKitInstruction(instruction) : instruction);
this.recentBlockhash = args.recentBlockhash;
this.transactionConfig = args.transactionConfig;
}
static decompile(message, args) {
const { header, compiledInstructions, recentBlockhash } = message;
const { numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts } = header;
const numWritableSignedAccounts = numRequiredSignatures - numReadonlySignedAccounts;
assert_default(numWritableSignedAccounts > 0, "Message header is invalid");
const numWritableUnsignedAccounts = message.staticAccountKeys.length - numRequiredSignatures - numReadonlyUnsignedAccounts;
assert_default(numWritableUnsignedAccounts >= 0, "Message header is invalid");
const accountKeys = message.getAccountKeys(args);
const payerKey = accountKeys.get(0);
if (payerKey === void 0) throw new Error("Failed to decompile message because no account keys were found");
const instructions = [];
for (const compiledIx of compiledInstructions) {
const keys = [];
for (const keyIndex of compiledIx.accountKeyIndexes) {
const pubkey = accountKeys.get(keyIndex);
if (pubkey === void 0) throw new Error(`Failed to find key for account key index ${keyIndex}`);
const isSigner = keyIndex < numRequiredSignatures;
let isWritable;
if (isSigner) isWritable = keyIndex < numWritableSignedAccounts;
else if (keyIndex < accountKeys.staticAccountKeys.length) isWritable = keyIndex - numRequiredSignatures < numWritableUnsignedAccounts;
else isWritable = keyIndex - accountKeys.staticAccountKeys.length < accountKeys.accountKeysFromLookups.writable.length;
keys.push({
pubkey,
isSigner: keyIndex < header.numRequiredSignatures,
isWritable
});
}
const programId = accountKeys.get(compiledIx.programIdIndex);
if (programId === void 0) throw new Error(`Failed to find program id for program id index ${compiledIx.programIdIndex}`);
instructions.push(new TransactionInstruction({
programId,
data: Uint8Array.from(compiledIx.data),
keys
}));
}
return new TransactionMessage({
payerKey,
instructions,
recentBlockhash,
transactionConfig: message.version === 1 ? message.transactionConfig : void 0
});
}
compileToLegacyMessage() {
return Message.compile({
payerKey: this.payerKey,
recentBlockhash: this.recentBlockhash,
instructions: this.instructions
});
}
compileToV0Message(addressLookupTableAccounts) {
return MessageV0.compile({
payerKey: this.payerKey,
recentBlockhash: this.recentBlockhash,
instructions: this.instructions,
addressLookupTableAccounts
});
}
/**
* Compile to a v1 message (SIMD-0385).
*
* v1 messages do not support address lookup tables. Resource limits and
* prioritization are set through `transactionConfig` rather than Compute
* Budget program instructions, which are no-ops in v1 transactions.
*
* @param transactionConfig When provided, takes precedence over the
* `transactionConfig` set on this `TransactionMessage`.
*/
compileToV1Message(transactionConfig) {
return MessageV1.compile({
payerKey: this.payerKey,
recentBlockhash: this.recentBlockhash,
instructions: this.instructions,
transactionConfig: transactionConfig ?? this.transactionConfig
});
}
};
// src/transaction/versioned.ts
const SIGNATURE_ENCODER = fixEncoderSize(getBytesEncoder(), 64);
const SIGNATURE_DECODER = fixDecoderSize(getBytesDecoder(), 64);
const VERSIONED_TRANSACTION_ENCODER = getStructEncoder([["signatures", getArrayEncoder(SIGNATURE_ENCODER, { size: getShortU16Encoder() })], ["serializedMessage", getBytesEncoder()]]);
const VERSIONED_TRANSACTION_DECODER = getStructDecoder([["signatures", getArrayDecoder(SIGNATURE_DECODER, { size: getShortU16Decoder() })], ["serializedMessage", getBytesDecoder()]]);
/**
* Versioned transaction class
*/
var VersionedTransaction = class VersionedTransaction {
signatures;
message;
get version() {
return this.message.version;
}
constructor(message, signatures) {
if (signatures !== void 0) {
assert_default(signatures.length === message.header.numRequiredSignatures, "Expected signatures length to be equal to the number of required signatures");
this.signatures = signatures;
} else {
const defaultSignatures = [];
for (let i = 0; i < message.header.numRequiredSignatures; i++) defaultSignatures.push(/* @__PURE__ */ new Uint8Array(64));
this.signatures = defaultSignatures;
}
this.message = message;
}
serialize() {
const serializedMessage = this.message.serialize();
for (const signature of this.signatures) assert_default(signature.byteLength === 64, "Signature must be 64 bytes long");
if (this.message.version === 1) {
const serializedTransaction = new Uint8Array(serializedMessage.length + this.signatures.length * 64);
serializedTransaction.set(serializedMessage, 0);
this.signatures.forEach((signature, index) => {
serializedTransaction.set(signature, serializedMessage.length + index * 64);
});
return serializedTransaction;
}
return Uint8Array.from(VERSIONED_TRANSACTION_ENCODER.encode({
signatures: this.signatures,
serializedMessage
}));
}
static deserialize(serializedTransaction) {
const prefix = serializedTransaction[0];
if ((prefix & -128) !== 0) {
if (prefix !== 129) {
if ((prefix & 127) === 0) throw new Error("Version 0 transactions must be serialized signatures first");
throw new Error(`Invalid transaction discriminator ${prefix}`);
}
const numSignatures = serializedTransaction[1];
const messageLength = serializedTransaction.length - numSignatures * 64;
assert_default(messageLength > 0, "Transaction is too short for the number of signatures it requires");
const message = VersionedMessage.deserialize(serializedTransaction.subarray(0, messageLength));
const signatures = [];
for (let i = 0; i < numSignatures; i++) {
const offset = messageLength + i * 64;
signatures.push(Uint8Array.from(serializedTransaction.subarray(offset, offset + 64)));
}
return new VersionedTransaction(message, signatures);
}
const { serializedMessage, signatures } = VERSIONED_TRANSACTION_DECODER.decode(serializedTransaction);
const message = VersionedMessage.deserialize(Uint8Array.from(serializedMessage));
assert_default(message.version !== 1, "Invalid message version for a signatures-first transaction");
return new VersionedTransaction(message, signatures.map((signature) => Uint8Array.from(signature)));
}
async sign(signers, config) {
const signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures);
for (const signer of signers) assert_default(signerPubkeys.some((pubkey) => pubkey.toBase58() === signer.address), `Cannot sign with non signer key ${signer.address}`);
const signatures = await signTransactionBytesWithSigners(signers, this.message.serialize(), signerPubkeys.map((publicKey, index) => ({
publicKey,
signature: this.signatures[index]
})), config?.lastValidBlockHeight);
signerPubkeys.forEach((pubkey, index) => {
const signature = signatures[pubkey.toBase58()];
if (signature != null) this.signatures[index] = signature;
});
}
addSignature(publicKey, signature) {
assert_default(signature.byteLength === 64, "Signature must be 64 bytes long");
const signerIndex = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures).findIndex((pubkey) => pubkey.equals(publicKey));
assert_default(signerIndex >= 0, `Can not add signature; \`${publicKey.toBase58()}\` is not required to sign this transaction`);
this.signatures[signerIndex] = signature;
}
};
// src/programs/system.ts
const SYSTEM_PROGRAM_ID = new PublicKey(SYSTEM_PROGRAM_ADDRESS);
/**
* System Instruction class
*/
var SystemInstruction = class {
/**
* @internal
*/
constructor() {}
/**
* Decode a system instruction and retrieve the instruction type.
*/
static decodeInstructionType(instruction) {
this.checkProgramId(instruction.programId);
return GENERATED_TO_LEGACY_INSTRUCTION_TYPE$4[identifySystemInstruction(instruction.data)];
}
/**
* Decode a create account system instruction and retrieve the instruction params.
*/
static decodeCreateAccount(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.CreateAccount);
return {
fromPubkey: new PublicKey(parsedInstruction.accounts.payer.address),
newAccountPubkey: new PublicKey(parsedInstruction.accounts.newAccount.address),
lamports: parsedInstruction.data.lamports,
space: parsedInstruction.data.space,
programId: new PublicKey(parsedInstruction.data.programAddress)
};
}
/**
* Decode a transfer system instruction and retrieve the instruction params.
*/
static decodeTransfer(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.TransferSol);
return {
fromPubkey: new PublicKey(parsedInstruction.accounts.source.address),
toPubkey: new PublicKey(parsedInstruction.accounts.destination.address),
lamports: parsedInstruction.data.amount
};
}
/**
* Decode a transfer with seed system instruction and retrieve the instruction params.
*/
static decodeTransferWithSeed(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.TransferSolWithSeed);
return {
fromPubkey: new PublicKey(parsedInstruction.accounts.source.address),
basePubkey: new PublicKey(parsedInstruction.accounts.baseAccount.address),
toPubkey: new PublicKey(parsedInstruction.accounts.destination.address),
lamports: parsedInstruction.data.amount,
seed: parsedInstruction.data.fromSeed,
programId: new PublicKey(parsedInstruction.data.fromOwner)
};
}
/**
* Decode an allocate system instruction and retrieve the instruction params.
*/
static decodeAllocate(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.Allocate);
return {
accountPubkey: new PublicKey(parsedInstruction.accounts.newAccount.address),
space: parsedInstruction.data.space
};
}
/**
* Decode an allocate with seed system instruction and retrieve the instruction params.
*/
static decodeAllocateWithSeed(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.AllocateWithSeed);
return {
accountPubkey: new PublicKey(parsedInstruction.accounts.newAccount.address),
basePubkey: new PublicKey(parsedInstruction.data.base),
seed: parsedInstruction.data.seed,
space: parsedInstruction.data.space,
programId: new PublicKey(parsedInstruction.data.programAddress)
};
}
/**
* Decode an assign system instruction and retrieve the instruction params.
*/
static decodeAssign(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.Assign);
return {
accountPubkey: new PublicKey(parsedInstruction.accounts.account.address),
programId: new PublicKey(parsedInstruction.data.programAddress)
};
}
/**
* Decode an assign with seed system instruction and retrieve the instruction params.
*/
static decodeAssignWithSeed(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.AssignWithSeed);
return {
accountPubkey: new PublicKey(parsedInstruction.accounts.account.address),
basePubkey: new PublicKey(parsedInstruction.data.base),
seed: parsedInstruction.data.seed,
programId: new PublicKey(parsedInstruction.data.programAddress)
};
}
/**
* Decode a create account with seed system instruction and retrieve the instruction params.
*/
static decodeCreateWithSeed(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.CreateAccountWithSeed);
return {
fromPubkey: new PublicKey(parsedInstruction.accounts.payer.address),
newAccountPubkey: new PublicKey(parsedInstruction.accounts.newAccount.address),
basePubkey: new PublicKey(parsedInstruction.data.base),
seed: parsedInstruction.data.seed,
lamports: parsedInstruction.data.amount,
space: parsedInstruction.data.space,
programId: new PublicKey(parsedInstruction.data.programAddress)
};
}
/**
* Decode a nonce initialize system instruction and retrieve the instruction params.
*/
static decodeNonceInitialize(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.InitializeNonceAccount);
return {
noncePubkey: new PublicKey(parsedInstruction.accounts.nonceAccount.address),
authorizedPubkey: new PublicKey(parsedInstruction.data.nonceAuthority)
};
}
/**
* Decode a nonce advance system instruction and retrieve the instruction params.
*/
static decodeNonceAdvance(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.AdvanceNonceAccount);
return {
noncePubkey: new PublicKey(parsedInstruction.accounts.nonceAccount.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.nonceAuthority.address)
};
}
/**
* Decode a nonce withdraw system instruction and retrieve the instruction params.
*/
static decodeNonceWithdraw(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.WithdrawNonceAccount);
return {
noncePubkey: new PublicKey(parsedInstruction.accounts.nonceAccount.address),
toPubkey: new PublicKey(parsedInstruction.accounts.recipientAccount.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.nonceAuthority.address),
lamports: parsedInstruction.data.withdrawAmount
};
}
/**
* Decode a nonce authorize system instruction and retrieve the instruction params.
*/
static decodeNonceAuthorize(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseSystemInstructionOfType(instruction, SystemInstruction$1.AuthorizeNonceAccount);
return {
noncePubkey: new PublicKey(parsedInstruction.accounts.nonceAccount.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.nonceAuthority.address),
newAuthorizedPubkey: new PublicKey(parsedInstruction.data.newNonceAuthority)
};
}
/**
* @internal
*/
static checkProgramId(programId) {
if (!programId.equals(SystemProgram.programId)) throw new Error("invalid instruction; programId is not SystemProgram");
}
};
const GENERATED_TO_LEGACY_INSTRUCTION_TYPE$4 = {
[SystemInstruction$1.AdvanceNonceAccount]: "AdvanceNonceAccount",
[SystemInstruction$1.Allocate]: "Allocate",
[SystemInstruction$1.AllocateWithSeed]: "AllocateWithSeed",
[SystemInstruction$1.Assign]: "Assign",
[SystemInstruction$1.AssignWithSeed]: "AssignWithSeed",
[SystemInstruction$1.AuthorizeNonceAccount]: "AuthorizeNonceAccount",
[SystemInstruction$1.CreateAccount]: "Create",
[SystemInstruction$1.CreateAccountAllowPrefund]: "CreateAllowPrefund",
[SystemInstruction$1.CreateAccountWithSeed]: "CreateWithSeed",
[SystemInstruction$1.InitializeNonceAccount]: "InitializeNonceAccount",
[SystemInstruction$1.TransferSol]: "Transfer",
[SystemInstruction$1.TransferSolWithSeed]: "TransferWithSeed",
[SystemInstruction$1.UpgradeNonceAccount]: "UpgradeNonceAccount",
[SystemInstruction$1.WithdrawNonceAccount]: "WithdrawNonceAccount"
};
function parseSystemInstructionOfType(instruction, expectedInstructionType) {
const parsedInstruction = parseSystemInstruction(toKitInstruction(instruction));
if (parsedInstruction.instructionType !== expectedInstructionType) throw new Error("invalid instruction; instruction type mismatch");
return parsedInstruction;
}
/**
* Factory class for transactions to interact with the System program
*/
var SystemProgram = class SystemProgram {
/**
* @internal
*/
constructor() {}
/**
* Public key that identifies the System program
*/
static programId = SYSTEM_PROGRAM_ID;
/**
* Generate a transaction instruction that creates a new account
*/
static createAccount(params) {
return fromKitInstruction(getCreateAccountInstruction({
payer: createNoopSigner(params.fromPubkey.toBase58()),
newAccount: createNoopSigner(params.newAccountPubkey.toBase58()),
lamports: params.lamports,
space: params.space,
programAddress: params.programId.toBase58()
}));
}
/**
* Generate a transaction instruction that transfers lamports from one account to another
*/
static transfer(params) {
if ("basePubkey" in params) return fromKitInstruction(getTransferSolWithSeedInstruction({
source: params.fromPubkey.toBase58(),
baseAccount: createNoopSigner(params.basePubkey.toBase58()),
destination: params.toPubkey.toBase58(),
amount: BigInt(params.lamports),
fromSeed: params.seed,
fromOwner: params.programId.toBase58()
}));
else return fromKitInstruction(getTransferSolInstruction({
source: createNoopSigner(params.fromPubkey.toBase58()),
destination: params.toPubkey.toBase58(),
amount: BigInt(params.lamports)
}));
}
/**
* Generate a transaction instruction that assigns an account to a program
*/
static assign(params) {
if ("basePubkey" in params) return fromKitInstruction(getAssignWithSeedInstruction({
account: params.accountPubkey.toBase58(),
baseAccount: createNoopSigner(params.basePubkey.toBase58()),
base: params.basePubkey.toBase58(),
seed: params.seed,
programAddress: params.programId.toBase58()
}));
else return fromKitInstruction(getAssignInstruction({
account: createNoopSigner(params.accountPubkey.toBase58()),
programAddress: params.programId.toBase58()
}));
}
/**
* Generate a transaction instruction that creates a new account at
* an address generated with `from`, a seed, and programId
*/
static createAccountWithSeed(params) {
return fromKitInstruction(getCreateAccountWithSeedInstruction({
payer: createNoopSigner(params.fromPubkey.toBase58()),
newAccount: params.newAccountPubkey.toBase58(),
...params.basePubkey.equals(params.fromPubkey) ? {} : { baseAccount: createNoopSigner(params.basePubkey.toBase58()) },
base: params.basePubkey.toBase58(),
seed: params.seed,
amount: params.lamports,
space: params.space,
programAddress: params.programId.toBase58()
}));
}
/**
* Generate a transaction that creates a new Nonce account
*
* Durable nonces are planned for deprecation on Solana. They remain valid on
* mainnet today and no removal date is set. See
* {@link https://solana.com/upgrades/durable-nonce-deprecation} for the
* timeline and migration guidance.
*/
static createNonceAccount(params) {
const transaction = new Transaction();
if ("basePubkey" in params && "seed" in params) transaction.add(SystemProgram.createAccountWithSeed({
fromPubkey: params.fromPubkey,
newAccountPubkey: params.noncePubkey,
basePubkey: params.basePubkey,
seed: params.seed,
lamports: params.lamports,
space: NONCE_ACCOUNT_LENGTH,
programId: this.programId
}));
else transaction.add(SystemProgram.createAccount({
fromPubkey: params.fromPubkey,
newAccountPubkey: params.noncePubkey,
lamports: params.lamports,
space: NONCE_ACCOUNT_LENGTH,
programId: this.programId
}));
const initParams = {
noncePubkey: params.noncePubkey,
authorizedPubkey: params.authorizedPubkey
};
transaction.add(this.nonceInitialize(initParams));
return transaction;
}
/**
* Generate an instruction to initialize a Nonce account
*
* Durable nonces are planned for deprecation on Solana. They remain valid on
* mainnet today and no removal date is set. See
* {@link https://solana.com/upgrades/durable-nonce-deprecation} for the
* timeline and migration guidance.
*/
static nonceInitialize(params) {
return fromKitInstruction(getInitializeNonceAccountInstruction({
nonceAccount: params.noncePubkey.toBase58(),
recentBlockhashesSysvar: SYSVAR_RECENT_BLOCKHASHES_PUBKEY.toBase58(),
rentSysvar: SYSVAR_RENT_PUBKEY.toBase58(),
nonceAuthority: params.authorizedPubkey.toBase58()
}));
}
/**
* Generate an instruction to advance the nonce in a Nonce account
*
* Durable nonces are planned for deprecation on Solana. They remain valid on
* mainnet today and no removal date is set. See
* {@link https://solana.com/upgrades/durable-nonce-deprecation} for the
* timeline and migration guidance.
*/
static nonceAdvance(params) {
return fromKitInstruction(getAdvanceNonceAccountInstruction({
nonceAccount: params.noncePubkey.toBase58(),
recentBlockhashesSysvar: SYSVAR_RECENT_BLOCKHASHES_PUBKEY.toBase58(),
nonceAuthority: createNoopSigner(params.authorizedPubkey.toBase58())
}));
}
/**
* Generate a transaction instruction that withdraws lamports from a Nonce account
*
* Durable nonces are planned for deprecation on Solana. They remain valid on
* mainnet today and no removal date is set. See
* {@link https://solana.com/upgrades/durable-nonce-deprecation} for the
* timeline and migration guidance.
*/
static nonceWithdraw(params) {
return fromKitInstruction(getWithdrawNonceAccountInstruction({
nonceAccount: params.noncePubkey.toBase58(),
recipientAccount: params.toPubkey.toBase58(),
recentBlockhashesSysvar: SYSVAR_RECENT_BLOCKHASHES_PUBKEY.toBase58(),
rentSysvar: SYSVAR_RENT_PUBKEY.toBase58(),
nonceAuthority: createNoopSigner(params.authorizedPubkey.toBase58()),
withdrawAmount: params.lamports
}));
}
/**
* Generate a transaction instruction that authorizes a new PublicKey as the authority
* on a Nonce account.
*
* Durable nonces are planned for deprecation on Solana. They remain valid on
* mainnet today and no removal date is set. See
* {@link https://solana.com/upgrades/durable-nonce-deprecation} for the
* timeline and migration guidance.
*/
static nonceAuthorize(params) {
return fromKitInstruction(getAuthorizeNonceAccountInstruction({
nonceAccount: params.noncePubkey.toBase58(),
nonceAuthority: createNoopSigner(params.authorizedPubkey.toBase58()),
newNonceAuthority: params.newAuthorizedPubkey.toBase58()
}));
}
/**
* Generate a transaction instruction that allocates space in an account without funding
*/
static allocate(params) {
if ("basePubkey" in params) return fromKitInstruction(getAllocateWithSeedInstruction({
newAccount: params.accountPubkey.toBase58(),
baseAccount: createNoopSigner(params.basePubkey.toBase58()),
base: params.basePubkey.toBase58(),
seed: params.seed,
space: params.space,
programAddress: params.programId.toBase58()
}));
else return fromKitInstruction(getAllocateInstruction({
newAccount: createNoopSigner(params.accountPubkey.toBase58()),
space: params.space
}));
}
};
// src/errors.ts
const LOG_FETCH_RETRY_DELAY_MS = 500;
const LOG_FETCH_RETRY_ATTEMPTS = 10;
var SendTransactionError = class extends Error {
signature;
transactionMessage;
transactionLogs;
constructor({ action, signature, transactionMessage, logs }) {
const maybeLogsOutput = logs ? `Logs: \n${JSON.stringify(logs.slice(-10), null, 2)}. ` : "";
const guideText = "\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";
let message;
switch (action) {
case "send":
message = `Transaction ${signature} resulted in an error. \n${transactionMessage}. ` + maybeLogsOutput + guideText;
break;
case "simulate":
message = `Simulation failed. \nMessage: ${transactionMessage}. \n` + maybeLogsOutput + guideText;
break;
default: message = `Unknown action '${String(((a) => a)(action))}'`;
}
super(message);
this.signature = signature;
this.transactionMessage = transactionMessage;
this.transactionLogs = logs ? logs : void 0;
}
get transactionError() {
return {
message: this.transactionMessage,
logs: Array.isArray(this.transactionLogs) ? this.transactionLogs : void 0
};
}
get logs() {
const cachedLogs = this.transactionLogs;
if (cachedLogs != null && typeof cachedLogs === "object" && "then" in cachedLogs) return;
return cachedLogs;
}
async getLogs(connection) {
if (!Array.isArray(this.transactionLogs)) this.transactionLogs = (async () => {
try {
for (let attempt = 0; attempt < LOG_FETCH_RETRY_ATTEMPTS; attempt++) {
const tx = await connection.getTransaction(this.signature);
if (tx?.meta?.logMessages) {
const logs = tx.meta.logMessages;
this.transactionLogs = logs;
return logs;
}
if (attempt + 1 < LOG_FETCH_RETRY_ATTEMPTS) await new Promise((resolve) => {
setTimeout(resolve, LOG_FETCH_RETRY_DELAY_MS);
});
}
throw new Error("Log messages not found");
} catch (error) {
this.transactionLogs = void 0;
throw error;
}
})();
return await this.transactionLogs;
}
};
const SolanaJSONRPCErrorCode = {
JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,
JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,
JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,
JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,
JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,
JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,
JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,
JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,
JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,
JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,
JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,
JSON_RPC_SCAN_ERROR: -32012,
JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,
JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,
JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,
JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016
};
var SolanaJSONRPCError = class extends Error {
code;
data;
constructor({ code, message, data }, customMessage) {
super(customMessage != null ? `${customMessage}: ${message}` : message);
this.code = code;
this.data = data;
this.name = "SolanaJSONRPCError";
}
};
// src/utils/send-and-confirm-transaction.ts
/**
* Sign, send and confirm a transaction.
*
* If `commitment` option is not specified, falls back to the connection's
* commitment, then to 'finalized'.
*
* @param {Connection} connection
* @param {Transaction} transaction
* @param {Array<TransactionPartialSigner>} signers
* @param {ConfirmOptions} [options]
* @returns {Promise<TransactionSignature>}
*/
async function sendAndConfirmTransaction(connection, transaction, signers, options) {
const sendOptions = options && {
skipPreflight: options.skipPreflight,
preflightCommitment: options.preflightCommitment || options.commitment,
maxRetries: options.maxRetries,
minContextSlot: options.minContextSlot
};
const commitment = options?.commitment ?? connection.commitment ?? "finalized";
const abortSignal = options?.abortSignal;
let nonceAccountPubkey;
if (transaction.nonceInfo != null) try {
nonceAccountPubkey = SystemInstruction.decodeNonceAdvance(transaction.nonceInfo.nonceInstruction).noncePubkey;
} catch {
throw new Error("Transaction nonceInfo must contain a valid advance nonce instruction");
}
const signature = await connection.sendTransaction(transaction, signers, sendOptions);
let status;
if (transaction.nonceInfo != null) {
assert_default(nonceAccountPubkey != null);
status = (await connection.confirmTransaction({
abortSignal,
minContextSlot: transaction.minNonceContextSlot,
nonceAccountPubkey,
nonceValue: transaction.nonceInfo.nonce,
signature
}, commitment)).value;
} else if (transaction.recentBlockhash != null && transaction.lastValidBlockHeight != null) status = (await connection.confirmTransaction({
abortSignal,
signature,
blockhash: transaction.recentBlockhash,
lastValidBlockHeight: transaction.lastValidBlockHeight
}, commitment)).value;
else {
if (abortSignal != null) console.warn("sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` or `nonceInfo` are abortable.");
status = (await connection.confirmTransaction(signature, commitment)).value;
}
if (status.err) throw new SendTransactionError({
action: "send",
signature,
transactionMessage: `Status: (${stringifyJsonWithBigInts(status)})`
});
return signature;
}
// src/utils/sleep.ts
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// src/loader.ts
const CHUNK_SIZE = 932;
const U32_CODEC$2 = getU32Codec();
const LOAD_INSTRUCTION_HEADER_CODEC = getStructCodec([
["instruction", U32_CODEC$2],
["offset", U32_CODEC$2],
["bytesLength", U32_CODEC$2],
["bytesLengthPadding", U32_CODEC$2]
]);
const FINALIZE_INSTRUCTION_CODEC = getStructCodec([["instruction", U32_CODEC$2]]);
const encodeLoadInstructionChunk = ({ instruction, offset, bytes, chunkSize, bytesLengthPadding = 0 }) => {
if (bytes.length > chunkSize) throw new Error("instruction data exceeds chunk size");
const header = LOAD_INSTRUCTION_HEADER_CODEC.encode({
instruction,
offset,
bytesLength: bytes.length,
bytesLengthPadding
});
const data = new Uint8Array(header.length + chunkSize);
data.set(header, 0);
data.set(bytes, header.length);
return data;
};
/**
* Program loader interface
*/
var Loader = class Loader {
/**
* @internal
*/
constructor() {}
/**
* Amount of program data placed in each load Transaction
*/
static chunkSize = CHUNK_SIZE;
/**
* Minimum number of signatures required to load a program not including
* retries
*
* Can be used to calculate transaction fees
*/
static getMinNumSignatures(dataLength) {
return 2 * (Math.ceil(dataLength / Loader.chunkSize) + 1 + 1);
}
/**
* Loads a generic program
*
* @param connection The connection to use
* @param payer System account that pays to load the program
* @param program Account to load the program into
* @param programId Public key that identifies the loader
* @param data Program octets
* @return true if program was loaded successfully, false if program was already loaded
*/
static async load(connection, payer, program, programId, data) {
const payerPubkey = new PublicKey(payer.address);
const programPubkey = new PublicKey(program.address);
{
const balanceNeeded = await connection.getMinimumBalanceForRentExemption(data.length);
const programInfo = await connection.getAccountInfo(programPubkey, "confirmed");
let transaction = null;
if (programInfo !== null) {
if (programInfo.executable) {
console.error("Program load failed, account is already executable");
return false;
}
if (programInfo.data.length !== data.length) {
transaction = transaction || new Transaction();
transaction.add(SystemProgram.allocate({
accountPubkey: programPubkey,
space: data.length
}));
}
if (!programInfo.owner.equals(programId)) {
transaction = transaction || new Transaction();
transaction.add(SystemProgram.assign({
accountPubkey: programPubkey,
programId
}));
}
if (programInfo.lamports < BigInt(balanceNeeded)) {
transaction = transaction || new Transaction();
transaction.add(SystemProgram.transfer({
fromPubkey: payerPubkey,
toPubkey: programPubkey,
lamports: BigInt(balanceNeeded) - programInfo.lamports
}));
}
} else transaction = new Transaction().add(SystemProgram.createAccount({
fromPubkey: payerPubkey,
newAccountPubkey: programPubkey,
lamports: Number(balanceNeeded > 0 ? balanceNeeded : 1),
space: data.length,
programId
}));
if (transaction !== null) await sendAndConfirmTransaction(connection, transaction, [payer, program], { commitment: "confirmed" });
}
const chunkSize = Loader.chunkSize;
let offset = 0;
let bytesRemaining = toUint8ArrayView(data);
const transactions = [];
while (bytesRemaining.length > 0) {
const bytes = bytesRemaining.subarray(0, chunkSize);
const data = encodeLoadInstructionChunk({
instruction: 0,
offset,
bytes,
chunkSize
});
const transaction = new Transaction().add({
keys: [{
pubkey: programPubkey,
isSigner: true,
isWritable: true
}],
programId,
data
});
transactions.push(sendAndConfirmTransaction(connection, transaction, [payer, program], { commitment: "confirmed" }));
if (connection._rpcEndpoint.includes("solana.com")) await sleep(250);
offset += chunkSize;
bytesRemaining = bytesRemaining.subarray(chunkSize);
}
await Promise.all(transactions);
{
const data = toUint8ArrayView(FINALIZE_INSTRUCTION_CODEC.encode({ instruction: 1 }));
const transaction = new Transaction().add({
keys: [{
pubkey: programPubkey,
isSigner: true,
isWritable: true
}, {
pubkey: SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false
}],
programId,
data
});
const deployCommitment = "processed";
const finalizeSignature = await connection.sendTransaction(transaction, [payer, program], { preflightCommitment: deployCommitment });
const { context, value } = await connection.confirmTransaction({
signature: finalizeSignature,
lastValidBlockHeight: transaction.lastValidBlockHeight,
blockhash: transaction.recentBlockhash
}, deployCommitment);
if (value.err) throw new Error(`Transaction ${finalizeSignature} failed (${JSON.stringify(value)})`);
while (true) {
try {
if (await connection.getSlot({ commitment: deployCommitment }) > context.slot) break;
} catch {}
await new Promise((resolve) => setTimeout(resolve, Math.round(200)));
}
}
return true;
}
};
// src/bpf-loader.ts
/**
* @deprecated Deprecated since Solana v1.17.20.
*/
const BPF_LOADER_PROGRAM_ID = new PublicKey("BPFLoader2111111111111111111111111111111111");
/**
* Factory class for transactions to interact with a program loader
*
* @deprecated Deprecated since Solana v1.17.20.
*/
var BpfLoader = class {
/**
* Minimum number of signatures required to load a program not including
* retries
*
* Can be used to calculate transaction fees
*/
static getMinNumSignatures(dataLength) {
return Loader.getMinNumSignatures(dataLength);
}
/**
* Load a SBF program
*
* @param connection The connection to use
* @param payer Account that will pay program loading fees
* @param program Account to load the program into
* @param elf The entire ELF containing the SBF program
* @param loaderProgramId The program id of the BPF loader to use
* @return true if program was loaded successfully, false if program was already loaded
*/
static load(connection, payer, program, elf, loaderProgramId) {
return Loader.load(connection, payer, program, loaderProgramId, elf);
}
};
// src/epoch-schedule.ts
const MINIMUM_SLOT_PER_EPOCH = 32n;
function trailingZeros(n) {
let trailingZeros = 0n;
while (n > 1n) {
n /= 2n;
trailingZeros++;
}
return trailingZeros;
}
function nextPowerOfTwo(n) {
if (n === 0n) return 1n;
n--;
n |= n >> 1n;
n |= n >> 2n;
n |= n >> 4n;
n |= n >> 8n;
n |= n >> 16n;
n |= n >> 32n;
return n + 1n;
}
/**
* Epoch schedule
* (see https://docs.solana.com/terminology#epoch)
* Can be retrieved with the {@link Connection.getEpochSchedule} method
*/
var EpochSchedule = class {
/** The maximum number of slots in each epoch */
slotsPerEpoch;
/** The number of slots before beginning of an epoch to calculate a leader schedule for that epoch */
leaderScheduleSlotOffset;
/** Indicates whether epochs start short and grow */
warmup;
/** The first epoch with `slotsPerEpoch` slots */
firstNormalEpoch;
/** The first slot of `firstNormalEpoch` */
firstNormalSlot;
constructor(slotsPerEpoch, leaderScheduleSlotOffset, warmup, firstNormalEpoch, firstNormalSlot) {
this.slotsPerEpoch = slotsPerEpoch;
this.leaderScheduleSlotOffset = leaderScheduleSlotOffset;
this.warmup = warmup;
this.firstNormalEpoch = firstNormalEpoch;
this.firstNormalSlot = firstNormalSlot;
}
getEpoch(slot) {
return this.getEpochAndSlotIndex(slot)[0];
}
getEpochAndSlotIndex(slot) {
if (slot < this.firstNormalSlot) {
const epoch = trailingZeros(nextPowerOfTwo(slot + MINIMUM_SLOT_PER_EPOCH + 1n)) - trailingZeros(MINIMUM_SLOT_PER_EPOCH) - 1n;
return [epoch, slot - (this.getSlotsInEpoch(epoch) - MINIMUM_SLOT_PER_EPOCH)];
} else {
const normalSlotIndex = slot - this.firstNormalSlot;
const normalEpochIndex = normalSlotIndex / this.slotsPerEpoch;
return [this.firstNormalEpoch + normalEpochIndex, normalSlotIndex % this.slotsPerEpoch];
}
}
getFirstSlotInEpoch(epoch) {
if (epoch <= this.firstNormalEpoch) return (2n ** epoch - 1n) * MINIMUM_SLOT_PER_EPOCH;
else return (epoch - this.firstNormalEpoch) * this.slotsPerEpoch + this.firstNormalSlot;
}
getLastSlotInEpoch(epoch) {
return this.getFirstSlotInEpoch(epoch) + this.getSlotsInEpoch(epoch) - 1n;
}
getSlotsInEpoch(epoch) {
if (epoch < this.firstNormalEpoch) return 2n ** (epoch + trailingZeros(MINIMUM_SLOT_PER_EPOCH));
else return this.slotsPerEpoch;
}
};
// src/utils/bigint.ts
function coerceNumericToBigInt(value, valueName) {
if (typeof value === "bigint") return value;
assert_default(Number.isSafeInteger(value), `${valueName ?? "Value"} must be a safe integer or bigint`);
return BigInt(value);
}
function coerceOptionalNumericToBigInt(value, valueName) {
return value == null ? void 0 : coerceNumericToBigInt(value, valueName);
}
function coerceNullableNumericToBigInt(value, valueName) {
return value == null ? null : coerceNumericToBigInt(value, valueName);
}
// src/kit-adapters/request.ts
/**
* Boundary: Connection -> Kit RPC request shaping.
*
* This module translates Connection's public request inputs into the explicit
* request configs expected by Kit RPC calls. Connection methods and
* subscription spec builders use it at the API edge.
*/
const BASE58_ENCODER$3 = getBase58Encoder();
const BASE64_CODEC$3 = getBase64Codec();
function coerceToBase58EncodedBytes(bytes) {
BASE58_ENCODER$3.encode(bytes);
return bytes;
}
function coerceToBase64EncodedBytes(bytes) {
BASE64_CODEC$3.encode(bytes);
return bytes;
}
function getTypedBlockConfigBase(finality, config) {
return {
...finality != null ? { commitment: finality } : null,
...config?.maxSupportedTransactionVersion != null ? { maxSupportedTransactionVersion: config.maxSupportedTransactionVersion } : null,
...config?.rewards != null ? { rewards: config.rewards } : null
};
}
function getTypedBlockWithoutTransactionsConfig(transactionDetails, finality, config) {
return {
...getTypedBlockConfigBase(finality, config),
transactionDetails
};
}
function buildTypedAccountsBlockConfig(finality, config, parseTransactions) {
return parseTransactions ? {
encoding: "jsonParsed",
...getTypedBlockConfigBase(finality, config),
transactionDetails: "accounts"
} : {
...getTypedBlockConfigBase(finality, config),
transactionDetails: "accounts"
};
}
function buildTypedFullBlockConfig(finality, config, hasRawConfig) {
if (config?.transactionDetails === "full") return {
...getTypedBlockConfigBase(finality, config),
transactionDetails: "full"
};
return hasRawConfig ? getTypedBlockConfigBase(finality, config) : void 0;
}
function buildTypedParsedFullBlockConfig(finality, config) {
return {
encoding: "jsonParsed",
...getTypedBlockConfigBase(finality, config),
...config?.transactionDetails === "full" ? { transactionDetails: "full" } : null
};
}
function getTypedTransactionConfigBase(finality, config) {
const minContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
return {
...finality != null ? { commitment: finality } : null,
...config?.maxSupportedTransactionVersion != null ? { maxSupportedTransactionVersion: config.maxSupportedTransactionVersion } : null,
...minContextSlot != null ? { minContextSlot } : null
};
}
function buildTypedTransactionConfig(finality, config) {
const typedConfig = getTypedTransactionConfigBase(finality, config);
return Object.keys(typedConfig).length > 0 ? typedConfig : void 0;
}
function buildTypedParsedTransactionConfig(finality, config) {
return {
encoding: "jsonParsed",
...getTypedTransactionConfigBase(finality, config)
};
}
function buildTypedNumericComparison(comparison, valueName) {
const gt = coerceOptionalNumericToBigInt(comparison.gt, `${valueName}.gt`);
const gte = coerceOptionalNumericToBigInt(comparison.gte, `${valueName}.gte`);
const lt = coerceOptionalNumericToBigInt(comparison.lt, `${valueName}.lt`);
const lte = coerceOptionalNumericToBigInt(comparison.lte, `${valueName}.lte`);
return {
...gt != null ? { gt } : null,
...gte != null ? { gte } : null,
...lt != null ? { lt } : null,
...lte != null ? { lte } : null
};
}
function buildTypedBlockTimeComparison(comparison) {
const { gt, gte, lt, lte } = buildTypedNumericComparison(comparison, "blockTime");
const eq = coerceOptionalNumericToBigInt(comparison.eq, "blockTime.eq");
return {
...eq != null ? { eq } : null,
...gt != null ? { gt } : null,
...gte != null ? { gte } : null,
...lt != null ? { lt } : null,
...lte != null ? { lte } : null
};
}
function buildTypedSignatureComparison(comparison) {
const { gt, gte, lt, lte } = comparison;
[
gt,
gte,
lt,
lte
].forEach((signature) => {
if (signature != null) assertIsSignature(signature);
});
return {
...gt != null ? { gt } : null,
...gte != null ? { gte } : null,
...lt != null ? { lt } : null,
...lte != null ? { lte } : null
};
}
function buildTypedTransactionsForAddressFilters(filters) {
return {
...filters.blockTime != null ? { blockTime: buildTypedBlockTimeComparison(filters.blockTime) } : null,
...filters.signature != null ? { signature: buildTypedSignatureComparison(filters.signature) } : null,
...filters.slot != null ? { slot: buildTypedNumericComparison(filters.slot, "slot") } : null,
...filters.status != null ? { status: filters.status } : null,
...filters.tokenAccounts != null ? { tokenAccounts: filters.tokenAccounts } : null
};
}
function buildTypedTransactionsForAddressConfig(finality, config) {
const isFull = config?.transactionDetails === "full";
const minContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
return {
commitment: finality,
...config?.filters != null ? { filters: buildTypedTransactionsForAddressFilters(config.filters) } : null,
...isFull && config?.encoding != null ? { encoding: config.encoding } : null,
...config?.limit != null ? { limit: config.limit } : null,
...isFull && config?.maxSupportedTransactionVersion != null ? { maxSupportedTransactionVersion: config.maxSupportedTransactionVersion } : null,
...minContextSlot != null ? { minContextSlot } : null,
...config?.paginationToken != null ? { paginationToken: config.paginationToken } : null,
...config?.sortOrder != null ? { sortOrder: config.sortOrder } : null,
...isFull ? { transactionDetails: "full" } : null
};
}
/**
* Always sends `searchTransactionHistory` when a config object is present. Agave
* releases before anza-xyz/agave#15091 reject the config if the field is missing;
* the explicit `false` fallback can be dropped once those releases are no longer
* in use.
*/
function buildTypedSignatureStatusesConfig(config) {
const minContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
const typedConfig = {
...config?.commitment != null ? { commitment: config.commitment } : null,
...minContextSlot != null ? { minContextSlot } : null
};
if (Object.keys(typedConfig).length === 0 && config?.searchTransactionHistory == null) return;
return {
...typedConfig,
searchTransactionHistory: config?.searchTransactionHistory ?? false
};
}
function getTokenAccountsRpcFilter(filter) {
const hasMint = "mint" in filter && filter.mint != null;
if (hasMint === ("programId" in filter && filter.programId != null)) throw new Error("Ambiguous token accounts filter. Supply exactly one of `mint` or `programId`.");
return hasMint ? { mint: filter.mint.toBase58() } : { programId: filter.programId.toBase58() };
}
function getProgramAccountsRpcFilters(filters) {
return filters?.map((filter) => {
const hasMemcmp = "memcmp" in filter && filter.memcmp != null;
if (hasMemcmp === ("dataSize" in filter && filter.dataSize != null)) throw new Error("Ambiguous program accounts filter. Supply exactly one of `memcmp` or `dataSize` per filter.");
if (hasMemcmp) {
const encoding = filter.memcmp.encoding ?? "base58";
if (encoding !== "base58" && encoding !== "base64") throw new Error(`Unsupported memcmp encoding \`${String(encoding)}\`. Expected \`base58\` or \`base64\`.`);
const offset = coerceNumericToBigInt(filter.memcmp.offset, "offset");
return encoding === "base64" ? { memcmp: {
bytes: coerceToBase64EncodedBytes(filter.memcmp.bytes),
encoding: "base64",
offset
} } : { memcmp: {
bytes: coerceToBase58EncodedBytes(filter.memcmp.bytes),
encoding: "base58",
offset
} };
}
return { dataSize: coerceNumericToBigInt(filter.dataSize, "dataSize") };
});
}
// src/kit-adapters/response.ts
/**
* Boundary: Kit payload mapping -> Connection result shapes.
*
* This module centralizes shared mapping helpers for data coming back from
* Kit, including bigint coercion, address normalization, and
* transaction/block mapping. Connection request methods use it for RPC
* responses, and websocket notification adapters reuse the same helpers when
* notification payloads need the same public shaping.
*/
const BASE58_ENCODER$2 = getBase58Encoder();
const BASE64_CODEC$2 = getBase64Codec();
function isRecord$3(value) {
return value != null && typeof value === "object";
}
function assertHasRawAccountRentEpoch(account, expectation) {
assert_default("rentEpoch" in account && typeof account.rentEpoch === "bigint", expectation);
}
function decodeBase64AccountData(value) {
return toUint8ArrayView(BASE64_CODEC$2.encode(value));
}
function mapParsedAccountData(data) {
return {
parsed: data.parsed,
program: data.program,
space: data.space
};
}
function mapBase64AccountInfo(account, expectation = "Expected raw account info rentEpoch") {
if (account == null) return null;
assertHasRawAccountRentEpoch(account, expectation);
return {
executable: account.executable,
owner: new PublicKey(account.owner),
lamports: account.lamports,
data: decodeBase64AccountData(account.data[0]),
rentEpoch: account.rentEpoch,
space: account.space
};
}
function mapJsonParsedAccountInfo(account, expectation = "Expected parsed account info rentEpoch") {
if (account == null) return null;
assertHasRawAccountRentEpoch(account, expectation);
return {
executable: account.executable,
owner: new PublicKey(account.owner),
lamports: account.lamports,
data: Array.isArray(account.data) ? decodeBase64AccountData(account.data[0]) : mapParsedAccountData(account.data),
rentEpoch: account.rentEpoch,
space: account.space
};
}
function mapParsedAccountInfo(account, expectation = "Expected parsed account info rentEpoch") {
if (account == null) return null;
assertHasRawAccountRentEpoch(account, expectation);
return {
executable: account.executable,
owner: new PublicKey(account.owner),
lamports: account.lamports,
data: mapParsedAccountData(account.data),
rentEpoch: account.rentEpoch,
space: account.space
};
}
function mapKeyedAccounts(value, mapAccount) {
return value.map(({ account, pubkey }) => ({
account: mapAccount(account),
pubkey: new PublicKey(pubkey)
}));
}
function mapKeyedBase64AccountInfos(value, expectation = "Expected raw account info rentEpoch") {
return mapKeyedAccounts(value, (account) => mapBase64AccountInfo(account, expectation));
}
function mapKeyedJsonParsedAccountInfos(value, expectation = "Expected parsed account info rentEpoch") {
return mapKeyedAccounts(value, (account) => mapJsonParsedAccountInfo(account, expectation));
}
function mapKeyedParsedAccountInfos(value, expectation = "Expected parsed account info rentEpoch") {
return mapKeyedAccounts(value, (account) => mapParsedAccountInfo(account, expectation));
}
function mapSimulatedAccountInfo(account) {
if (account == null) return null;
let rentEpoch;
if (account.rentEpoch != null) {
assert_default(typeof account.rentEpoch === "bigint", "Expected simulated account rentEpoch to be bigint");
rentEpoch = account.rentEpoch;
}
return {
data: [account.data[0], account.data[1]],
executable: account.executable,
lamports: account.lamports,
owner: account.owner,
rentEpoch,
space: account.space
};
}
function mapSimulatedAccounts(accounts) {
return accounts == null ? null : accounts.map(mapSimulatedAccountInfo);
}
function isRawSimulatedReplacementBlockhash(value) {
return isRecord$3(value) && typeof value.blockhash === "string" && typeof value.lastValidBlockHeight === "bigint";
}
function mapSimulatedReplacementBlockhash(replacementBlockhash) {
return {
blockhash: blockhash(replacementBlockhash.blockhash),
lastValidBlockHeight: replacementBlockhash.lastValidBlockHeight
};
}
function mapSimulatedReturnData(returnData) {
if (returnData == null) return null;
return {
data: [returnData.data[0], returnData.data[1]],
programId: returnData.programId
};
}
function isRpcParsedInnerInstructions(innerInstructions) {
return Array.isArray(innerInstructions) && innerInstructions.every(({ instructions }) => instructions.every((instruction) => isRecord$3(instruction) && "programId" in instruction));
}
function mapBlockRewards(rewards) {
return rewards?.map((reward) => ({
commission: reward.commission,
lamports: coerceNumericToBigInt(reward.lamports, "lamports"),
postBalance: reward.postBalance == null ? null : coerceNumericToBigInt(reward.postBalance, "postBalance"),
pubkey: reward.pubkey,
rewardType: reward.rewardType
}));
}
function mapBlockBase(block) {
return {
...block,
blockhash: blockhash(block.blockhash),
blockHeight: block.blockHeight == null ? null : coerceNumericToBigInt(block.blockHeight, "blockHeight"),
blockTime: block.blockTime == null ? null : coerceNumericToBigInt(block.blockTime, "blockTime"),
parentSlot: coerceNumericToBigInt(block.parentSlot, "parentSlot"),
previousBlockhash: blockhash(block.previousBlockhash),
rewards: mapBlockRewards(block.rewards)
};
}
function mapSimulatedTransactionResponseValue(value) {
const mappedValue = {
err: value.err,
logs: value.logs == null ? null : [...value.logs]
};
if ("accounts" in value) mappedValue.accounts = mapSimulatedAccounts(value.accounts ?? null);
if ("fee" in value) mappedValue.fee = value.fee == null ? null : coerceNumericToBigInt(value.fee, "fee");
if ("preBalances" in value) mappedValue.preBalances = value.preBalances == null ? null : value.preBalances.map((balance) => coerceNumericToBigInt(balance, "preBalance"));
if ("postBalances" in value) mappedValue.postBalances = value.postBalances == null ? null : value.postBalances.map((balance) => coerceNumericToBigInt(balance, "postBalance"));
if ("preTokenBalances" in value) mappedValue.preTokenBalances = cloneOptionalArray(value.preTokenBalances) ?? null;
if ("postTokenBalances" in value) mappedValue.postTokenBalances = cloneOptionalArray(value.postTokenBalances) ?? null;
if ("loadedAddresses" in value) mappedValue.loadedAddresses = value.loadedAddresses == null ? null : mapLoadedAddresses(value.loadedAddresses);
if (value.loadedAccountsDataSize !== void 0) mappedValue.loadedAccountsDataSize = value.loadedAccountsDataSize;
if ("replacementBlockhash" in value && isRawSimulatedReplacementBlockhash(value.replacementBlockhash)) mappedValue.replacementBlockhash = mapSimulatedReplacementBlockhash(value.replacementBlockhash);
if (value.unitsConsumed !== void 0) mappedValue.unitsConsumed = value.unitsConsumed;
if ("returnData" in value) mappedValue.returnData = mapSimulatedReturnData(value.returnData ?? null);
if ("innerInstructions" in value) {
const innerInstructions = value.innerInstructions;
assert_default(innerInstructions == null || isRpcParsedInnerInstructions(innerInstructions), "Expected parsed inner instructions in simulateTransaction result");
mappedValue.innerInstructions = mapRpcParsedInnerInstructions(innerInstructions ?? null);
}
return mappedValue;
}
function legacyMessageFromResponse(message, recentBlockhash) {
return new Message({
accountKeys: [...message.accountKeys],
header: message.header,
instructions: message.instructions.map((ix) => ({
...ix.stackHeight != null ? { stackHeight: ix.stackHeight } : null,
accounts: [...ix.accounts],
data: ix.data,
programIdIndex: ix.programIdIndex
})),
recentBlockhash
});
}
function version0MessageFromResponse(message, recentBlockhash) {
return new MessageV0({
header: message.header,
staticAccountKeys: message.accountKeys.map((accountKey) => new PublicKey(accountKey)),
recentBlockhash,
compiledInstructions: message.instructions.map((ix) => ({
programIdIndex: ix.programIdIndex,
accountKeyIndexes: [...ix.accounts],
data: toUint8ArrayView(BASE58_ENCODER$2.encode(ix.data))
})),
addressTableLookups: message.addressTableLookups?.map(mapParsedAddressTableLookup) ?? []
});
}
function mapTransactionConfigResponse(config) {
const mapped = {};
if (config.computeUnitLimit != null) mapped.computeUnitLimit = Number(config.computeUnitLimit);
if (config.heapSize != null) mapped.heapSize = Number(config.heapSize);
if (config.loadedAccountsDataSizeLimit != null) mapped.loadedAccountsDataSizeLimit = Number(config.loadedAccountsDataSizeLimit);
if (config.priorityFee != null) mapped.priorityFeeLamports = coerceNumericToBigInt(config.priorityFee, "priorityFee");
return Object.keys(mapped).length > 0 ? mapped : void 0;
}
function version1MessageFromResponse(message, recentBlockhash) {
return new MessageV1({
header: message.header,
staticAccountKeys: message.accountKeys.map((accountKey) => new PublicKey(accountKey)),
recentBlockhash,
compiledInstructions: message.instructions.map((ix) => ({
programIdIndex: ix.programIdIndex,
accountKeyIndexes: [...ix.accounts],
data: toUint8ArrayView(BASE58_ENCODER$2.encode(ix.data))
})),
transactionConfig: message.transactionConfig != null ? mapTransactionConfigResponse(message.transactionConfig) : void 0
});
}
function isVersion0Message(version, message) {
return version === 0;
}
function isVersion1Message(version, message) {
return version === 1;
}
function versionedMessageFromResponse(version, message) {
const recentBlockhash = blockhash(message.recentBlockhash);
if (isVersion0Message(version, message)) return version0MessageFromResponse(message, recentBlockhash);
if (isVersion1Message(version, message)) return version1MessageFromResponse(message, recentBlockhash);
return legacyMessageFromResponse(message, recentBlockhash);
}
function mapLoadedAddresses(loadedAddresses) {
return {
readonly: loadedAddresses.readonly.map((address) => address instanceof PublicKey ? address : new PublicKey(address)),
writable: loadedAddresses.writable.map((address) => address instanceof PublicKey ? address : new PublicKey(address))
};
}
function hasCostUnits(value) {
return "costUnits" in value && (typeof value.costUnits === "number" || typeof value.costUnits === "bigint");
}
function hasLoadedAddresses(value) {
return "loadedAddresses" in value;
}
function mapParsedMessageAccount(account) {
return {
...account,
pubkey: account.pubkey instanceof PublicKey ? account.pubkey : new PublicKey(account.pubkey)
};
}
function mapParsedAddressTableLookup(lookup) {
return {
...lookup,
accountKey: lookup.accountKey instanceof PublicKey ? lookup.accountKey : new PublicKey(lookup.accountKey),
readonlyIndexes: [...lookup.readonlyIndexes],
writableIndexes: [...lookup.writableIndexes]
};
}
function mapRpcParsedInstruction(instruction) {
if ("parsed" in instruction) return {
...instruction.stackHeight != null ? { stackHeight: instruction.stackHeight } : null,
parsed: instruction.parsed,
program: instruction.program,
programId: instruction.programId instanceof PublicKey ? instruction.programId : new PublicKey(instruction.programId)
};
return {
...instruction.stackHeight != null ? { stackHeight: instruction.stackHeight } : null,
accounts: instruction.accounts.map((account) => account instanceof PublicKey ? account : new PublicKey(account)),
data: instruction.data,
programId: instruction.programId instanceof PublicKey ? instruction.programId : new PublicKey(instruction.programId)
};
}
function cloneOptionalArray(value) {
return value == null ? value : [...value];
}
function mapRpcParsedInnerInstructions(innerInstructions) {
if (innerInstructions == null) return null;
return innerInstructions.map(({ index, instructions }) => ({
index,
instructions: instructions.map(mapRpcParsedInstruction)
}));
}
function mapTypedFullBlockMeta(meta) {
if (meta == null) return null;
const mappedMeta = hasCostUnits(meta) ? {
...meta,
costUnits: coerceNumericToBigInt(meta.costUnits, "costUnits")
} : meta;
if (hasLoadedAddresses(mappedMeta) && mappedMeta.loadedAddresses != null) return {
...mappedMeta,
loadedAddresses: mapLoadedAddresses(mappedMeta.loadedAddresses)
};
return mappedMeta;
}
function mapTypedParsedBlockMeta(meta) {
if (meta == null) return null;
const mappedMeta = hasCostUnits(meta) ? {
...meta,
costUnits: coerceNumericToBigInt(meta.costUnits, "costUnits")
} : meta;
if (hasLoadedAddresses(mappedMeta)) {
const { innerInstructions, loadedAddresses, ...rest } = mappedMeta;
return {
...rest,
...innerInstructions != null ? { innerInstructions: mapRpcParsedInnerInstructions(innerInstructions) } : null,
...loadedAddresses != null ? { loadedAddresses: mapLoadedAddresses(loadedAddresses) } : null
};
}
const { innerInstructions, ...rest } = mappedMeta;
return {
...rest,
...innerInstructions != null ? { innerInstructions: mapRpcParsedInnerInstructions(innerInstructions) } : null
};
}
function mapTypedAccountsModeBlockTransactions(transactions) {
return transactions.map((transactionResponse) => {
const meta = transactionResponse.meta != null && hasCostUnits(transactionResponse.meta) ? {
...transactionResponse.meta,
costUnits: coerceNumericToBigInt(transactionResponse.meta.costUnits, "costUnits")
} : transactionResponse.meta;
return {
..."version" in transactionResponse ? { version: normalizeTransactionVersion(transactionResponse.version) } : null,
meta,
transaction: {
...transactionResponse.transaction,
accountKeys: transactionResponse.transaction.accountKeys.map(mapParsedMessageAccount),
signatures: [...transactionResponse.transaction.signatures]
}
};
});
}
function mapTypedFullBlockTransaction(transactionResponse) {
const version = normalizeTransactionVersion("version" in transactionResponse ? transactionResponse.version : void 0);
return {
...version != null ? { version } : null,
meta: mapTypedFullBlockMeta(transactionResponse.meta),
transaction: {
...transactionResponse.transaction,
signatures: [...transactionResponse.transaction.signatures],
message: versionedMessageFromResponse(version, transactionResponse.transaction.message)
}
};
}
function mapParsedTransaction(transaction) {
const addressTableLookups = "addressTableLookups" in transaction.message && Array.isArray(transaction.message.addressTableLookups) ? transaction.message.addressTableLookups.map(mapParsedAddressTableLookup) : null;
const { transactionConfig: rawTransactionConfig, ...rawMessage } = transaction.message;
const transactionConfig = rawTransactionConfig != null ? mapTransactionConfigResponse(rawTransactionConfig) : void 0;
return {
...transaction,
signatures: [...transaction.signatures],
message: {
...rawMessage,
accountKeys: transaction.message.accountKeys.map(mapParsedMessageAccount),
...addressTableLookups != null ? { addressTableLookups } : null,
...transactionConfig != null ? { transactionConfig } : null,
instructions: transaction.message.instructions.map(mapRpcParsedInstruction)
}
};
}
function mapTypedParsedBlockTransaction(transactionResponse) {
const version = normalizeTransactionVersion("version" in transactionResponse ? transactionResponse.version : void 0);
return {
...version != null ? { version } : null,
meta: mapTypedParsedBlockMeta(transactionResponse.meta),
transaction: mapParsedTransaction(transactionResponse.transaction)
};
}
function mapTransactionMetaCompat(meta) {
if (meta == null) return null;
return {
...meta.computeUnitsConsumed != null ? { computeUnitsConsumed: coerceNumericToBigInt(meta.computeUnitsConsumed, "computeUnitsConsumed") } : null,
err: meta.err,
fee: coerceNumericToBigInt(meta.fee, "fee"),
innerInstructions: meta.innerInstructions == null ? meta.innerInstructions : meta.innerInstructions.map(({ index, instructions }) => ({
index,
instructions: instructions.map((ix) => ({
...ix.stackHeight != null ? { stackHeight: ix.stackHeight } : null,
accounts: [...ix.accounts],
data: ix.data,
programIdIndex: ix.programIdIndex
}))
})),
...hasLoadedAddresses(meta) && meta.loadedAddresses != null ? { loadedAddresses: mapLoadedAddresses(meta.loadedAddresses) } : null,
logMessages: meta.logMessages == null ? null : [...meta.logMessages],
postBalances: meta.postBalances.map((balance) => coerceNumericToBigInt(balance, "postBalance")),
..."postTokenBalances" in meta ? { postTokenBalances: cloneOptionalArray(meta.postTokenBalances) } : null,
preBalances: meta.preBalances.map((balance) => coerceNumericToBigInt(balance, "preBalance")),
..."preTokenBalances" in meta ? { preTokenBalances: cloneOptionalArray(meta.preTokenBalances) } : null,
..."returnData" in meta ? { returnData: mapSimulatedReturnData(meta.returnData ?? null) } : null,
..."rewards" in meta ? { rewards: meta.rewards == null ? meta.rewards : mapBlockRewards(meta.rewards) } : null,
...hasCostUnits(meta) ? { costUnits: coerceNumericToBigInt(meta.costUnits, "costUnits") } : null
};
}
function mapParsedTransactionMetaCompat(meta) {
if (meta == null) return null;
return {
...meta.computeUnitsConsumed != null ? { computeUnitsConsumed: coerceNumericToBigInt(meta.computeUnitsConsumed, "computeUnitsConsumed") } : null,
err: meta.err,
fee: coerceNumericToBigInt(meta.fee, "fee"),
innerInstructions: meta.innerInstructions == null ? meta.innerInstructions : meta.innerInstructions.map(({ index, instructions }) => ({
index,
instructions: instructions.map(mapRpcParsedInstruction)
})),
...hasLoadedAddresses(meta) && meta.loadedAddresses != null ? { loadedAddresses: mapLoadedAddresses(meta.loadedAddresses) } : null,
logMessages: meta.logMessages == null ? null : [...meta.logMessages],
postBalances: meta.postBalances.map((balance) => coerceNumericToBigInt(balance, "postBalance")),
..."postTokenBalances" in meta ? { postTokenBalances: cloneOptionalArray(meta.postTokenBalances) } : null,
preBalances: meta.preBalances.map((balance) => coerceNumericToBigInt(balance, "preBalance")),
..."preTokenBalances" in meta ? { preTokenBalances: cloneOptionalArray(meta.preTokenBalances) } : null,
..."returnData" in meta ? { returnData: mapSimulatedReturnData(meta.returnData ?? null) } : null,
..."rewards" in meta ? { rewards: meta.rewards == null ? meta.rewards : mapBlockRewards(meta.rewards) } : null,
...hasCostUnits(meta) ? { costUnits: coerceNumericToBigInt(meta.costUnits, "costUnits") } : null
};
}
function normalizeTransactionVersion(version) {
if (version === void 0 || version === "legacy") return version;
const numericVersion = typeof version === "bigint" ? Number(version) : version;
assert_default(numericVersion === 0 || numericVersion === 1, `Unsupported transaction version: ${String(version)}`);
return numericVersion;
}
function mapTypedTransactionResponse(response) {
const version = normalizeTransactionVersion("version" in response ? response.version : void 0);
return {
blockTime: response.blockTime == null ? null : coerceNumericToBigInt(response.blockTime, "blockTime"),
meta: mapTransactionMetaCompat(response.meta),
slot: coerceNumericToBigInt(response.slot, "slot"),
transaction: {
...response.transaction,
message: versionedMessageFromResponse(version, response.transaction.message),
signatures: [...response.transaction.signatures]
},
...version != null ? { version } : null
};
}
function mapTypedEncodedTransactionResponse(response) {
const version = normalizeTransactionVersion("version" in response ? response.version : void 0);
return {
blockTime: response.blockTime == null ? null : coerceNumericToBigInt(response.blockTime, "blockTime"),
meta: mapTransactionMetaCompat(response.meta),
slot: coerceNumericToBigInt(response.slot, "slot"),
transaction: response.transaction,
...version != null ? { version } : null
};
}
function mapTypedParsedTransactionResponse(response) {
const version = normalizeTransactionVersion("version" in response ? response.version : void 0);
return {
blockTime: response.blockTime == null ? null : coerceNumericToBigInt(response.blockTime, "blockTime"),
meta: mapParsedTransactionMetaCompat(response.meta),
slot: coerceNumericToBigInt(response.slot, "slot"),
transaction: mapParsedTransaction(response.transaction),
...version != null ? { version } : null
};
}
// src/kit-adapters/subscription-specs.ts
function normalizeDeprecatedProgramSubscriptionFilters(filters) {
return getProgramAccountsRpcFilters(filters);
}
function buildAccountSubscriptionSpec(address, config) {
return {
address: address.toBase58(),
kind: "account",
options: {
commitment: config.commitment,
encoding: config.encoding ?? "base64"
}
};
}
function buildProgramSubscriptionSpec(address, config, deprecatedFilters) {
const filters = config.filters !== void 0 ? getProgramAccountsRpcFilters(config.filters) : normalizeDeprecatedProgramSubscriptionFilters(deprecatedFilters);
return {
address: address.toBase58(),
kind: "program",
options: {
commitment: config.commitment,
encoding: config.encoding ?? "base64",
...filters == null ? null : { filters }
}
};
}
function buildLogsSubscriptionSpec(filter, commitment) {
return {
filter: typeof filter === "object" ? { mentions: [filter.toString()] } : filter,
kind: "logs",
options: { commitment }
};
}
function buildSignatureSubscriptionSpec(signature, options) {
return {
kind: "signature",
options,
signature
};
}
function buildBlockSubscriptionSpec(filter, config) {
return {
filter: filter === "all" ? "all" : { mentionsAccountOrProgram: filter.toBase58() },
kind: "block",
options: {
commitment: config.commitment,
...config.encoding != null ? { encoding: config.encoding } : null,
...config.maxSupportedTransactionVersion !== void 0 ? { maxSupportedTransactionVersion: config.maxSupportedTransactionVersion } : null,
...config.rewards !== void 0 ? { showRewards: config.rewards } : null,
...config.transactionDetails !== void 0 ? { transactionDetails: config.transactionDetails } : null
}
};
}
// src/programs/address-lookup-table/state.ts
var AddressLookupTableAccount = class {
key;
state;
constructor(args) {
this.key = args.key;
this.state = args.state;
}
isActive() {
const U64_MAX = BigInt("0xffffffffffffffff");
return this.state.deactivationSlot === U64_MAX;
}
static deserialize(accountData) {
const state = getAddressLookupTableDecoder().decode(accountData);
if (state.discriminator !== ADDRESS_LOOKUP_TABLE_DISCRIMINATOR) throw new Error(`Invalid address lookup table discriminator: ${state.discriminator}`);
const authority = unwrapOption(state.authority);
return {
deactivationSlot: state.deactivationSlot,
lastExtendedSlot: state.lastExtendedSlot,
lastExtendedSlotStartIndex: state.lastExtendedSlotStartIndex,
authority: authority == null ? void 0 : new PublicKey(authority),
addresses: state.addresses.map((address) => new PublicKey(address))
};
}
};
// src/programs/address-lookup-table/index.ts
const ADDRESS_LOOKUP_TABLE_PROGRAM_ID = new PublicKey(ADDRESS_LOOKUP_TABLE_PROGRAM_ADDRESS);
var AddressLookupTableInstruction = class {
/**
* @internal
*/
constructor() {}
static decodeInstructionType(instruction) {
this.checkProgramId(instruction.programId);
return GENERATED_TO_LEGACY_INSTRUCTION_TYPE$3[identifyAddressLookupTableInstruction(instruction.data)];
}
static decodeCreateLookupTable(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseAddressLookupTableInstructionOfType(instruction, AddressLookupTableInstruction$1.CreateLookupTable);
return {
authority: new PublicKey(parsedInstruction.accounts.authority.address),
payer: new PublicKey(parsedInstruction.accounts.payer.address),
recentSlot: Number(parsedInstruction.data.recentSlot)
};
}
static decodeExtendLookupTable(instruction) {
this.checkProgramId(instruction.programId);
if (instruction.keys.length < 2) throw new Error(`invalid instruction; found ${instruction.keys.length} keys, expected at least 2`);
if (identifyAddressLookupTableInstruction(instruction.data) !== AddressLookupTableInstruction$1.ExtendLookupTable) throw new Error("invalid instruction; instruction type mismatch");
const { addresses } = getExtendLookupTableInstructionDataDecoder().decode(instruction.data);
return {
lookupTable: instruction.keys[0].pubkey,
authority: instruction.keys[1].pubkey,
payer: instruction.keys.length > 2 ? instruction.keys[2].pubkey : void 0,
addresses: addresses.map((address) => new PublicKey(address))
};
}
static decodeCloseLookupTable(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseAddressLookupTableInstructionOfType(instruction, AddressLookupTableInstruction$1.CloseLookupTable);
return {
lookupTable: new PublicKey(parsedInstruction.accounts.address.address),
authority: new PublicKey(parsedInstruction.accounts.authority.address),
recipient: new PublicKey(parsedInstruction.accounts.recipient.address)
};
}
static decodeFreezeLookupTable(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseAddressLookupTableInstructionOfType(instruction, AddressLookupTableInstruction$1.FreezeLookupTable);
return {
lookupTable: new PublicKey(parsedInstruction.accounts.address.address),
authority: new PublicKey(parsedInstruction.accounts.authority.address)
};
}
static decodeDeactivateLookupTable(instruction) {
this.checkProgramId(instruction.programId);
const parsedInstruction = parseAddressLookupTableInstructionOfType(instruction, AddressLookupTableInstruction$1.DeactivateLookupTable);
return {
lookupTable: new PublicKey(parsedInstruction.accounts.address.address),
authority: new PublicKey(parsedInstruction.accounts.authority.address)
};
}
/**
* @internal
*/
static checkProgramId(programId) {
if (!programId.equals(AddressLookupTableProgram.programId)) throw new Error("invalid instruction; programId is not AddressLookupTable Program");
}
};
const GENERATED_TO_LEGACY_INSTRUCTION_TYPE$3 = {
[AddressLookupTableInstruction$1.CreateLookupTable]: "CreateLookupTable",
[AddressLookupTableInstruction$1.FreezeLookupTable]: "FreezeLookupTable",
[AddressLookupTableInstruction$1.ExtendLookupTable]: "ExtendLookupTable",
[AddressLookupTableInstruction$1.DeactivateLookupTable]: "DeactivateLookupTable",
[AddressLookupTableInstruction$1.CloseLookupTable]: "CloseLookupTable"
};
function parseAddressLookupTableInstructionOfType(instruction, expectedInstructionType) {
const parsedInstruction = parseAddressLookupTableInstruction(toKitInstruction(instruction));
if (parsedInstruction.instructionType !== expectedInstructionType) throw new Error("invalid instruction; instruction type mismatch");
return parsedInstruction;
}
function buildExtendLookupTableInstructionWithoutPayer(params) {
return new TransactionInstruction({
keys: [{
pubkey: params.lookupTable,
isSigner: false,
isWritable: true
}, {
pubkey: params.authority,
isSigner: true,
isWritable: false
}],
programId: ADDRESS_LOOKUP_TABLE_PROGRAM_ID,
data: Uint8Array.from(getExtendLookupTableInstructionDataEncoder().encode({ addresses: params.addresses.map((address) => address.toBase58()) }))
});
}
var AddressLookupTableProgram = class {
/**
* @internal
*/
constructor() {}
static programId = ADDRESS_LOOKUP_TABLE_PROGRAM_ID;
static async createLookupTable(params) {
const [lookupTableAddress, bumpSeed] = await PublicKey.findProgramAddress([params.authority.toBytes(), getU64Encoder().encode(params.recentSlot)], this.programId);
return [fromKitInstruction(getCreateLookupTableInstruction({
address: [lookupTableAddress.toBase58(), bumpSeed],
authority: params.authority.toBase58(),
payer: createNoopSigner(params.payer.toBase58()),
recentSlot: params.recentSlot
})), lookupTableAddress];
}
static freezeLookupTable(params) {
return fromKitInstruction(getFreezeLookupTableInstruction({
address: params.lookupTable.toBase58(),
authority: createNoopSigner(params.authority.toBase58())
}));
}
static extendLookupTable(params) {
if (!params.payer) return buildExtendLookupTableInstructionWithoutPayer(params);
return fromKitInstruction(getExtendLookupTableInstruction({
address: params.lookupTable.toBase58(),
authority: createNoopSigner(params.authority.toBase58()),
payer: createNoopSigner(params.payer.toBase58()),
addresses: params.addresses.map((address) => address.toBase58())
}));
}
static deactivateLookupTable(params) {
return fromKitInstruction(getDeactivateLookupTableInstruction({
address: params.lookupTable.toBase58(),
authority: createNoopSigner(params.authority.toBase58())
}));
}
static closeLookupTable(params) {
return fromKitInstruction(getCloseLookupTableInstruction({
address: params.lookupTable.toBase58(),
authority: createNoopSigner(params.authority.toBase58()),
recipient: params.recipient.toBase58()
}));
}
};
// src/kit-adapters/account-notifications.ts
/**
* Boundary: Kit websocket account payloads -> Connection account info shapes.
*
* This module translates the shared raw account payload carried by both
* `accountSubscribe` and `programSubscribe` notifications into the normalized
* account-info values that Connection callbacks expect. The controller uses it
* during dispatch; the runtime only transports raw events and the registry
* only stores subscription state and callbacks.
*/
const BASE58_ENCODER$1 = getBase58Encoder();
const BASE64_CODEC$1 = getBase64Codec();
function decodeBase64WireData(value) {
return toUint8ArrayView(BASE64_CODEC$1.encode(value));
}
function decodeBase58WireData(value) {
if (value === "error: data too large for bs58 encoding") throw new Error("Account data too large for base58 encoding; subscribe with `encoding: 'base64'` to receive this account's data");
return toUint8ArrayView(BASE58_ENCODER$1.encode(value));
}
function normalizeWebSocketAccountInfo(value) {
let data;
if (typeof value.data === "string") data = decodeBase58WireData(value.data);
else if (Array.isArray(value.data)) {
const [wireData, encoding] = value.data;
switch (encoding) {
case "base58":
data = decodeBase58WireData(wireData);
break;
case "base64":
data = decodeBase64WireData(wireData);
break;
case "base64+zstd":
data = value.data;
break;
default: assert_default(false, `Unsupported account notification encoding: ${String(encoding)}`);
}
} else data = {
parsed: value.data.parsed,
program: value.data.program,
space: value.data.space
};
assert_default(value.rentEpoch != null, "Expected account notification rentEpoch");
return {
data,
executable: value.executable,
lamports: value.lamports,
owner: new PublicKey(value.owner),
rentEpoch: value.rentEpoch,
space: value.space
};
}
// src/kit-adapters/block-notifications.ts
function isRecord$2(value) {
return value != null && typeof value === "object";
}
function inferBlockNotificationTransactionKind(value) {
if (!isRecord$2(value)) return;
const transaction = value.transaction;
if (Array.isArray(transaction) && transaction.length === 2) switch (transaction[1]) {
case "base58": return "base58";
case "base64": return "base64";
default: return;
}
if (!isRecord$2(transaction)) return;
if (Array.isArray(transaction.accountKeys)) return "accounts";
const message = transaction.message;
if (!isRecord$2(message)) return;
const accountKeys = message.accountKeys;
if (!Array.isArray(accountKeys)) return;
if (accountKeys.length === 0 || isRecord$2(accountKeys[0]) && typeof accountKeys[0].pubkey === "string") return "parsed";
return typeof accountKeys[0] === "string" ? "json" : void 0;
}
function inferBlockNotificationTransactionsSourceKind(blockSource) {
let sourceKind;
for (const transaction of blockSource.transactions) {
const transactionKind = inferBlockNotificationTransactionKind(transaction);
if (transactionKind == null) return;
if (sourceKind == null) sourceKind = transactionKind;
else if (sourceKind !== transactionKind) return;
}
return sourceKind ?? "json";
}
function hasTransactionsArray(block) {
return isRecord$2(block) && Array.isArray(block.transactions);
}
function hasSignaturesArray(block) {
return isRecord$2(block) && Array.isArray(block.signatures);
}
function normalizeBlockNotificationMeta(meta, expectation) {
return {
...meta,
fee: coerceNumericToBigInt(meta.fee, `${expectation}.fee`),
postBalances: meta.postBalances.map((balance, index) => coerceNumericToBigInt(balance, `${expectation}.postBalances[${index}]`)),
preBalances: meta.preBalances.map((balance, index) => coerceNumericToBigInt(balance, `${expectation}.preBalances[${index}]`)),
...meta.computeUnitsConsumed != null ? { computeUnitsConsumed: coerceNumericToBigInt(meta.computeUnitsConsumed, `${expectation}.computeUnitsConsumed`) } : null,
...meta.costUnits != null ? { costUnits: coerceNumericToBigInt(meta.costUnits, `${expectation}.costUnits`) } : null
};
}
function mapBlockNotificationLoadedAddresses(meta) {
return "loadedAddresses" in meta && meta.loadedAddresses != null ? { loadedAddresses: meta.loadedAddresses } : null;
}
function mapBlockNotificationTransactionMeta(meta, expectation) {
if (meta == null) return null;
return {
...normalizeBlockNotificationMeta(meta, expectation),
...mapBlockNotificationLoadedAddresses(meta)
};
}
function mapBlockNotificationAccountsTransactionMeta(meta, expectation) {
if (meta == null) return null;
return normalizeBlockNotificationMeta(meta, expectation);
}
function assertBlockNotificationTransactionsSourceHasKind(blockSource, kind, expectation) {
assert_default(blockSource.transactions.every((transaction) => inferBlockNotificationTransactionKind(transaction) === kind), expectation);
}
function mapBlockNotificationTransactions(transactions, expectationPrefix, mapMeta) {
return transactions.map((transactionResponse, index) => {
const { version: rawVersion, ...transaction } = transactionResponse;
const version = normalizeTransactionVersion(rawVersion);
return {
...transaction,
...version != null ? { version } : null,
meta: mapMeta(transaction.meta, `Expected block subscription ${expectationPrefix} transactions[${index}].meta`)
};
});
}
function mapBlockNotificationWithTransactionKind(blockSource, kind) {
switch (kind) {
case "accounts":
assertBlockNotificationTransactionsSourceHasKind(blockSource, "accounts", "Expected block subscription accounts transactions");
return {
...mapBlockBase(blockSource),
transactions: mapBlockNotificationTransactions(blockSource.transactions, "accounts", mapBlockNotificationAccountsTransactionMeta)
};
case "parsed":
assertBlockNotificationTransactionsSourceHasKind(blockSource, "parsed", "Expected block subscription parsed transactions");
return {
...mapBlockBase(blockSource),
transactions: mapBlockNotificationTransactions(blockSource.transactions, "parsed", mapBlockNotificationTransactionMeta)
};
case "base58":
assertBlockNotificationTransactionsSourceHasKind(blockSource, "base58", "Expected block subscription base58 transactions");
return {
...mapBlockBase(blockSource),
transactions: mapBlockNotificationTransactions(blockSource.transactions, "base58", mapBlockNotificationTransactionMeta)
};
case "base64":
assertBlockNotificationTransactionsSourceHasKind(blockSource, "base64", "Expected block subscription base64 transactions");
return {
...mapBlockBase(blockSource),
transactions: mapBlockNotificationTransactions(blockSource.transactions, "base64", mapBlockNotificationTransactionMeta)
};
case "json":
assertBlockNotificationTransactionsSourceHasKind(blockSource, "json", "Expected block subscription json transactions");
return {
...mapBlockBase(blockSource),
transactions: mapBlockNotificationTransactions(blockSource.transactions, "json", mapBlockNotificationTransactionMeta)
};
}
}
function mapBlockNotificationSignaturesBlock(block) {
const { signatures, ...mappedBlock } = mapBlockBase(block);
return {
...mappedBlock,
signatures: [...signatures]
};
}
function mapBlockNotificationBlock(notificationBlock, dispatchConfig) {
if (notificationBlock == null) return null;
if (dispatchConfig == null || dispatchConfig === "default") {
if (hasTransactionsArray(notificationBlock)) {
const transactionKind = inferBlockNotificationTransactionsSourceKind(notificationBlock);
assert_default(transactionKind != null, "Expected block subscription transactions");
return mapBlockNotificationWithTransactionKind(notificationBlock, transactionKind);
}
if (hasSignaturesArray(notificationBlock)) return mapBlockNotificationSignaturesBlock(notificationBlock);
return mapBlockBase(notificationBlock);
}
switch (dispatchConfig.transactionDetails ?? "full") {
case "accounts":
assert_default(hasTransactionsArray(notificationBlock), "Expected block subscription accounts transactions");
return mapBlockNotificationWithTransactionKind(notificationBlock, "accounts");
case "none": return mapBlockBase(notificationBlock);
case "signatures":
assert_default(hasSignaturesArray(notificationBlock), "Expected block subscription signatures");
return mapBlockNotificationSignaturesBlock(notificationBlock);
case "full":
assert_default(hasTransactionsArray(notificationBlock), "Expected block subscription transactions");
return mapBlockNotificationWithTransactionKind(notificationBlock, dispatchConfig.encoding === "jsonParsed" ? "parsed" : dispatchConfig.encoding ?? "json");
}
}
// src/rpc-subscriptions/controller.ts
/**
* Boundary: subscription orchestration between Connection, runtime, and
* registry.
*
* This module receives raw notification and lifecycle events from the runtime,
* drives state transitions in the registry, and dispatches Connection-facing
* callback arguments after adapter normalization. It is the coordination layer
* of the subscription subsystem.
*/
var ConnectionSubscriptionsController = class {
_subscriptionRegistry;
_getSubscriptionsRuntime;
_getSubscriptionConfigHash;
constructor(_subscriptionRegistry, _getSubscriptionsRuntime, _getSubscriptionConfigHash) {
this._subscriptionRegistry = _subscriptionRegistry;
this._getSubscriptionsRuntime = _getSubscriptionsRuntime;
this._getSubscriptionConfigHash = _getSubscriptionConfigHash;
}
handleNotification({ kind, notification }) {
switch (kind) {
case "account": {
const { result, subscription } = notification;
const accountInfo = normalizeWebSocketAccountInfo(result.value);
this._subscriptionRegistry.dispatchNotification(subscription, [accountInfo, result.context]);
return;
}
case "block": {
const { result, subscription } = notification;
const dispatchConfig = this._subscriptionRegistry.getBlockDispatchConfigForServerId(subscription);
const block = mapBlockNotificationBlock(result.value.block, dispatchConfig);
this._subscriptionRegistry.dispatchNotification(subscription, [{
block,
err: result.value.err,
slot: coerceNumericToBigInt(result.value.slot, "slot")
}, result.context]);
return;
}
case "logs": {
const { result, subscription } = notification;
this._subscriptionRegistry.dispatchNotification(subscription, [{
err: result.value.err,
logs: [...result.value.logs],
signature: result.value.signature
}, result.context]);
return;
}
case "program": {
const { result, subscription } = notification;
const accountId = new PublicKey(result.value.pubkey);
const accountInfo = normalizeWebSocketAccountInfo(result.value.account);
this._subscriptionRegistry.dispatchNotification(subscription, [{
accountId,
accountInfo
}, result.context]);
return;
}
case "root": {
const { result, subscription } = notification;
this._subscriptionRegistry.dispatchNotification(subscription, [result]);
return;
}
case "signature": {
const { result, subscription } = notification;
const signatureNotification = result.value === "receivedSignature" ? { type: "received" } : {
type: "status",
result: { err: result.value.err }
};
if (signatureNotification.type === "status") this._subscriptionRegistry.markAutoDisposedSubscription(subscription);
this._subscriptionRegistry.dispatchNotification(subscription, [signatureNotification, result.context]);
return;
}
case "slot": {
const { result, subscription } = notification;
this._subscriptionRegistry.dispatchNotification(subscription, [result]);
return;
}
case "slotsUpdates": {
const { result, subscription } = notification;
this._subscriptionRegistry.dispatchNotification(subscription, [result]);
return;
}
case "vote": {
const { result, subscription } = notification;
this._subscriptionRegistry.dispatchNotification(subscription, [{
hash: result.hash,
signature: result.signature,
slots: [...result.slots],
timestamp: result.timestamp,
votePubkey: new PublicKey(result.votePubkey)
}]);
return;
}
}
}
handleRuntimeDisconnected(code) {
if (code === 1e3) {
this.updateSubscriptions();
return;
}
for (const hash of this._subscriptionRegistry.getSubscriptionHashes()) {
const subscription = this._subscriptionRegistry.getSubscription(hash);
if (subscription == null) continue;
this._subscriptionRegistry.setSubscription(hash, {
callbacks: subscription.callbacks,
spec: subscription.spec,
state: "pending"
});
}
this.updateSubscriptions();
}
registerSubscription(subscriptionConfig, dispatchConfig) {
const hash = this._getSubscriptionConfigHash(subscriptionConfig.spec);
if (dispatchConfig?.defaultDispatchConfig !== void 0) this._subscriptionRegistry.setDefaultBlockDispatchConfig(hash, dispatchConfig.defaultDispatchConfig);
if (dispatchConfig?.dispatchConfig !== void 0) this._subscriptionRegistry.setBlockDispatchConfig(hash, dispatchConfig.dispatchConfig);
this._subscriptionRegistry.addSubscriptionCallback(hash, subscriptionConfig.callback, subscriptionConfig.spec);
const clientSubscriptionId = this._subscriptionRegistry.createClientSubscription(hash, subscriptionConfig.callback);
this.updateSubscriptions();
return clientSubscriptionId;
}
async removeClientSubscription(clientSubscriptionId, subscriptionName) {
const clientSubscription = this._subscriptionRegistry.removeClientSubscription(clientSubscriptionId);
if (clientSubscription != null && this._subscriptionRegistry.removeSubscriptionCallback(clientSubscription.hash, clientSubscription.callback)) await this.updateSubscriptions();
else console.warn(`Ignored unsubscribe request because an active subscription with id \`${clientSubscriptionId}\` for '${subscriptionName}' events could not be found.`);
}
async updateSubscriptions() {
const subscriptionsRuntime = this._getSubscriptionsRuntime();
for (const hash of this._subscriptionRegistry.getSubscriptionHashes()) {
const subscription = this._subscriptionRegistry.getSubscription(hash);
if (subscription != null && subscription.callbacks.size === 0 && (subscription.state === "pending" || subscription.state === "unsubscribed" || subscription.state === "failed")) this._subscriptionRegistry.pruneSubscription(hash);
}
if (!this._subscriptionRegistry.hasSubscriptions()) {
subscriptionsRuntime.scheduleIdleClose();
return;
}
subscriptionsRuntime.cancelIdleClose();
if (subscriptionsRuntime.channel === null) {
subscriptionsRuntime.ensureConnected();
return;
}
const activeSubscriptionChannelAbortController = subscriptionsRuntime.connectionGeneration;
const isCurrentConnectionStillActive = () => activeSubscriptionChannelAbortController !== null && activeSubscriptionChannelAbortController === this._getSubscriptionsRuntime().connectionGeneration;
await Promise.all(this._subscriptionRegistry.getSubscriptionHashes().map(async (hash) => {
const subscription = this._subscriptionRegistry.getSubscription(hash);
if (subscription === void 0) return;
const getCurrentSubscriptionForUpdate = () => {
const currentSubscription = this._subscriptionRegistry.getSubscription(hash);
if (!isCurrentConnectionStillActive() || currentSubscription === void 0 || currentSubscription.callbacks !== subscription.callbacks) return;
return currentSubscription;
};
const getPendingSubscriptionUpdateDisposition = (currentSubscription) => {
if (currentSubscription === void 0) return "stop";
if (currentSubscription.callbacks.size > 0) return "continue";
return "prune";
};
switch (subscription.state) {
case "pending":
case "unsubscribed":
if (getPendingSubscriptionUpdateDisposition(subscription) === "prune") {
this._subscriptionRegistry.pruneSubscription(hash);
await this.updateSubscriptions();
return;
}
this._subscriptionRegistry.setSubscription(hash, {
...subscription,
state: "subscribing"
});
try {
const subscriptionHandle = await subscriptionsRuntime.openSubscription(subscription.spec);
const disposition = getPendingSubscriptionUpdateDisposition(getCurrentSubscriptionForUpdate());
if (disposition === "stop") {
subscriptionHandle.unsubscribe();
return;
}
if (disposition === "prune") {
subscriptionHandle.unsubscribe();
this._subscriptionRegistry.pruneSubscription(hash);
await this.updateSubscriptions();
return;
}
this._subscriptionRegistry.setSubscription(hash, {
...subscription,
serverSubscriptionId: subscriptionHandle.serverSubscriptionId,
state: "subscribed",
subscriptionHandle
});
this._subscriptionRegistry.attachBlockDispatchConfigToServerId(hash, subscriptionHandle.serverSubscriptionId);
} catch (error) {
const disposition = getPendingSubscriptionUpdateDisposition(getCurrentSubscriptionForUpdate());
if (disposition === "stop") return;
if (disposition === "prune") {
this._subscriptionRegistry.pruneSubscription(hash);
await this.updateSubscriptions();
return;
}
this._subscriptionRegistry.setSubscription(hash, {
callbacks: subscription.callbacks,
spec: subscription.spec,
state: "failed"
});
console.error(`Received ${error instanceof Error ? "" : "JSON-RPC "}error opening \`${subscription.spec.kind}\` subscription`, {
spec: subscription.spec,
error
});
return;
}
if (getCurrentSubscriptionForUpdate() === void 0) return;
await this.updateSubscriptions();
return;
case "subscribed":
if (subscription.callbacks.size === 0) {
if (!this._subscriptionRegistry.consumeAutoDisposedSubscription(subscription.serverSubscriptionId)) {
this._subscriptionRegistry.setSubscription(hash, {
...subscription,
serverSubscriptionId: subscription.serverSubscriptionId,
state: "unsubscribing",
subscriptionHandle: subscription.subscriptionHandle
});
try {
await subscription.subscriptionHandle.unsubscribe();
} catch (error) {
if (getCurrentSubscriptionForUpdate() === void 0) return;
this._subscriptionRegistry.setSubscription(hash, {
...subscription,
serverSubscriptionId: subscription.serverSubscriptionId,
state: "subscribed",
subscriptionHandle: subscription.subscriptionHandle
});
if (error instanceof Error) console.error(`${subscription.spec.kind} unsubscribe error:`, error.message);
await this.updateSubscriptions();
return;
}
} else this._subscriptionRegistry.abortServerSubscription(subscription.serverSubscriptionId);
if (getCurrentSubscriptionForUpdate() === void 0) return;
this._subscriptionRegistry.setSubscription(hash, {
...subscription,
serverSubscriptionId: subscription.serverSubscriptionId,
state: "unsubscribed"
});
await this.updateSubscriptions();
}
break;
case "failed": if (subscription.callbacks.size === 0) this._subscriptionRegistry.pruneSubscription(hash);
}
}));
}
};
// src/rpc-subscriptions/registry.ts
var ConnectionSubscriptionRegistry = class {
_blockDispatchConfigByHash = /* @__PURE__ */ new Map();
_blockDispatchConfigByServerId = /* @__PURE__ */ new Map();
_clientSubscriptionsById = /* @__PURE__ */ new Map();
_nextClientSubscriptionId = 0;
_nextServerSubscriptionId = 0;
_abortControllersByServerId = /* @__PURE__ */ new Map();
_callbacksByServerId = /* @__PURE__ */ new Map();
_stateChangeCallbacksByHash = /* @__PURE__ */ new Map();
_stateChangeCallbacksByClientSubscriptionId = /* @__PURE__ */ new Map();
_autoDisposedServerSubscriptions = /* @__PURE__ */ new Set();
_subscriptionsByHash = /* @__PURE__ */ new Map();
addSubscriptionCallback(hash, callback, spec) {
const existingSubscription = this._subscriptionsByHash.get(hash);
if (existingSubscription == null) {
this.setSubscription(hash, {
callbacks: /* @__PURE__ */ new Set([callback]),
spec,
state: "pending"
});
return;
}
existingSubscription.callbacks.add(callback);
if (existingSubscription.state === "failed") this.setSubscription(hash, {
callbacks: existingSubscription.callbacks,
spec: existingSubscription.spec,
state: "pending"
});
}
attachBlockDispatchConfigToServerId(hash, serverSubscriptionId) {
const dispatchConfig = this._blockDispatchConfigByHash.get(hash);
if (dispatchConfig !== void 0) this._blockDispatchConfigByServerId.set(serverSubscriptionId, dispatchConfig);
}
consumeAutoDisposedSubscription(serverSubscriptionId) {
if (!this._autoDisposedServerSubscriptions.has(serverSubscriptionId)) return false;
this._autoDisposedServerSubscriptions.delete(serverSubscriptionId);
return true;
}
createClientSubscription(hash, callback) {
const clientSubscriptionId = this._nextClientSubscriptionId++;
this._clientSubscriptionsById.set(clientSubscriptionId, {
callback,
hash
});
return clientSubscriptionId;
}
createServerSubscription() {
const abortController = new AbortController();
const serverSubscriptionId = ++this._nextServerSubscriptionId;
this._abortControllersByServerId.set(serverSubscriptionId, abortController);
return {
abortController,
serverSubscriptionId
};
}
deleteServerSubscription(serverSubscriptionId) {
this._abortControllersByServerId.delete(serverSubscriptionId);
}
dispatchNotification(serverSubscriptionId, callbackArgs) {
const callbacks = this._callbacksByServerId.get(serverSubscriptionId);
if (callbacks == null) return;
callbacks.forEach((callback) => {
try {
callback(...callbackArgs);
} catch (error) {
console.error("Subscription notification callback failed", { serverSubscriptionId }, error);
}
});
}
getBlockDispatchConfig(hash) {
return this._blockDispatchConfigByHash.get(hash);
}
getBlockDispatchConfigForServerId(serverSubscriptionId) {
return this._blockDispatchConfigByServerId.get(serverSubscriptionId);
}
getSubscription(hash) {
return this._subscriptionsByHash.get(hash);
}
getSubscriptionHashes() {
return [...this._subscriptionsByHash.keys()];
}
hasSubscriptions() {
return this.getSubscriptionHashes().length > 0;
}
hasServerSubscription(serverSubscriptionId) {
return this._abortControllersByServerId.has(serverSubscriptionId);
}
markAutoDisposedSubscription(serverSubscriptionId) {
this._autoDisposedServerSubscriptions.add(serverSubscriptionId);
}
/** @internal */
observeStateChanges(clientSubscriptionId, callback) {
const hash = this._clientSubscriptionsById.get(clientSubscriptionId)?.hash;
if (hash == null) return {
currentState: "inactive",
dispose: () => {}
};
const stateChangeCallbacks = this._stateChangeCallbacksByHash.get(hash) ?? /* @__PURE__ */ new Set();
this._stateChangeCallbacksByHash.set(hash, stateChangeCallbacks);
stateChangeCallbacks.add(callback);
const clientStateChangeCallbacks = this._stateChangeCallbacksByClientSubscriptionId.get(clientSubscriptionId) ?? /* @__PURE__ */ new Set();
this._stateChangeCallbacksByClientSubscriptionId.set(clientSubscriptionId, clientStateChangeCallbacks);
clientStateChangeCallbacks.add(callback);
return {
currentState: this._subscriptionsByHash.get(hash)?.state ?? "inactive",
dispose: () => {
stateChangeCallbacks.delete(callback);
if (stateChangeCallbacks.size === 0) this._stateChangeCallbacksByHash.delete(hash);
clientStateChangeCallbacks.delete(callback);
if (clientStateChangeCallbacks.size === 0) this._stateChangeCallbacksByClientSubscriptionId.delete(clientSubscriptionId);
}
};
}
abortServerSubscription(serverSubscriptionId) {
const abortController = this._abortControllersByServerId.get(serverSubscriptionId);
if (abortController == null) return false;
this._abortControllersByServerId.delete(serverSubscriptionId);
if (!abortController.signal.aborted) abortController.abort();
return true;
}
abortAllServerSubscriptions() {
for (const serverSubscriptionId of this._abortControllersByServerId.keys()) this.abortServerSubscription(serverSubscriptionId);
}
pruneSubscription(hash) {
const subscription = this._subscriptionsByHash.get(hash);
if (subscription == null) return;
if ("serverSubscriptionId" in subscription) {
this._callbacksByServerId.delete(subscription.serverSubscriptionId);
this._blockDispatchConfigByServerId.delete(subscription.serverSubscriptionId);
this._autoDisposedServerSubscriptions.delete(subscription.serverSubscriptionId);
}
this._stateChangeCallbacksByHash.get(hash)?.forEach((callback) => {
try {
callback("inactive");
} catch (error) {
console.error("Subscription state observer transition callback failed", {
hash,
state: "inactive"
}, error);
}
});
this._subscriptionsByHash.delete(hash);
this._blockDispatchConfigByHash.delete(hash);
this._stateChangeCallbacksByHash.delete(hash);
}
removeClientSubscription(clientSubscriptionId) {
const clientSubscription = this._clientSubscriptionsById.get(clientSubscriptionId);
if (clientSubscription != null) {
this._clientSubscriptionsById.delete(clientSubscriptionId);
const clientStateChangeCallbacks = this._stateChangeCallbacksByClientSubscriptionId.get(clientSubscriptionId);
if (clientStateChangeCallbacks != null) {
this._stateChangeCallbacksByClientSubscriptionId.delete(clientSubscriptionId);
const stateChangeCallbacks = this._stateChangeCallbacksByHash.get(clientSubscription.hash);
clientStateChangeCallbacks.forEach((callback) => {
stateChangeCallbacks?.delete(callback);
try {
callback("inactive");
} catch (error) {
console.error("Subscription state observer transition callback failed", {
hash: clientSubscription.hash,
state: "inactive"
}, error);
}
});
if (stateChangeCallbacks?.size === 0) this._stateChangeCallbacksByHash.delete(clientSubscription.hash);
}
}
return clientSubscription;
}
removeSubscriptionCallback(hash, callback) {
const subscription = this._subscriptionsByHash.get(hash);
if (subscription == null) return false;
subscription.callbacks.delete(callback);
return true;
}
setDefaultBlockDispatchConfig(hash, dispatchConfig) {
if (!this._blockDispatchConfigByHash.has(hash)) this._blockDispatchConfigByHash.set(hash, dispatchConfig);
}
setBlockDispatchConfig(hash, dispatchConfig) {
this._blockDispatchConfigByHash.set(hash, dispatchConfig);
}
setSubscription(hash, nextSubscription) {
const prevSubscription = this._subscriptionsByHash.get(hash);
const prevState = prevSubscription?.state;
if (prevSubscription != null && "serverSubscriptionId" in prevSubscription && (nextSubscription.state === "unsubscribed" || !("serverSubscriptionId" in nextSubscription) || nextSubscription.serverSubscriptionId !== prevSubscription.serverSubscriptionId)) {
this._callbacksByServerId.delete(prevSubscription.serverSubscriptionId);
this._blockDispatchConfigByServerId.delete(prevSubscription.serverSubscriptionId);
this._autoDisposedServerSubscriptions.delete(prevSubscription.serverSubscriptionId);
}
this._subscriptionsByHash.set(hash, nextSubscription);
if ("serverSubscriptionId" in nextSubscription) this._callbacksByServerId.set(nextSubscription.serverSubscriptionId, nextSubscription.callbacks);
if (prevState !== nextSubscription.state) this._stateChangeCallbacksByHash.get(hash)?.forEach((callback) => {
try {
callback(nextSubscription.state);
} catch (error) {
console.error("Subscription state observer transition callback failed", {
hash,
state: nextSubscription.state
}, error);
}
});
}
};
// src/rpc-subscriptions/runtime.ts
/**
* Boundary: Kit websocket transport -> internal subscription events.
*
* This module opens and maintains Solana Kit websocket subscriptions and emits
* typed notification and lifecycle events for the controller. It consumes
* normalized subscription specs from the Connection edge and deliberately does
* not own callback dispatch or durable subscription state.
*/
const SUBSCRIPTION_CHANNEL_CLOSE_CODE_NORMAL = 1e3;
const SUBSCRIPTION_CHANNEL_CLOSE_CODE_UNEXPECTED = 1006;
const SUBSCRIPTION_CHANNEL_IDLE_CLOSE_DELAY_MS = 500;
const createSubscriptionChannel = (endpoint, config) => createDefaultSolanaRpcSubscriptionsChannelCreator({
...config,
url: endpoint
});
var KitSubscriptionRuntime = class {
_subscriptionRegistry;
_callbacks;
_dispatchNotification;
_channel = null;
_channelAbortController = null;
_channelIdleTimeout = null;
_createSubscriptionChannel;
_subscriptions;
constructor(endpoint, _subscriptionRegistry, _callbacks, _dispatchNotification, subscriptionChannelConfig, defaultCommitment) {
this._subscriptionRegistry = _subscriptionRegistry;
this._callbacks = _callbacks;
this._dispatchNotification = _dispatchNotification;
this._createSubscriptionChannel = createSubscriptionChannel(endpoint, subscriptionChannelConfig);
this._subscriptions = createSubscriptionRpc({
api: createSolanaRpcSubscriptionsApi({
...DEFAULT_RPC_SUBSCRIPTIONS_CONFIG,
defaultCommitment: defaultCommitment ?? DEFAULT_RPC_SUBSCRIPTIONS_CONFIG.defaultCommitment
}),
transport: createDefaultRpcSubscriptionsTransport({ createChannel: this._createSubscriptionChannel })
});
}
get channel() {
return this._channel;
}
get connectionGeneration() {
return this._channelAbortController;
}
get rpcSubscriptions() {
return this._subscriptions;
}
cancelIdleClose() {
if (this._channelIdleTimeout !== null) {
clearTimeout(this._channelIdleTimeout);
this._channelIdleTimeout = null;
}
}
ensureConnected() {
if (this._channelAbortController !== null) return;
const abortController = new AbortController();
this._channelAbortController = abortController;
this._createSubscriptionChannel({ abortSignal: abortController.signal }).then((channel) => {
if (this._channelAbortController !== abortController || abortController.signal.aborted) return;
this._channel = channel;
channel.on("error", (error) => {
if (this._channelAbortController !== abortController) return;
this._disconnectChannel(SUBSCRIPTION_CHANNEL_CLOSE_CODE_UNEXPECTED, error instanceof Error ? error : new Error(String(error)));
}, { signal: abortController.signal });
this._callbacks.onConnected();
}).catch((error) => {
if (this._channelAbortController !== abortController || abortController.signal.aborted) return;
this._disconnectChannel(SUBSCRIPTION_CHANNEL_CLOSE_CODE_UNEXPECTED, error instanceof Error ? error : new Error(String(error)));
});
}
openSubscription(spec) {
const { abortController, serverSubscriptionId } = this._subscriptionRegistry.createServerSubscription();
const abortSignal = abortController.signal;
try {
switch (spec.kind) {
case "account": {
const typedAddress = spec.address;
assertIsAddress(typedAddress);
const openAccountNotifications = this._subscriptions.accountNotifications;
const notificationStream = openAccountNotifications(typedAddress, spec.options).subscribe({ abortSignal });
return this._createSubscriptionHandle(notificationStream, serverSubscriptionId, abortController, (result) => {
this._dispatchNotification({
kind: "account",
notification: {
result,
subscription: serverSubscriptionId
}
});
});
}
case "block": {
let filter;
if (spec.filter !== "all") {
assertIsAddress(spec.filter.mentionsAccountOrProgram);
filter = { mentionsAccountOrProgram: spec.filter.mentionsAccountOrProgram };
} else filter = "all";
return this._createSubscriptionHandle(this._subscriptions.blockNotifications(filter, spec.options).subscribe({ abortSignal }), serverSubscriptionId, abortController, (result) => {
this._dispatchNotification({
kind: "block",
notification: {
result,
subscription: serverSubscriptionId
}
});
});
}
case "logs": {
const openLogsNotifications = this._subscriptions.logsNotifications;
const filter = spec.filter === "all" || spec.filter === "allWithVotes" ? spec.filter : (() => {
const address = spec.filter.mentions[0];
assertIsAddress(address);
return { mentions: [address] };
})();
return this._createSubscriptionHandle(openLogsNotifications(filter, spec.options).subscribe({ abortSignal }), serverSubscriptionId, abortController, (result) => {
this._dispatchNotification({
kind: "logs",
notification: {
result,
subscription: serverSubscriptionId
}
});
});
}
case "program": {
const typedAddress = spec.address;
assertIsAddress(typedAddress);
const openProgramNotifications = this._subscriptions.programNotifications;
const notificationStream = openProgramNotifications(typedAddress, spec.options).subscribe({ abortSignal });
return this._createSubscriptionHandle(notificationStream, serverSubscriptionId, abortController, (result) => {
this._dispatchNotification({
kind: "program",
notification: {
result,
subscription: serverSubscriptionId
}
});
});
}
case "root": return this._createSubscriptionHandle(this._subscriptions.rootNotifications().subscribe({ abortSignal }), serverSubscriptionId, abortController, (result) => {
this._dispatchNotification({
kind: "root",
notification: {
result,
subscription: serverSubscriptionId
}
});
});
case "signature": {
const typedSignature = spec.signature;
assertIsSignature(typedSignature);
return this._createSubscriptionHandle(this._subscriptions.signatureNotifications(typedSignature, spec.options).subscribe({ abortSignal }), serverSubscriptionId, abortController, (result) => {
this._dispatchNotification({
kind: "signature",
notification: {
result,
subscription: serverSubscriptionId
}
});
});
}
case "slot": return this._createSubscriptionHandle(this._subscriptions.slotNotifications().subscribe({ abortSignal }), serverSubscriptionId, abortController, (result) => {
this._dispatchNotification({
kind: "slot",
notification: {
result,
subscription: serverSubscriptionId
}
});
});
case "slotsUpdates": return this._createSubscriptionHandle(this._subscriptions.slotsUpdatesNotifications().subscribe({ abortSignal }), serverSubscriptionId, abortController, (result) => {
this._dispatchNotification({
kind: "slotsUpdates",
notification: {
result,
subscription: serverSubscriptionId
}
});
});
case "vote": return this._createSubscriptionHandle(this._subscriptions.voteNotifications().subscribe({ abortSignal }), serverSubscriptionId, abortController, (result) => {
this._dispatchNotification({
kind: "vote",
notification: {
result,
subscription: serverSubscriptionId
}
});
});
}
} catch (error) {
this._subscriptionRegistry.deleteServerSubscription(serverSubscriptionId);
if (!abortController.signal.aborted) abortController.abort();
throw error;
}
}
scheduleIdleClose() {
if (this._channel === null || this._channelIdleTimeout !== null) return;
this._channelIdleTimeout = setTimeout(() => {
this._channelIdleTimeout = null;
this._disconnectChannel(SUBSCRIPTION_CHANNEL_CLOSE_CODE_NORMAL);
}, SUBSCRIPTION_CHANNEL_IDLE_CLOSE_DELAY_MS);
}
async _createSubscriptionHandle(stream, serverSubscriptionId, abortController, onNotification) {
let notificationStream;
try {
notificationStream = await stream;
} catch (error) {
this._subscriptionRegistry.abortServerSubscription(serverSubscriptionId);
throw error;
}
(async () => {
try {
for await (const result of notificationStream) {
if (abortController.signal.aborted || !this._subscriptionRegistry.hasServerSubscription(serverSubscriptionId)) return;
try {
onNotification(result);
} catch (error) {
console.error("Subscription notification could not be dispatched", { serverSubscriptionId }, error);
}
}
} catch (error) {
if (abortController.signal.aborted || !this._subscriptionRegistry.hasServerSubscription(serverSubscriptionId)) return;
const normalizedError = error instanceof Error ? error : new Error(String(error));
if (this._channel !== null) this._disconnectChannel(SUBSCRIPTION_CHANNEL_CLOSE_CODE_UNEXPECTED, normalizedError);
else console.error("ws error:", normalizedError.message);
return;
}
this._subscriptionRegistry.abortServerSubscription(serverSubscriptionId);
})();
return {
serverSubscriptionId,
unsubscribe: () => Promise.resolve(this._subscriptionRegistry.abortServerSubscription(serverSubscriptionId))
};
}
_disconnectChannel(code, error) {
const abortController = this._channelAbortController;
this._channel = null;
this._channelAbortController = null;
this.cancelIdleClose();
if (abortController != null && !abortController.signal.aborted) abortController.abort();
if (error != null && this._subscriptionRegistry.hasSubscriptions()) console.error("ws error:", error.message);
this._subscriptionRegistry.abortAllServerSubscriptions();
this._callbacks.onDisconnected(code);
}
};
// src/runtime-config.ts
function getRuntimeVersion() {
return "3.2.1";
}
// src/utils/makeWebsocketUrl.ts
const URL_RE = /^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;
function makeWebsocketUrl(endpoint) {
const matches = endpoint.match(URL_RE);
if (matches == null) throw TypeError(`Failed to validate endpoint URL \`${endpoint}\``);
const [_, hostish, portWithColon, rest] = matches;
const protocol = endpoint.startsWith("https:") ? "wss:" : "ws:";
const startPort = portWithColon == null ? null : parseInt(portWithColon.slice(1), 10);
return `${protocol}//${hostish}${startPort == null ? "" : `:${startPort + 1}`}${rest}`;
}
// src/connection.ts
function assertIsTransactionSignatureArray(signatures) {
for (const signature of signatures) assertIsSignature(signature);
}
function encodeBase64WireData(value) {
return BASE64_CODEC.decode(value);
}
const BASE58_ENCODER = getBase58Encoder();
const BASE64_CODEC = getBase64Codec();
/**
* Attempt to use a recent blockhash for up to 30 seconds
* @internal
*/
const BLOCKHASH_CACHE_TIMEOUT_MS = 3e4;
function isRecord$1(value) {
return typeof value === "object" && value !== null;
}
function assertEndpointUrl(putativeUrl) {
if (/^https?:/.test(putativeUrl) === false) throw new TypeError("Endpoint URL must start with `http:` or `https:`.");
return putativeUrl;
}
/** @internal */
function extractCommitmentFromConfig(commitmentOrConfig) {
let commitment;
let config;
if (typeof commitmentOrConfig === "string") commitment = commitmentOrConfig;
else if (commitmentOrConfig) {
const { commitment: specifiedCommitment, ...specifiedConfig } = commitmentOrConfig;
commitment = specifiedCommitment;
config = specifiedConfig;
}
return {
commitment,
config
};
}
/**
* @internal
*/
function coerceToBase64EncodedWireTransaction(transaction) {
BASE64_CODEC.encode(transaction);
return transaction;
}
function createConnectionHttpTransport(url, config) {
const normalizedHeaders = { "solana-client": `js/${getRuntimeVersion() ?? "UNKNOWN"}` };
if (config.headers != null) for (const headerName in config.headers) normalizedHeaders[headerName.toLowerCase()] = config.headers[headerName];
return async ({ payload, signal }) => {
const body = stringifyJsonWithBigInts(payload);
const requestInfo = {
body,
headers: {
...normalizedHeaders,
accept: "application/json",
"content-length": body.length.toString(),
"content-type": "application/json; charset=utf-8"
},
method: "POST",
signal
};
const response = await config.fetch(url, requestInfo);
if (!response.ok) throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, {
headers: response.headers,
message: response.statusText,
statusCode: response.status
});
const rawResponse = await response.text();
return rawResponse.length === 0 ? null : parseJsonWithBigInts(rawResponse);
};
}
function createRpcTransport(url, config = {}) {
const { disableRetryOnRateLimit, fetch, fetchMiddleware, httpHeaders } = config;
const transport = createFetchRpcTransport(url, {
fetch,
fetchMiddleware,
httpHeaders
});
return async ({ payload, signal }) => {
let too_many_requests_retries = 5;
let waitTime = 500;
for (;;) {
try {
return await transport({
payload,
signal
});
} catch (error) {
if (disableRetryOnRateLimit === true || !isSolanaError(error, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) || error.context.statusCode !== 429) throw error;
too_many_requests_retries -= 1;
if (too_many_requests_retries === 0) throw error;
}
console.error(`Server responded with 429 Too Many Requests. Retrying after ${waitTime}ms delay...`);
await sleep(waitTime);
waitTime *= 2;
}
};
}
function createFetchRpcTransport(url, config) {
const { fetch: customFetch, fetchMiddleware, httpHeaders } = config;
const fetch = customFetch ?? globalThis.fetch;
return createConnectionHttpTransport(url, {
fetch: fetchMiddleware == null ? async (requestUrl, options) => await fetch(requestUrl, options) : async (requestUrl, options) => {
const [modifiedUrl, modifiedOptions] = await new Promise((resolve, reject) => {
try {
fetchMiddleware(requestUrl, options, (nextUrl, nextOptions) => resolve([nextUrl, nextOptions]));
} catch (error) {
reject(error);
}
});
return await fetch(modifiedUrl, modifiedOptions);
},
headers: httpHeaders
});
}
function createKitRpcClient(url, config) {
const typedTransport = createRpcTransport(url, config);
return { typedRpc: createRpc({
api: createSolanaRpcApi({
...DEFAULT_RPC_CONFIG,
defaultCommitment: config.commitment ?? "confirmed"
}),
transport: typedTransport
}) };
}
function isJsonRpcErrorLike(value) {
return !!value && typeof value === "object" && "code" in value && typeof value.message === "string";
}
function throwSolanaRpcErrorIfNeeded(error, context) {
if (isJsonRpcErrorLike(error)) throw new SolanaJSONRPCError(error, context);
throw error;
}
function extractSendTransactionErrorDetails(error) {
if (isSolanaError(error, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE)) {
const logs = error.context.logs == null ? void 0 : error.context.logs.filter((log) => typeof log === "string");
return {
logs,
transactionMessage: logs?.at(-1) ?? (error.cause instanceof Error ? error.cause.message : void 0) ?? error.message
};
}
if (!isJsonRpcErrorLike(error)) return null;
let logs = void 0;
if ("data" in error && isRecord$1(error.data)) {
const maybeLogs = error.data.logs;
if (Array.isArray(maybeLogs) && maybeLogs.every((log) => typeof log === "string")) logs = maybeLogs;
}
return {
logs,
transactionMessage: error.message
};
}
async function fetchTypedBlockWithMappers(typedRpc, slot, finality, config, args) {
switch (config?.transactionDetails) {
case "none": {
const result = await sendTypedBlockRequest(typedRpc, slot, getTypedBlockWithoutTransactionsConfig("none", finality, config));
return result ? mapBlockBase(result) : null;
}
case "signatures": {
const result = await sendTypedBlockRequest(typedRpc, slot, getTypedBlockWithoutTransactionsConfig("signatures", finality, config));
return result ? {
...mapBlockBase(result),
signatures: [...result.signatures]
} : null;
}
case "accounts": {
const result = await sendTypedBlockRequest(typedRpc, slot, buildTypedAccountsBlockConfig(finality, config, args.fullConfig != null && "encoding" in args.fullConfig));
return result ? args.mapAccountsBlock(result) : null;
}
default: {
const result = await sendTypedBlockRequest(typedRpc, slot, args.fullConfig);
return result ? args.mapFullBlock(result) : null;
}
}
}
function sendTypedBlockRequest(typedRpc, slot, config) {
const getBlock = typedRpc.getBlock;
return getBlock(slot, config).send();
}
function sendTypedTransactionRequest(typedRpc, signature, config) {
const getTransaction = typedRpc.getTransaction;
return getTransaction(signature, config).send();
}
async function fetchBlockSignaturesFromRpc(typedRpc, slot, commitment, notFoundMessage, errorContext) {
try {
const result = await typedRpc.getBlock(coerceNumericToBigInt(slot, "slot"), {
...commitment != null ? { commitment } : null,
transactionDetails: "signatures",
rewards: false
}).send();
if (!result) throw new Error(notFoundMessage);
return {
...result,
signatures: [...result.signatures]
};
} catch (error) {
if (error instanceof Error && error.message === notFoundMessage) throw error;
throwSolanaRpcErrorIfNeeded(error, errorContext);
}
}
async function fetchTransactionsBySignature(signatures, config, fetcher) {
return await Promise.all(signatures.map((signature) => fetcher(signature, config)));
}
function confirmationStatusSatisfiesCommitment(commitment, confirmationStatus, allowMissingConfirmationStatus = true) {
switch (commitment) {
case void 0: return true;
case "processed": return allowMissingConfirmationStatus || confirmationStatus != null;
case "confirmed": return confirmationStatus === "confirmed" || confirmationStatus === "finalized";
case "finalized": return confirmationStatus === "finalized";
default: return false;
}
}
function getLegacyTransactionConfirmationTimeoutMs(initialTimeoutMs, commitment) {
switch (commitment) {
case "processed":
case "confirmed": return initialTimeoutMs || 3e4;
case "finalized":
case void 0: return initialTimeoutMs || 6e4;
default: return initialTimeoutMs || 6e4;
}
}
/**
* A connection to a fullnode JSON RPC endpoint
*/
var Connection = class {
/**
* The Kit `Rpc` client backing this connection. Exposed to satisfy Kit's
* [`ClientWithRpc`](https://www.solanakit.com/api/type-aliases/ClientWithRpc)
* interface so a `Connection` can be passed to Kit-based libraries; for
* direct calls, prefer the `Connection` methods.
*/
rpc;
/**
* The Kit `RpcSubscriptions` client backing this connection. Exposed to
* satisfy Kit's
* [`ClientWithRpcSubscriptions`](https://www.solanakit.com/api/type-aliases/ClientWithRpcSubscriptions)
* interface; for direct subscriptions, prefer the `Connection` `on*Change`
* methods.
*/
rpcSubscriptions;
/** @internal */ _commitment;
/** @internal */ _confirmTransactionInitialTimeout;
/** @internal */ _rpcEndpoint;
/** @internal */ _rpcHttpHeaders;
/** @internal */ _rpcWsEndpoint;
/** @internal */ _typedRpc;
/** @internal */ _subscriptionsRuntime;
/** @internal */ _subscriptionController;
/** @internal */ _subscriptionRegistry = new ConnectionSubscriptionRegistry();
/** @internal */ _disableBlockhashCaching = false;
/** @internal */ _pollingBlockhash = false;
/** @internal */ _blockhashInfo = {
latestBlockhash: null,
lastFetch: 0,
transactionSignatures: [],
simulatedSignatures: []
};
/**
* Establish a JSON RPC connection
*
* @param endpoint URL to the fullnode JSON RPC endpoint
* @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object
*/
constructor(endpoint, commitmentOrConfig) {
let customFetch;
let fetchMiddleware;
let wsEndpoint;
let httpHeaders;
let disableRetryOnRateLimit;
let subscriptionChannelConfig;
if (commitmentOrConfig && typeof commitmentOrConfig === "string") this._commitment = commitmentOrConfig;
else if (commitmentOrConfig) {
this._commitment = commitmentOrConfig.commitment;
this._confirmTransactionInitialTimeout = commitmentOrConfig.confirmTransactionInitialTimeout;
wsEndpoint = commitmentOrConfig.wsEndpoint;
subscriptionChannelConfig = commitmentOrConfig.subscriptions?.channelConfig;
customFetch = commitmentOrConfig.fetch;
fetchMiddleware = commitmentOrConfig.fetchMiddleware;
httpHeaders = commitmentOrConfig.httpHeaders;
disableRetryOnRateLimit = commitmentOrConfig.disableRetryOnRateLimit;
}
this._rpcEndpoint = assertEndpointUrl(endpoint);
this._rpcHttpHeaders = httpHeaders;
this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint);
const { typedRpc } = createKitRpcClient(endpoint, Object.freeze({
commitment: this._commitment,
disableRetryOnRateLimit,
fetch: customFetch,
fetchMiddleware,
httpHeaders
}));
this._typedRpc = typedRpc;
this.rpc = typedRpc;
const subscriptionController = new ConnectionSubscriptionsController(this._subscriptionRegistry, () => this._subscriptionsRuntime, (spec) => fastStableStringify(spec));
this._subscriptionController = subscriptionController;
const dispatchSubscriptionNotification = (notificationEvent) => {
subscriptionController.handleNotification(notificationEvent);
};
const subscriptionsRuntime = new KitSubscriptionRuntime(this._rpcWsEndpoint, this._subscriptionRegistry, {
onConnected: () => {
subscriptionController.updateSubscriptions();
},
onDisconnected: (code) => {
subscriptionController.handleRuntimeDisconnected(code);
}
}, dispatchSubscriptionNotification, subscriptionChannelConfig, this._commitment);
this._subscriptionsRuntime = subscriptionsRuntime;
this.rpcSubscriptions = subscriptionsRuntime.rpcSubscriptions;
}
/** @internal */
get _subscriptionChannel() {
return this._subscriptionsRuntime.channel;
}
/**
* The default commitment used for requests
*/
get commitment() {
return this._commitment;
}
/**
* The RPC endpoint
*/
get rpcEndpoint() {
return this._rpcEndpoint;
}
/**
* The HTTP headers used by this connection for JSON-RPC requests.
*/
get rpcHttpHeaders() {
return this._rpcHttpHeaders;
}
/**
* Fetch the balance for the specified public key, return with context
*/
async getBalanceAndContext(publicKey, commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
try {
return await (rpcCommitment == null && minContextSlot == null ? this._typedRpc.getBalance(publicKey.toBase58()) : this._typedRpc.getBalance(publicKey.toBase58(), {
...rpcCommitment != null ? { commitment: rpcCommitment } : null,
...minContextSlot != null ? { minContextSlot } : null
})).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get balance for ${publicKey.toBase58()}`);
}
}
/**
* Fetch the balance for the specified public key
*/
async getBalance(publicKey, commitmentOrConfig) {
return (await this.getBalanceAndContext(publicKey, commitmentOrConfig)).value;
}
/**
* Fetch the estimated production time of a block
*/
async getBlockTime(slot) {
try {
return await this._typedRpc.getBlockTime(coerceNumericToBigInt(slot, "slot")).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get block time for slot ${slot}`);
}
}
/**
* Fetch the lowest slot that the node has information about in its ledger.
* This value may increase over time if the node is configured to purge older ledger data
*/
async getMinimumLedgerSlot() {
try {
return await this._typedRpc.minimumLedgerSlot().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get minimum ledger slot");
}
}
/**
* Fetch the slot of the lowest confirmed block that has not been purged from the ledger
*/
async getFirstAvailableBlock() {
try {
return await this._typedRpc.getFirstAvailableBlock().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get first available block");
}
}
/**
* Fetch information about the current supply
*/
async getSupply(config) {
const { commitment, config: rawConfig } = extractCommitmentFromConfig(config);
const rpcCommitment = this._resolveCommitment(commitment);
try {
const response = await (rawConfig?.excludeNonCirculatingAccountsList === true ? this._typedRpc.getSupply({
...rpcCommitment != null ? { commitment: rpcCommitment } : null,
excludeNonCirculatingAccountsList: true
}) : rpcCommitment != null ? this._typedRpc.getSupply({ commitment: rpcCommitment }) : this._typedRpc.getSupply()).send();
return {
...response,
value: {
...response.value,
nonCirculatingAccounts: response.value.nonCirculatingAccounts.map((address) => new PublicKey(address))
}
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get supply");
}
}
/**
* Fetch the current supply of a token mint
*/
async getTokenSupply(tokenMintAddress, commitmentOrConfig) {
const { commitment } = extractCommitmentFromConfig(commitmentOrConfig);
const typedMintAddress = tokenMintAddress.toBase58();
const rpcCommitment = this._resolveCommitment(commitment);
try {
return await (rpcCommitment == null ? this._typedRpc.getTokenSupply(typedMintAddress) : this._typedRpc.getTokenSupply(typedMintAddress, { commitment: rpcCommitment })).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get token supply");
}
}
/**
* Fetch the current balance of a token account
*/
async getTokenAccountBalance(tokenAddress, commitmentOrConfig) {
const { commitment } = extractCommitmentFromConfig(commitmentOrConfig);
const typedTokenAddress = tokenAddress.toBase58();
const rpcCommitment = this._resolveCommitment(commitment);
try {
return await (rpcCommitment == null ? this._typedRpc.getTokenAccountBalance(typedTokenAddress) : this._typedRpc.getTokenAccountBalance(typedTokenAddress, { commitment: rpcCommitment })).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get token account balance");
}
}
/**
* Fetch all the token accounts owned by the specified account
*
* @return {Promise<RpcResponseAndContext<GetProgramAccountsResponse>}
*/
async getTokenAccountsByOwner(ownerAddress, filter, commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const typedFilter = getTokenAccountsRpcFilter(filter);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
try {
const response = await this._typedRpc.getTokenAccountsByOwner(ownerAddress.toBase58(), typedFilter, {
commitment: rpcCommitment,
dataSlice: config?.dataSlice,
encoding: "base64",
minContextSlot
}).send();
return {
context: response.context,
value: mapKeyedBase64AccountInfos(response.value, "Expected token account rentEpoch")
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get token accounts owned by account ${ownerAddress.toBase58()}`);
}
}
/**
* Fetch all the token accounts delegated to the specified account
*
* @return {Promise<RpcResponseAndContext<GetProgramAccountsResponse>}
*/
async getTokenAccountsByDelegate(delegateAddress, filter, commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const typedFilter = getTokenAccountsRpcFilter(filter);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
try {
const response = await this._typedRpc.getTokenAccountsByDelegate(delegateAddress.toBase58(), typedFilter, {
commitment: rpcCommitment,
dataSlice: config?.dataSlice,
encoding: "base64",
minContextSlot
}).send();
return {
context: response.context,
value: mapKeyedBase64AccountInfos(response.value, "Expected delegated token account rentEpoch")
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get token accounts delegated to account ${delegateAddress.toBase58()}`);
}
}
/**
* Fetch parsed token accounts owned by the specified account
*
* @return {Promise<RpcResponseAndContext<Array<{pubkey: PublicKey, account: AccountInfo<ParsedAccountData>}>>>}
*/
async getParsedTokenAccountsByOwner(ownerAddress, filter, commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const typedFilter = getTokenAccountsRpcFilter(filter);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
try {
const response = await this._typedRpc.getTokenAccountsByOwner(ownerAddress.toBase58(), typedFilter, {
commitment: rpcCommitment,
encoding: "jsonParsed",
minContextSlot
}).send();
return {
context: response.context,
value: mapKeyedParsedAccountInfos(response.value, "Expected token account rentEpoch")
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get token accounts owned by account ${ownerAddress.toBase58()}`);
}
}
/**
* Fetch the 20 largest accounts with their current balances
*/
async getLargestAccounts(config) {
const rpcCommitment = this._resolveCommitment(config?.commitment);
const rpcConfig = {
...config?.filter != null ? { filter: config.filter } : null,
...rpcCommitment != null ? { commitment: rpcCommitment } : null
};
try {
const result = await (config?.filter != null || rpcCommitment != null ? this._typedRpc.getLargestAccounts(rpcConfig) : this._typedRpc.getLargestAccounts()).send();
return {
...result,
context: result.context,
value: result.value.map((account) => ({
...account,
address: new PublicKey(account.address)
}))
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get largest accounts");
}
}
/**
* Fetch the 20 largest token accounts with their current balances
* for a given mint.
*/
async getTokenLargestAccounts(mintAddress, commitmentOrConfig) {
const { commitment } = extractCommitmentFromConfig(commitmentOrConfig);
const typedMintAddress = mintAddress.toBase58();
const rpcCommitment = this._resolveCommitment(commitment);
try {
const result = await (rpcCommitment == null ? this._typedRpc.getTokenLargestAccounts(typedMintAddress) : this._typedRpc.getTokenLargestAccounts(typedMintAddress, { commitment: rpcCommitment })).send();
return {
...result,
context: result.context,
value: result.value.map((account) => ({
...account,
address: new PublicKey(account.address)
}))
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get token largest accounts");
}
}
/**
* Fetch all the account info for the specified public key, return with context
*/
async getAccountInfoAndContext(publicKey, commitmentOrConfig) {
try {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const typedPublicKey = publicKey.toBase58();
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
const response = await this._typedRpc.getAccountInfo(typedPublicKey, {
commitment: rpcCommitment,
dataSlice: config?.dataSlice,
encoding: "base64",
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
}).send();
return {
context: response.context,
value: mapBase64AccountInfo(response.value, "Expected raw account info rentEpoch")
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get info about account ${publicKey.toBase58()}`);
}
}
/**
* Fetch parsed account info for the specified public key
*/
async getParsedAccountInfo(publicKey, commitmentOrConfig) {
try {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const typedPublicKey = publicKey.toBase58();
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
const response = await this._typedRpc.getAccountInfo(typedPublicKey, {
commitment: rpcCommitment,
encoding: "jsonParsed",
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
}).send();
return {
context: response.context,
value: mapJsonParsedAccountInfo(response.value, "Expected parsed account info rentEpoch")
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get info about account ${publicKey.toBase58()}`);
}
}
/**
* Fetch all the account info for the specified public key
*/
async getAccountInfo(publicKey, commitmentOrConfig) {
try {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const typedPublicKey = publicKey.toBase58();
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
const response = await this._typedRpc.getAccountInfo(typedPublicKey, {
commitment: rpcCommitment,
dataSlice: config?.dataSlice,
encoding: "base64",
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
}).send();
if (response.value == null) return null;
return mapBase64AccountInfo(response.value, "Expected raw account info rentEpoch");
} catch (e) {
throw new Error("failed to get info about account " + publicKey.toBase58() + ": " + String(e));
}
}
/**
* Fetch all the account info for multiple accounts specified by an array of public keys, return with context
*/
async getMultipleParsedAccounts(publicKeys, rawConfig) {
try {
const { commitment, config } = extractCommitmentFromConfig(rawConfig);
const typedPublicKeys = publicKeys.map((key) => key.toBase58());
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
const response = await this._typedRpc.getMultipleAccounts(typedPublicKeys, {
commitment: rpcCommitment,
encoding: "jsonParsed",
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
}).send();
return {
context: response.context,
value: response.value.map((account) => mapJsonParsedAccountInfo(account, "Expected parsed account info rentEpoch"))
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get info for accounts ${publicKeys.map((key) => key.toBase58()).join(",")}`);
}
}
/**
* Fetch all the account info for multiple accounts specified by an array of public keys, return with context
*/
async getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig) {
try {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const typedPublicKeys = publicKeys.map((key) => key.toBase58());
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
const response = await this._typedRpc.getMultipleAccounts(typedPublicKeys, {
commitment: rpcCommitment,
dataSlice: config?.dataSlice,
encoding: "base64",
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
}).send();
return {
context: response.context,
value: response.value.map((account) => mapBase64AccountInfo(account, "Expected raw account info rentEpoch"))
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get info for accounts ${publicKeys.map((key) => key.toBase58()).join(",")}`);
}
}
/**
* Fetch all the account info for multiple accounts specified by an array of public keys
*/
async getMultipleAccountsInfo(publicKeys, commitmentOrConfig) {
return (await this.getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig)).value;
}
async getProgramAccounts(programId, configOrCommitment) {
const { commitment, config } = extractCommitmentFromConfig(configOrCommitment);
const configWithoutEncoding = config || {};
const rpcCommitment = this._resolveCommitment(commitment);
const filters = getProgramAccountsRpcFilters(configWithoutEncoding.filters);
const minContextSlot = coerceOptionalNumericToBigInt(configWithoutEncoding.minContextSlot, "minContextSlot");
const typedProgramId = programId.toBase58();
const rpcConfig = {
commitment: rpcCommitment,
dataSlice: configWithoutEncoding.dataSlice,
encoding: "base64",
filters,
minContextSlot
};
try {
if (configWithoutEncoding.withContext === true) {
const response = await this._typedRpc.getProgramAccounts(typedProgramId, {
...rpcConfig,
withContext: true
}).send();
return {
context: response.context,
value: mapKeyedBase64AccountInfos(response.value, "Expected program account rentEpoch")
};
}
return mapKeyedBase64AccountInfos(await this._typedRpc.getProgramAccounts(typedProgramId, rpcConfig).send(), "Expected program account rentEpoch");
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get accounts owned by program ${programId.toBase58()}`);
}
}
/**
* Fetch and parse all the accounts owned by the specified program id
*
* @return {Promise<Array<{pubkey: PublicKey, account: AccountInfo<Uint8Array | ParsedAccountData>}>>}
*/
async getParsedProgramAccounts(programId, configOrCommitment) {
const { commitment, config } = extractCommitmentFromConfig(configOrCommitment);
const rpcCommitment = this._resolveCommitment(commitment);
const filters = getProgramAccountsRpcFilters(config?.filters);
const minContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
try {
return mapKeyedJsonParsedAccountInfos(await this._typedRpc.getProgramAccounts(programId.toBase58(), {
commitment: rpcCommitment,
encoding: "jsonParsed",
filters,
minContextSlot
}).send(), "Expected program account rentEpoch");
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get accounts owned by program ${programId.toBase58()}`);
}
}
async confirmTransaction(strategy, commitment) {
let rawSignature;
if (typeof strategy == "string") rawSignature = strategy;
else {
const config = strategy;
if (config.abortSignal?.aborted) throw config.abortSignal.reason;
rawSignature = config.signature;
}
let decodedSignature;
try {
decodedSignature = BASE58_ENCODER.encode(rawSignature);
} catch {
throw new Error("signature must be base58 encoded: " + rawSignature);
}
assert_default(decodedSignature.length === 64, "signature has invalid length");
if (typeof strategy === "string") return await this.confirmTransactionUsingLegacyTimeoutStrategy({
commitment: this._resolveCommitment(commitment),
signature: rawSignature
});
else if ("lastValidBlockHeight" in strategy) return await this.confirmTransactionUsingBlockHeightExceedanceStrategy({
commitment: this._resolveCommitment(commitment),
strategy
});
else return await this.confirmTransactionUsingDurableNonceStrategy({
commitment: this._resolveCommitment(commitment),
strategy
});
}
getCancellationPromise(signal) {
return new Promise((_, reject) => {
if (signal == null) return;
if (signal.aborted) reject(signal.reason);
else signal.addEventListener("abort", () => {
reject(signal.reason);
});
});
}
_resolveCommitment(requestedCommitment) {
return requestedCommitment ?? this._commitment ?? "confirmed";
}
_resolveSupportedFinality(requestedCommitment) {
const rpcCommitment = this._resolveCommitment(requestedCommitment);
if (!["confirmed", "finalized"].includes(rpcCommitment)) throw new Error("Method does not support commitment below `confirmed`");
return rpcCommitment;
}
_resolveSubscriptionCommitment(requestedCommitment) {
return this._resolveCommitment(requestedCommitment);
}
/**
* Normalize a subscription's commitment-or-config input into a config object
* with an explicit commitment.
*/
_resolveSubscriptionConfig(commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
return {
...config,
commitment: this._resolveSubscriptionCommitment(commitment)
};
}
getTransactionConfirmationPromise({ commitment, signature }) {
let signatureSubscriptionId;
let disposeSignatureSubscriptionStateChangeObserver;
let done = false;
const confirmationPromise = new Promise((resolve, reject) => {
try {
signatureSubscriptionId = this.onSignature(signature, (result, context) => {
signatureSubscriptionId = void 0;
resolve({
__type: 1,
response: {
context,
value: result
}
});
}, commitment);
const subscriptionSetupPromise = new Promise((resolveSubscriptionSetup) => {
if (signatureSubscriptionId == null) resolveSubscriptionSetup();
else {
const settleSubscriptionSetup = (nextState) => {
if (nextState !== "failed" && nextState !== "inactive" && nextState !== "subscribed") return;
if (disposeSignatureSubscriptionStateChangeObserver) {
disposeSignatureSubscriptionStateChangeObserver();
disposeSignatureSubscriptionStateChangeObserver = void 0;
}
resolveSubscriptionSetup();
};
const { currentState, dispose } = this._subscriptionRegistry.observeStateChanges(signatureSubscriptionId, settleSubscriptionSetup);
disposeSignatureSubscriptionStateChangeObserver = dispose;
settleSubscriptionSetup(currentState);
}
});
(async () => {
try {
await subscriptionSetupPromise;
if (done) return;
const response = await this.getSignatureStatus(signature);
if (done) return;
if (response == null) return;
const { context, value } = response;
if (value == null) return;
if (value?.err) reject(value.err);
else if (confirmationStatusSatisfiesCommitment(commitment, value.confirmationStatus)) {
done = true;
resolve({
__type: 1,
response: {
context: { slot: context.slot },
value
}
});
}
} catch {}
})();
} catch (err) {
reject(err);
}
});
const abortConfirmation = async () => {
if (disposeSignatureSubscriptionStateChangeObserver) {
disposeSignatureSubscriptionStateChangeObserver();
disposeSignatureSubscriptionStateChangeObserver = void 0;
}
if (signatureSubscriptionId != null) {
await this.removeSignatureListener(signatureSubscriptionId);
signatureSubscriptionId = void 0;
}
};
return {
abortConfirmation,
confirmationPromise
};
}
async confirmTransactionUsingBlockHeightExceedanceStrategy({ commitment, strategy: { abortSignal, lastValidBlockHeight, signature } }) {
let done = false;
const lastValidBlockHeightBigInt = coerceNumericToBigInt(lastValidBlockHeight, "lastValidBlockHeight");
const cancellationPromise = this.getCancellationPromise(abortSignal);
const cancellationSentinel = Symbol("blockheight-cancelled");
const expiryPromise = new Promise((resolve) => {
const checkBlockHeight = async () => {
try {
return await this._typedRpc.getBlockHeight({ commitment }).send(abortSignal == null ? void 0 : { abortSignal });
} catch {
return -1n;
}
};
(async () => {
let currentBlockHeight = await Promise.race([checkBlockHeight(), cancellationPromise.catch(() => cancellationSentinel)]);
if (done || currentBlockHeight === cancellationSentinel) return;
while (currentBlockHeight <= lastValidBlockHeightBigInt) {
const sleepResult = await Promise.race([sleep(1e3), cancellationPromise.catch(() => cancellationSentinel)]);
if (done || sleepResult === cancellationSentinel) return;
currentBlockHeight = await Promise.race([checkBlockHeight(), cancellationPromise.catch(() => cancellationSentinel)]);
if (done || currentBlockHeight === cancellationSentinel) return;
}
resolve({ __type: 0 });
})();
});
const { abortConfirmation, confirmationPromise } = this.getTransactionConfirmationPromise({
commitment,
signature
});
let result;
try {
const outcome = await Promise.race([
cancellationPromise,
confirmationPromise,
expiryPromise
]);
if (outcome.__type === 1) result = outcome.response;
else {
const signatureStatus = await Promise.race([this.getSignatureStatus(signature), cancellationPromise]);
if (signatureStatus?.value && confirmationStatusSatisfiesCommitment(commitment, signatureStatus.value.confirmationStatus, false)) result = {
context: { slot: signatureStatus.context.slot },
value: { err: signatureStatus.value.err }
};
else throw new TransactionExpiredBlockheightExceededError(signature);
}
} finally {
done = true;
await abortConfirmation();
}
return result;
}
async confirmTransactionUsingDurableNonceStrategy({ commitment, strategy: { abortSignal, minContextSlot, nonceAccountPubkey, nonceValue, signature } }) {
let done = false;
const nonceMinContextSlot = coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot");
const cancellationPromise = this.getCancellationPromise(abortSignal);
const cancellationSentinel = Symbol("nonce-cancelled");
const expiryPromise = new Promise((resolve) => {
let currentNonceValue = nonceValue;
let lastCheckedSlot = null;
const getCurrentNonceValue = async () => {
try {
const { context, value: nonceAccount } = await this.getNonceAndContext(nonceAccountPubkey, {
commitment,
minContextSlot
});
lastCheckedSlot = context.slot;
return nonceAccount?.nonce;
} catch {
return currentNonceValue;
}
};
(async () => {
const initialNonceValue = await Promise.race([getCurrentNonceValue(), cancellationPromise.catch(() => cancellationSentinel)]);
if (done || initialNonceValue === cancellationSentinel) return;
currentNonceValue = initialNonceValue;
while (true) {
if (nonceValue !== currentNonceValue) {
resolve({
__type: 3,
slotInWhichNonceDidAdvance: lastCheckedSlot
});
return;
}
const sleepResult = await Promise.race([sleep(2e3), cancellationPromise.catch(() => cancellationSentinel)]);
if (done || sleepResult === cancellationSentinel) return;
const nextNonceValue = await Promise.race([getCurrentNonceValue(), cancellationPromise.catch(() => cancellationSentinel)]);
if (done || nextNonceValue === cancellationSentinel) return;
currentNonceValue = nextNonceValue;
}
})();
});
const { abortConfirmation, confirmationPromise } = this.getTransactionConfirmationPromise({
commitment,
signature
});
let result;
try {
const outcome = await Promise.race([
cancellationPromise,
confirmationPromise,
expiryPromise
]);
if (outcome.__type === 1) result = outcome.response;
else {
let signatureStatus;
while (true) {
const status = await Promise.race([this.getSignatureStatus(signature, { searchTransactionHistory: true }), cancellationPromise]);
if (status == null) break;
if (status.context.slot < (outcome.slotInWhichNonceDidAdvance ?? nonceMinContextSlot ?? 0n)) {
await Promise.race([sleep(400), cancellationPromise]);
continue;
}
signatureStatus = status;
break;
}
if (signatureStatus?.value) {
const { confirmationStatus } = signatureStatus.value;
if (!confirmationStatusSatisfiesCommitment(commitment, confirmationStatus, false)) throw new TransactionExpiredNonceInvalidError(signature);
result = {
context: { slot: signatureStatus.context.slot },
value: { err: signatureStatus.value.err }
};
} else throw new TransactionExpiredNonceInvalidError(signature);
}
} finally {
done = true;
await abortConfirmation();
}
return result;
}
async confirmTransactionUsingLegacyTimeoutStrategy({ commitment, signature }) {
let timeoutId;
const expiryPromise = new Promise((resolve) => {
const timeoutMs = getLegacyTransactionConfirmationTimeoutMs(this._confirmTransactionInitialTimeout, commitment);
timeoutId = setTimeout(() => resolve({
__type: 2,
timeoutMs
}), timeoutMs);
});
const { abortConfirmation, confirmationPromise } = this.getTransactionConfirmationPromise({
commitment,
signature
});
let result;
try {
const outcome = await Promise.race([confirmationPromise, expiryPromise]);
if (outcome.__type === 1) result = outcome.response;
else throw new TransactionExpiredTimeoutError(signature, outcome.timeoutMs / 1e3);
} finally {
clearTimeout(timeoutId);
await abortConfirmation();
}
return result;
}
/**
* Return the list of nodes that are currently participating in the cluster
*/
async getClusterNodes() {
try {
return await this._typedRpc.getClusterNodes().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get cluster nodes");
}
}
/**
* Fetch the RPC node health status.
*/
async getHealth() {
try {
return await this._typedRpc.getHealth().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get health");
}
}
/**
* Fetch the RPC node identity.
*/
async getIdentity() {
try {
return { identity: new PublicKey((await this._typedRpc.getIdentity().send()).identity) };
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get identity");
}
}
/**
* Fetch the highest full and incremental snapshot slots available on the RPC node.
*/
async getHighestSnapshotSlot() {
try {
return await this._typedRpc.getHighestSnapshotSlot().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get highest snapshot slot");
}
}
/**
* Fetch the highest slot seen by retransmit stage.
*/
async getMaxRetransmitSlot() {
try {
return await this._typedRpc.getMaxRetransmitSlot().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get max retransmit slot");
}
}
/**
* Fetch the highest slot seen by blockstore.
*/
async getMaxShredInsertSlot() {
try {
return await this._typedRpc.getMaxShredInsertSlot().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get max shred insert slot");
}
}
/**
* Return the list of nodes that are currently participating in the cluster
*/
async getVoteAccounts(commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const typedVotePubkey = config?.votePubkey == null ? void 0 : new PublicKey(config.votePubkey).toBase58();
const delinquentSlotDistance = config?.delinquentSlotDistance == null ? void 0 : coerceNumericToBigInt(config.delinquentSlotDistance, "delinquentSlotDistance");
const rpcConfig = {
...rpcCommitment != null ? { commitment: rpcCommitment } : null,
...typedVotePubkey != null ? { votePubkey: typedVotePubkey } : null,
...config?.keepUnstakedDelinquents != null ? { keepUnstakedDelinquents: config.keepUnstakedDelinquents } : null,
...delinquentSlotDistance != null ? { delinquentSlotDistance } : null
};
try {
return await (rpcCommitment != null || typedVotePubkey != null || config?.keepUnstakedDelinquents != null || delinquentSlotDistance != null ? this._typedRpc.getVoteAccounts(rpcConfig) : this._typedRpc.getVoteAccounts()).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get vote accounts");
}
}
/**
* Fetch the current slot that the node is processing
*/
async getSlot(commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
try {
if (rpcCommitment == null && minContextSlot == null) return await this._typedRpc.getSlot().send();
return await this._typedRpc.getSlot({
commitment: rpcCommitment,
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
}).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get slot");
}
}
/**
* Fetch the current slot leader of the cluster
*/
async getSlotLeader(commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
try {
return await (rpcCommitment == null && minContextSlot == null ? this._typedRpc.getSlotLeader() : this._typedRpc.getSlotLeader({
commitment: rpcCommitment,
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
})).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get slot leader");
}
}
/**
* Fetch `limit` number of slot leaders starting from `startSlot`
*
* @param startSlot fetch slot leaders starting from this slot
* @param limit number of slot leaders to return
*/
async getSlotLeaders(startSlot, limit) {
try {
return (await this._typedRpc.getSlotLeaders(coerceNumericToBigInt(startSlot, "startSlot"), limit).send()).map((address) => new PublicKey(address));
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get slot leaders");
}
}
/**
* Fetch the current status of a signature
*/
async getSignatureStatus(signature, config) {
const { context, value: values } = await this.getSignatureStatuses([signature], config);
assert_default(values.length === 1);
return {
context,
value: values[0]
};
}
/**
* Fetch the current statuses of a batch of signatures
*/
async getSignatureStatuses(signatures, config) {
try {
assertIsTransactionSignatureArray(signatures);
const rpcConfig = buildTypedSignatureStatusesConfig(config);
const response = await (rpcConfig == null ? this._typedRpc.getSignatureStatuses(signatures) : this._typedRpc.getSignatureStatuses(signatures, rpcConfig)).send();
return {
context: response.context,
value: response.value.map((status) => status == null ? null : {
confirmationStatus: status.confirmationStatus,
confirmations: status.confirmations,
err: status.err,
slot: status.slot
})
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get signature status");
}
}
/**
* Fetch the current transaction count of the cluster
*/
async getTransactionCount(commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
try {
if (rpcCommitment == null && minContextSlot == null) return await this._typedRpc.getTransactionCount().send();
return await this._typedRpc.getTransactionCount({
commitment: rpcCommitment,
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
}).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get transaction count");
}
}
/**
* Fetch the cluster InflationGovernor parameters
*/
async getInflationGovernor(commitmentOrConfig) {
const { commitment } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
try {
return await (rpcCommitment == null ? this._typedRpc.getInflationGovernor() : this._typedRpc.getInflationGovernor({ commitment: rpcCommitment })).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get inflation");
}
}
/**
* Fetch the inflation reward for a list of addresses for an epoch
*/
async getInflationReward(addresses, epoch, commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const rpcEpoch = epoch != null ? coerceNumericToBigInt(epoch, "epoch") : config?.epoch == null ? void 0 : coerceNumericToBigInt(config.epoch, "epoch");
const minContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
const typedAddresses = addresses.map((address) => address.toBase58());
const rpcConfig = rpcCommitment != null || rpcEpoch != null || minContextSlot != null ? {
...rpcCommitment != null ? { commitment: rpcCommitment } : null,
...rpcEpoch != null ? { epoch: rpcEpoch } : null,
...minContextSlot != null ? { minContextSlot } : null
} : void 0;
const getInflationReward = this._typedRpc.getInflationReward;
try {
return [...await getInflationReward(typedAddresses, rpcConfig).send()];
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get inflation reward");
}
}
/**
* Fetch the specific inflation values for the current epoch
*/
async getInflationRate() {
try {
return await this._typedRpc.getInflationRate().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get inflation rate");
}
}
/**
* Fetch the Epoch Info parameters
*/
async getEpochInfo(commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
try {
return await (rpcCommitment == null && minContextSlot == null ? this._typedRpc.getEpochInfo() : this._typedRpc.getEpochInfo({
commitment: rpcCommitment,
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
})).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get epoch info");
}
}
/**
* Fetch the Epoch Schedule parameters
*/
async getEpochSchedule() {
try {
const epochSchedule = await this._typedRpc.getEpochSchedule().send();
return new EpochSchedule(epochSchedule.slotsPerEpoch, epochSchedule.leaderScheduleSlotOffset, epochSchedule.warmup, epochSchedule.firstNormalEpoch, epochSchedule.firstNormalSlot);
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get epoch schedule");
}
}
/**
* Fetch the leader schedule for the current epoch
* @return {Promise<RpcResponseAndContext<LeaderSchedule>>}
*/
async getLeaderSchedule(slotOrCommitmentOrConfig, commitmentOrConfig) {
let slot;
let rawCommitmentOrConfig;
if (typeof slotOrCommitmentOrConfig === "number" || typeof slotOrCommitmentOrConfig === "bigint" || slotOrCommitmentOrConfig === null) {
slot = slotOrCommitmentOrConfig;
rawCommitmentOrConfig = commitmentOrConfig;
} else rawCommitmentOrConfig = slotOrCommitmentOrConfig;
const { commitment, config } = extractCommitmentFromConfig(rawCommitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const rpcIdentity = config?.identity;
if (rpcIdentity != null) assertIsAddress(rpcIdentity);
const rpcKeyByVoteAccount = config?.keyByVoteAccount;
const rpcConfig = rpcCommitment != null || rpcIdentity != null || rpcKeyByVoteAccount != null ? {
...rpcCommitment != null ? { commitment: rpcCommitment } : null,
...rpcIdentity != null ? { identity: rpcIdentity } : null,
...rpcKeyByVoteAccount != null ? { keyByVoteAccount: rpcKeyByVoteAccount } : null
} : void 0;
const getLeaderSchedule = this._typedRpc.getLeaderSchedule;
const rpcSlot = typeof slot === "number" || typeof slot === "bigint" ? coerceNumericToBigInt(slot, "slot") : slot;
try {
if (rpcSlot === void 0 && rpcConfig == null) return await getLeaderSchedule().send();
return await getLeaderSchedule(rpcSlot ?? null, rpcConfig).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get leader schedule");
}
}
/**
* Fetch the minimum balance needed to exempt an account of `dataLength`
* size from rent
*/
async getMinimumBalanceForRentExemption(dataLength, commitmentOrConfig) {
const { commitment } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const rpcDataLength = coerceNumericToBigInt(dataLength, "dataLength");
try {
return await (rpcCommitment == null ? this._typedRpc.getMinimumBalanceForRentExemption(rpcDataLength) : this._typedRpc.getMinimumBalanceForRentExemption(rpcDataLength, { commitment: rpcCommitment })).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `failed to get minimum balance for rent exemption for ${dataLength} bytes`);
}
}
/**
* Fetch the minimum rent-exempt balance for an account with `space` bytes of
* data, including the 128-byte account header unless `withoutHeader` is set.
* Satisfies Kit's
* [`ClientWithGetMinimumBalance`](https://www.solanakit.com/api/type-aliases/ClientWithGetMinimumBalance)
* interface.
*/
getMinimumBalance = async (space, config) => {
if (config?.withoutHeader) {
const dataLength = coerceNumericToBigInt(space, "space");
const lamportsPerByte = await this.getMinimumBalanceForRentExemption(0) / BigInt(BASE_ACCOUNT_SIZE);
return lamports(lamportsPerByte * dataLength);
}
return await this.getMinimumBalanceForRentExemption(space);
};
/**
* Fetch recent performance samples
* @return {Promise<readonly PerfSample[]>}
*/
async getRecentPerformanceSamples(limit) {
try {
return await (limit ? this._typedRpc.getRecentPerformanceSamples(limit) : this._typedRpc.getRecentPerformanceSamples()).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get recent performance samples");
}
}
/**
* Fetch the fee for a message from the cluster, return with context
*/
async getFeeForMessage(message, commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
const wireMessage = encodeBase64WireData(message.serialize());
try {
const response = await (rpcCommitment == null && minContextSlot == null ? this._typedRpc.getFeeForMessage(wireMessage) : this._typedRpc.getFeeForMessage(wireMessage, {
commitment: rpcCommitment,
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
})).send();
if (response.value === null) throw new Error("invalid blockhash");
return response;
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get fee for message");
}
}
/**
* Fetch a list of prioritization fees from recent blocks.
*/
async getRecentPrioritizationFees(config) {
const accounts = config?.lockedWritableAccounts?.map((key) => key.toBase58());
try {
return await (accounts == null ? this._typedRpc.getRecentPrioritizationFees() : this._typedRpc.getRecentPrioritizationFees(accounts)).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get recent prioritization fees");
}
}
/**
* Fetch the latest blockhash from the cluster
* @return {Promise<BlockhashWithExpiryBlockHeight>}
*/
getLatestBlockhash(commitmentOrConfig) {
return this.getLatestBlockhashAndContext(commitmentOrConfig).then((response) => response.value).catch((e) => {
throw new Error("failed to get recent blockhash: " + e);
});
}
/**
* Fetch the latest blockhash from the cluster
* @return {Promise<BlockhashWithExpiryBlockHeight>}
*/
async getLatestBlockhashAndContext(commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
try {
const response = await (rpcCommitment == null && minContextSlot == null ? this._typedRpc.getLatestBlockhash() : this._typedRpc.getLatestBlockhash({
...rpcCommitment != null ? { commitment: rpcCommitment } : null,
...minContextSlot != null ? { minContextSlot: coerceNumericToBigInt(minContextSlot, "minContextSlot") } : null
})).send();
return {
context: response.context,
value: {
blockhash: response.value.blockhash,
lastValidBlockHeight: response.value.lastValidBlockHeight
}
};
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get latest blockhash");
}
}
/**
* Returns whether a blockhash is still valid or not
*/
async isBlockhashValid(blockhash, rawConfig) {
const rpcBlockhash = blockhash;
const { commitment, config } = extractCommitmentFromConfig(rawConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const minContextSlot = config?.minContextSlot;
try {
return await (rpcCommitment == null && minContextSlot == null ? this._typedRpc.isBlockhashValid(rpcBlockhash) : this._typedRpc.isBlockhashValid(rpcBlockhash, {
commitment: rpcCommitment,
minContextSlot: coerceOptionalNumericToBigInt(minContextSlot, "minContextSlot")
})).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to determine if the blockhash `" + blockhash + "`is valid");
}
}
/**
* Fetch the Alpenglow genesis certificate, or `null` if the node does not
* have one.
*/
async getAgGenesisCert() {
try {
return await this._typedRpc.getAgGenesisCert().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get Alpenglow genesis certificate");
}
}
/**
* Fetch the node version
*/
async getVersion() {
try {
return await this._typedRpc.getVersion().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get version");
}
}
/**
* Fetch the genesis hash
*/
async getGenesisHash() {
try {
return await this._typedRpc.getGenesisHash().send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get genesis hash");
}
}
/**
* Fetch a processed block from the cluster.
*/
async getBlock(slot, rawConfig) {
const { commitment, config } = extractCommitmentFromConfig(rawConfig);
const finality = this._resolveSupportedFinality(commitment);
const rpcSlot = coerceNumericToBigInt(slot, "slot");
const fullConfig = buildTypedFullBlockConfig(finality, config, rawConfig != null);
try {
return await fetchTypedBlockWithMappers(this._typedRpc, rpcSlot, finality, config, {
mapAccountsBlock: (result) => ({
...mapBlockBase(result),
transactions: mapTypedAccountsModeBlockTransactions(result.transactions)
}),
fullConfig,
mapFullBlock: (result) => ({
...mapBlockBase(result),
transactions: result.transactions.map(mapTypedFullBlockTransaction)
})
});
} catch (e) {
throw new SolanaJSONRPCError(e, "failed to get confirmed block");
}
}
async getParsedBlock(slot, rawConfig) {
const { commitment, config } = extractCommitmentFromConfig(rawConfig);
const finality = this._resolveSupportedFinality(commitment);
const rpcSlot = coerceNumericToBigInt(slot, "slot");
const fullConfig = buildTypedParsedFullBlockConfig(finality, config);
try {
return await fetchTypedBlockWithMappers(this._typedRpc, rpcSlot, finality, config, {
mapAccountsBlock: (result) => ({
...mapBlockBase(result),
transactions: mapTypedAccountsModeBlockTransactions(result.transactions)
}),
fullConfig,
mapFullBlock: (result) => ({
...mapBlockBase(result),
transactions: result.transactions.map(mapTypedParsedBlockTransaction)
})
});
} catch (e) {
throw new SolanaJSONRPCError(e, "failed to get block");
}
}
getBlockHeight = (() => {
const requestPromises = {};
return (commitmentOrConfig) => {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
const rpcMinContextSlot = coerceOptionalNumericToBigInt(config?.minContextSlot, "minContextSlot");
const rpcConfig = rpcCommitment == null && rpcMinContextSlot == null ? void 0 : {
...rpcCommitment != null ? { commitment: rpcCommitment } : null,
...rpcMinContextSlot != null ? { minContextSlot: rpcMinContextSlot } : null
};
const requestHash = fastStableStringify({
commitment: rpcCommitment ?? null,
minContextSlot: rpcMinContextSlot?.toString() ?? null
});
requestPromises[requestHash] = requestPromises[requestHash] ?? (async () => {
try {
return await (rpcConfig == null ? this._typedRpc.getBlockHeight() : this._typedRpc.getBlockHeight(rpcConfig)).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get block height information");
} finally {
delete requestPromises[requestHash];
}
})();
return requestPromises[requestHash];
};
})();
async getBlockProduction(configOrCommitment) {
const { commitment, config } = extractCommitmentFromConfig(configOrCommitment);
const rpcCommitment = this._resolveCommitment(commitment);
const rpcIdentity = config?.identity;
const rpcRange = config?.range == null ? void 0 : {
firstSlot: coerceNumericToBigInt(config.range.firstSlot, "firstSlot"),
...config.range.lastSlot == null ? null : { lastSlot: coerceNumericToBigInt(config.range.lastSlot, "lastSlot") }
};
const rpcConfig = rpcCommitment == null && rpcIdentity == null && rpcRange == null ? void 0 : {
...rpcCommitment != null ? { commitment: rpcCommitment } : null,
...rpcIdentity != null ? { identity: rpcIdentity } : null,
...rpcRange != null ? { range: rpcRange } : null
};
try {
return await (rpcConfig == null ? this._typedRpc.getBlockProduction() : this._typedRpc.getBlockProduction(rpcConfig)).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get block production information");
}
}
/**
* Fetch a confirmed or finalized transaction from the cluster.
*/
async getTransaction(signature, rawConfig) {
const { commitment, config } = extractCommitmentFromConfig(rawConfig);
const typedConfig = buildTypedTransactionConfig(this._resolveSupportedFinality(commitment), config);
try {
const result = await sendTypedTransactionRequest(this._typedRpc, signature, typedConfig);
return result ? mapTypedTransactionResponse(result) : null;
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get transaction");
}
}
/**
* Fetch parsed transaction details for a confirmed or finalized transaction
*/
async getParsedTransaction(signature, commitmentOrConfig) {
const { commitment, config } = extractCommitmentFromConfig(commitmentOrConfig);
const typedConfig = buildTypedParsedTransactionConfig(this._resolveSupportedFinality(commitment), config);
try {
const result = await sendTypedTransactionRequest(this._typedRpc, signature, typedConfig);
return result ? mapTypedParsedTransactionResponse(result) : null;
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get transaction");
}
}
/**
* Fetch parsed transaction details for a batch of confirmed transactions
*/
async getParsedTransactions(signatures, commitmentOrConfig) {
return await fetchTransactionsBySignature(signatures, commitmentOrConfig == null ? void 0 : typeof commitmentOrConfig === "string" ? { commitment: commitmentOrConfig } : commitmentOrConfig, (signature, config) => this.getParsedTransaction(signature, config));
}
/**
* Fetch transaction details for a batch of confirmed transactions.
* Similar to {@link getParsedTransactions} but returns a {@link
* VersionedTransactionResponse}.
*/
async getTransactions(signatures, commitmentOrConfig) {
return await fetchTransactionsBySignature(signatures, commitmentOrConfig == null ? void 0 : typeof commitmentOrConfig === "string" ? { commitment: commitmentOrConfig } : commitmentOrConfig, (signature, config) => this.getTransaction(signature, config));
}
/**
* Fetch a list of Transactions and transaction statuses from the cluster
* for a confirmed block.
*
* @deprecated Deprecated since RPC v1.7.0. Please use {@link getBlock} instead.
*/
async getConfirmedBlock(slot, commitment) {
const result = await this.getBlock(slot, { commitment: this._resolveSupportedFinality(commitment) });
if (!result) throw new Error("Confirmed block " + slot + " not found");
return {
blockTime: result.blockTime,
blockhash: result.blockhash,
parentSlot: result.parentSlot,
previousBlockhash: result.previousBlockhash,
rewards: result.rewards,
transactions: result.transactions.map(({ transaction, meta }) => ({
meta,
transaction: Transaction.populate(transaction.message, transaction.signatures)
}))
};
}
async getBlocks(startSlot, endSlotOrCommitmentOrConfig, commitmentOrConfig) {
const rpcStartSlot = coerceNumericToBigInt(startSlot, "startSlot");
let rpcEndSlot;
let rawCommitmentOrConfig;
if (typeof endSlotOrCommitmentOrConfig === "number" || typeof endSlotOrCommitmentOrConfig === "bigint") {
rpcEndSlot = coerceNumericToBigInt(endSlotOrCommitmentOrConfig, "endSlot");
rawCommitmentOrConfig = commitmentOrConfig;
} else rawCommitmentOrConfig = endSlotOrCommitmentOrConfig ?? commitmentOrConfig;
const { commitment } = extractCommitmentFromConfig(rawCommitmentOrConfig);
const rpcConfig = { commitment: this._resolveSupportedFinality(commitment) };
const getBlocks = this._typedRpc.getBlocks;
try {
return await getBlocks(rpcStartSlot, rpcEndSlot, rpcConfig).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get blocks");
}
}
async getBlocksWithLimit(startSlot, limit, commitmentOrConfig) {
const { commitment } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcConfig = { commitment: this._resolveSupportedFinality(commitment) };
const rpcStartSlot = coerceNumericToBigInt(startSlot, "startSlot");
const getBlocksWithLimit = this._typedRpc.getBlocksWithLimit;
try {
return await getBlocksWithLimit(rpcStartSlot, limit, rpcConfig).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get blocks with limit");
}
}
/**
* Fetch the amount of cluster stake that has voted on a block.
*/
async getBlockCommitment(slot) {
try {
return await this._typedRpc.getBlockCommitment(coerceNumericToBigInt(slot, "slot")).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get block commitment");
}
}
/**
* Fetch a list of Signatures from the cluster for a block, excluding rewards
*/
getBlockSignatures(slot, commitment) {
return fetchBlockSignaturesFromRpc(this._typedRpc, slot, this._resolveSupportedFinality(commitment), `Block ${slot} not found`, "failed to get block");
}
/**
* Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards
*
* @deprecated Deprecated since RPC v1.7.0. Please use {@link getBlockSignatures} instead.
*/
getConfirmedBlockSignatures(slot, commitment) {
return fetchBlockSignaturesFromRpc(this._typedRpc, slot, this._resolveSupportedFinality(commitment), `Confirmed block ${slot} not found`, "failed to get confirmed block");
}
/**
* Fetch a transaction details for a confirmed transaction
*
* @deprecated Deprecated since RPC v1.7.0. Please use {@link getTransaction} instead.
*/
async getConfirmedTransaction(signature, commitment) {
const config = { commitment: this._resolveSupportedFinality(commitment) };
const result = await this.getTransaction(signature, config);
if (!result) return null;
return {
...result,
transaction: Transaction.populate(result.transaction.message, result.transaction.signatures)
};
}
/**
* Fetch parsed transaction details for a confirmed transaction
*
* @deprecated Deprecated since RPC v1.7.0. Please use {@link getParsedTransaction} instead.
*/
getParsedConfirmedTransaction(signature, commitment) {
const config = { commitment: this._resolveSupportedFinality(commitment) };
return this.getParsedTransaction(signature, config);
}
/**
* Fetch parsed transaction details for a batch of confirmed transactions
*
* @deprecated Deprecated since RPC v1.7.0. Please use {@link getParsedTransactions} instead.
*/
getParsedConfirmedTransactions(signatures, commitment) {
const config = { commitment: this._resolveSupportedFinality(commitment) };
return this.getParsedTransactions(signatures, config);
}
/**
* Returns confirmed signatures for transactions involving an
* address backwards in time from the provided signature or most recent confirmed block
*
*
* @param address queried address
* @param options
*/
async getSignaturesForAddress(address, options, commitment) {
const rpcFinality = this._resolveSupportedFinality(commitment);
if (options?.before != null) assertIsSignature(options.before);
if (options?.until != null) assertIsSignature(options.until);
const rpcConfig = {
...options?.before != null ? { before: options.before } : null,
commitment: rpcFinality,
...options?.limit != null ? { limit: options.limit } : null,
...options?.minContextSlot != null ? { minContextSlot: coerceNumericToBigInt(options.minContextSlot, "minContextSlot") } : null,
...options?.until != null ? { until: options.until } : null
};
try {
return (await this._typedRpc.getSignaturesForAddress(address.toBase58(), rpcConfig).send()).map(({ signature, ...rest }) => ({
signature,
...rest
}));
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get signatures for address");
}
}
async getTransactionsForAddress(address, config) {
const rpcConfig = buildTypedTransactionsForAddressConfig(this._resolveSupportedFinality(config?.commitment), config);
const getTransactionsForAddress = this._typedRpc.getTransactionsForAddress;
try {
const { data, paginationToken } = await getTransactionsForAddress(address.toBase58(), rpcConfig).send();
if (config?.transactionDetails !== "full") return {
data: data.map(({ signature, ...rest }) => ({
signature,
...rest
})),
paginationToken
};
switch (config.encoding) {
case "jsonParsed": return {
data: data.map((transaction) => ({
...mapTypedParsedTransactionResponse(transaction),
transactionIndex: transaction.transactionIndex
})),
paginationToken
};
case "base64": return {
data: data.map((transaction) => ({
...mapTypedEncodedTransactionResponse(transaction),
transactionIndex: transaction.transactionIndex
})),
paginationToken
};
default: return {
data: data.map((transaction) => ({
...mapTypedTransactionResponse(transaction),
transactionIndex: transaction.transactionIndex
})),
paginationToken
};
}
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get transactions for address");
}
}
async getAddressLookupTable(accountKey, config) {
const { context, value: accountInfo } = await this.getAccountInfoAndContext(accountKey, config);
let value = null;
if (accountInfo !== null) {
if (!accountInfo.owner.equals(AddressLookupTableProgram.programId)) throw new Error(`Account ${accountKey.toBase58()} is not owned by the Address Lookup Table program`);
value = new AddressLookupTableAccount({
key: accountKey,
state: AddressLookupTableAccount.deserialize(accountInfo.data)
});
}
return {
context,
value
};
}
/**
* Fetch the contents of a Nonce account from the cluster, return with context
*
* Durable nonces are planned for deprecation on Solana. They remain valid on
* mainnet today and no removal date is set. See
* {@link https://solana.com/upgrades/durable-nonce-deprecation} for the
* timeline and migration guidance.
*/
async getNonceAndContext(nonceAccount, commitmentOrConfig) {
const { context, value: accountInfo } = await this.getAccountInfoAndContext(nonceAccount, commitmentOrConfig);
let value = null;
if (accountInfo !== null) value = NonceAccount.fromAccountData(accountInfo.data);
return {
context,
value
};
}
/**
* Fetch the contents of a Nonce account from the cluster
*
* Durable nonces are planned for deprecation on Solana. They remain valid on
* mainnet today and no removal date is set. See
* {@link https://solana.com/upgrades/durable-nonce-deprecation} for the
* timeline and migration guidance.
*/
async getNonce(nonceAccount, commitmentOrConfig) {
return await this.getNonceAndContext(nonceAccount, commitmentOrConfig).then((x) => x.value).catch((e) => {
throw new Error("failed to get nonce for account " + nonceAccount.toBase58() + ": " + e);
});
}
/**
* Request an allocation of lamports to the specified address
*
* ```typescript
* import { Connection, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js";
*
* (async () => {
* const connection = new Connection("https://api.testnet.solana.com", "confirmed");
* const myAddress = new PublicKey("2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM");
* const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL);
* await connection.confirmTransaction(signature);
* })();
* ```
*/
async requestAirdrop(to, lamports$1, commitmentOrConfig) {
const { commitment } = extractCommitmentFromConfig(commitmentOrConfig);
const rpcCommitment = this._resolveCommitment(commitment);
try {
return await (rpcCommitment == null ? this._typedRpc.requestAirdrop(to.toBase58(), lamports(coerceNumericToBigInt(lamports$1, "lamports"))) : this._typedRpc.requestAirdrop(to.toBase58(), lamports(coerceNumericToBigInt(lamports$1, "lamports")), { commitment: rpcCommitment })).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, `airdrop to ${to.toBase58()} failed`);
}
}
/**
* @internal
*/
async _blockhashWithExpiryBlockHeight(disableCache) {
if (!disableCache) {
while (this._pollingBlockhash) await sleep(100);
const expired = Date.now() - this._blockhashInfo.lastFetch >= BLOCKHASH_CACHE_TIMEOUT_MS;
if (this._blockhashInfo.latestBlockhash !== null && !expired) return this._blockhashInfo.latestBlockhash;
}
return await this._pollNewBlockhash();
}
/**
* @internal
*/
async _pollNewBlockhash() {
this._pollingBlockhash = true;
try {
const startTime = Date.now();
const cachedLatestBlockhash = this._blockhashInfo.latestBlockhash;
const cachedBlockhash = cachedLatestBlockhash ? cachedLatestBlockhash.blockhash : null;
for (let i = 0; i < 50; i++) {
const latestBlockhashResult = await this.getLatestBlockhash("finalized");
const latestBlockhash = {
blockhash: latestBlockhashResult.blockhash,
lastValidBlockHeight: latestBlockhashResult.lastValidBlockHeight
};
if (cachedBlockhash !== latestBlockhash.blockhash) {
this._blockhashInfo = {
latestBlockhash,
lastFetch: Date.now(),
transactionSignatures: [],
simulatedSignatures: []
};
return latestBlockhash;
}
await sleep(200);
}
throw new Error(`Unable to obtain a new blockhash after ${Date.now() - startTime}ms`);
} finally {
this._pollingBlockhash = false;
}
}
/**
* get the stake minimum delegation
*/
async getStakeMinimumDelegation(config) {
try {
return await this._typedRpc.getStakeMinimumDelegation({ commitment: this._resolveCommitment(config?.commitment) }).send();
} catch (error) {
throwSolanaRpcErrorIfNeeded(error, "failed to get stake minimum delegation");
}
}
/**
* Simulate a transaction
*/
async simulateTransaction(transactionOrMessage, configOrSigners, includeAccounts) {
let encodedTransaction;
let config;
let useLegacySimulationError = false;
if ("message" in transactionOrMessage) {
encodedTransaction = encodeBase64WireData(transactionOrMessage.serialize());
if (Array.isArray(configOrSigners) || includeAccounts !== void 0) throw new Error("Invalid arguments");
config = {
...configOrSigners,
commitment: this._resolveCommitment(configOrSigners?.commitment)
};
} else {
let transaction;
if (transactionOrMessage instanceof Transaction) {
const originalTx = transactionOrMessage;
transaction = new Transaction();
transaction.feePayer = originalTx.feePayer;
transaction.instructions = transactionOrMessage.instructions;
transaction.nonceInfo = originalTx.nonceInfo;
transaction.signatures = originalTx.signatures;
} else {
transaction = Transaction.populate(transactionOrMessage);
transaction._message = transaction._json = void 0;
}
if (configOrSigners !== void 0 && !Array.isArray(configOrSigners)) throw new Error("Invalid arguments");
const signers = configOrSigners;
if (transaction.nonceInfo && signers) await transaction.sign(...signers);
else {
let disableCache = this._disableBlockhashCaching;
for (;;) {
const latestBlockhash = await this._blockhashWithExpiryBlockHeight(disableCache);
transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;
transaction.recentBlockhash = latestBlockhash.blockhash;
if (!signers) break;
await transaction.sign(...signers);
if (!transaction.signature) throw new Error("!signature");
const signature = encodeBase64WireData(transaction.signature);
if (!this._blockhashInfo.simulatedSignatures.includes(signature) && !this._blockhashInfo.transactionSignatures.includes(signature)) {
this._blockhashInfo.simulatedSignatures.push(signature);
break;
} else disableCache = true;
}
}
const message = transaction._compile();
const signData = message.serialize();
encodedTransaction = encodeBase64WireData(transaction._serialize(signData));
config = { commitment: this._resolveCommitment() };
if (includeAccounts) {
const addresses = (Array.isArray(includeAccounts) ? includeAccounts : message.nonProgramIds()).map((key) => key.toBase58());
config.accounts = {
encoding: "base64",
addresses
};
}
if (signers) config.sigVerify = true;
useLegacySimulationError = true;
}
const minContextSlot = coerceOptionalNumericToBigInt(config.minContextSlot, "minContextSlot");
assert_default(!(config.sigVerify === true && config.replaceRecentBlockhash === true), "sigVerify and replaceRecentBlockhash cannot both be true");
const rpcConfigBase = {
encoding: "base64",
...config.accounts != null ? { accounts: {
encoding: "base64",
addresses: config.accounts.addresses.map((address) => new PublicKey(address).toBase58())
} } : null,
...config.commitment != null ? { commitment: config.commitment } : null,
...config.innerInstructions !== void 0 ? { innerInstructions: config.innerInstructions } : null,
...minContextSlot != null ? { minContextSlot } : null
};
const base64EncodedWireTransaction = coerceToBase64EncodedWireTransaction(encodedTransaction);
const simulateTransaction = this._typedRpc.simulateTransaction;
const rpcConfig = {
...rpcConfigBase,
...config.sigVerify === true ? { sigVerify: true } : config.replaceRecentBlockhash === true ? { replaceRecentBlockhash: true } : null
};
try {
const response = await simulateTransaction(base64EncodedWireTransaction, rpcConfig).send();
return {
context: response.context,
value: mapSimulatedTransactionResponseValue(response.value)
};
} catch (error) {
if (!useLegacySimulationError) throw new Error("failed to simulate transaction: " + (isJsonRpcErrorLike(error) ? error.message : error instanceof Error ? error.message : String(error)));
const errorDetails = extractSendTransactionErrorDetails(error) ?? {
logs: void 0,
transactionMessage: error instanceof Error ? error.message : String(error)
};
if (errorDetails.logs) {
const traceIndent = "\n ";
const logTrace = traceIndent + errorDetails.logs.join(traceIndent);
console.error(errorDetails.transactionMessage, logTrace);
}
throw new SendTransactionError({
action: "simulate",
signature: "",
transactionMessage: errorDetails.transactionMessage,
logs: errorDetails.logs
});
}
}
/**
* Sign and send a transaction
*/
async sendTransaction(transaction, signersOrOptions, options) {
if ("version" in transaction) {
if (signersOrOptions && Array.isArray(signersOrOptions)) throw new Error("Invalid arguments");
const wireTransaction = transaction.serialize();
return await this.sendRawTransaction(wireTransaction, signersOrOptions);
}
if (signersOrOptions === void 0 || !Array.isArray(signersOrOptions)) throw new Error("Invalid arguments");
const signers = signersOrOptions;
if (transaction.nonceInfo) await transaction.sign(...signers);
else {
let disableCache = this._disableBlockhashCaching;
for (;;) {
const latestBlockhash = await this._blockhashWithExpiryBlockHeight(disableCache);
transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;
transaction.recentBlockhash = latestBlockhash.blockhash;
await transaction.sign(...signers);
if (!transaction.signature) throw new Error("!signature");
const signature = encodeBase64WireData(transaction.signature);
if (!this._blockhashInfo.transactionSignatures.includes(signature)) {
this._blockhashInfo.transactionSignatures.push(signature);
break;
} else disableCache = true;
}
}
const wireTransaction = await transaction.serialize();
return await this.sendRawTransaction(wireTransaction, options);
}
/**
* Send a transaction that has already been signed and serialized into the
* wire format
*/
async sendRawTransaction(rawTransaction, options) {
const encodedTransaction = encodeBase64WireData(toUint8ArrayView(rawTransaction));
return await this.sendEncodedTransaction(encodedTransaction, options);
}
/**
* Send a transaction that has already been signed, serialized into the
* wire format, and encoded as a base64 string
*/
async sendEncodedTransaction(encodedTransaction, options) {
const skipPreflight = options && options.skipPreflight;
const preflightCommitment = skipPreflight === true ? "processed" : options && options.preflightCommitment || this.commitment;
const config = {
encoding: "base64",
...options?.maxRetries != null ? { maxRetries: options.maxRetries } : null,
...options?.minContextSlot != null ? { minContextSlot: options.minContextSlot } : null,
...skipPreflight ? { skipPreflight } : null,
...preflightCommitment != null ? { preflightCommitment } : null
};
try {
return await this._typedRpc.sendTransaction(coerceToBase64EncodedWireTransaction(encodedTransaction), config).send();
} catch (error) {
const sendTransactionErrorDetails = extractSendTransactionErrorDetails(error);
if (sendTransactionErrorDetails == null) throw error;
throw new SendTransactionError({
action: skipPreflight ? "send" : "simulate",
signature: "",
transactionMessage: sendTransactionErrorDetails.transactionMessage,
logs: sendTransactionErrorDetails.logs
});
}
}
/**
* @internal
*/
_registerSubscription(subscriptionConfig, dispatchConfig) {
return this._subscriptionController.registerSubscription(subscriptionConfig, dispatchConfig);
}
/**
* Wait until an active subscription has either been established or failed.
*
* This rejects if the supplied subscription id is not active when
* observation begins, or if the subscription becomes inactive before setup
* reaches a terminal state.
*/
async awaitSubscriptionReady(clientSubscriptionId, config) {
if (config?.abortSignal?.aborted) throw config.abortSignal.reason;
let disposeStateChangeObserver;
const readinessPromise = new Promise((resolve, reject) => {
const settleSubscriptionReadiness = (nextState) => {
if (nextState === "subscribed") {
resolve();
return;
}
if (nextState === "failed") {
reject(/* @__PURE__ */ new Error(`Subscription with id \`${clientSubscriptionId}\` failed to establish.`));
return;
}
if (nextState === "inactive") reject(/* @__PURE__ */ new Error(`Subscription with id \`${clientSubscriptionId}\` is no longer active.`));
};
const { currentState, dispose } = this._subscriptionRegistry.observeStateChanges(clientSubscriptionId, settleSubscriptionReadiness);
disposeStateChangeObserver = dispose;
settleSubscriptionReadiness(currentState);
});
try {
await Promise.race([readinessPromise, this.getCancellationPromise(config?.abortSignal)]);
} finally {
if (disposeStateChangeObserver) {
disposeStateChangeObserver();
disposeStateChangeObserver = void 0;
}
}
}
onAccountChange(publicKey, callback, commitmentOrConfig) {
return this._registerSubscription({
callback,
spec: buildAccountSubscriptionSpec(publicKey, this._resolveSubscriptionConfig(commitmentOrConfig))
});
}
/**
* Deregister an account notification callback
*
* @param clientSubscriptionId client subscription id to deregister
*/
async removeAccountChangeListener(clientSubscriptionId) {
await this._unsubscribeClientSubscription(clientSubscriptionId, "account change");
}
onProgramAccountChange(programId, callback, commitmentOrConfig, maybeFilters) {
return this._registerSubscription({
callback,
spec: buildProgramSubscriptionSpec(programId, this._resolveSubscriptionConfig(commitmentOrConfig), maybeFilters)
});
}
/**
* Deregister an account notification callback
*
* @param clientSubscriptionId client subscription id to deregister
*/
async removeProgramAccountChangeListener(clientSubscriptionId) {
await this._unsubscribeClientSubscription(clientSubscriptionId, "program account change");
}
/**
* Registers a callback to be invoked whenever logs are emitted.
*/
onLogs(filter, callback, commitment) {
return this._registerSubscription({
callback,
spec: buildLogsSubscriptionSpec(filter, this._resolveSubscriptionCommitment(commitment))
});
}
/**
* Deregister a logs callback.
*
* @param clientSubscriptionId client subscription id to deregister.
*/
async removeOnLogsListener(clientSubscriptionId) {
await this._unsubscribeClientSubscription(clientSubscriptionId, "logs");
}
/**
* Register a callback to be invoked upon slot changes
*
* @param callback Function to invoke whenever the slot changes
* @return subscription id
*/
onSlotChange(callback) {
return this._registerSubscription({
callback,
spec: { kind: "slot" }
});
}
/**
* Deregister a slot notification callback
*
* @param clientSubscriptionId client subscription id to deregister
*/
async removeSlotChangeListener(clientSubscriptionId) {
await this._unsubscribeClientSubscription(clientSubscriptionId, "slot change");
}
/**
* Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s
* may be useful to track live progress of a cluster.
*
* @param callback Function to invoke whenever the slot updates
* @return subscription id
*/
onSlotUpdate(callback) {
return this._registerSubscription({
callback,
spec: { kind: "slotsUpdates" }
});
}
/**
* Deregister a slot update notification callback
*
* @param clientSubscriptionId client subscription id to deregister
*/
async removeSlotUpdateListener(clientSubscriptionId) {
await this._unsubscribeClientSubscription(clientSubscriptionId, "slot update");
}
/**
* @internal
*/
async _unsubscribeClientSubscription(clientSubscriptionId, subscriptionName) {
await this._subscriptionController.removeClientSubscription(clientSubscriptionId, subscriptionName);
}
/**
* Register a callback to be invoked upon signature updates
*
* @param signature Transaction signature string in base 58
* @param callback Function to invoke on signature notifications
* @param commitment Specify the commitment level signature must reach before notification
* @return subscription id
*/
onSignature(signature, callback, commitment) {
const clientSubscriptionId = this._registerSubscription({
callback: (notification, context) => {
if (notification.type !== "status") return;
try {
callback(notification.result, context);
} finally {
try {
this.removeSignatureListener(clientSubscriptionId);
} catch {}
}
},
spec: buildSignatureSubscriptionSpec(signature, { commitment: this._resolveSubscriptionCommitment(commitment) })
});
return clientSubscriptionId;
}
onSignatureWithOptions(signature, callback, options) {
const clientSubscriptionId = this._registerSubscription({
callback: (notification, context) => {
try {
if (options?.enableReceivedNotification === true) callback(notification, context);
else if (notification.type === "status") callback(notification.result, context);
} finally {
if (notification.type === "status") try {
this.removeSignatureListener(clientSubscriptionId);
} catch {}
}
},
spec: buildSignatureSubscriptionSpec(signature, this._resolveSubscriptionConfig(options))
});
return clientSubscriptionId;
}
/**
* Deregister a signature notification callback
*
* @param clientSubscriptionId client subscription id to deregister
*/
async removeSignatureListener(clientSubscriptionId) {
await this._unsubscribeClientSubscription(clientSubscriptionId, "signature result");
}
/**
* Register a callback to be invoked upon root changes
*
* @param callback Function to invoke whenever the root changes
* @return subscription id
*/
onRootChange(callback) {
return this._registerSubscription({
callback,
spec: { kind: "root" }
});
}
/**
* Deregister a root notification callback
*
* @param clientSubscriptionId client subscription id to deregister
*/
async removeRootChangeListener(clientSubscriptionId) {
await this._unsubscribeClientSubscription(clientSubscriptionId, "root change");
}
onBlock(filter, callback, config) {
const normalizedConfig = this._resolveSubscriptionConfig(config);
const { commitment } = normalizedConfig;
if (commitment !== "confirmed" && commitment !== "finalized") throw new Error("Using Connection with default commitment: `" + this._commitment + "`, but method requires at least `confirmed`");
return this._registerSubscription({
callback,
spec: buildBlockSubscriptionSpec(filter, {
...normalizedConfig,
commitment
})
}, config == null ? { defaultDispatchConfig: "default" } : { dispatchConfig: config });
}
/**
* Deregister a block notification callback
*
* @param clientSubscriptionId client subscription id to deregister
*/
async removeBlockListener(clientSubscriptionId) {
await this._unsubscribeClientSubscription(clientSubscriptionId, "block");
}
/**
* Register a callback to be invoked when a new vote is observed in gossip.
*
* This subscription is unstable and requires the validator to be started with
* `--rpc-pubsub-enable-vote-subscription`.
*
* @param callback Function to invoke whenever a vote is observed
* @return subscription id
*/
onVote(callback) {
return this._registerSubscription({
callback,
spec: { kind: "vote" }
});
}
/**
* Deregister a vote notification callback
*
* @param clientSubscriptionId client subscription id to deregister
*/
async removeVoteListener(clientSubscriptionId) {
await this._unsubscribeClientSubscription(clientSubscriptionId, "vote");
}
};
// src/keypair.ts
/**
* An account keypair backed by WebCrypto.
*
* Implements Kit's `KeyPairSigner` (and therefore `MessagePartialSigner`
* and `TransactionPartialSigner`), so instances can be passed directly to
* Kit APIs and generated program clients that accept a `TransactionSigner`
* or `KeyPairSigner`.
*/
var Keypair = class Keypair {
#signer;
#privateKeyBytes;
#publicKeyBytes;
constructor(signer, privateKeyBytes, publicKeyBytes) {
this.#signer = signer;
this.#privateKeyBytes = privateKeyBytes;
this.#publicKeyBytes = publicKeyBytes;
}
/**
* Generate a new random keypair.
*/
static async generate() {
const privateKeyBytes = /* @__PURE__ */ new Uint8Array(32);
globalThis.crypto.getRandomValues(privateKeyBytes);
return await this.fromSeed(privateKeyBytes);
}
/**
* Create a keypair from a raw 64-byte secret key (32-byte private key
* followed by 32-byte public key).
*/
static async fromSecretKey(secretKey) {
const packedSecretKey = Uint8Array.from(secretKey);
const signer = await createKeyPairSignerFromBytes(packedSecretKey);
const publicKeyBytes = new PublicKey(signer.address).toBytes();
return new Keypair(signer, packedSecretKey.slice(0, 32), publicKeyBytes);
}
/**
* Create a keypair from a 32-byte seed (private-key bytes).
*/
static async fromSeed(seed) {
const packedSeed = Uint8Array.from(seed);
const signer = await createKeyPairSignerFromPrivateKeyBytes(packedSeed);
const publicKeyBytes = new PublicKey(signer.address).toBytes();
return new Keypair(signer, packedSeed, publicKeyBytes);
}
/**
* Returns the base-58 address as a Kit-compatible branded `Address` string.
*
* This property is provided for structural compatibility with
* `@solana/signers` / Kit (so `Keypair` can be used where a
* `TransactionSigner` is expected).
*
* Most users of this library should use {@link publicKey} instead.
*/
get address() {
return this.#signer.address;
}
/**
* The PublicKey for this keypair
*
* @returns {PublicKey} PublicKey
*/
get publicKey() {
return new PublicKey(this.#publicKeyBytes);
}
/**
* The underlying WebCrypto `CryptoKeyPair`.
*/
get keyPair() {
return this.#signer.keyPair;
}
/**
* Returns this keypair's 64-byte secret key bytes
*/
get secretKey() {
const secretKey = /* @__PURE__ */ new Uint8Array(64);
secretKey.set(this.#privateKeyBytes);
secretKey.set(this.#publicKeyBytes, 32);
return secretKey;
}
/**
* Sign one or more messages as a Kit `MessagePartialSigner`.
*
* Declared as an arrow-function field so callers can destructure
* (`const {signMessages} = keypair`) without losing `this` binding.
*/
signMessages = (messages, config) => this.#signer.signMessages(messages, config);
/**
* Sign one or more transactions as a Kit `TransactionPartialSigner`.
*
* Declared as an arrow-function field so callers can destructure
* (`const {signTransactions} = keypair`) without losing `this` binding.
*/
signTransactions = (transactions, config) => this.#signer.signTransactions(transactions, config);
/**
* Sign raw message bytes and return the 64-byte ed25519 signature.
*/
async signBytes(message) {
return await signBytes(this.#signer.keyPair.privateKey, toPackedUint8Array(message));
}
/**
* Verify a signature against the provided message using this keypair's
* public key.
*/
async verifySignature(signature, message) {
return await verifySignature(this.#signer.keyPair.publicKey, signatureBytes(toPackedUint8Array(signature)), toPackedUint8Array(message));
}
};
// src/programs/compute-budget.ts
const COMPUTE_BUDGET_PROGRAM_ID = new PublicKey(COMPUTE_BUDGET_PROGRAM_ADDRESS);
const GENERATED_TO_LEGACY_INSTRUCTION_TYPE$2 = {
[ComputeBudgetInstruction$1.RequestUnits]: "RequestUnits",
[ComputeBudgetInstruction$1.RequestHeapFrame]: "RequestHeapFrame",
[ComputeBudgetInstruction$1.SetComputeUnitLimit]: "SetComputeUnitLimit",
[ComputeBudgetInstruction$1.SetComputeUnitPrice]: "SetComputeUnitPrice",
[ComputeBudgetInstruction$1.SetLoadedAccountsDataSizeLimit]: "SetLoadedAccountsDataSizeLimit"
};
function getInstructionType$2(instruction) {
checkProgramId$2(instruction.programId);
const generatedInstructionType = identifyComputeBudgetInstruction(instruction.data);
const instructionType = generatedInstructionType in GENERATED_TO_LEGACY_INSTRUCTION_TYPE$2 ? GENERATED_TO_LEGACY_INSTRUCTION_TYPE$2[generatedInstructionType] : void 0;
if (!instructionType) throw new Error("Instruction type incorrect; not a ComputeBudgetInstruction");
return instructionType;
}
function parseComputeBudgetInstructionOfType(instruction, expectedInstructionType) {
checkProgramId$2(instruction.programId);
const parsedInstruction = parseComputeBudgetInstruction(toKitInstruction(instruction));
if (parsedInstruction.instructionType !== expectedInstructionType) throw new Error("invalid instruction; instruction type mismatch");
return parsedInstruction;
}
function checkProgramId$2(programId) {
if (!programId.equals(ComputeBudgetProgram.programId)) throw new Error("invalid instruction; programId is not ComputeBudgetProgram");
}
/**
* Compute Budget Instruction class
*/
var ComputeBudgetInstruction = class {
/**
* @internal
*/
constructor() {}
/**
* Decode a compute budget instruction and retrieve the instruction type.
*/
static decodeInstructionType(instruction) {
return getInstructionType$2(instruction);
}
/**
* Decode request units compute budget instruction and retrieve the instruction params.
*/
static decodeRequestUnits(instruction) {
const parsedInstruction = parseComputeBudgetInstructionOfType(instruction, ComputeBudgetInstruction$1.RequestUnits);
return {
units: parsedInstruction.data.units,
additionalFee: parsedInstruction.data.additionalFee
};
}
/**
* Decode request heap frame compute budget instruction and retrieve the instruction params.
*/
static decodeRequestHeapFrame(instruction) {
return { bytes: parseComputeBudgetInstructionOfType(instruction, ComputeBudgetInstruction$1.RequestHeapFrame).data.bytes };
}
/**
* Decode set compute unit limit compute budget instruction and retrieve the instruction params.
*/
static decodeSetComputeUnitLimit(instruction) {
return { units: parseComputeBudgetInstructionOfType(instruction, ComputeBudgetInstruction$1.SetComputeUnitLimit).data.units };
}
/**
* Decode set compute unit price compute budget instruction and retrieve the instruction params.
*/
static decodeSetComputeUnitPrice(instruction) {
return { microLamports: parseComputeBudgetInstructionOfType(instruction, ComputeBudgetInstruction$1.SetComputeUnitPrice).data.microLamports };
}
/**
* Decode set loaded accounts data size limit compute budget instruction and retrieve the instruction params.
*/
static decodeSetLoadedAccountsDataSizeLimit(instruction) {
return { accountDataSizeLimit: parseComputeBudgetInstructionOfType(instruction, ComputeBudgetInstruction$1.SetLoadedAccountsDataSizeLimit).data.accountDataSizeLimit };
}
};
/**
* Factory class for transaction instructions to interact with the Compute Budget program
*/
var ComputeBudgetProgram = class {
/**
* @internal
*/
constructor() {}
/**
* Public key that identifies the Compute Budget program
*/
static programId = COMPUTE_BUDGET_PROGRAM_ID;
/**
* @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}
*/
static requestUnits(params) {
return fromKitInstruction(getRequestUnitsInstruction(params));
}
static requestHeapFrame(params) {
return fromKitInstruction(getRequestHeapFrameInstruction(params));
}
static setComputeUnitLimit(params) {
return fromKitInstruction(getSetComputeUnitLimitInstruction(params));
}
static setComputeUnitPrice(params) {
return fromKitInstruction(getSetComputeUnitPriceInstruction(params));
}
static setLoadedAccountsDataSizeLimit(params) {
return fromKitInstruction(getSetLoadedAccountsDataSizeLimitInstruction(params));
}
};
// src/programs/loader-v3.ts
const LOADER_V3_PROGRAM_ID = new PublicKey(LOADER_V3_PROGRAM_ADDRESS);
const GENERATED_TO_LEGACY_INSTRUCTION_TYPE$1 = {
[LoaderV3Instruction$1.InitializeBuffer]: "InitializeBuffer",
[LoaderV3Instruction$1.Write]: "Write",
[LoaderV3Instruction$1.DeployWithMaxDataLen]: "DeployWithMaxDataLen",
[LoaderV3Instruction$1.Upgrade]: "Upgrade",
[LoaderV3Instruction$1.SetAuthority]: "SetAuthority",
[LoaderV3Instruction$1.Close]: "Close",
[LoaderV3Instruction$1.ExtendProgram]: "ExtendProgram",
[LoaderV3Instruction$1.SetAuthorityChecked]: "SetAuthorityChecked"
};
function getInstructionType$1(instruction) {
checkProgramId$1(instruction.programId);
return GENERATED_TO_LEGACY_INSTRUCTION_TYPE$1[identifyLoaderV3Instruction(instruction.data)];
}
function parseLoaderV3InstructionOfType(instruction, expectedInstructionType) {
checkProgramId$1(instruction.programId);
const parsedInstruction = parseLoaderV3Instruction(toKitInstruction(instruction));
if (parsedInstruction.instructionType !== expectedInstructionType) throw new Error("invalid instruction; instruction type mismatch");
return parsedInstruction;
}
function checkProgramId$1(programId) {
if (!programId.equals(LoaderV3Program.programId)) throw new Error("invalid instruction; programId is not LoaderV3Program");
}
/**
* Loader V3 Instruction class
*/
var LoaderV3Instruction = class {
/**
* @internal
*/
constructor() {}
/**
* Decode a loader v3 instruction and retrieve the instruction type.
*/
static decodeInstructionType(instruction) {
return getInstructionType$1(instruction);
}
/**
* Decode an initialize buffer instruction and retrieve the instruction params.
*/
static decodeInitializeBuffer(instruction) {
const parsedInstruction = parseLoaderV3InstructionOfType(instruction, LoaderV3Instruction$1.InitializeBuffer);
return {
sourceAccount: new PublicKey(parsedInstruction.accounts.sourceAccount.address),
bufferAuthority: new PublicKey(parsedInstruction.accounts.bufferAuthority.address)
};
}
/**
* Decode a write instruction and retrieve the instruction params.
*/
static decodeWrite(instruction) {
const parsedInstruction = parseLoaderV3InstructionOfType(instruction, LoaderV3Instruction$1.Write);
return {
bufferAccount: new PublicKey(parsedInstruction.accounts.bufferAccount.address),
bufferAuthority: new PublicKey(parsedInstruction.accounts.bufferAuthority.address),
offset: parsedInstruction.data.offset,
bytes: Uint8Array.from(parsedInstruction.data.bytes)
};
}
/**
* Decode a deploy with max data len instruction and retrieve the instruction params.
*/
static decodeDeployWithMaxDataLen(instruction) {
const parsedInstruction = parseLoaderV3InstructionOfType(instruction, LoaderV3Instruction$1.DeployWithMaxDataLen);
return {
payerAccount: new PublicKey(parsedInstruction.accounts.payerAccount.address),
programDataAccount: new PublicKey(parsedInstruction.accounts.programDataAccount.address),
programAccount: new PublicKey(parsedInstruction.accounts.programAccount.address),
bufferAccount: new PublicKey(parsedInstruction.accounts.bufferAccount.address),
authority: new PublicKey(parsedInstruction.accounts.authority.address),
maxDataLen: parsedInstruction.data.maxDataLen,
rentSysvar: new PublicKey(parsedInstruction.accounts.rentSysvar.address),
clockSysvar: new PublicKey(parsedInstruction.accounts.clockSysvar.address),
systemProgram: new PublicKey(parsedInstruction.accounts.systemProgram.address)
};
}
/**
* Decode an upgrade instruction and retrieve the instruction params.
*/
static decodeUpgrade(instruction) {
const parsedInstruction = parseLoaderV3InstructionOfType(instruction, LoaderV3Instruction$1.Upgrade);
return {
programDataAccount: new PublicKey(parsedInstruction.accounts.programDataAccount.address),
programAccount: new PublicKey(parsedInstruction.accounts.programAccount.address),
bufferAccount: new PublicKey(parsedInstruction.accounts.bufferAccount.address),
spillAccount: new PublicKey(parsedInstruction.accounts.spillAccount.address),
authority: new PublicKey(parsedInstruction.accounts.authority.address),
rentSysvar: new PublicKey(parsedInstruction.accounts.rentSysvar.address),
clockSysvar: new PublicKey(parsedInstruction.accounts.clockSysvar.address)
};
}
/**
* Decode a set authority instruction and retrieve the instruction params.
*/
static decodeSetAuthority(instruction) {
const parsedInstruction = parseLoaderV3InstructionOfType(instruction, LoaderV3Instruction$1.SetAuthority);
return {
bufferOrProgramDataAccount: new PublicKey(parsedInstruction.accounts.bufferOrProgramDataAccount.address),
currentAuthority: new PublicKey(parsedInstruction.accounts.currentAuthority.address),
...parsedInstruction.accounts.newAuthority ? { newAuthority: new PublicKey(parsedInstruction.accounts.newAuthority.address) } : {}
};
}
/**
* Decode a set authority checked instruction and retrieve the instruction params.
*/
static decodeSetAuthorityChecked(instruction) {
const parsedInstruction = parseLoaderV3InstructionOfType(instruction, LoaderV3Instruction$1.SetAuthorityChecked);
return {
bufferOrProgramDataAccount: new PublicKey(parsedInstruction.accounts.bufferOrProgramDataAccount.address),
currentAuthority: new PublicKey(parsedInstruction.accounts.currentAuthority.address),
newAuthority: new PublicKey(parsedInstruction.accounts.newAuthority.address)
};
}
/**
* Decode a close instruction and retrieve the instruction params.
*/
static decodeClose(instruction) {
const parsedInstruction = parseLoaderV3InstructionOfType(instruction, LoaderV3Instruction$1.Close);
return {
bufferOrProgramDataAccount: new PublicKey(parsedInstruction.accounts.bufferOrProgramDataAccount.address),
destinationAccount: new PublicKey(parsedInstruction.accounts.destinationAccount.address),
...parsedInstruction.accounts.authority ? { authority: new PublicKey(parsedInstruction.accounts.authority.address) } : {},
...parsedInstruction.accounts.programAccount ? { programAccount: new PublicKey(parsedInstruction.accounts.programAccount.address) } : {}
};
}
/**
* Decode an extend program instruction and retrieve the instruction params.
*/
static decodeExtendProgram(instruction) {
const parsedInstruction = parseLoaderV3InstructionOfType(instruction, LoaderV3Instruction$1.ExtendProgram);
return {
programDataAccount: new PublicKey(parsedInstruction.accounts.programDataAccount.address),
programAccount: new PublicKey(parsedInstruction.accounts.programAccount.address),
additionalBytes: parsedInstruction.data.additionalBytes,
...parsedInstruction.accounts.systemProgram ? { systemProgram: new PublicKey(parsedInstruction.accounts.systemProgram.address) } : {},
...parsedInstruction.accounts.payer ? { payer: new PublicKey(parsedInstruction.accounts.payer.address) } : {}
};
}
};
/**
* Factory class for transaction instructions to interact with the Loader V3 program
*/
var LoaderV3Program = class {
/**
* @internal
*/
constructor() {}
/**
* Public key that identifies the Loader V3 program
*/
static programId = LOADER_V3_PROGRAM_ID;
static initializeBuffer(params) {
return fromKitInstruction(getInitializeBufferInstruction({
sourceAccount: params.sourceAccount.toBase58(),
bufferAuthority: params.bufferAuthority.toBase58()
}));
}
static write(params) {
return fromKitInstruction(getWriteInstruction({
bufferAccount: params.bufferAccount.toBase58(),
bufferAuthority: createNoopSigner(params.bufferAuthority.toBase58()),
offset: params.offset,
bytes: params.bytes
}));
}
static deployWithMaxDataLen(params) {
return fromKitInstruction(getDeployWithMaxDataLenInstruction({
payerAccount: createNoopSigner(params.payerAccount.toBase58()),
programDataAccount: params.programDataAccount.toBase58(),
programAccount: params.programAccount.toBase58(),
bufferAccount: params.bufferAccount.toBase58(),
authority: createNoopSigner(params.authority.toBase58()),
maxDataLen: params.maxDataLen,
...params.rentSysvar ? { rentSysvar: params.rentSysvar.toBase58() } : {},
...params.clockSysvar ? { clockSysvar: params.clockSysvar.toBase58() } : {},
...params.systemProgram ? { systemProgram: params.systemProgram.toBase58() } : {}
}));
}
static upgrade(params) {
return fromKitInstruction(getUpgradeInstruction({
programDataAccount: params.programDataAccount.toBase58(),
programAccount: params.programAccount.toBase58(),
bufferAccount: params.bufferAccount.toBase58(),
spillAccount: params.spillAccount.toBase58(),
authority: createNoopSigner(params.authority.toBase58()),
...params.rentSysvar ? { rentSysvar: params.rentSysvar.toBase58() } : {},
...params.clockSysvar ? { clockSysvar: params.clockSysvar.toBase58() } : {}
}));
}
static setAuthority(params) {
return fromKitInstruction(getSetAuthorityInstruction({
bufferOrProgramDataAccount: params.bufferOrProgramDataAccount.toBase58(),
currentAuthority: createNoopSigner(params.currentAuthority.toBase58()),
...params.newAuthority ? { newAuthority: params.newAuthority.toBase58() } : {}
}));
}
static setAuthorityChecked(params) {
return fromKitInstruction(getSetAuthorityCheckedInstruction({
bufferOrProgramDataAccount: params.bufferOrProgramDataAccount.toBase58(),
currentAuthority: createNoopSigner(params.currentAuthority.toBase58()),
newAuthority: createNoopSigner(params.newAuthority.toBase58())
}));
}
static close(params) {
return fromKitInstruction(getCloseInstruction({
bufferOrProgramDataAccount: params.bufferOrProgramDataAccount.toBase58(),
destinationAccount: params.destinationAccount.toBase58(),
...params.authority ? { authority: createNoopSigner(params.authority.toBase58()) } : {},
...params.programAccount ? { programAccount: params.programAccount.toBase58() } : {}
}));
}
static extendProgram(params) {
return fromKitInstruction(getExtendProgramInstruction({
programDataAccount: params.programDataAccount.toBase58(),
programAccount: params.programAccount.toBase58(),
additionalBytes: params.additionalBytes,
...params.systemProgram ? { systemProgram: params.systemProgram.toBase58() } : {},
...params.payer ? { payer: createNoopSigner(params.payer.toBase58()) } : {}
}));
}
};
// src/programs/ed25519.ts
const PRIVATE_KEY_BYTES$1 = 64;
const PUBLIC_KEY_BYTES$1 = 32;
const SIGNATURE_BYTES$1 = 64;
const ED25519_INSTRUCTION_HEADER_ENCODER = getStructEncoder([
["numSignatures", getU8Encoder()],
["padding", getU8Encoder()],
["signatureOffset", getU16Encoder()],
["signatureInstructionIndex", getU16Encoder()],
["publicKeyOffset", getU16Encoder()],
["publicKeyInstructionIndex", getU16Encoder()],
["messageDataOffset", getU16Encoder()],
["messageDataSize", getU16Encoder()],
["messageInstructionIndex", getU16Encoder()]
]);
var Ed25519Program = class Ed25519Program {
/**
* @internal
*/
constructor() {}
/**
* Public key that identifies the ed25519 program
*/
static programId = new PublicKey("Ed25519SigVerify111111111111111111111111111");
/**
* Create an ed25519 instruction with a public key and signature. The
* public key must be 32 bytes long, and the signature must be 64 bytes
* long.
*/
static createInstructionWithPublicKey(params) {
const { publicKey, message, signature, instructionIndex } = params;
assert_default(publicKey.length === PUBLIC_KEY_BYTES$1, `Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey.length} bytes`);
assert_default(signature.length === SIGNATURE_BYTES$1, `Signature must be ${SIGNATURE_BYTES$1} bytes but received ${signature.length} bytes`);
const publicKeyOffset = ED25519_INSTRUCTION_HEADER_ENCODER.fixedSize;
const signatureOffset = publicKeyOffset + publicKey.length;
const messageDataOffset = signatureOffset + signature.length;
const numSignatures = 1;
const index = instructionIndex == null ? 65535 : instructionIndex;
const instructionData = new Uint8Array(messageDataOffset + message.length);
ED25519_INSTRUCTION_HEADER_ENCODER.write({
numSignatures,
padding: 0,
signatureOffset,
signatureInstructionIndex: index,
publicKeyOffset,
publicKeyInstructionIndex: index,
messageDataOffset,
messageDataSize: message.length,
messageInstructionIndex: index
}, instructionData, 0);
instructionData.set(publicKey, publicKeyOffset);
instructionData.set(signature, signatureOffset);
instructionData.set(message, messageDataOffset);
return new TransactionInstruction({
keys: [],
programId: Ed25519Program.programId,
data: instructionData
});
}
/**
* Create an ed25519 instruction with a private key. The private key
* must be 64 bytes long.
*/
static async createInstructionWithPrivateKey(params) {
const { privateKey, message, instructionIndex } = params;
assert_default(privateKey.length === PRIVATE_KEY_BYTES$1, `Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);
try {
const publicKey = (await Keypair.fromSecretKey(privateKey)).publicKey.toBytes();
const signature = await sign(message, privateKey);
return this.createInstructionWithPublicKey({
publicKey,
message,
signature,
instructionIndex
});
} catch (error) {
throw new Error(`Error creating instruction; ${String(error)}`);
}
}
};
// src/utils/secp256k1.ts
const ecdsaSign = (msgHash, privKey) => {
const signature = secp256k1.sign(msgHash, privKey);
return [signature.toCompactRawBytes(), signature.recovery];
};
secp256k1.utils.isValidPrivateKey;
const publicKeyCreate = secp256k1.getPublicKey;
// src/programs/secp256k1.ts
const PRIVATE_KEY_BYTES = 32;
const ETHEREUM_ADDRESS_BYTES = 20;
const PUBLIC_KEY_BYTES = 64;
const SIGNATURE_BYTES = 64;
const BASE16_ENCODER = getBase16Encoder();
const ETHEREUM_ADDRESS_STRING_PATTERN = /^(?:0x)?([0-9a-fA-F]{40})$/;
const SECP256K1_INSTRUCTION_DATA_ENCODER = getStructEncoder([
["numSignatures", getU8Encoder()],
["signatureOffset", getU16Encoder()],
["signatureInstructionIndex", getU8Encoder()],
["ethAddressOffset", getU16Encoder()],
["ethAddressInstructionIndex", getU8Encoder()],
["messageDataOffset", getU16Encoder()],
["messageDataSize", getU16Encoder()],
["messageInstructionIndex", getU8Encoder()],
["ethAddress", fixEncoderSize(getBytesEncoder(), ETHEREUM_ADDRESS_BYTES)],
["signature", fixEncoderSize(getBytesEncoder(), SIGNATURE_BYTES)],
["recoveryId", getU8Encoder()]
]);
var Secp256k1Program = class Secp256k1Program {
/**
* @internal
*/
constructor() {}
/**
* Public key that identifies the secp256k1 program
*/
static programId = new PublicKey("KeccakSecp256k11111111111111111111111111111");
/**
* Construct an Ethereum address from a secp256k1 public key.
* @param {Uint8Array | Array<number>} publicKey a 64 byte
* secp256k1 public key
*/
static publicKeyToEthAddress(publicKey) {
const publicKeyBytes = toPackedUint8Array(publicKey);
assert_default(publicKeyBytes.length === PUBLIC_KEY_BYTES, `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKeyBytes.length} bytes`);
try {
return keccak_256(publicKeyBytes).slice(-20);
} catch (error) {
throw new Error(`Error constructing Ethereum address: ${String(error)}`);
}
}
/**
* Create an secp256k1 instruction with a public key. The public key
* must be 64 bytes long.
*/
static createInstructionWithPublicKey(params) {
const { publicKey, message, signature, recoveryId, instructionIndex } = params;
return Secp256k1Program.createInstructionWithEthAddress({
ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey),
message,
signature,
recoveryId,
instructionIndex
});
}
/**
* Create an secp256k1 instruction with an Ethereum address. The address
* must be a hex string or 20 raw bytes.
*/
static createInstructionWithEthAddress(params) {
const { ethAddress: rawAddress, message, signature, recoveryId, instructionIndex = 0 } = params;
const messageBytes = toUint8ArrayView(message);
const signatureBytes = toUint8ArrayView(signature);
let ethAddressBytes;
if (typeof rawAddress === "string") {
const addressMatch = ETHEREUM_ADDRESS_STRING_PATTERN.exec(rawAddress);
assert_default(addressMatch, `Address must be a 40-character hex string with an optional 0x prefix`);
ethAddressBytes = new Uint8Array(BASE16_ENCODER.encode(addressMatch[1]));
} else ethAddressBytes = toUint8ArrayView(rawAddress);
assert_default(ethAddressBytes.length === ETHEREUM_ADDRESS_BYTES, `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddressBytes.length} bytes`);
assert_default(signatureBytes.length === SIGNATURE_BYTES, `Signature must be ${SIGNATURE_BYTES} bytes but received ${signatureBytes.length} bytes`);
const dataStart = 12;
const ethAddressOffset = dataStart;
const signatureOffset = dataStart + ethAddressBytes.length;
const messageDataOffset = signatureOffset + SIGNATURE_BYTES + 1;
const numSignatures = 1;
const instructionData = new Uint8Array(SECP256K1_INSTRUCTION_DATA_ENCODER.fixedSize + messageBytes.length);
SECP256K1_INSTRUCTION_DATA_ENCODER.write({
numSignatures,
signatureOffset,
signatureInstructionIndex: instructionIndex,
ethAddressOffset,
ethAddressInstructionIndex: instructionIndex,
messageDataOffset,
messageDataSize: messageBytes.length,
messageInstructionIndex: instructionIndex,
signature: signatureBytes,
ethAddress: ethAddressBytes,
recoveryId
}, instructionData, 0);
instructionData.set(messageBytes, SECP256K1_INSTRUCTION_DATA_ENCODER.fixedSize);
return new TransactionInstruction({
keys: [],
programId: Secp256k1Program.programId,
data: instructionData
});
}
/**
* Create an secp256k1 instruction with a private key. The private key
* must be 32 bytes long.
*/
static createInstructionWithPrivateKey(params) {
const { privateKey: pkey, message, instructionIndex } = params;
const privateKey = toPackedUint8Array(pkey);
const messageBytes = toPackedUint8Array(message);
assert_default(privateKey.length === PRIVATE_KEY_BYTES, `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${privateKey.length} bytes`);
try {
const publicKey = publicKeyCreate(privateKey, false).slice(1);
const messageHash = keccak_256(messageBytes);
const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);
return this.createInstructionWithPublicKey({
publicKey,
message: messageBytes,
signature,
recoveryId,
instructionIndex
});
} catch (error) {
throw new Error(`Error creating instruction; ${String(error)}`);
}
}
};
// src/programs/stake.ts
/**
* PublicKey of the stake config account which configures the rate
* of stake warmup and cooldown as well as the slashing penalty.
*/
const STAKE_CONFIG_ID = new PublicKey("StakeConfig11111111111111111111111111111111");
const STAKE_PROGRAM_ID = new PublicKey(STAKE_PROGRAM_ADDRESS);
/**
* Stake account authority info
*/
var Authorized = class {
/** stake authority */
staker;
/** withdraw authority */
withdrawer;
/**
* Create a new Authorized object
* @param staker the stake authority
* @param withdrawer the withdraw authority
*/
constructor(staker, withdrawer) {
this.staker = staker;
this.withdrawer = withdrawer;
}
};
/**
* Stake account lockup info
*/
var Lockup = class Lockup {
/** Unix timestamp of lockup expiration */
unixTimestamp;
/** Epoch of lockup expiration */
epoch;
/** Lockup custodian authority */
custodian;
/**
* Create a new Lockup object
*/
constructor(unixTimestamp, epoch, custodian) {
this.unixTimestamp = unixTimestamp;
this.epoch = epoch;
this.custodian = custodian;
}
/**
* Default, inactive Lockup value
*/
static default = new Lockup(0, 0, PublicKey.default);
};
/**
* StakeAccount class
*/
var StakeAccount = class StakeAccount {
state;
/**
* @internal
*/
constructor(args) {
this.state = args.state;
}
/**
* Deserialize StakeAccount from the account data.
*
* @param bufferLike account data
* @return StakeAccount
*/
static fromAccountData(bufferLike) {
const decoded = getStakeStateAccountDecoder().decode(toUint8ArrayView(bufferLike));
return new StakeAccount({ state: parseStakeAccountState(decoded.state) });
}
};
const GENERATED_TO_LEGACY_INSTRUCTION_TYPE = {
[StakeInstruction$1.Authorize]: "Authorize",
[StakeInstruction$1.AuthorizeChecked]: "AuthorizeChecked",
[StakeInstruction$1.AuthorizeCheckedWithSeed]: "AuthorizeCheckedWithSeed",
[StakeInstruction$1.AuthorizeWithSeed]: "AuthorizeWithSeed",
[StakeInstruction$1.DeactivateDelinquent]: "DeactivateDelinquent",
[StakeInstruction$1.Deactivate]: "Deactivate",
[StakeInstruction$1.DelegateStake]: "Delegate",
[StakeInstruction$1.GetMinimumDelegation]: "GetMinimumDelegation",
[StakeInstruction$1.InitializeChecked]: "InitializeChecked",
[StakeInstruction$1.Initialize]: "Initialize",
[StakeInstruction$1.Merge]: "Merge",
[StakeInstruction$1.MoveLamports]: "MoveLamports",
[StakeInstruction$1.MoveStake]: "MoveStake",
[StakeInstruction$1.SetLockup]: "SetLockup",
[StakeInstruction$1.SetLockupChecked]: "SetLockupChecked",
[StakeInstruction$1.Split]: "Split",
[StakeInstruction$1.Withdraw]: "Withdraw"
};
function toGeneratedAuthorized(authorized) {
return {
staker: authorized.staker.toBase58(),
withdrawer: authorized.withdrawer.toBase58()
};
}
function fromGeneratedAuthorized(authorized) {
return new Authorized(new PublicKey(authorized.staker), new PublicKey(authorized.withdrawer));
}
function parseStakeAccountAuthorized(authorized) {
return {
staker: new PublicKey(authorized.staker),
withdrawer: new PublicKey(authorized.withdrawer)
};
}
function toGeneratedLockup(lockup) {
return {
unixTimestamp: lockup.unixTimestamp,
epoch: lockup.epoch,
custodian: lockup.custodian.toBase58()
};
}
function fromGeneratedLockup(lockup) {
return new Lockup(Number(lockup.unixTimestamp), Number(lockup.epoch), new PublicKey(lockup.custodian));
}
function parseStakeAccountLockup(lockup) {
return {
unixTimestamp: lockup.unixTimestamp,
epoch: lockup.epoch,
custodian: new PublicKey(lockup.custodian)
};
}
function parseStakeAccountDelegation(delegation) {
return {
voterPubkey: new PublicKey(delegation.voterPubkey),
stake: delegation.stake,
activationEpoch: delegation.activationEpoch,
deactivationEpoch: delegation.deactivationEpoch,
reserved: delegation.reserved
};
}
function parseStakeAccountMeta(meta) {
return {
rentExemptReserve: meta.rentExemptReserve,
authorized: parseStakeAccountAuthorized(meta.authorized),
lockup: parseStakeAccountLockup(meta.lockup)
};
}
function parseStakeAccountStake(stake) {
return {
delegation: parseStakeAccountDelegation(stake.delegation),
creditsObserved: stake.creditsObserved
};
}
function parseStakeAccountFlags(stakeFlags) {
return { bits: stakeFlags.bits };
}
function parseStakeAccountState(state) {
switch (state.__kind) {
case "Uninitialized": return { __kind: "Uninitialized" };
case "Initialized": {
const [meta] = state.fields;
return {
__kind: "Initialized",
meta: parseStakeAccountMeta(meta)
};
}
case "Stake": {
const [meta, stake, stakeFlags] = state.fields;
return {
__kind: "Stake",
meta: parseStakeAccountMeta(meta),
stake: parseStakeAccountStake(stake),
stakeFlags: parseStakeAccountFlags(stakeFlags)
};
}
case "RewardsPool": return { __kind: "RewardsPool" };
default: throw new Error("Unsupported stake account state");
}
}
function toGeneratedStakeAuthorize(stakeAuthorizationType) {
return stakeAuthorizationType.index;
}
function fromGeneratedStakeAuthorize(stakeAuthorize) {
return { index: stakeAuthorize };
}
function unwrapGeneratedOption(value) {
return value.__option === "Some" ? value.value : void 0;
}
function checkProgramId(programId) {
if (!programId.equals(StakeProgram.programId)) throw new Error("invalid instruction; programId is not StakeProgram");
}
function getInstructionType(instruction) {
checkProgramId(instruction.programId);
const generatedInstructionType = identifyStakeInstruction(instruction.data);
const instructionType = generatedInstructionType in GENERATED_TO_LEGACY_INSTRUCTION_TYPE ? GENERATED_TO_LEGACY_INSTRUCTION_TYPE[generatedInstructionType] : void 0;
if (!instructionType) throw new Error("Instruction type incorrect; not a StakeInstruction");
return instructionType;
}
function parseStakeInstructionOfType(instruction, expectedInstructionType) {
checkProgramId(instruction.programId);
const parsedInstruction = parseStakeInstruction(toKitInstruction(instruction));
if (parsedInstruction.instructionType !== expectedInstructionType) throw new Error("invalid instruction; instruction type mismatch");
return parsedInstruction;
}
/**
* Stake Instruction class
*/
var StakeInstruction = class {
/**
* @internal
*/
constructor() {}
/**
* Decode a stake instruction and retrieve the instruction type.
*/
static decodeInstructionType(instruction) {
return getInstructionType(instruction);
}
/**
* Decode a initialize stake instruction and retrieve the instruction params.
*/
static decodeInitialize(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.Initialize);
return {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
authorized: fromGeneratedAuthorized(parsedInstruction.data.arg0),
lockup: fromGeneratedLockup(parsedInstruction.data.arg1)
};
}
/**
* Decode an initialize-checked stake instruction and retrieve the instruction params.
*/
static decodeInitializeChecked(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.InitializeChecked);
return {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
authorized: new Authorized(new PublicKey(parsedInstruction.accounts.stakeAuthority.address), new PublicKey(parsedInstruction.accounts.withdrawAuthority.address))
};
}
/**
* Decode a delegate stake instruction and retrieve the instruction params.
*/
static decodeDelegate(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.DelegateStake);
return {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
votePubkey: new PublicKey(parsedInstruction.accounts.vote.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.stakeAuthority.address)
};
}
/**
* Decode an authorize stake instruction and retrieve the instruction params.
*/
static decodeAuthorize(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.Authorize);
const o = {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.authority.address),
newAuthorizedPubkey: new PublicKey(parsedInstruction.data.arg0),
stakeAuthorizationType: fromGeneratedStakeAuthorize(parsedInstruction.data.arg1)
};
if (parsedInstruction.accounts.lockupAuthority) o.custodianPubkey = new PublicKey(parsedInstruction.accounts.lockupAuthority.address);
return o;
}
/**
* Decode an authorize-checked stake instruction and retrieve the instruction params.
*/
static decodeAuthorizeChecked(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.AuthorizeChecked);
const o = {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.authority.address),
newAuthorizedPubkey: new PublicKey(parsedInstruction.accounts.newAuthority.address),
stakeAuthorizationType: fromGeneratedStakeAuthorize(parsedInstruction.data.stakeAuthorize)
};
if (parsedInstruction.accounts.lockupAuthority) o.custodianPubkey = new PublicKey(parsedInstruction.accounts.lockupAuthority.address);
return o;
}
/**
* Decode an authorize-with-seed stake instruction and retrieve the instruction params.
*/
static decodeAuthorizeWithSeed(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.AuthorizeWithSeed);
const o = {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
authorityBase: new PublicKey(parsedInstruction.accounts.base.address),
authoritySeed: parsedInstruction.data.authoritySeed,
authorityOwner: new PublicKey(parsedInstruction.data.authorityOwner),
newAuthorizedPubkey: new PublicKey(parsedInstruction.data.newAuthorizedPubkey),
stakeAuthorizationType: fromGeneratedStakeAuthorize(parsedInstruction.data.stakeAuthorize)
};
if (parsedInstruction.accounts.lockupAuthority) o.custodianPubkey = new PublicKey(parsedInstruction.accounts.lockupAuthority.address);
return o;
}
/**
* Decode an authorize-checked-with-seed stake instruction and retrieve the instruction params.
*/
static decodeAuthorizeCheckedWithSeed(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.AuthorizeCheckedWithSeed);
const o = {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
authorityBase: new PublicKey(parsedInstruction.accounts.base.address),
authoritySeed: parsedInstruction.data.authoritySeed,
authorityOwner: new PublicKey(parsedInstruction.data.authorityOwner),
newAuthorizedPubkey: new PublicKey(parsedInstruction.accounts.newAuthority.address),
stakeAuthorizationType: fromGeneratedStakeAuthorize(parsedInstruction.data.stakeAuthorize)
};
if (parsedInstruction.accounts.lockupAuthority) o.custodianPubkey = new PublicKey(parsedInstruction.accounts.lockupAuthority.address);
return o;
}
/**
* Decode a set-lockup stake instruction and retrieve the instruction params.
*/
static decodeSetLockup(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.SetLockup);
const o = {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.authority.address)
};
const unixTimestamp = unwrapGeneratedOption(parsedInstruction.data.unixTimestamp);
const epoch = unwrapGeneratedOption(parsedInstruction.data.epoch);
const custodian = unwrapGeneratedOption(parsedInstruction.data.custodian);
if (unixTimestamp !== void 0) o.unixTimestamp = unixTimestamp;
if (epoch !== void 0) o.epoch = epoch;
if (custodian !== void 0) o.custodian = new PublicKey(custodian);
return o;
}
/**
* Decode a set-lockup-checked stake instruction and retrieve the instruction params.
*/
static decodeSetLockupChecked(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.SetLockupChecked);
const o = {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.authority.address)
};
if (parsedInstruction.accounts.newAuthority) o.newAuthorizedPubkey = new PublicKey(parsedInstruction.accounts.newAuthority.address);
const unixTimestamp = unwrapGeneratedOption(parsedInstruction.data.unixTimestamp);
const epoch = unwrapGeneratedOption(parsedInstruction.data.epoch);
if (unixTimestamp !== void 0) o.unixTimestamp = unixTimestamp;
if (epoch !== void 0) o.epoch = epoch;
return o;
}
/**
* Decode a split stake instruction and retrieve the instruction params.
*/
static decodeSplit(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.Split);
return {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
splitStakePubkey: new PublicKey(parsedInstruction.accounts.splitStake.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.stakeAuthority.address),
lamports: parsedInstruction.data.args
};
}
/**
* Decode a get-minimum-delegation stake instruction and retrieve the instruction params.
*/
static decodeGetMinimumDelegation(instruction) {
parseStakeInstructionOfType(instruction, StakeInstruction$1.GetMinimumDelegation);
return {};
}
/**
* Decode a merge stake instruction and retrieve the instruction params.
*/
static decodeMerge(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.Merge);
return {
stakePubkey: new PublicKey(parsedInstruction.accounts.destinationStake.address),
sourceStakePubKey: new PublicKey(parsedInstruction.accounts.sourceStake.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.stakeAuthority.address)
};
}
/**
* Decode a withdraw stake instruction and retrieve the instruction params.
*/
static decodeWithdraw(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.Withdraw);
const o = {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
toPubkey: new PublicKey(parsedInstruction.accounts.recipient.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.withdrawAuthority.address),
lamports: parsedInstruction.data.args
};
if (parsedInstruction.accounts.lockupAuthority) o.custodianPubkey = new PublicKey(parsedInstruction.accounts.lockupAuthority.address);
return o;
}
/**
* Decode a deactivate stake instruction and retrieve the instruction params.
*/
static decodeDeactivate(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.Deactivate);
return {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.stakeAuthority.address)
};
}
/**
* Decode a deactivate-delinquent stake instruction and retrieve the instruction params.
*/
static decodeDeactivateDelinquent(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.DeactivateDelinquent);
return {
stakePubkey: new PublicKey(parsedInstruction.accounts.stake.address),
delinquentVotePubkey: new PublicKey(parsedInstruction.accounts.delinquentVote.address),
referenceVotePubkey: new PublicKey(parsedInstruction.accounts.referenceVote.address)
};
}
/**
* Decode a move-stake instruction and retrieve the instruction params.
*/
static decodeMoveStake(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.MoveStake);
return {
sourceStakePubkey: new PublicKey(parsedInstruction.accounts.sourceStake.address),
destinationStakePubkey: new PublicKey(parsedInstruction.accounts.destinationStake.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.stakeAuthority.address),
lamports: parsedInstruction.data.args
};
}
/**
* Decode a move-lamports instruction and retrieve the instruction params.
*/
static decodeMoveLamports(instruction) {
const parsedInstruction = parseStakeInstructionOfType(instruction, StakeInstruction$1.MoveLamports);
return {
sourceStakePubkey: new PublicKey(parsedInstruction.accounts.sourceStake.address),
destinationStakePubkey: new PublicKey(parsedInstruction.accounts.destinationStake.address),
authorizedPubkey: new PublicKey(parsedInstruction.accounts.stakeAuthority.address),
lamports: parsedInstruction.data.args
};
}
/**
* @internal
*/
static checkProgramId(programId) {
checkProgramId(programId);
}
};
/**
* An enumeration of valid StakeAuthorizationLayout's
*/
const StakeAuthorizationLayout = Object.freeze({
Staker: { index: 0 },
Withdrawer: { index: 1 }
});
/**
* Factory class for transactions to interact with the Stake program
*/
var StakeProgram = class {
/**
* @internal
*/
constructor() {}
/**
* Public key that identifies the Stake program
*/
static programId = STAKE_PROGRAM_ID;
/**
* Max space of a Stake account
*
* This is generated from the solana-stake-program StakeState struct as
* `StakeStateV2::size_of()`:
* https://docs.rs/solana-stake-program/latest/solana_stake_program/stake_state/enum.StakeStateV2.html
*/
static space = 200;
/**
* Generate an Initialize instruction to add to a Stake Create transaction
*/
static initialize(params) {
const { stakePubkey, authorized, lockup: maybeLockup } = params;
const lockup = maybeLockup || Lockup.default;
return fromKitInstruction(getInitializeInstruction({
stake: stakePubkey.toBase58(),
rentSysvar: SYSVAR_RENT_PUBKEY.toBase58(),
arg0: toGeneratedAuthorized(authorized),
arg1: toGeneratedLockup(lockup)
}));
}
/**
* Generate an InitializeChecked instruction.
*/
static initializeChecked(params) {
const { stakePubkey, authorized } = params;
return fromKitInstruction(getInitializeCheckedInstruction({
stake: stakePubkey.toBase58(),
rentSysvar: SYSVAR_RENT_PUBKEY.toBase58(),
stakeAuthority: authorized.staker.toBase58(),
withdrawAuthority: createNoopSigner(authorized.withdrawer.toBase58())
}));
}
/**
* Generate a Transaction that creates a new Stake account at
* an address generated with `from`, a seed, and the Stake programId
*/
static createAccountWithSeed(params) {
const transaction = new Transaction();
transaction.add(SystemProgram.createAccountWithSeed({
fromPubkey: params.fromPubkey,
newAccountPubkey: params.stakePubkey,
basePubkey: params.basePubkey,
seed: params.seed,
lamports: params.lamports,
space: this.space,
programId: this.programId
}));
const { stakePubkey, authorized, lockup } = params;
return transaction.add(this.initialize({
stakePubkey,
authorized,
lockup
}));
}
/**
* Generate a Transaction that creates a new Stake account
*/
static createAccount(params) {
const transaction = new Transaction();
transaction.add(SystemProgram.createAccount({
fromPubkey: params.fromPubkey,
newAccountPubkey: params.stakePubkey,
lamports: params.lamports,
space: this.space,
programId: this.programId
}));
const { stakePubkey, authorized, lockup } = params;
return transaction.add(this.initialize({
stakePubkey,
authorized,
lockup
}));
}
/**
* Generate a Transaction that delegates Stake tokens to a validator
* Vote PublicKey. This transaction can also be used to redelegate Stake
* to a new validator Vote PublicKey.
*/
static delegate(params) {
const { stakePubkey, authorizedPubkey, votePubkey } = params;
return new Transaction().add(fromKitInstruction(getDelegateStakeInstruction({
stake: stakePubkey.toBase58(),
vote: votePubkey.toBase58(),
clockSysvar: SYSVAR_CLOCK_PUBKEY.toBase58(),
stakeHistory: SYSVAR_STAKE_HISTORY_PUBKEY.toBase58(),
unused: STAKE_CONFIG_ID.toBase58(),
stakeAuthority: createNoopSigner(authorizedPubkey.toBase58())
})));
}
/**
* Generate a Transaction that authorizes a new PublicKey as Staker
* or Withdrawer on the Stake account.
*/
static authorize(params) {
const { stakePubkey, authorizedPubkey, newAuthorizedPubkey, stakeAuthorizationType, custodianPubkey } = params;
return new Transaction().add(fromKitInstruction(getAuthorizeInstruction({
stake: stakePubkey.toBase58(),
clockSysvar: SYSVAR_CLOCK_PUBKEY.toBase58(),
authority: createNoopSigner(authorizedPubkey.toBase58()),
...custodianPubkey ? { lockupAuthority: createNoopSigner(custodianPubkey.toBase58()) } : {},
arg0: newAuthorizedPubkey.toBase58(),
arg1: toGeneratedStakeAuthorize(stakeAuthorizationType)
})));
}
/**
* Generate a Transaction that authorizes a new signer as Staker or Withdrawer on the Stake account.
*/
static authorizeChecked(params) {
const { stakePubkey, authorizedPubkey, newAuthorizedPubkey, stakeAuthorizationType, custodianPubkey } = params;
return new Transaction().add(fromKitInstruction(getAuthorizeCheckedInstruction({
stake: stakePubkey.toBase58(),
clockSysvar: SYSVAR_CLOCK_PUBKEY.toBase58(),
authority: createNoopSigner(authorizedPubkey.toBase58()),
newAuthority: createNoopSigner(newAuthorizedPubkey.toBase58()),
...custodianPubkey ? { lockupAuthority: createNoopSigner(custodianPubkey.toBase58()) } : {},
stakeAuthorize: toGeneratedStakeAuthorize(stakeAuthorizationType)
})));
}
/**
* Generate a Transaction that authorizes a new PublicKey as Staker
* or Withdrawer on the Stake account.
*/
static authorizeWithSeed(params) {
const { stakePubkey, authorityBase, authoritySeed, authorityOwner, newAuthorizedPubkey, stakeAuthorizationType, custodianPubkey } = params;
return new Transaction().add(fromKitInstruction(getAuthorizeWithSeedInstruction({
stake: stakePubkey.toBase58(),
base: createNoopSigner(authorityBase.toBase58()),
clockSysvar: SYSVAR_CLOCK_PUBKEY.toBase58(),
...custodianPubkey ? { lockupAuthority: createNoopSigner(custodianPubkey.toBase58()) } : {},
newAuthorizedPubkey: newAuthorizedPubkey.toBase58(),
stakeAuthorize: toGeneratedStakeAuthorize(stakeAuthorizationType),
authoritySeed,
authorityOwner: authorityOwner.toBase58()
})));
}
/**
* Generate a Transaction that authorizes a new signer as Staker or Withdrawer on the Stake account using a derived key.
*/
static authorizeCheckedWithSeed(params) {
const { stakePubkey, authorityBase, authoritySeed, authorityOwner, newAuthorizedPubkey, stakeAuthorizationType, custodianPubkey } = params;
return new Transaction().add(fromKitInstruction(getAuthorizeCheckedWithSeedInstruction({
stake: stakePubkey.toBase58(),
base: createNoopSigner(authorityBase.toBase58()),
clockSysvar: SYSVAR_CLOCK_PUBKEY.toBase58(),
newAuthority: createNoopSigner(newAuthorizedPubkey.toBase58()),
...custodianPubkey ? { lockupAuthority: createNoopSigner(custodianPubkey.toBase58()) } : {},
stakeAuthorize: toGeneratedStakeAuthorize(stakeAuthorizationType),
authoritySeed,
authorityOwner: authorityOwner.toBase58()
})));
}
/**
* Generate a Transaction that updates a stake account lockup.
*/
static setLockup(params) {
const { stakePubkey, authorizedPubkey, unixTimestamp, epoch, custodian } = params;
return new Transaction().add(fromKitInstruction(getSetLockupInstruction({
stake: stakePubkey.toBase58(),
authority: createNoopSigner(authorizedPubkey.toBase58()),
unixTimestamp: unixTimestamp ?? null,
epoch: epoch ?? null,
custodian: custodian ? custodian.toBase58() : null
})));
}
/**
* Generate a Transaction that updates a stake account lockup using checked authorities.
*/
static setLockupChecked(params) {
const { stakePubkey, authorizedPubkey, newAuthorizedPubkey, unixTimestamp, epoch } = params;
return new Transaction().add(fromKitInstruction(getSetLockupCheckedInstruction({
stake: stakePubkey.toBase58(),
authority: createNoopSigner(authorizedPubkey.toBase58()),
...newAuthorizedPubkey ? { newAuthority: createNoopSigner(newAuthorizedPubkey.toBase58()) } : {},
unixTimestamp: unixTimestamp ?? null,
epoch: epoch ?? null
})));
}
/**
* @internal
*/
static splitInstruction(params) {
const { stakePubkey, authorizedPubkey, splitStakePubkey, lamports } = params;
return fromKitInstruction(getSplitInstruction({
stake: stakePubkey.toBase58(),
splitStake: splitStakePubkey.toBase58(),
stakeAuthority: createNoopSigner(authorizedPubkey.toBase58()),
args: lamports
}));
}
/**
* Generate a Transaction that splits Stake tokens into another stake account
*/
static split(params, rentExemptReserve) {
const transaction = new Transaction();
transaction.add(SystemProgram.createAccount({
fromPubkey: params.authorizedPubkey,
newAccountPubkey: params.splitStakePubkey,
lamports: rentExemptReserve,
space: this.space,
programId: this.programId
}));
return transaction.add(this.splitInstruction(params));
}
/**
* Generate a Transaction that splits Stake tokens into another account
* derived from a base public key and seed
*/
static splitWithSeed(params, rentExemptReserve) {
const { stakePubkey, authorizedPubkey, splitStakePubkey, basePubkey, seed, lamports } = params;
const transaction = new Transaction();
transaction.add(SystemProgram.allocate({
accountPubkey: splitStakePubkey,
basePubkey,
seed,
space: this.space,
programId: this.programId
}));
if (rentExemptReserve && rentExemptReserve > 0) transaction.add(SystemProgram.transfer({
fromPubkey: params.authorizedPubkey,
toPubkey: splitStakePubkey,
lamports: rentExemptReserve
}));
return transaction.add(this.splitInstruction({
stakePubkey,
authorizedPubkey,
splitStakePubkey,
lamports
}));
}
/**
* Generate a Transaction that merges Stake accounts.
*/
static merge(params) {
const { stakePubkey, sourceStakePubKey, authorizedPubkey } = params;
return new Transaction().add(fromKitInstruction(getMergeInstruction({
destinationStake: stakePubkey.toBase58(),
sourceStake: sourceStakePubKey.toBase58(),
clockSysvar: SYSVAR_CLOCK_PUBKEY.toBase58(),
stakeHistory: SYSVAR_STAKE_HISTORY_PUBKEY.toBase58(),
stakeAuthority: createNoopSigner(authorizedPubkey.toBase58())
})));
}
/**
* Generate a get-minimum-delegation instruction.
*/
static getMinimumDelegation() {
return fromKitInstruction(getGetMinimumDelegationInstruction());
}
/**
* Generate a Transaction that withdraws deactivated Stake tokens.
*/
static withdraw(params) {
const { stakePubkey, authorizedPubkey, toPubkey, lamports, custodianPubkey } = params;
return new Transaction().add(fromKitInstruction(getWithdrawInstruction({
stake: stakePubkey.toBase58(),
recipient: toPubkey.toBase58(),
clockSysvar: SYSVAR_CLOCK_PUBKEY.toBase58(),
stakeHistory: SYSVAR_STAKE_HISTORY_PUBKEY.toBase58(),
withdrawAuthority: createNoopSigner(authorizedPubkey.toBase58()),
...custodianPubkey ? { lockupAuthority: createNoopSigner(custodianPubkey.toBase58()) } : {},
args: lamports
})));
}
/**
* Generate a Transaction that deactivates Stake tokens.
*/
static deactivate(params) {
const { stakePubkey, authorizedPubkey } = params;
return new Transaction().add(fromKitInstruction(getDeactivateInstruction({
stake: stakePubkey.toBase58(),
clockSysvar: SYSVAR_CLOCK_PUBKEY.toBase58(),
stakeAuthority: createNoopSigner(authorizedPubkey.toBase58())
})));
}
/**
* Generate a Transaction that deactivates stake delegated to a delinquent vote account.
*/
static deactivateDelinquent(params) {
const { stakePubkey, delinquentVotePubkey, referenceVotePubkey } = params;
return new Transaction().add(fromKitInstruction(getDeactivateDelinquentInstruction({
stake: stakePubkey.toBase58(),
delinquentVote: delinquentVotePubkey.toBase58(),
referenceVote: referenceVotePubkey.toBase58()
})));
}
/**
* Generate a Transaction that moves active stake between stake accounts.
*/
static moveStake(params) {
const { sourceStakePubkey, destinationStakePubkey, authorizedPubkey, lamports } = params;
return new Transaction().add(fromKitInstruction(getMoveStakeInstruction({
sourceStake: sourceStakePubkey.toBase58(),
destinationStake: destinationStakePubkey.toBase58(),
stakeAuthority: createNoopSigner(authorizedPubkey.toBase58()),
args: lamports
})));
}
/**
* Generate a Transaction that moves lamports between compatible stake accounts.
*/
static moveLamports(params) {
const { sourceStakePubkey, destinationStakePubkey, authorizedPubkey, lamports } = params;
return new Transaction().add(fromKitInstruction(getMoveLamportsInstruction({
sourceStake: sourceStakePubkey.toBase58(),
destinationStake: destinationStakePubkey.toBase58(),
stakeAuthority: createNoopSigner(authorizedPubkey.toBase58()),
args: lamports
})));
}
};
// src/codecs.ts
const RUST_STRING_CODEC = addCodecSizePrefix(getUtf8Codec(), getU64Codec());
// src/programs/vote.ts
/**
* Vote account info
*/
var VoteInit = class {
nodePubkey;
authorizedVoter;
authorizedWithdrawer;
/** Expected percentage commission value, in the inclusive range [0, 100]. */
commission;
constructor(nodePubkey, authorizedVoter, authorizedWithdrawer, commission) {
this.nodePubkey = nodePubkey;
this.authorizedVoter = authorizedVoter;
this.authorizedWithdrawer = authorizedWithdrawer;
this.commission = commission;
}
};
const VOTE_PROGRAM_ID$1 = new PublicKey("Vote111111111111111111111111111111111111111");
const U32_CODEC$1 = getU32Codec();
const U8_CODEC$1 = getU8Codec();
const U64_BIGINT_CODEC$1 = transformCodec(getU64Codec(), (value) => coerceU64ToBigInt(value, "u64"), (decoded) => decoded);
const PUBLIC_KEY_BYTES_CODEC = fixCodecSize(getBytesCodec(), 32);
function coerceU64ToBigInt(value, valueName) {
const coerced = coerceNumericToBigInt(value, valueName);
assert_default(coerced >= 0n, `${valueName ?? "Value"} must be greater than or equal to 0`);
return coerced;
}
const INITIALIZE_ACCOUNT_INSTRUCTION_INDEX = 0;
const AUTHORIZE_INSTRUCTION_INDEX = 1;
const VOTE_INSTRUCTION_INDEX = 2;
const WITHDRAW_INSTRUCTION_INDEX = 3;
const UPDATE_VALIDATOR_IDENTITY_INSTRUCTION_INDEX = 4;
const UPDATE_COMMISSION_INSTRUCTION_INDEX = 5;
const VOTE_SWITCH_INSTRUCTION_INDEX = 6;
const AUTHORIZE_CHECKED_INSTRUCTION_INDEX = 7;
const UPDATE_VOTE_STATE_INSTRUCTION_INDEX = 8;
const UPDATE_VOTE_STATE_SWITCH_INSTRUCTION_INDEX = 9;
const AUTHORIZE_WITH_SEED_INSTRUCTION_INDEX = 10;
const AUTHORIZE_CHECKED_WITH_SEED_INSTRUCTION_INDEX = 11;
const COMPACT_UPDATE_VOTE_STATE_INSTRUCTION_INDEX = 12;
const COMPACT_UPDATE_VOTE_STATE_SWITCH_INSTRUCTION_INDEX = 13;
const TOWER_SYNC_INSTRUCTION_INDEX = 14;
const TOWER_SYNC_SWITCH_INSTRUCTION_INDEX = 15;
const VOTE_INIT_CODEC = getStructCodec([
["nodePubkey", PUBLIC_KEY_BYTES_CODEC],
["authorizedVoter", PUBLIC_KEY_BYTES_CODEC],
["authorizedWithdrawer", PUBLIC_KEY_BYTES_CODEC],
["commission", U8_CODEC$1]
]);
const VOTE_AUTHORIZE_WITH_SEED_CODEC = getStructCodec([
["voteAuthorizationType", U32_CODEC$1],
["currentAuthorityDerivedKeyOwnerPubkey", PUBLIC_KEY_BYTES_CODEC],
["currentAuthorityDerivedKeySeed", RUST_STRING_CODEC],
["newAuthorized", PUBLIC_KEY_BYTES_CODEC]
]);
const INITIALIZE_ACCOUNT_CODEC = getStructCodec([["instruction", U32_CODEC$1], ["voteInit", VOTE_INIT_CODEC]]);
const AUTHORIZE_CODEC = getStructCodec([
["instruction", U32_CODEC$1],
["newAuthorized", PUBLIC_KEY_BYTES_CODEC],
["voteAuthorizationType", U32_CODEC$1]
]);
const AUTHORIZE_CHECKED_CODEC = getStructCodec([["instruction", U32_CODEC$1], ["voteAuthorizationType", U32_CODEC$1]]);
const WITHDRAW_CODEC = getStructCodec([["instruction", U32_CODEC$1], ["lamports", U64_BIGINT_CODEC$1]]);
const UPDATE_VALIDATOR_IDENTITY_CODEC = getStructCodec([["instruction", U32_CODEC$1]]);
const UPDATE_COMMISSION_CODEC = getStructCodec([["instruction", U32_CODEC$1], ["commission", U8_CODEC$1]]);
const AUTHORIZE_WITH_SEED_CODEC = getStructCodec([["instruction", U32_CODEC$1], ["voteAuthorizeWithSeedArgs", VOTE_AUTHORIZE_WITH_SEED_CODEC]]);
const AUTHORIZE_CHECKED_WITH_SEED_CODEC = getStructCodec([
["instruction", U32_CODEC$1],
["voteAuthorizationType", U32_CODEC$1],
["currentAuthorityDerivedKeyOwnerPubkey", PUBLIC_KEY_BYTES_CODEC],
["currentAuthorityDerivedKeySeed", RUST_STRING_CODEC]
]);
function encodeVoteInstructionData(instruction, codec, params) {
return toUint8ArrayView(codec.encode({
instruction,
...params
}));
}
function decodeVoteInstructionData(instruction, expectedInstruction, codec) {
let decoded;
try {
decoded = codec.decode(instruction.data);
} catch (err) {
if (err instanceof Error && err.message.startsWith("invalid instruction;")) throw err;
throw new Error("invalid instruction; " + String(err));
}
if (decoded.instruction !== expectedInstruction) throw new Error(`invalid instruction; instruction index mismatch ${decoded.instruction} != ${expectedInstruction}`);
const { instruction: _instruction, ...rest } = decoded;
return rest;
}
function getVoteInstructionType(instruction) {
const instructionIndex = U32_CODEC$1.decode(instruction.data);
switch (instructionIndex) {
case INITIALIZE_ACCOUNT_INSTRUCTION_INDEX: return "InitializeAccount";
case AUTHORIZE_INSTRUCTION_INDEX: return "Authorize";
case WITHDRAW_INSTRUCTION_INDEX: return "Withdraw";
case UPDATE_VALIDATOR_IDENTITY_INSTRUCTION_INDEX: return "UpdateValidatorIdentity";
case UPDATE_COMMISSION_INSTRUCTION_INDEX: return "UpdateCommission";
case AUTHORIZE_CHECKED_INSTRUCTION_INDEX: return "AuthorizeChecked";
case AUTHORIZE_WITH_SEED_INSTRUCTION_INDEX: return "AuthorizeWithSeed";
case AUTHORIZE_CHECKED_WITH_SEED_INSTRUCTION_INDEX: return "AuthorizeCheckedWithSeed";
case VOTE_INSTRUCTION_INDEX:
case VOTE_SWITCH_INSTRUCTION_INDEX:
case UPDATE_VOTE_STATE_INSTRUCTION_INDEX:
case UPDATE_VOTE_STATE_SWITCH_INSTRUCTION_INDEX:
case COMPACT_UPDATE_VOTE_STATE_INSTRUCTION_INDEX:
case COMPACT_UPDATE_VOTE_STATE_SWITCH_INSTRUCTION_INDEX:
case TOWER_SYNC_INSTRUCTION_INDEX:
case TOWER_SYNC_SWITCH_INSTRUCTION_INDEX: throw new Error(`invalid instruction; unsupported vote-program instruction index ${instructionIndex}`);
default: throw new Error(`invalid instruction; unknown instruction index ${instructionIndex}`);
}
}
/**
* An enumeration of valid VoteAuthorization layouts.
*/
const VoteAuthorizationLayout = Object.freeze({
Voter: { index: 0 },
Withdrawer: { index: 1 }
});
/**
* Vote Instruction class
*/
var VoteInstruction = class {
/**
* Decode a vote instruction and retrieve the instruction type.
*/
static decodeInstructionType(instruction) {
this.checkProgramId(instruction.programId);
return getVoteInstructionType(instruction);
}
/**
* Decode an initialize vote instruction and retrieve the instruction params.
*/
static decodeInitializeAccount(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 4);
const { voteInit } = decodeVoteInstructionData(instruction, INITIALIZE_ACCOUNT_INSTRUCTION_INDEX, INITIALIZE_ACCOUNT_CODEC);
return {
votePubkey: instruction.keys[0].pubkey,
nodePubkey: instruction.keys[3].pubkey,
voteInit: new VoteInit(new PublicKey(voteInit.nodePubkey), new PublicKey(voteInit.authorizedVoter), new PublicKey(voteInit.authorizedWithdrawer), voteInit.commission)
};
}
/**
* Decode an authorize instruction and retrieve the instruction params.
*/
static decodeAuthorize(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 3);
const { newAuthorized, voteAuthorizationType } = decodeVoteInstructionData(instruction, AUTHORIZE_INSTRUCTION_INDEX, AUTHORIZE_CODEC);
return {
votePubkey: instruction.keys[0].pubkey,
authorizedPubkey: instruction.keys[2].pubkey,
newAuthorizedPubkey: new PublicKey(newAuthorized),
voteAuthorizationType: { index: voteAuthorizationType }
};
}
/**
* Decode an authorize-checked instruction and retrieve the instruction params.
*/
static decodeAuthorizeChecked(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 4);
const { voteAuthorizationType } = decodeVoteInstructionData(instruction, AUTHORIZE_CHECKED_INSTRUCTION_INDEX, AUTHORIZE_CHECKED_CODEC);
return {
votePubkey: instruction.keys[0].pubkey,
authorizedPubkey: instruction.keys[2].pubkey,
newAuthorizedPubkey: instruction.keys[3].pubkey,
voteAuthorizationType: { index: voteAuthorizationType }
};
}
/**
* Decode an authorize instruction and retrieve the instruction params.
*/
static decodeAuthorizeWithSeed(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 3);
const { voteAuthorizeWithSeedArgs: { currentAuthorityDerivedKeyOwnerPubkey, currentAuthorityDerivedKeySeed, newAuthorized, voteAuthorizationType } } = decodeVoteInstructionData(instruction, AUTHORIZE_WITH_SEED_INSTRUCTION_INDEX, AUTHORIZE_WITH_SEED_CODEC);
return {
currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey,
currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(currentAuthorityDerivedKeyOwnerPubkey),
currentAuthorityDerivedKeySeed,
newAuthorizedPubkey: new PublicKey(newAuthorized),
voteAuthorizationType: { index: voteAuthorizationType },
votePubkey: instruction.keys[0].pubkey
};
}
/**
* Decode an authorize-checked-with-seed instruction and retrieve the params.
*/
static decodeAuthorizeCheckedWithSeed(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 4);
const { currentAuthorityDerivedKeyOwnerPubkey, currentAuthorityDerivedKeySeed, voteAuthorizationType } = decodeVoteInstructionData(instruction, AUTHORIZE_CHECKED_WITH_SEED_INSTRUCTION_INDEX, AUTHORIZE_CHECKED_WITH_SEED_CODEC);
return {
currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey,
currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(currentAuthorityDerivedKeyOwnerPubkey),
currentAuthorityDerivedKeySeed,
newAuthorizedPubkey: instruction.keys[3].pubkey,
voteAuthorizationType: { index: voteAuthorizationType },
votePubkey: instruction.keys[0].pubkey
};
}
/**
* Decode a withdraw instruction and retrieve the instruction params.
*/
static decodeWithdraw(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 3);
const { lamports } = decodeVoteInstructionData(instruction, WITHDRAW_INSTRUCTION_INDEX, WITHDRAW_CODEC);
return {
votePubkey: instruction.keys[0].pubkey,
authorizedWithdrawerPubkey: instruction.keys[2].pubkey,
lamports,
toPubkey: instruction.keys[1].pubkey
};
}
/**
* Decode an update-validator-identity instruction and retrieve the params.
*/
static decodeUpdateValidatorIdentity(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 3);
decodeVoteInstructionData(instruction, UPDATE_VALIDATOR_IDENTITY_INSTRUCTION_INDEX, UPDATE_VALIDATOR_IDENTITY_CODEC);
return {
votePubkey: instruction.keys[0].pubkey,
nodePubkey: instruction.keys[1].pubkey,
authorizedWithdrawerPubkey: instruction.keys[2].pubkey
};
}
/**
* Decode an update-commission instruction and retrieve the params.
*/
static decodeUpdateCommission(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 2);
const { commission } = decodeVoteInstructionData(instruction, UPDATE_COMMISSION_INSTRUCTION_INDEX, UPDATE_COMMISSION_CODEC);
return {
votePubkey: instruction.keys[0].pubkey,
authorizedWithdrawerPubkey: instruction.keys[1].pubkey,
commission
};
}
/**
* @internal
*/
static checkProgramId(programId) {
if (!programId.equals(VoteProgram.programId)) throw new Error("invalid instruction; programId is not VoteProgram");
}
/**
* @internal
*/
static checkKeyLength(keys, expectedLength) {
if (keys.length < expectedLength) throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`);
}
};
/**
* Factory class for transactions to interact with the Vote program
*/
var VoteProgram = class VoteProgram {
/**
* Public key that identifies the Vote program
*/
static programId = VOTE_PROGRAM_ID$1;
/**
* Max Space for newly created vote accounts using the current Agave vote-state
* layout targeted by this client.
*
* Vote Program v3.1.13 (https://docs.rs/solana-vote-program/3.1.13/solana_vote_program/) reports:
* - `VoteStateV4::size_of() == 3762`
* - `VoteStateV3::size_of() == 3762`
* - `VoteState1_14_11::size_of() == 3731`
*
* The smaller legacy `VoteState1_14_11` size does not change this
* constant: existing historical vote accounts may still use that older
* layout, but new accounts should allocate enough space for the current
* V3/V4 layout.
*
* Keep this in sync with Agave vote-program sizing in
* https://github.com/anza-xyz/agave/blob/3134055b562e95902233be308453fffa1c4a8902/programs/vote/src/vote_state/mod.rs.
*/
static space = 3762;
/**
* Generate an Initialize instruction.
*/
static initializeAccount(params) {
const { votePubkey, nodePubkey, voteInit } = params;
return new TransactionInstruction({
keys: [
{
pubkey: votePubkey,
isSigner: false,
isWritable: true
},
{
pubkey: SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false
},
{
pubkey: SYSVAR_CLOCK_PUBKEY,
isSigner: false,
isWritable: false
},
{
pubkey: nodePubkey,
isSigner: true,
isWritable: false
}
],
programId: this.programId,
data: encodeVoteInstructionData(INITIALIZE_ACCOUNT_INSTRUCTION_INDEX, INITIALIZE_ACCOUNT_CODEC, { voteInit: {
nodePubkey: voteInit.nodePubkey.toBytes(),
authorizedVoter: voteInit.authorizedVoter.toBytes(),
authorizedWithdrawer: voteInit.authorizedWithdrawer.toBytes(),
commission: voteInit.commission
} })
});
}
/**
* Generate a transaction that creates a new Vote account.
*/
static createAccount(params) {
const transaction = new Transaction();
transaction.add(SystemProgram.createAccount({
fromPubkey: params.fromPubkey,
newAccountPubkey: params.votePubkey,
lamports: params.lamports,
space: this.space,
programId: this.programId
}));
return transaction.add(this.initializeAccount({
votePubkey: params.votePubkey,
nodePubkey: params.voteInit.nodePubkey,
voteInit: params.voteInit
}));
}
/**
* Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.
*/
static authorize(params) {
const { votePubkey, authorizedPubkey, newAuthorizedPubkey, voteAuthorizationType } = params;
const keys = [
{
pubkey: votePubkey,
isSigner: false,
isWritable: true
},
{
pubkey: SYSVAR_CLOCK_PUBKEY,
isSigner: false,
isWritable: false
},
{
pubkey: authorizedPubkey,
isSigner: true,
isWritable: false
}
];
return new Transaction().add(new TransactionInstruction({
keys,
programId: this.programId,
data: encodeVoteInstructionData(AUTHORIZE_INSTRUCTION_INDEX, AUTHORIZE_CODEC, {
newAuthorized: newAuthorizedPubkey.toBytes(),
voteAuthorizationType: voteAuthorizationType.index
})
}));
}
/**
* Generate a transaction that authorizes a new Voter or Withdrawer and requires the new
* authority to sign.
*/
static authorizeChecked(params) {
const { votePubkey, authorizedPubkey, newAuthorizedPubkey, voteAuthorizationType } = params;
return new Transaction().add(new TransactionInstruction({
keys: [
{
pubkey: votePubkey,
isSigner: false,
isWritable: true
},
{
pubkey: SYSVAR_CLOCK_PUBKEY,
isSigner: false,
isWritable: false
},
{
pubkey: authorizedPubkey,
isSigner: true,
isWritable: false
},
{
pubkey: newAuthorizedPubkey,
isSigner: true,
isWritable: false
}
],
programId: this.programId,
data: encodeVoteInstructionData(AUTHORIZE_CHECKED_INSTRUCTION_INDEX, AUTHORIZE_CHECKED_CODEC, { voteAuthorizationType: voteAuthorizationType.index })
}));
}
/**
* Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account
* where the current Voter or Withdrawer authority is a derived key.
*/
static authorizeWithSeed(params) {
const { currentAuthorityDerivedKeyBasePubkey, currentAuthorityDerivedKeyOwnerPubkey, currentAuthorityDerivedKeySeed, newAuthorizedPubkey, voteAuthorizationType, votePubkey } = params;
const keys = [
{
pubkey: votePubkey,
isSigner: false,
isWritable: true
},
{
pubkey: SYSVAR_CLOCK_PUBKEY,
isSigner: false,
isWritable: false
},
{
pubkey: currentAuthorityDerivedKeyBasePubkey,
isSigner: true,
isWritable: false
}
];
return new Transaction().add(new TransactionInstruction({
keys,
programId: this.programId,
data: encodeVoteInstructionData(AUTHORIZE_WITH_SEED_INSTRUCTION_INDEX, AUTHORIZE_WITH_SEED_CODEC, { voteAuthorizeWithSeedArgs: {
currentAuthorityDerivedKeyOwnerPubkey: currentAuthorityDerivedKeyOwnerPubkey.toBytes(),
currentAuthorityDerivedKeySeed,
newAuthorized: newAuthorizedPubkey.toBytes(),
voteAuthorizationType: voteAuthorizationType.index
} })
}));
}
/**
* Generate a transaction that authorizes a new Voter or Withdrawer from a derived key and
* requires the new authority to sign.
*/
static authorizeCheckedWithSeed(params) {
const { currentAuthorityDerivedKeyBasePubkey, currentAuthorityDerivedKeyOwnerPubkey, currentAuthorityDerivedKeySeed, newAuthorizedPubkey, voteAuthorizationType, votePubkey } = params;
return new Transaction().add(new TransactionInstruction({
keys: [
{
pubkey: votePubkey,
isSigner: false,
isWritable: true
},
{
pubkey: SYSVAR_CLOCK_PUBKEY,
isSigner: false,
isWritable: false
},
{
pubkey: currentAuthorityDerivedKeyBasePubkey,
isSigner: true,
isWritable: false
},
{
pubkey: newAuthorizedPubkey,
isSigner: true,
isWritable: false
}
],
programId: this.programId,
data: encodeVoteInstructionData(AUTHORIZE_CHECKED_WITH_SEED_INSTRUCTION_INDEX, AUTHORIZE_CHECKED_WITH_SEED_CODEC, {
voteAuthorizationType: voteAuthorizationType.index,
currentAuthorityDerivedKeyOwnerPubkey: currentAuthorityDerivedKeyOwnerPubkey.toBytes(),
currentAuthorityDerivedKeySeed
})
}));
}
/**
* Generate a transaction to withdraw from a Vote account.
*/
static withdraw(params) {
const { votePubkey, authorizedWithdrawerPubkey, lamports, toPubkey } = params;
const keys = [
{
pubkey: votePubkey,
isSigner: false,
isWritable: true
},
{
pubkey: toPubkey,
isSigner: false,
isWritable: true
},
{
pubkey: authorizedWithdrawerPubkey,
isSigner: true,
isWritable: false
}
];
return new Transaction().add(new TransactionInstruction({
keys,
programId: this.programId,
data: encodeVoteInstructionData(WITHDRAW_INSTRUCTION_INDEX, WITHDRAW_CODEC, { lamports })
}));
}
/**
* Generate a transaction to withdraw safely from a Vote account.
*
* This function was created as a safeguard for vote accounts running validators, `safeWithdraw`
* checks that the withdraw amount will not exceed the specified balance while leaving enough left
* to cover rent. If you wish to close the vote account by withdrawing the full amount, call the
* `withdraw` method directly.
*/
static safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) {
if (coerceU64ToBigInt(params.lamports, "lamports") > coerceU64ToBigInt(currentVoteAccountBalance, "currentVoteAccountBalance") - coerceU64ToBigInt(rentExemptMinimum, "rentExemptMinimum")) throw new Error("Withdraw will leave vote account with insufficient funds.");
return VoteProgram.withdraw(params);
}
/**
* Generate a transaction to update the commission on a Vote account.
*/
static updateCommission(params) {
const { votePubkey, authorizedWithdrawerPubkey, commission } = params;
return new Transaction().add(new TransactionInstruction({
keys: [{
pubkey: votePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: authorizedWithdrawerPubkey,
isSigner: true,
isWritable: false
}],
programId: this.programId,
data: encodeVoteInstructionData(UPDATE_COMMISSION_INSTRUCTION_INDEX, UPDATE_COMMISSION_CODEC, { commission })
}));
}
/**
* Generate a transaction to update the validator identity (node pubkey) of a Vote account.
*/
static updateValidatorIdentity(params) {
const { votePubkey, authorizedWithdrawerPubkey, nodePubkey } = params;
const keys = [
{
pubkey: votePubkey,
isSigner: false,
isWritable: true
},
{
pubkey: nodePubkey,
isSigner: true,
isWritable: false
},
{
pubkey: authorizedWithdrawerPubkey,
isSigner: true,
isWritable: false
}
];
return new Transaction().add(new TransactionInstruction({
keys,
programId: this.programId,
data: encodeVoteInstructionData(UPDATE_VALIDATOR_IDENTITY_INSTRUCTION_INDEX, UPDATE_VALIDATOR_IDENTITY_CODEC)
}));
}
};
// src/validator-info.ts
const SHORT_U16_DECODER = getShortU16Decoder();
const U8_DECODER = getU8Decoder();
const CONFIG_KEY_DECODER = getStructDecoder([["publicKey", fixDecoderSize(getBytesDecoder(), 32)], ["isSigner", U8_DECODER]]);
const VALIDATOR_INFO_KEY = new PublicKey("Va1idator1nfo111111111111111111111111111111");
function isRecord(value) {
return typeof value === "object" && value !== null;
}
function parseOptionalStringField(info, key) {
const value = info[key];
assert_default(value === void 0 || typeof value === "string", `Expected validator info field "${key}" to be a string`);
return value;
}
function parseInfo(value) {
assert_default(isRecord(value), "Expected validator info to be an object");
assert_default(typeof value.name === "string", "Expected validator info field \"name\" to be a string");
const website = parseOptionalStringField(value, "website");
const details = parseOptionalStringField(value, "details");
const iconUrl = parseOptionalStringField(value, "iconUrl");
const keybaseUsername = parseOptionalStringField(value, "keybaseUsername");
return {
name: value.name,
...website !== void 0 ? { website } : null,
...details !== void 0 ? { details } : null,
...iconUrl !== void 0 ? { iconUrl } : null,
...keybaseUsername !== void 0 ? { keybaseUsername } : null
};
}
const VALIDATOR_INFO_CONFIG_DECODER = getStructDecoder([["configKeys", getArrayDecoder(CONFIG_KEY_DECODER, { size: SHORT_U16_DECODER })], ["info", RUST_STRING_CODEC]]);
/**
* ValidatorInfo class
*/
var ValidatorInfo = class ValidatorInfo {
/**
* validator public key
*/
key;
/**
* validator information
*/
info;
/**
* Construct a valid ValidatorInfo
*
* @param key validator public key
* @param info validator information
*/
constructor(key, info) {
this.key = key;
this.info = info;
}
/**
* Deserialize ValidatorInfo from the config account data. Exactly two config
* keys are required in the data.
*
* @param buffer config account data
* @return null if info was not found
*/
static fromConfigData(buffer) {
const { configKeys: decodedConfigKeys, info: rawInfo } = VALIDATOR_INFO_CONFIG_DECODER.decode(toUint8ArrayView(buffer));
if (decodedConfigKeys.length !== 2) return null;
const configKeys = decodedConfigKeys.map((configKey) => ({
publicKey: new PublicKey(configKey.publicKey),
isSigner: configKey.isSigner === 1
}));
if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) {
if (configKeys[1].isSigner) {
const info = parseInfo(JSON.parse(rawInfo));
return new ValidatorInfo(configKeys[1].publicKey, info);
}
}
return null;
}
};
// src/vote-account.ts
const VOTE_PROGRAM_ID = new PublicKey("Vote111111111111111111111111111111111111111");
/**
* Vote account state versions
*/
const VoteStateVersion = {
V1_14_11: 1,
V3: 2,
V4: 3
};
const PRIOR_VOTERS_COUNT = 32;
const BLS_PUBLIC_KEY_COMPRESSED_SIZE = 48;
const U8_CODEC = getU8Codec();
const U16_CODEC = getU16Codec();
const U32_CODEC = getU32Codec();
const U64_CODEC = getU64Codec();
const U64_BIGINT_CODEC = transformCodec(U64_CODEC, (value) => coerceNumericToBigInt(value, "u64"), (value) => value);
const I64_BIGINT_CODEC = transformCodec(getI64Codec(), (value) => coerceNumericToBigInt(value, "i64"), (value) => value);
const PUBLIC_KEY_CODEC = transformCodec(fixCodecSize(getBytesCodec(), 32), (value) => value, (value) => new Uint8Array(value));
const NULLABLE_U64_BIGINT_CODEC = transformCodec(getOptionCodec(U64_CODEC), (value) => coerceNullableNumericToBigInt(value, "u64"), (value) => {
const unwrapped = unwrapOption(value);
return unwrapped == null ? null : unwrapped;
});
const NULLABLE_BLS_PUBLIC_KEY_COMPRESSED_CODEC = transformCodec(getOptionCodec(fixCodecSize(getBytesCodec(), BLS_PUBLIC_KEY_COMPRESSED_SIZE)), (value) => value, (value) => {
const unwrapped = unwrapOption(value);
return unwrapped == null ? null : new Uint8Array(unwrapped);
});
const LOCKOUT_CODEC = getStructCodec([["slot", U64_BIGINT_CODEC], ["confirmationCount", U32_CODEC]]);
const LANDED_VOTE_CODEC = transformCodec(getStructCodec([
["latency", U8_CODEC],
["slot", U64_BIGINT_CODEC],
["confirmationCount", U32_CODEC]
]), (value) => ({
latency: value.latency,
slot: value.lockout.slot,
confirmationCount: value.lockout.confirmationCount
}), (value) => ({
latency: value.latency,
lockout: {
slot: value.slot,
confirmationCount: value.confirmationCount
}
}));
const AUTHORIZED_VOTER_CODEC = getStructCodec([["epoch", U64_BIGINT_CODEC], ["authorizedVoter", PUBLIC_KEY_CODEC]]);
const PRIOR_VOTER_CODEC = getStructCodec([
["authorizedPubkey", PUBLIC_KEY_CODEC],
["epochOfLastAuthorizedSwitch", U64_BIGINT_CODEC],
["targetEpoch", U64_BIGINT_CODEC]
]);
const PRIOR_VOTERS_CODEC = getStructCodec([
["buf", getArrayCodec(PRIOR_VOTER_CODEC, { size: PRIOR_VOTERS_COUNT })],
["idx", U64_BIGINT_CODEC],
["isEmpty", U8_CODEC]
]);
const EPOCH_CREDITS_CODEC = getStructCodec([
["epoch", U64_BIGINT_CODEC],
["credits", U64_BIGINT_CODEC],
["prevCredits", U64_BIGINT_CODEC]
]);
const BLOCK_TIMESTAMP_CODEC = getStructCodec([["slot", U64_BIGINT_CODEC], ["timestamp", I64_BIGINT_CODEC]]);
const VOTE_ACCOUNT_V1_14_11_CODEC = getStructCodec([
["nodePubkey", PUBLIC_KEY_CODEC],
["authorizedWithdrawer", PUBLIC_KEY_CODEC],
["commission", U8_CODEC],
["votes", getArrayCodec(LOCKOUT_CODEC, { size: U64_BIGINT_CODEC })],
["rootSlot", NULLABLE_U64_BIGINT_CODEC],
["authorizedVoters", getArrayCodec(AUTHORIZED_VOTER_CODEC, { size: U64_BIGINT_CODEC })],
["priorVoters", PRIOR_VOTERS_CODEC],
["epochCredits", getArrayCodec(EPOCH_CREDITS_CODEC, { size: U64_BIGINT_CODEC })],
["lastTimestamp", BLOCK_TIMESTAMP_CODEC]
]);
const VOTE_ACCOUNT_V3_CODEC = getStructCodec([
["nodePubkey", PUBLIC_KEY_CODEC],
["authorizedWithdrawer", PUBLIC_KEY_CODEC],
["commission", U8_CODEC],
["votes", getArrayCodec(LANDED_VOTE_CODEC, { size: U64_BIGINT_CODEC })],
["rootSlot", NULLABLE_U64_BIGINT_CODEC],
["authorizedVoters", getArrayCodec(AUTHORIZED_VOTER_CODEC, { size: U64_BIGINT_CODEC })],
["priorVoters", PRIOR_VOTERS_CODEC],
["epochCredits", getArrayCodec(EPOCH_CREDITS_CODEC, { size: U64_BIGINT_CODEC })],
["lastTimestamp", BLOCK_TIMESTAMP_CODEC]
]);
const VOTE_ACCOUNT_V4_CODEC = getStructCodec([
["nodePubkey", PUBLIC_KEY_CODEC],
["authorizedWithdrawer", PUBLIC_KEY_CODEC],
["inflationRewardsCollector", PUBLIC_KEY_CODEC],
["blockRevenueCollector", PUBLIC_KEY_CODEC],
["inflationRewardsCommissionBps", U16_CODEC],
["blockRevenueCommissionBps", U16_CODEC],
["pendingDelegatorRewards", U64_BIGINT_CODEC],
["blsPubkeyCompressed", NULLABLE_BLS_PUBLIC_KEY_COMPRESSED_CODEC],
["votes", getArrayCodec(LANDED_VOTE_CODEC, { size: U64_BIGINT_CODEC })],
["rootSlot", NULLABLE_U64_BIGINT_CODEC],
["authorizedVoters", getArrayCodec(AUTHORIZED_VOTER_CODEC, { size: U64_BIGINT_CODEC })],
["epochCredits", getArrayCodec(EPOCH_CREDITS_CODEC, { size: U64_BIGINT_CODEC })],
["lastTimestamp", BLOCK_TIMESTAMP_CODEC]
]);
function normalizePriorVoters({ buf, idx, isEmpty }) {
if (idx < 0n || idx >= BigInt(PRIOR_VOTERS_COUNT)) throw new Error("Invalid vote account data: prior voters index out of range");
if (isEmpty) return [];
const normalizedIndex = Number(idx);
return [...buf.slice(normalizedIndex + 1), ...buf.slice(0, normalizedIndex + 1)];
}
function commissionPercentFromBps(commissionBps) {
return Math.min(Math.floor(commissionBps / 100), 255);
}
function decodeVoteAccountDataV1_14_11(decoded) {
return {
nodePubkey: decoded.nodePubkey,
authorizedWithdrawer: decoded.authorizedWithdrawer,
commission: decoded.commission,
votes: decoded.votes,
rootSlot: decoded.rootSlot,
authorizedVoters: decoded.authorizedVoters,
priorVoters: normalizePriorVoters(decoded.priorVoters),
epochCredits: decoded.epochCredits,
lastTimestamp: decoded.lastTimestamp,
inflationRewardsCollector: null,
blockRevenueCollector: null,
inflationRewardsCommissionBps: null,
blockRevenueCommissionBps: null,
pendingDelegatorRewards: null,
blsPubkeyCompressed: null
};
}
function decodeVoteAccountDataV3(decoded) {
return {
nodePubkey: decoded.nodePubkey,
authorizedWithdrawer: decoded.authorizedWithdrawer,
commission: decoded.commission,
votes: decoded.votes.map((vote) => vote.lockout),
rootSlot: decoded.rootSlot,
authorizedVoters: decoded.authorizedVoters,
priorVoters: normalizePriorVoters(decoded.priorVoters),
epochCredits: decoded.epochCredits,
lastTimestamp: decoded.lastTimestamp,
inflationRewardsCollector: null,
blockRevenueCollector: null,
inflationRewardsCommissionBps: null,
blockRevenueCommissionBps: null,
pendingDelegatorRewards: null,
blsPubkeyCompressed: null
};
}
function decodeVoteAccountDataV4(decoded) {
return {
nodePubkey: decoded.nodePubkey,
authorizedWithdrawer: decoded.authorizedWithdrawer,
inflationRewardsCollector: decoded.inflationRewardsCollector,
blockRevenueCollector: decoded.blockRevenueCollector,
inflationRewardsCommissionBps: decoded.inflationRewardsCommissionBps,
blockRevenueCommissionBps: decoded.blockRevenueCommissionBps,
pendingDelegatorRewards: decoded.pendingDelegatorRewards,
blsPubkeyCompressed: decoded.blsPubkeyCompressed,
commission: commissionPercentFromBps(decoded.inflationRewardsCommissionBps),
votes: decoded.votes.map((vote) => vote.lockout),
rootSlot: decoded.rootSlot,
authorizedVoters: decoded.authorizedVoters,
priorVoters: [],
epochCredits: decoded.epochCredits,
lastTimestamp: decoded.lastTimestamp
};
}
/**
* @internal
*/
const __TEST_ONLY__VOTE_ACCOUNT_V1_14_11_CODEC = transformCodec(VOTE_ACCOUNT_V1_14_11_CODEC, (value) => ({
...value,
rootSlot: value.rootSlotValid ? value.rootSlot : null
}), (value) => ({
...value,
rootSlotValid: value.rootSlot == null ? 0 : 1,
rootSlot: value.rootSlot ?? 0n
}));
/** @internal */
const __TEST_ONLY__VOTE_ACCOUNT_V3_CODEC = VOTE_ACCOUNT_V3_CODEC;
/** @internal */
const __TEST_ONLY__VOTE_ACCOUNT_V4_CODEC = VOTE_ACCOUNT_V4_CODEC;
/**
* See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88
*
* @internal
*/
const decodeVoteAccountData = (bytes) => {
const version = U32_CODEC.decode(bytes);
switch (version) {
case VoteStateVersion.V1_14_11: return decodeVoteAccountDataV1_14_11(VOTE_ACCOUNT_V1_14_11_CODEC.decode(bytes, U32_CODEC.fixedSize));
case VoteStateVersion.V3: return decodeVoteAccountDataV3(VOTE_ACCOUNT_V3_CODEC.decode(bytes, U32_CODEC.fixedSize));
case VoteStateVersion.V4: return decodeVoteAccountDataV4(VOTE_ACCOUNT_V4_CODEC.decode(bytes, U32_CODEC.fixedSize));
case 0: throw new Error("Old vote account version is not supported");
default: throw new Error(`Unsupported vote account version: ${version}. Supported versions: ${VoteStateVersion.V1_14_11}, ${VoteStateVersion.V3}, ${VoteStateVersion.V4}.`);
}
};
/**
* VoteAccount class
*/
var VoteAccount = class VoteAccount {
nodePubkey;
authorizedWithdrawer;
blsPubkeyCompressed;
blockRevenueCollector;
blockRevenueCommissionBps;
commission;
rootSlot;
votes;
authorizedVoters;
inflationRewardsCollector;
inflationRewardsCommissionBps;
priorVoters;
epochCredits;
lastTimestamp;
pendingDelegatorRewards;
/**
* @internal
*/
constructor(args) {
this.nodePubkey = args.nodePubkey;
this.authorizedWithdrawer = args.authorizedWithdrawer;
this.blsPubkeyCompressed = args.blsPubkeyCompressed;
this.blockRevenueCollector = args.blockRevenueCollector;
this.blockRevenueCommissionBps = args.blockRevenueCommissionBps;
this.commission = args.commission;
this.rootSlot = args.rootSlot;
this.votes = args.votes;
this.authorizedVoters = args.authorizedVoters;
this.inflationRewardsCollector = args.inflationRewardsCollector;
this.inflationRewardsCommissionBps = args.inflationRewardsCommissionBps;
this.priorVoters = args.priorVoters;
this.epochCredits = args.epochCredits;
this.lastTimestamp = args.lastTimestamp;
this.pendingDelegatorRewards = args.pendingDelegatorRewards;
}
/**
* Deserialize VoteAccount from the account data.
*
* @param bufferLike account data
* @return VoteAccount
*/
static fromAccountData(bufferLike) {
const va = decodeVoteAccountData(toUint8ArrayView(bufferLike));
return new VoteAccount({
nodePubkey: new PublicKey(va.nodePubkey),
authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer),
blsPubkeyCompressed: va.blsPubkeyCompressed,
blockRevenueCollector: va.blockRevenueCollector ? new PublicKey(va.blockRevenueCollector) : null,
blockRevenueCommissionBps: va.blockRevenueCommissionBps,
commission: va.commission,
votes: va.votes,
rootSlot: va.rootSlot,
authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter),
inflationRewardsCollector: va.inflationRewardsCollector ? new PublicKey(va.inflationRewardsCollector) : null,
inflationRewardsCommissionBps: va.inflationRewardsCommissionBps,
priorVoters: va.priorVoters.map(parsePriorVoters),
epochCredits: va.epochCredits,
lastTimestamp: va.lastTimestamp,
pendingDelegatorRewards: va.pendingDelegatorRewards
});
}
};
function parseAuthorizedVoter({ authorizedVoter, epoch }) {
return {
epoch,
authorizedVoter: new PublicKey(authorizedVoter)
};
}
function parsePriorVoters({ authorizedPubkey, epochOfLastAuthorizedSwitch, targetEpoch }) {
return {
authorizedPubkey: new PublicKey(authorizedPubkey),
epochOfLastAuthorizedSwitch,
targetEpoch
};
}
// src/utils/cluster.ts
const endpoint = {
http: {
devnet: "http://api.devnet.solana.com",
testnet: "http://api.testnet.solana.com",
mainnet: "http://api.mainnet.solana.com/",
"mainnet-beta": "http://api.mainnet-beta.solana.com/"
},
https: {
devnet: "https://api.devnet.solana.com",
testnet: "https://api.testnet.solana.com",
mainnet: "https://api.mainnet.solana.com/",
"mainnet-beta": "https://api.mainnet-beta.solana.com/"
}
};
function clusterApiUrl(cluster, tls) {
const key = tls === false ? "http" : "https";
if (!cluster) return endpoint[key]["devnet"];
const url = endpoint[key][cluster];
if (!url) throw new Error(`Unknown ${key} cluster: ${cluster}`);
return url;
}
// src/utils/send-and-confirm-raw-transaction.ts
async function sendAndConfirmRawTransaction(connection, rawTransaction, confirmationStrategyOrConfirmOptions, maybeConfirmOptions) {
let confirmationStrategy;
let options;
if (confirmationStrategyOrConfirmOptions && "lastValidBlockHeight" in confirmationStrategyOrConfirmOptions) {
confirmationStrategy = confirmationStrategyOrConfirmOptions;
options = maybeConfirmOptions;
} else if (confirmationStrategyOrConfirmOptions && "nonceValue" in confirmationStrategyOrConfirmOptions) {
confirmationStrategy = confirmationStrategyOrConfirmOptions;
options = maybeConfirmOptions;
} else options = confirmationStrategyOrConfirmOptions;
const sendOptions = options && {
skipPreflight: options.skipPreflight,
preflightCommitment: options.preflightCommitment || options.commitment,
maxRetries: options.maxRetries,
minContextSlot: options.minContextSlot
};
const commitment = options?.commitment ?? connection.commitment ?? "finalized";
const signature = await connection.sendRawTransaction(rawTransaction, sendOptions);
const status = (await (confirmationStrategy ? connection.confirmTransaction(confirmationStrategy, commitment) : connection.confirmTransaction(signature, commitment))).value;
if (status.err) throw new SendTransactionError({
action: "send",
signature,
transactionMessage: `Status: (${stringifyJsonWithBigInts(status)})`
});
return signature;
}
// src/index.ts
/**
* There are 1-billion lamports in one SOL
*/
const LAMPORTS_PER_SOL = 1e9;
export { AddressLookupTableAccount, AddressLookupTableInstruction, AddressLookupTableProgram, Authorized, BLOCKHASH_CACHE_TIMEOUT_MS, BPF_LOADER_DEPRECATED_PROGRAM_ID, BPF_LOADER_PROGRAM_ID, BpfLoader, ComputeBudgetInstruction, ComputeBudgetProgram, Connection, Ed25519Program, EpochSchedule, Keypair, LAMPORTS_PER_SOL, Loader, LoaderV3Instruction, LoaderV3Program, Lockup, MAX_SEED_LENGTH, Message, MessageAccountKeys, MessageV0, MessageV1, NONCE_ACCOUNT_LENGTH, NonceAccount, PACKET_DATA_SIZE, PUBLIC_KEY_LENGTH, PublicKey, SIGNATURE_LENGTH_IN_BYTES, STAKE_CONFIG_ID, SYSVAR_CLOCK_PUBKEY, SYSVAR_EPOCH_SCHEDULE_PUBKEY, SYSVAR_INSTRUCTIONS_PUBKEY, SYSVAR_RECENT_BLOCKHASHES_PUBKEY, SYSVAR_RENT_PUBKEY, SYSVAR_REWARDS_PUBKEY, SYSVAR_SLOT_HASHES_PUBKEY, SYSVAR_SLOT_HISTORY_PUBKEY, SYSVAR_STAKE_HISTORY_PUBKEY, Secp256k1Program, SendTransactionError, SolanaJSONRPCError, SolanaJSONRPCErrorCode, StakeAccount, StakeAuthorizationLayout, StakeInstruction, StakeProgram, SystemInstruction, SystemProgram, Transaction, TransactionExpiredBlockheightExceededError, TransactionExpiredNonceInvalidError, TransactionExpiredTimeoutError, TransactionInstruction, TransactionMessage, TransactionStatus, V1_MAX_INSTRUCTIONS, V1_MESSAGE_PREFIX, VALIDATOR_INFO_KEY, VERSION_PREFIX_MASK, VOTE_PROGRAM_ID, ValidatorInfo, VersionedMessage, VersionedTransaction, VoteAccount, VoteAuthorizationLayout, VoteInit, VoteInstruction, VoteProgram, VoteStateVersion, __TEST_ONLY__VOTE_ACCOUNT_V1_14_11_CODEC, __TEST_ONLY__VOTE_ACCOUNT_V3_CODEC, __TEST_ONLY__VOTE_ACCOUNT_V4_CODEC, clusterApiUrl, sendAndConfirmRawTransaction, sendAndConfirmTransaction };
//# sourceMappingURL=index.browser.esm.js.map