@solana/web3.js
Version:
Solana Javascript API
20,935 lines • 789 kB
JavaScript
"use strict";
var solanaWeb3 = (function(exports) {
var SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;
var SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;
var SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;
var SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;
var SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND = -32020;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;
var SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;
var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;
var SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 28e5;
var SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;
var SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;
var SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;
var SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;
var SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;
var SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;
var SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;
var SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 361e4;
var SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;
var SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;
var SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;
var SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;
var SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;
var SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611e3;
var SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704e3;
var SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;
var SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;
var SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;
var SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;
var SOLANA_ERROR__KEYS__VERIFICATION_REQUIRES_EXTRACTABLE_PUBLIC_KEY = 3704007;
var SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128e3;
var SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;
var SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;
var SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;
var SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;
var SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;
var SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED = 5663021;
var SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE = 5663022;
var SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES = 5663023;
var SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES = 5663024;
var SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS = 5663028;
var SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX = 5663029;
var SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND = 5663030;
var SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078e3;
var SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;
var SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;
var SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;
var SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;
var SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;
var SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;
var SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;
var SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;
var SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;
var SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;
var SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;
var SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;
var SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;
var SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE = 8078024;
var SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES = 8078025;
var SOLANA_ERROR__CODECS__INVALID_UTF8_BYTES = 8078026;
var SOLANA_ERROR__CODECS__INVALID_UTF8_STRING = 8078027;
var SOLANA_ERROR__CODECS__SENTINEL_MISSING_AT_END_OF_BYTES = 8078028;
var SOLANA_ERROR__CODECS__SENTINEL_MUST_NOT_BE_EMPTY = 8078029;
var SOLANA_ERROR__CODECS__UNEXPECTED_ZERO_FIXED_SIZE_ITEM_FOR_ARRAY_LIKE_SIZE_STRATEGY = 8078030;
var SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 81e5;
var SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;
var SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;
var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 819e4;
var SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;
var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;
var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;
var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;
var SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS = 85e5;
var SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE = 8500001;
var SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION = 8500002;
var SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE = 8500003;
var SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL = 8500004;
var SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_SIGNER = 8500007;
var SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 99e5;
var SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;
var SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;
function encodeValue(value) {
if (Array.isArray(value)) return "%5B" + value.map(encodeValue).join("%2C%20") + "%5D";
else if (typeof value === "bigint") return `${value}n`;
else return encodeURIComponent(String(value != null && Object.getPrototypeOf(value) === null ? { ...value } : value));
}
function encodeObjectContextEntry([key, value]) {
return `${key}=${encodeValue(value)}`;
}
function encodeContextObject(context) {
const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join("&");
return btoa(searchParamsString);
}
function getErrorMessage(code, context = {}) {
{
let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`;
if (Object.keys(context).length) decodingAdviceMessage += ` '${encodeContextObject(context)}'`;
return `${decodingAdviceMessage}\``;
}
}
function isSolanaError(e, code) {
if (e instanceof Error && e.name === "SolanaError") {
if (code !== void 0) return e.context.__code === code;
return true;
}
return false;
}
var SolanaError = class extends Error {
/**
* Indicates the root cause of this {@link SolanaError}, if any.
*
* For example, a transaction error might have an instruction error as its root cause. In this
* case, you will be able to access the instruction error on the transaction error as `cause`.
*/
cause = this.cause;
/**
* Contains context that can assist in understanding or recovering from a {@link SolanaError}.
*/
context;
constructor(...[code, contextAndErrorOptions]) {
let context;
let errorOptions;
if (contextAndErrorOptions) Object.entries(Object.getOwnPropertyDescriptors(contextAndErrorOptions)).forEach(([name, descriptor]) => {
if (name === "cause") errorOptions = { cause: descriptor.value };
else {
if (context === void 0) context = { __code: code };
Object.defineProperty(context, name, descriptor);
}
});
const message = getErrorMessage(code, context);
super(message, errorOptions);
this.context = Object.freeze(context === void 0 ? { __code: code } : context);
this.name = "SolanaError";
}
};
function safeCaptureStackTrace(...args) {
if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") Error.captureStackTrace(...args);
}
function getSolanaErrorFromRpcError({ errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }, constructorOpt) {
let rpcErrorName;
let rpcErrorContext;
if (typeof rpcEnumError === "string") rpcErrorName = rpcEnumError;
else {
rpcErrorName = Object.keys(rpcEnumError)[0];
rpcErrorContext = rpcEnumError[rpcErrorName];
}
const errorCode = errorCodeBaseOffset + orderedErrorNames.indexOf(rpcErrorName);
const err = new SolanaError(errorCode, getErrorContext(errorCode, rpcErrorName, rpcErrorContext));
safeCaptureStackTrace(err, constructorOpt);
return err;
}
var ORDERED_ERROR_NAMES = [
"GenericError",
"InvalidArgument",
"InvalidInstructionData",
"InvalidAccountData",
"AccountDataTooSmall",
"InsufficientFunds",
"IncorrectProgramId",
"MissingRequiredSignature",
"AccountAlreadyInitialized",
"UninitializedAccount",
"UnbalancedInstruction",
"ModifiedProgramId",
"ExternalAccountLamportSpend",
"ExternalAccountDataModified",
"ReadonlyLamportChange",
"ReadonlyDataModified",
"DuplicateAccountIndex",
"ExecutableModified",
"RentEpochModified",
"NotEnoughAccountKeys",
"AccountDataSizeChanged",
"AccountNotExecutable",
"AccountBorrowFailed",
"AccountBorrowOutstanding",
"DuplicateAccountOutOfSync",
"Custom",
"InvalidError",
"ExecutableDataModified",
"ExecutableLamportChange",
"ExecutableAccountNotRentExempt",
"UnsupportedProgramId",
"CallDepth",
"MissingAccount",
"ReentrancyNotAllowed",
"MaxSeedLengthExceeded",
"InvalidSeeds",
"InvalidRealloc",
"ComputationalBudgetExceeded",
"PrivilegeEscalation",
"ProgramEnvironmentSetupFailure",
"ProgramFailedToComplete",
"ProgramFailedToCompile",
"Immutable",
"IncorrectAuthority",
"BorshIoError",
"AccountNotRentExempt",
"InvalidAccountOwner",
"ArithmeticOverflow",
"UnsupportedSysvar",
"IllegalOwner",
"MaxAccountsDataAllocationsExceeded",
"MaxAccountsExceeded",
"MaxInstructionTraceLengthExceeded",
"BuiltinProgramsMustConsumeComputeUnits"
];
function getSolanaErrorFromInstructionError(index, instructionError) {
const numberIndex = Number(index);
return getSolanaErrorFromRpcError({
errorCodeBaseOffset: 4615001,
getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {
if (errorCode === 4615e3) return {
errorName: rpcErrorName,
index: numberIndex,
...rpcErrorContext !== void 0 ? { instructionErrorContext: rpcErrorContext } : null
};
else if (errorCode === 4615026) return {
code: Number(rpcErrorContext),
index: numberIndex
};
return { index: numberIndex };
},
orderedErrorNames: ORDERED_ERROR_NAMES,
rpcEnumError: instructionError
}, getSolanaErrorFromInstructionError);
}
var ORDERED_ERROR_NAMES2 = [
"AccountInUse",
"AccountLoadedTwice",
"AccountNotFound",
"ProgramAccountNotFound",
"InsufficientFundsForFee",
"InvalidAccountForFee",
"AlreadyProcessed",
"BlockhashNotFound",
"CallChainTooDeep",
"MissingSignatureForFee",
"InvalidAccountIndex",
"SignatureFailure",
"InvalidProgramForExecution",
"SanitizeFailure",
"ClusterMaintenance",
"AccountBorrowOutstanding",
"WouldExceedMaxBlockCostLimit",
"UnsupportedVersion",
"InvalidWritableAccount",
"WouldExceedMaxAccountCostLimit",
"WouldExceedAccountDataBlockLimit",
"TooManyAccountLocks",
"AddressLookupTableNotFound",
"InvalidAddressLookupTableOwner",
"InvalidAddressLookupTableData",
"InvalidAddressLookupTableIndex",
"InvalidRentPayingAccount",
"WouldExceedMaxVoteCostLimit",
"WouldExceedAccountDataTotalLimit",
"DuplicateInstruction",
"InsufficientFundsForRent",
"MaxLoadedAccountsDataSizeExceeded",
"InvalidLoadedAccountsDataSizeLimit",
"ResanitizationNeeded",
"ProgramExecutionTemporarilyRestricted",
"UnbalancedTransaction"
];
function getSolanaErrorFromTransactionError(transactionError) {
if (typeof transactionError === "object" && "InstructionError" in transactionError) return getSolanaErrorFromInstructionError(...transactionError.InstructionError);
return getSolanaErrorFromRpcError({
errorCodeBaseOffset: 7050001,
getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {
if (errorCode === 705e4) return {
errorName: rpcErrorName,
...rpcErrorContext !== void 0 ? { transactionErrorContext: rpcErrorContext } : null
};
else if (errorCode === 7050030) return { index: Number(rpcErrorContext) };
else if (errorCode === 7050031 || errorCode === 7050035) return { accountIndex: Number(rpcErrorContext.account_index) };
},
orderedErrorNames: ORDERED_ERROR_NAMES2,
rpcEnumError: transactionError
}, getSolanaErrorFromTransactionError);
}
function getSolanaErrorFromJsonRpcError(putativeErrorResponse) {
let out;
if (isRpcErrorResponse(putativeErrorResponse)) {
const { code: rawCode, data, message } = putativeErrorResponse;
const code = Number(rawCode);
if (code === -32002) {
const { err, ...preflightErrorContext } = data;
const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null;
out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, {
...preflightErrorContext,
...causeObject
});
} else {
let errorContext;
switch (code) {
case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:
case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:
case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:
case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:
case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:
case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:
case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:
case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:
case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:
case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND:
case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:
case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:
case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:
case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:
case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:
errorContext = { __serverMessage: message };
break;
default: if (typeof data === "object" && !Array.isArray(data)) errorContext = data;
}
out = new SolanaError(code, errorContext);
}
} else out = new SolanaError(10, {
error: putativeErrorResponse,
message: typeof putativeErrorResponse === "object" && putativeErrorResponse !== null && "message" in putativeErrorResponse && typeof putativeErrorResponse.message === "string" ? putativeErrorResponse.message : "Malformed JSON-RPC error with no message attribute"
});
safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError);
return out;
}
function isRpcErrorResponse(value) {
return typeof value === "object" && value !== null && "code" in value && "message" in value && (typeof value.code === "number" || typeof value.code === "bigint") && typeof value.message === "string";
}
// ../../node_modules/.pnpm/@solana+assertions@8.6.0_typescript@5.9.3/node_modules/@solana/assertions/dist/index.browser.mjs
function assertPRNGIsAvailable() {
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.getRandomValues !== "function") throw new SolanaError(SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED);
}
function assertIsSecureContext() {
if (!globalThis.isSecureContext) throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT);
}
function assertDigestCapabilityIsAvailable() {
assertIsSecureContext();
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.digest !== "function") throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED);
}
function assertKeyExporterIsAvailable() {
assertIsSecureContext();
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED);
}
function assertSigningCapabilityIsAvailable() {
assertIsSecureContext();
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED);
}
function assertVerificationCapabilityIsAvailable() {
assertIsSecureContext();
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED);
}
// ../../node_modules/.pnpm/@solana+codecs-core@8.6.0_typescript@5.9.3/node_modules/@solana/codecs-core/dist/index.browser.mjs
function padBytes(bytes, length) {
if (bytes.length >= length) return bytes;
const paddedBytes = new Uint8Array(length).fill(0);
paddedBytes.set(bytes);
return paddedBytes;
}
var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);
function containsBytes(data, bytes, offset) {
return bytesEqual((offset === 0 || offset <= -data.byteLength) && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length), bytes);
}
function bytesEqual(bytes1, bytes2) {
return bytes1.length === bytes2.length && bytes1.every((value, index) => value === bytes2[index]);
}
function getEncodedSize(value, encoder) {
return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
}
function createEncoder(encoder) {
return Object.freeze({
...encoder,
encode: (value) => {
const bytes = new Uint8Array(getEncodedSize(value, encoder));
encoder.write(value, bytes, 0);
return bytes;
}
});
}
function createDecoder(decoder) {
return Object.freeze({
...decoder,
decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
});
}
function createCodec(codec) {
return Object.freeze({
...codec,
decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],
encode: (value) => {
const bytes = new Uint8Array(getEncodedSize(value, codec));
codec.write(value, bytes, 0);
return bytes;
}
});
}
function isFixedSize(codec) {
return "fixedSize" in codec && typeof codec.fixedSize === "number";
}
function assertIsFixedSize(codec) {
if (!isFixedSize(codec)) throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);
}
function isVariableSize(codec) {
return !isFixedSize(codec);
}
function combineCodec(encoder, decoder) {
if (isFixedSize(encoder) !== isFixedSize(decoder)) throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH);
if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, {
decoderFixedSize: decoder.fixedSize,
encoderFixedSize: encoder.fixedSize
});
if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, {
decoderMaxSize: decoder.maxSize,
encoderMaxSize: encoder.maxSize
});
return {
...decoder,
...encoder,
decode: decoder.decode,
encode: encoder.encode,
read: decoder.read,
write: encoder.write
};
}
function assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {
if (bytes.length - offset <= 0) throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, { codecDescription });
}
function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {
const bytesLength = bytes.length - offset;
if (bytesLength < expected) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {
bytesLength,
codecDescription,
expected
});
}
function addEncoderSizePrefix(encoder, prefix) {
const write = ((value, bytes, offset) => {
const encoderBytes = encoder.encode(value);
offset = prefix.write(encoderBytes.length, bytes, offset);
bytes.set(encoderBytes, offset);
return offset + encoderBytes.length;
});
if (isFixedSize(prefix) && isFixedSize(encoder)) return createEncoder({
...encoder,
fixedSize: prefix.fixedSize + encoder.fixedSize,
write
});
const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : encoder.maxSize ?? null;
const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;
return createEncoder({
...encoder,
...maxSize !== null ? { maxSize } : {},
getSizeFromValue: (value) => {
const encoderSize = getEncodedSize(value, encoder);
return getEncodedSize(encoderSize, prefix) + encoderSize;
},
write
});
}
function addDecoderSizePrefix(decoder, prefix) {
const read = ((bytes, offset) => {
const [bigintSize, decoderOffset] = prefix.read(bytes, offset);
const size = Number(bigintSize);
offset = decoderOffset;
if (offset > 0 || bytes.length > size) bytes = bytes.slice(offset, offset + size);
assertByteArrayHasEnoughBytesForCodec("addDecoderSizePrefix", size, bytes);
return [decoder.decode(bytes), offset + size];
});
if (isFixedSize(prefix) && isFixedSize(decoder)) return createDecoder({
...decoder,
fixedSize: prefix.fixedSize + decoder.fixedSize,
read
});
const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : decoder.maxSize ?? null;
const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;
return createDecoder({
...decoder,
...maxSize !== null ? { maxSize } : {},
read
});
}
function addCodecSizePrefix(codec, prefix) {
return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));
}
function toArrayBuffer(bytes, offset, length) {
let bytesOffset = bytes.byteOffset + (offset ?? 0);
const bytesLength = length ?? bytes.byteLength;
let buffer;
if (typeof SharedArrayBuffer === "undefined") buffer = bytes.buffer;
else if (bytes.buffer instanceof SharedArrayBuffer) {
buffer = new ArrayBuffer(bytes.length);
new Uint8Array(buffer).set(new Uint8Array(bytes));
bytesOffset = offset ?? 0;
} else buffer = bytes.buffer;
return (bytesOffset === 0 || bytesOffset === -buffer.byteLength) && bytesLength === buffer.byteLength ? buffer : buffer.slice(bytesOffset, bytesOffset + bytesLength);
}
function fixEncoderSize(encoder, fixedBytes) {
return createEncoder({
fixedSize: fixedBytes,
write: (value, bytes, offset) => {
const variableByteArray = encoder.encode(value);
const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;
bytes.set(fixedByteArray, offset);
return offset + fixedBytes;
}
});
}
function fixDecoderSize(decoder, fixedBytes) {
return createDecoder({
fixedSize: fixedBytes,
read: (bytes, offset) => {
assertByteArrayHasEnoughBytesForCodec("fixCodecSize", fixedBytes, bytes, offset);
if (offset > 0 || bytes.length > fixedBytes) bytes = bytes.slice(offset, offset + fixedBytes);
if (isFixedSize(decoder)) bytes = fixBytes(bytes, decoder.fixedSize);
const [value] = decoder.read(bytes, 0);
return [value, offset + fixedBytes];
}
});
}
function fixCodecSize(codec, fixedBytes) {
return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(codec, fixedBytes));
}
function transformEncoder(encoder, unmap) {
return createEncoder({
...isVariableSize(encoder) ? {
...encoder,
getSizeFromValue: (value) => encoder.getSizeFromValue(unmap(value))
} : encoder,
write: (value, bytes, offset) => encoder.write(unmap(value), bytes, offset)
});
}
function transformDecoder(decoder, map) {
return createDecoder({
...decoder,
read: (bytes, offset) => {
const [value, newOffset] = decoder.read(bytes, offset);
return [map(value, bytes, offset), newOffset];
}
});
}
function transformCodec(codec, unmap, map) {
return createCodec({
...transformEncoder(codec, unmap),
read: map ? transformDecoder(codec, map).read : codec.read
});
}
// ../../node_modules/.pnpm/@solana+codecs-strings@8.6.0_typescript@5.9.3/node_modules/@solana/codecs-strings/dist/index.browser.mjs
function assertValidBaseString$1(alphabet4, testValue, givenValue = testValue) {
if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
alphabet: alphabet4,
base: alphabet4.length,
value: givenValue
});
}
function assertIsWellFormedUtf8String(value) {
const isWellFormed = value.isWellFormed;
if (typeof isWellFormed === "function" && isWellFormed.call(value)) return;
for (let index = 0; index < value.length; index++) {
const unit = value.charCodeAt(index);
if (unit < 55296 || unit > 57343) continue;
const next = value.charCodeAt(index + 1);
if (unit <= 56319 && next >= 56320 && next <= 57343) {
index++;
continue;
}
throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_UTF8_STRING, {
index,
value
});
}
}
function findMalformedUtf8SequenceOffset(bytes, offset = 0) {
const length = bytes.length;
let index = offset;
while (index < length) {
const lead = bytes[index];
let count;
let min = 128;
let max = 191;
if (lead < 128) {
index++;
continue;
} else if (lead >= 194 && lead <= 223) count = 1;
else if (lead >= 224 && lead <= 239) {
count = 2;
if (lead === 224) min = 160;
if (lead === 237) max = 159;
} else if (lead >= 240 && lead <= 244) {
count = 3;
if (lead === 240) min = 144;
if (lead === 244) max = 143;
} else return index;
const start = index;
index++;
for (let i = 0; i < count; i++, index++) {
if (index >= length) return start;
const byte = bytes[index];
if (!(i === 0 ? byte >= min && byte <= max : byte >= 128 && byte <= 191)) return start;
}
}
return -1;
}
function assertIsWellFormedUtf8Bytes(bytes, offset = 0) {
const malformedOffset = findMalformedUtf8SequenceOffset(bytes, offset);
if (malformedOffset !== -1) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_UTF8_BYTES, {
bytes,
offset: malformedOffset
});
}
var getBaseXEncoder$1 = (alphabet4) => {
return createEncoder({
getSizeFromValue: (value) => {
const [leadingZeroes, tailChars] = partitionLeadingZeroes$1(value, alphabet4[0]);
if (!tailChars) return value.length;
const base10Number = getBigIntFromBaseX$1(tailChars, alphabet4);
return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
},
write(value, bytes, offset) {
assertValidBaseString$1(alphabet4, value);
if (value === "") return offset;
const [leadingZeroes, tailChars] = partitionLeadingZeroes$1(value, alphabet4[0]);
if (!tailChars) {
bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
return offset + leadingZeroes.length;
}
let base10Number = getBigIntFromBaseX$1(tailChars, alphabet4);
const tailBytes = [];
while (base10Number > 0n) {
tailBytes.unshift(Number(base10Number % 256n));
base10Number /= 256n;
}
const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
bytes.set(bytesToAdd, offset);
return offset + bytesToAdd.length;
}
});
};
var getBaseXDecoder$1 = (alphabet4) => {
return createDecoder({ read(rawBytes, offset) {
const bytes = offset === 0 || offset <= -rawBytes.byteLength ? rawBytes : rawBytes.slice(offset);
if (bytes.length === 0) return ["", rawBytes.length];
let trailIndex = bytes.findIndex((n) => n !== 0);
trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
const leadingZeroes = alphabet4[0].repeat(trailIndex);
if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];
return [leadingZeroes + getBaseXFromBigInt$1(bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n), alphabet4), rawBytes.length];
} });
};
var getBaseXCodec = (alphabet4) => combineCodec(getBaseXEncoder$1(alphabet4), getBaseXDecoder$1(alphabet4));
function partitionLeadingZeroes$1(value, zeroCharacter) {
const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));
return [leadingZeros, tailChars];
}
function getBigIntFromBaseX$1(value, alphabet4) {
const base = BigInt(alphabet4.length);
let sum = 0n;
for (const char of value) {
sum *= base;
sum += BigInt(alphabet4.indexOf(char));
}
return sum;
}
function getBaseXFromBigInt$1(value, alphabet4) {
const base = BigInt(alphabet4.length);
const tailChars = [];
while (value > 0n) {
tailChars.unshift(alphabet4[Number(value % base)]);
value /= base;
}
return tailChars.join("");
}
var INVALID_STRING_ERROR_BASE_CONFIG = {
alphabet: "0123456789abcdef",
base: 16
};
function charCodeToBase16(char) {
if (char >= 48 && char <= 57) return char - 48;
if (char >= 65 && char <= 70) return char - 55;
if (char >= 97 && char <= 102) return char - 87;
}
var getBase16Encoder = () => createEncoder({
getSizeFromValue: (value) => Math.ceil(value.length / 2),
write(value, bytes, offset) {
const len = value.length;
const al = Math.ceil(len / 2);
if (len === 1) {
const n = charCodeToBase16(value.charCodeAt(0));
if (n === void 0) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
...INVALID_STRING_ERROR_BASE_CONFIG,
value
});
bytes.set([n], offset);
return 1 + offset;
}
const hexBytes = new Uint8Array(al);
for (let i = 0, j = 0; i < al; i++) {
const c1 = value.charCodeAt(j++);
const c2 = value.charCodeAt(j++);
const n1 = charCodeToBase16(c1);
const n2 = charCodeToBase16(c2);
if (n1 === void 0 || n2 === void 0 && !Number.isNaN(c2)) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
...INVALID_STRING_ERROR_BASE_CONFIG,
value
});
hexBytes[i] = !Number.isNaN(c2) ? n1 << 4 | (n2 ?? 0) : n1;
}
bytes.set(hexBytes, offset);
return hexBytes.length + offset;
}
});
var alphabet2$1 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
var getBase58Encoder$1 = () => getBaseXEncoder$1(alphabet2$1);
var getBase58Decoder$1 = () => getBaseXDecoder$1(alphabet2$1);
var getBase58Codec = () => getBaseXCodec(alphabet2$1);
var alphabet3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var MAX_BYTES_PER_CHAR_CODE_CALL = 32768;
function getBinaryString(bytes) {
let binaryString = "";
for (let offset = 0; offset < bytes.length; offset += MAX_BYTES_PER_CHAR_CODE_CALL) binaryString += String.fromCharCode(...bytes.subarray(offset, offset + MAX_BYTES_PER_CHAR_CODE_CALL));
return binaryString;
}
var getBase64Encoder = () => {
return createEncoder({
getSizeFromValue: (value) => {
try {
return atob(value).length;
} catch {
throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
alphabet: alphabet3,
base: 64,
value
});
}
},
write(value, bytes, offset) {
try {
const bytesToAdd = atob(value).split("").map((c) => c.charCodeAt(0));
bytes.set(bytesToAdd, offset);
return bytesToAdd.length + offset;
} catch {
throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
alphabet: alphabet3,
base: 64,
value
});
}
}
});
};
var getBase64Decoder = () => {
return createDecoder({ read(bytes, offset = 0) {
return [btoa(getBinaryString(bytes.subarray(offset))), bytes.length];
} });
};
var getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());
var removeNullCharacters = (value) => value.replace(/\u0000/g, "");
var e$1 = globalThis.TextDecoder;
var o$5 = globalThis.TextEncoder;
var getUtf8Encoder = (config = {}) => {
let textEncoder;
return createEncoder({
getSizeFromValue: (value) => (textEncoder ||= new o$5()).encode(value).length,
write: (value, bytes, offset) => {
if (config.fatal) assertIsWellFormedUtf8String(value);
const bytesToAdd = (textEncoder ||= new o$5()).encode(value);
bytes.set(bytesToAdd, offset);
return offset + bytesToAdd.length;
}
});
};
var getUtf8Decoder = (config = {}) => {
let textDecoder;
return createDecoder({ read(bytes, offset) {
textDecoder ||= new e$1("utf-8", {
fatal: config.fatal ?? false,
ignoreBOM: config.ignoreBOM ?? false
});
let value = config.fatal ? decodeFatal(textDecoder, bytes, offset) : textDecoder.decode(bytes.slice(offset));
if (!config.ignoreBOM && textDecoder.ignoreBOM === void 0 && value.charCodeAt(0) === 65279) value = value.slice(1);
if (config.removeNullCharacters !== false) value = removeNullCharacters(value);
return [value, bytes.length];
} });
};
function decodeFatal(textDecoder, bytes, offset) {
const slice = bytes.slice(offset);
if (!textDecoder.fatal) {
assertIsWellFormedUtf8Bytes(bytes, offset);
return textDecoder.decode(slice);
}
try {
return textDecoder.decode(slice);
} catch {
throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_UTF8_BYTES, {
bytes,
offset: findMalformedUtf8SequenceOffset(bytes, offset)
});
}
}
var getUtf8Codec = (config = {}) => combineCodec(getUtf8Encoder(config), getUtf8Decoder(config));
// ../../node_modules/.pnpm/@solana+addresses@8.6.0_typescript@5.9.3/node_modules/@solana/addresses/dist/index.browser.mjs
var memoizedBase58Encoder;
var memoizedBase58Decoder;
function getMemoizedBase58Encoder() {
if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder$1();
return memoizedBase58Encoder;
}
function getMemoizedBase58Decoder() {
if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder$1();
return memoizedBase58Decoder;
}
function isAddress(putativeAddress) {
if (putativeAddress.length < 32 || putativeAddress.length > 44) return false;
const base58Encoder = getMemoizedBase58Encoder();
try {
return base58Encoder.encode(putativeAddress).byteLength === 32;
} catch {
return false;
}
}
function assertIsAddress(putativeAddress) {
if (putativeAddress.length < 32 || putativeAddress.length > 44) throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, { actualLength: putativeAddress.length });
const numBytes = getMemoizedBase58Encoder().encode(putativeAddress).byteLength;
if (numBytes !== 32) throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, { actualLength: numBytes });
}
function address(putativeAddress) {
assertIsAddress(putativeAddress);
return putativeAddress;
}
function getAddressEncoder() {
return transformEncoder(fixEncoderSize(getMemoizedBase58Encoder(), 32), (value) => address(typeof value === "string" ? value : value.address));
}
function getAddressDecoder() {
return fixDecoderSize(getMemoizedBase58Decoder(), 32);
}
function getAddressCodec() {
return combineCodec(getAddressEncoder(), getAddressDecoder());
}
var D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;
var P$1 = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;
var RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
function mod$1(a) {
const r = a % P$1;
return r >= 0n ? r : P$1 + r;
}
function pow2$1(x, power) {
let r = x;
while (power-- > 0n) {
r *= r;
r %= P$1;
}
return r;
}
function pow_2_252_3(x) {
const b2 = x * x % P$1 * x % P$1;
const b5 = pow2$1(pow2$1(b2, 2n) * b2 % P$1, 1n) * x % P$1;
const b10 = pow2$1(b5, 5n) * b5 % P$1;
const b20 = pow2$1(b10, 10n) * b10 % P$1;
const b40 = pow2$1(b20, 20n) * b20 % P$1;
const b80 = pow2$1(b40, 40n) * b40 % P$1;
return pow2$1(pow2$1(pow2$1(pow2$1(b80, 80n) * b80 % P$1, 80n) * b80 % P$1, 10n) * b10 % P$1, 2n) * x % P$1;
}
function uvRatio$1(u, v) {
const v3 = mod$1(v * v * v);
const pow = pow_2_252_3(u * mod$1(v3 * v3 * v));
let x = mod$1(u * v3 * pow);
const vx2 = mod$1(v * x * x);
const root1 = x;
const root2 = mod$1(x * RM1);
const useRoot1 = vx2 === u;
const useRoot2 = vx2 === mod$1(-u);
const noRoot = vx2 === mod$1(-u * RM1);
if (useRoot1) x = root1;
if (useRoot2 || noRoot) x = root2;
if ((mod$1(x) & 1n) === 1n) x = mod$1(-x);
if (!useRoot1 && !useRoot2) return null;
return x;
}
function pointIsOnCurve(y, lastByte) {
const y2 = mod$1(y * y);
const x = uvRatio$1(mod$1(y2 - 1n), mod$1(D * y2 + 1n));
if (x === null) return false;
const isLastByteOdd = (lastByte & 128) !== 0;
if (x === 0n && isLastByteOdd) return false;
return true;
}
function byteToHex(byte) {
const hexString = byte.toString(16);
if (hexString.length === 1) return `0${hexString}`;
else return hexString;
}
function decompressPointBytes(bytes) {
const integerLiteralString = `0x${bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & -129 : byte)}${acc}`, "")}`;
return BigInt(integerLiteralString);
}
function compressedPointBytesAreOnCurve(bytes) {
if (bytes.byteLength !== 32) return false;
return pointIsOnCurve(decompressPointBytes(bytes), bytes[31]);
}
function isProgramDerivedAddress(value) {
return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);
}
var MAX_SEED_LENGTH$1 = 32;
var MAX_SEEDS$1 = 16;
var PDA_MARKER_BYTES$1 = [
80,
114,
111,
103,
114,
97,
109,
68,
101,
114,
105,
118,
101,
100,
65,
100,
100,
114,
101,
115,
115
];
async function createProgramDerivedAddress({ programAddress, seeds }) {
assertDigestCapabilityIsAvailable();
if (seeds.length > MAX_SEEDS$1) throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {
actual: seeds.length,
maxSeeds: MAX_SEEDS$1
});
let textEncoder;
const seedBytes = seeds.reduce((acc, seed, ii) => {
const bytes = typeof seed === "string" ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;
if (bytes.byteLength > MAX_SEED_LENGTH$1) throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {
actual: bytes.byteLength,
index: ii,
maxSeedLength: MAX_SEED_LENGTH$1
});
acc.push(...bytes);
return acc;
}, []);
const base58EncodedAddressCodec = getAddressCodec();
const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);
const addressBytesBuffer = await crypto.subtle.digest("SHA-256", new Uint8Array([
...seedBytes,
...programAddressBytes,
...PDA_MARKER_BYTES$1
]));
const addressBytes = new Uint8Array(addressBytesBuffer);
if (compressedPointBytesAreOnCurve(addressBytes)) throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);
return base58EncodedAddressCodec.decode(addressBytes);
}
async function getProgramDerivedAddress({ programAddress, seeds }) {
let bumpSeed = 255;
while (bumpSeed > 0) try {
return [await createProgramDerivedAddress({
programAddress,
seeds: [...seeds, new Uint8Array([bumpSeed])]
}), bumpSeed];
} catch (e) {
if (isSolanaError(e, 2800008)) bumpSeed--;
else throw e;
}
throw new SolanaError(SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED);
}
async function createAddressWithSeed({ baseAddress, programAddress, seed }) {
const { encode, decode } = getAddressCodec();
const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
if (seedBytes.byteLength > MAX_SEED_LENGTH$1) throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {
actual: seedBytes.byteLength,
index: 0,
maxSeedLength: MAX_SEED_LENGTH$1
});
const programAddressBytes = encode(programAddress);
if (programAddressBytes.length >= PDA_MARKER_BYTES$1.length && bytesEqual(programAddressBytes.slice(-PDA_MARKER_BYTES$1.length), new Uint8Array(PDA_MARKER_BYTES$1))) throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER);
const addressBytesBuffer = await crypto.subtle.digest("SHA-256", new Uint8Array([
...encode(baseAddress),
...seedBytes,
...programAddressBytes
]));
return decode(new Uint8Array(addressBytesBuffer));
}
async function getAddressFromPublicKey(publicKey) {
assertKeyExporterIsAvailable();
if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);
const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));
}
// ../../node_modules/.pnpm/@solana+codecs-numbers@8.6.0_typescript@5.9.3/node_modules/@solana/codecs-numbers/dist/index.browser.mjs
function assertNumberIsBetweenForCodec(codecDescription, min, max, value) {
if (value < min || value > max) throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {
codecDescription,
max,
min,
value
});
}
function isLittleEndian(config) {
return config?.endian === 1 ? false : true;
}
function numberEncoderFactory(input) {
return createEncoder({
fixedSize: input.size,
write(value, bytes, offset) {
if (input.range) assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);
const arrayBuffer = new ArrayBuffer(input.size);
input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));
bytes.set(new Uint8Array(arrayBuffer), offset);
return offset + input.size;
}
});
}
function numberDecoderFactory(input) {
return createDecoder({
fixedSize: input.size,
read(bytes, offset = 0) {
assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);
assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);
const view = new DataView(toArrayBuffer(bytes, offset, input.size));
return [input.get(view, isLittleEndian(input.config)), offset + input.size];
}
});
}
var getI64Encoder = (config = {}) => numberEncoderFactory({
config,
name: "i64",
range: [-BigInt("0x7fffffffffffffff") - 1n, BigInt("0x7fffffffffffffff")],
set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),
size: 8
});
var getI64Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getBigInt64(0, le),
name: "i64",
size: 8
});
var getI64Codec = (config = {}) => combineCodec(getI64Encoder(config), getI64Decoder(config));
var MAX_SHORT_U16_VALUE = 65535;
var getShortU16Encoder = () => createEncoder({
getSizeFromValue: (value) => {
if (value <= 127) return 1;
if (value <= 16383) return 2;
return 3;
},
maxSize: 3,
write: (value, bytes, offset) => {
assertNumberIsBetweenForCodec("shortU16", 0, 65535, value);
const shortU16Bytes = [0];
for (let ii = 0;; ii += 1) {
const alignedValue = Number(value) >> ii * 7;
if (alignedValue === 0) break;
const nextSevenBits = 127 & alignedValue;
shortU16Bytes[ii] = nextSevenBits;
if (ii > 0) shortU16Bytes[ii - 1] |= 128;
}
bytes.set(shortU16Bytes, offset);
return offset + shortU16Bytes.length;
}
});
var getShortU16Decoder = () => createDecoder({
maxSize: 3,
read: (bytes, offset) => {
let value = 0;
let byteCount = 0;
while (++byteCount <= 3) {
assertByteArrayHasEnoughBytesForCodec("shortU16", byteCount, bytes, offset);
const byteIndex = byteCount - 1;
const currentByte = bytes[offset + byteIndex];
const nextSevenBits = 127 & currentByte;
value |= nextSevenBits << byteIndex * 7;
if ((currentByte & 128) === 0) {
assertNumberIsBetweenForCodec("shortU16", 0, MAX_SHORT_U16_VALUE, value);
return [value, offset + byteCount];
}
}
throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {
bytesLength: 4,
codecDescription: "shortU16",
expected: 3
});
}
});
var getU16Encoder = (config = {}) => numberEncoderFactory({
config,
name: "u16",
range: [0, 65535],
set: (view, value, le) => view.setUint16(0, Number(value), le),
size: 2
});
var getU16Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getUint16(0, le),
name: "u16",
size: 2
});
var getU16Codec = (config = {}) => combineCodec(getU16Encoder(config), getU16Decoder(config));
var getU32Encoder = (config = {}) => numberEncoderFactory({
config,
name: "u32",
range: [0, 4294967295],
set: (view, value, le) => view.setUint32(0, Number(value), le),
size: 4
});
var getU32Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getUint32(0, le),
name: "u32",
size: 4
});
var getU32Codec = (config = {}) => combineCodec(getU32Encoder(config), getU32Decoder(config));
var getU64Encoder = (config = {}) => numberEncoderFactory({
config,
name: "u64",
range: [0n, BigInt("0xffffffffffffffff")],
set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),
size: 8
});
var getU64Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getBigUint64(0, le),
name: "u64",
size: 8
});
var getU64Codec = (config = {}) => combineCodec(getU64Encoder(config), getU64Decoder(config));
var getU8Encoder = () => numberEncoderFactory({
name: "u8",
range: [0, 255],
set: (view, value) => view.setUint8(0, Number(value)),
size: 1
});
var getU8Decoder = () => numberDecoderFactory({
get: (view) => view.getUint8(0),
name: "u8",
size: 1
});
var getU8Codec = () => combineCodec(getU8Encoder(), getU8Decoder());
// ../../node_modules/.pnpm/@solana+codecs-data-structures@8.6.0_typescript@5.9.3/node_modules/@solana/codecs-data-structures/dist/index.browser.mjs
function assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {
if (expected !== actual) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, {
actual,
codecDescription,
expected
});
}
function maxCodecSizes(sizes) {
return sizes.reduce((all, size) => all === null || size === null ? null : Math.max(all, size), 0);
}
function sumCodecSizes(sizes) {
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
}
function getFixedSize(codec) {
return isFixedSize(codec) ? codec.fixedSize : null;
}
function getMaxSize(codec) {
return isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;
}
function getArrayEncoder(item, config = {}) {
const size = config.size ?? getU32Encoder();
assertValidSize(size);
const itemSize = getFixedSize(item);
assertItemCodecSupportsSizeStrategy(config.description ?? "array", size, itemSize);
const fixedSize = computeArrayLikeCodecSize(size, itemSize);
const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? void 0;
return createEncoder({
...fixedSize !== null ? { fixedSize } : {
getSizeFromValue: (array) => {
return (isPrefixSize(size) ? getEncodedSize(array.length, size) : 0) + (isSentinelSize(size) && size.strategy !== "omitted" ? size.sentinel.length : 0) + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);
},
maxSize
},
write: (array, bytes, offset) => {
if (typeof size === "number") assertValidNumberOfItemsForCodec(config.description ?? "array", size, array.length);
if (isPrefixSize(size)) offset = size.write(array.length, bytes, offset);
array.forEach((value) => {
offset = item.write(value, bytes, offset);
});
if (isSentinelSize(size) && size.strategy !== "omitted") {
bytes.set(size.sentinel, offset);
offset += size.sentinel.length;
}
return offset;
}
});
}
function getArrayDecoder(item, config = {}) {
const size = config.size ?? getU32Decoder();
assertValidSize(size);
const itemSize = getFixedSize(item);
assertItemCodecSupportsSizeStrategy(config.description ?? "array", size, itemSize);
const fixedSize = computeArrayLikeCodecSize(size, itemSize);
const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? void 0;
return createDecoder({
...fixedSize !== null ? { fixedSize } : { maxSize },
read: (bytes, offset) => {
const array = [];
if (isPrefixSize(size) && !config.requireSizePrefix && offset >= bytes.length) return [array, offset];
if (size === "remainder") {
while (offset < bytes.length) {
const [value, newOffset2] = item.read(bytes, offset);
offset = newOffset2;
array.push(value);
}
return [array, offset];
}
if (isSentinelSize(size)) {
const { sentinel, strategy = "required" } = size;
while (true) {
if (offset + sentinel.length > bytes.length) {
if (strategy === "required") throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MISSING_AT_END_OF_BYTES, {
codecDescription: config.description ?? "array",
hexSentinel: hexBytes(sentinel),
sentinel
});
break;
}
if (containsBytes(bytes, sentinel, offset)) {
offset += sentinel.length;
break;
}
const [value, newOffset2] = item.read(bytes, offset);
offset = newOffset2;
array.push(value);
}
return [array, offset];
}
const [resolvedSize, newOffset] = typeof size === "number" ? [size, offset] : size.read(bytes, offset);
offset = newOffset;
for (let i = 0; i < resolvedSize; i += 1) {
const [value, newOffset2] = item.read(bytes, offset);
offset = newOffset2;
array.push(value);
}
return [array, offset];
}
});
}
function getArrayCodec(item, config = {}) {
return combineCodec(getArrayEncoder(item, config), getArrayDecoder(item, config));
}
function computeArrayLikeCodecSize(size, itemSize) {
if (typeof size !== "number") return null;
if (size === 0) return 0;
return itemSize === null ? null : itemSize * size;
}
function isPrefixSize(size) {
return typeof size === "object" && size !== null && !isSentinelSize(size);
}
function isSentinelSize(size) {
return typeof size === "object" && size !== null && "__kind" in size && size.__kind === "sentinel";
}
function assertValidSize(size) {
if (isSentinelSize(size) && size.sentinel.length === 0) throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MUST_NOT_BE_EMPTY);
}
function assertItemCodecSupportsSizeStrategy(codecDescription, size, itemFixedSize) {
if (itemFixedSize !== 0) return;
if (size === "remainder" || isSentinelSize(size)) throw new SolanaError(SOLANA_ERROR__CODECS__UNEXPECTED_ZERO_FIXED_SIZE_ITEM_FOR_ARRAY_LIKE_SIZE_STRATEGY, {
codecDescription,
sizeStrategy: size === "remainder" ? "remainder" : "sentinel"
});
}
function hexBytes(bytes) {
return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
}
function getBooleanEncoder(config = {}) {
return transformEncoder(config.size ?? getU8Encoder(), (value) => value ? 1 : 0);
}
function getBooleanDecoder(config = {}) {
return transformDecoder(config.size ?? getU8Decoder(), (value) => Number(value) === 1);
}
function getBytesEncoder() {
return createEncoder({
getSizeFromValue: (value) => value.length,
write: (value, bytes, offset) => {
bytes.set(value, offset);
return offset + value.length;
}
});
}
function getBytesDecoder() {
return createDecoder({ read: (bytes, offset) => {
const slice = bytes.slice(offset);
return [slice, offset + slice.length];
} });
}
function getBytesCodec() {
return combineCodec(getBytesEncoder(), getBytesDecoder());
}
var getBase16Decoder = () => createDecoder({ read(bytes, offset) {
return [bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), ""), bytes.length];
} });
function getConstantEncoder(constant) {
return createEncoder({
fixedSize: constant.length,
write: (_, bytes, offset) => {
bytes.set(constant, offset);
return offset + constant.length;
}
});
}
function getConstantDecoder(constant) {
return createDecoder({
fixedSize: constant.length,
read: (bytes, offset) => {
const base16 = getBase16Decoder();
if (!containsBytes(bytes, constant, offset)) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_CONSTANT, {
constant,
data: bytes,
hexConstant: base16.decode(constant),
hexData: base16.decode(bytes),
offset
});
return [void 0, offset + constant.length];
}
});
}
function getTupleEncoder(items, config) {
const fixedSize = sumCodecSizes(items.map(getFixedSize));
const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? void 0;
return createEncoder({
...fixedSize === null ? {
getSizeFromValue: (value) => items.map((item, index) => getEncodedSize(value[index], item)).reduce((all, one) => all + one, 0),
maxSize
} : { fixedSize },
write: (value, bytes, offset) => {
assertValidNumberOfItemsForCodec(config?.description ?? "tuple", items.length, value.length);
items.forEach((item, index) => {
offset = item.write(value[index], bytes, offset);
});
return offset;
}
});
}
function getTupleDecoder(items) {
const fixedSize = sumCodecSizes(items.map(getFixedSize));
const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? void 0;
return createDecoder({
...fixedSize === null ? { maxSize } : { fixedSize },
read: (bytes, offset) => {
const values = [];
items.forEach((item) => {
const [newValue, newOffset] = item.read(bytes, offset);
values.push(newValue);
offset = newOffset;
});
return [values, offset];
}
});
}
function getUnionEncoder(variants, getIndexFromValue) {
const fixedSize = getUnionFixedSize(variants);
const write = (variant, bytes, offset) => {
const index = getIndexFromValue(variant);
assertValidVariantIndex(variants, index);
return variants[index].write(variant, bytes, offset);
};
if (fixedSize !== null) return createEncoder({
fixedSize,
write
});
const maxSize = getUnionMaxSize(variants);
return createEncoder({
...maxSize !== null ? { maxSize } : {},
getSizeFromValue: (variant) => {
const index = getIndexFromValue(variant);
assertValidVariantIndex(variants, index);
return getEncodedSize(variant, variants[index]);
},
write
});
}
function getUnionDecoder(variants, getIndexFromBytes) {
const fixedSize = getUnionFixedSize(variants);
const read = (bytes, offset) => {
const index = getIndexFromBytes(bytes, offset);
assertValidVariantIndex(variants, index);
return variants[index].read(bytes, offset);
};
if (fixedSize !== null) return createDecoder({
fixedSize,
read
});
const maxSize = getUnionMaxSize(variants);
return createDecoder({
...maxSize !== null ? { maxSize } : {},
read
});
}
function assertValidVariantIndex(variants, index) {
if (typeof variants[index] === "undefined") throw new SolanaError(SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, {
maxRange: variants.length - 1,
minRange: 0,
variant: index
});
}
function getUnionFixedSize(variants) {
if (variants.length === 0) return 0;
if (!isFixedSize(variants[0])) return null;
const variantSize = variants[0].fixedSize;
return variants.every((variant) => isFixedSize(variant) && variant.fixedSize === variantSize) ? variantSize : null;
}
function getUnionMaxSize(variants) {
return maxCodecSizes(variants.map((variant) => getMaxSize(variant)));
}
function getDiscriminatedUnionDecoder(variants, config = {}) {
const discriminatorProperty = config.discriminator ?? "__kind";
const prefix = config.size ?? getU8Decoder();
return getUnionDecoder(variants.map(([discriminator, variant]) => transformDecoder(getTupleDecoder([prefix, variant]), ([, value]) => ({
[discriminatorProperty]: discriminator,
...value
}))), (bytes, offset) => Number(prefix.read(bytes, offset)[0]));
}
function getEnumStats(constructor) {
const numericalValues = [...new Set(Object.values(constructor).filter((v) => typeof v === "number"))].sort();
const enumRecord = Object.fromEntries(Object.entries(constructor).slice(numericalValues.length));
const enumKeys = Object.keys(enumRecord);
const enumValues = Object.values(enumRecord);
return {
enumKeys,
enumRecord,
enumValues,
numericalValues,
stringValues: [.../* @__PURE__ */ new Set([...enumKeys, ...enumValues.filter((v) => typeof v === "string")])]
};
}
function getEnumIndexFromVariant({ enumKeys, enumValues, variant }) {
const valueIndex = findLastIndex(enumValues, (value) => value === variant);
if (valueIndex >= 0) return valueIndex;
return enumKeys.findIndex((key) => key === variant);
}
function getEnumIndexFromDiscriminator({ discriminator, enumKeys, enumValues, useValuesAsDiscriminators }) {
if (!useValuesAsDiscriminators) return discriminator >= 0 && discriminator < enumKeys.length ? discriminator : -1;
return findLastIndex(enumValues, (value) => value === discriminator);
}
function findLastIndex(array, predicate) {
let l = array.length;
while (l--) if (predicate(array[l], l, array)) return l;
return -1;
}
function formatNumericalValues(values) {
if (values.length === 0) return "";
let range = [values[0], values[0]];
const ranges = [];
for (let index = 1; index < values.length; index++) {
const value = values[index];
if (range[1] + 1 === value) range[1] = value;
else {
ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);
range = [value, value];
}
}
ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);
return ranges.join(", ");
}
function getEnumEncoder(constructor, config = {}) {
const prefix = config.size ?? getU8Encoder();
const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;
const { enumKeys, enumValues, numericalValues, stringValues } = getEnumStats(constructor);
if (useValuesAsDiscriminators && enumValues.some((value) => typeof value === "string")) throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, { stringValues: enumValues.filter((v) => typeof v === "string") });
return transformEncoder(prefix, (variant) => {
const index = getEnumIndexFromVariant({
enumKeys,
enumValues,
variant
});
if (index < 0) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT, {
formattedNumericalValues: formatNumericalValues(numericalValues),
numericalValues,
stringValues,
variant
});
return useValuesAsDiscriminators ? enumValues[index] : index;
});
}
function getEnumDecoder(constructor, config = {}) {
const prefix = config.size ?? getU8Decoder();
const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;
const { enumKeys, enumValues, numericalValues } = getEnumStats(constructor);
if (useValuesAsDiscriminators && enumValues.some((value) => typeof value === "string")) throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, { stringValues: enumValues.filter((v) => typeof v === "string") });
return transformDecoder(prefix, (value) => {
const discriminator = Number(value);
const index = getEnumIndexFromDiscriminator({
discriminator,
enumKeys,
enumValues,
useValuesAsDiscriminators
});
if (index < 0) {
const validDiscriminators = useValuesAsDiscriminators ? numericalValues : [...Array(enumKeys.length).keys()];
throw new SolanaError(SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE, {
discriminator,
formattedValidDiscriminators: formatNumericalValues(validDiscriminators),
validDiscriminators
});
}
return enumValues[index];
});
}
function getUnitEncoder() {
return createEncoder({
fixedSize: 0,
write: (_value, _bytes, offset) => offset
});
}
function getUnitDecoder() {
return createDecoder({
fixedSize: 0,
read: (_bytes, offset) => [void 0, offset]
});
}
function getNullableEncoder(item, config = {}) {
const prefix = (() => {
if (config.prefix === null) return transformEncoder(getUnitEncoder(), (_boolean) => void 0);
return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });
})();
return getUnionEncoder([transformEncoder(getTupleEncoder([prefix, (() => {
if (config.noneValue === "zeroes") {
assertIsFixedSize(item);
return fixEncoderSize(getUnitEncoder(), item.fixedSize);
}
if (!config.noneValue) return getUnitEncoder();
return getConstantEncoder(config.noneValue);
})()]), (_value) => [false, void 0]), transformEncoder(getTupleEncoder([prefix, item]), (value) => [true, value])], (variant) => Number(variant !== null));
}
function getPatternMatchEncoder(patterns) {
return getUnionEncoder(patterns.map(([, encoder]) => encoder), (value) => {
const index = patterns.findIndex(([predicate]) => predicate(value));
if (index === -1) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE);
return index;
});
}
function getPatternMatchDecoder(patterns) {
return getUnionDecoder(patterns.map(([, decoder]) => decoder), (value) => {
const index = patterns.findIndex(([predicate]) => predicate(value));
if (index === -1) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES, { bytes: value });
return index;
});
}
function getPredicateEncoder(predicate, ifTrue, ifFalse) {
return getUnionEncoder([ifTrue, ifFalse], (value) => predicate(value) ? 0 : 1);
}
function getStructEncoder(fields) {
const fieldCodecs = fields.map(([, codec]) => codec);
const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));
const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? void 0;
return createEncoder({
...fixedSize === null ? {
getSizeFromValue: (value) => fields.map(([key, codec]) => getEncodedSize(value[key], codec)).reduce((all, one) => all + one, 0),
maxSize
} : { fixedSize },
write: (struct, bytes, offset) => {
fields.forEach(([key, codec]) => {
offset = codec.write(struct[key], bytes, offset);
});
return offset;
}
});
}
function getStructDecoder(fields) {
const fieldCodecs = fields.map(([, codec]) => codec);
const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));
const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? void 0;
return createDecoder({
...fixedSize === null ? { maxSize } : { fixedSize },
read: (bytes, offset) => {
const struct = {};
fields.forEach(([key, codec]) => {
const [value, newOffset] = codec.read(bytes, offset);
offset = newOffset;
struct[key] = value;
});
return [struct, offset];
}
});
}
function getStructCodec(fields) {
return combineCodec(getStructEncoder(fields), getStructDecoder(fields));
}
// ../../node_modules/.pnpm/@solana+options@8.6.0_typescript@5.9.3/node_modules/@solana/options/dist/index.browser.mjs
var some = (value) => ({
__option: "Some",
value
});
var none = () => ({ __option: "None" });
var isOption = (input) => !!(input && typeof input === "object" && "__option" in input && (input.__option === "Some" && "value" in input || input.__option === "None"));
var isSome = (option) => option.__option === "Some";
function unwrapOption(option, fallback) {
if (isSome(option)) return option.value;
return fallback ? fallback() : null;
}
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
function getOptionEncoder(item, config = {}) {
const prefix = (() => {
if (config.prefix === null) return transformEncoder(getUnitEncoder(), (_boolean) => void 0);
return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });
})();
return getUnionEncoder([transformEncoder(getTupleEncoder([prefix, (() => {
if (config.noneValue === "zeroes") {
assertIsFixedSize(item);
return fixEncoderSize(getUnitEncoder(), item.fixedSize);
}
if (!config.noneValue) return getUnitEncoder();
return getConstantEncoder(config.noneValue);
})()]), (_value) => [false, void 0]), transformEncoder(getTupleEncoder([prefix, item]), (value) => [true, isOption(value) && isSome(value) ? value.value : value])], (variant) => {
const option = isOption(variant) ? variant : wrapNullable(variant);
return Number(isSome(option));
});
}
function getOptionDecoder(item, config = {}) {
const prefix = (() => {
if (config.prefix === null) return transformDecoder(getUnitDecoder(), () => false);
return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });
})();
const noneValue = (() => {
if (config.noneValue === "zeroes") {
assertIsFixedSize(item);
return fixDecoderSize(getUnitDecoder(), item.fixedSize);
}
if (!config.noneValue) return getUnitDecoder();
return getConstantDecoder(config.noneValue);
})();
return getUnionDecoder([transformDecoder(getTupleDecoder([prefix, noneValue]), () => none()), transformDecoder(getTupleDecoder([prefix, item]), ([, value]) => some(value))], (bytes, offset) => {
if (config.prefix === null && !config.noneValue) return Number(offset < bytes.length);
if (config.prefix === null && config.noneValue != null) return containsBytes(bytes, config.noneValue === "zeroes" ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue, offset) ? 0 : 1;
return Number(prefix.read(bytes, offset)[0]);
});
}
function getOptionCodec(item, config = {}) {
return combineCodec(getOptionEncoder(item, config), getOptionDecoder(item, config));
}
// ../../node_modules/.pnpm/@solana+functional@8.6.0_typescript@5.9.3/node_modules/@solana/functional/dist/index.browser.mjs
function pipe(init, ...fns) {
return fns.reduce((acc, fn) => fn(acc), init);
}
// ../../node_modules/.pnpm/@solana+instructions@8.6.0_typescript@5.9.3/node_modules/@solana/instructions/dist/index.browser.mjs
function assertIsInstructionWithAccounts(instruction) {
if (instruction.accounts === void 0) throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS, {
data: instruction.data,
programAddress: instruction.programAddress
});
}
var AccountRole = /* @__PURE__ */ ((AccountRole2) => {
AccountRole2[AccountRole2["WRITABLE_SIGNER"] = 3] = "WRITABLE_SIGNER";
AccountRole2[AccountRole2["READONLY_SIGNER"] = 2] = "READONLY_SIGNER";
AccountRole2[AccountRole2["WRITABLE"] = 1] = "WRITABLE";
AccountRole2[AccountRole2["READONLY"] = 0] = "READONLY";
return AccountRole2;
})(AccountRole || {});
var IS_SIGNER_BITMASK = 2;
var IS_WRITABLE_BITMASK = 1;
function isSignerRole(role) {
return role >= 2;
}
function isWritableRole(role) {
return (role & IS_WRITABLE_BITMASK) !== 0;
}
function upgradeRoleToSigner(role) {
return role | IS_SIGNER_BITMASK;
}
// ../../node_modules/.pnpm/@solana+rpc-types@8.6.0_typescript@5.9.3/node_modules/@solana/rpc-types/dist/index.browser.mjs
function assertIsBlockhash(putativeBlockhash) {
try {
assertIsAddress(putativeBlockhash);
} catch (error) {
if (isSolanaError(error, 2800001)) throw new SolanaError(4, error.context);
if (isSolanaError(error, 28e5)) throw new SolanaError(5, error.context);
throw error;
}
}
function blockhash(putativeBlockhash) {
assertIsBlockhash(putativeBlockhash);
return putativeBlockhash;
}
var maxU64Value = 18446744073709551615n;
function assertIsLamports(putativeLamports) {
if (putativeLamports < 0 || putativeLamports > maxU64Value) throw new SolanaError(6);
}
function lamports(putativeLamports) {
assertIsLamports(putativeLamports);
return putativeLamports;
}
var memoizedU8Encoder;
function getMemoizedU8Encoder() {
if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();
return memoizedU8Encoder;
}
var memoizedU8Decoder;
function getMemoizedU8Decoder() {
if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();
return memoizedU8Decoder;
}
function getMessageHeaderEncoder() {
return getStructEncoder([
["numSignerAccounts", getMemoizedU8Encoder()],
["numReadonlySignerAccounts", getMemoizedU8Encoder()],
["numReadonlyNonSignerAccounts", getMemoizedU8Encoder()]
]);
}
function getMessageHeaderDecoder() {
return getStructDecoder([
["numSignerAccounts", getMemoizedU8Decoder()],
["numReadonlySignerAccounts", getMemoizedU8Decoder()],
["numReadonlyNonSignerAccounts", getMemoizedU8Decoder()]
]);
}
var memoizedGetInstructionEncoder;
function getInstructionEncoder() {
if (!memoizedGetInstructionEncoder) memoizedGetInstructionEncoder = transformEncoder(getStructEncoder([
["programAddressIndex", getU8Encoder()],
["accountIndices", getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],
["data", addEncoderSizePrefix(getBytesEncoder(), getShortU16Encoder())]
]), (instruction) => {
if (instruction.accountIndices !== void 0 && instruction.data !== void 0) return instruction;
return {
...instruction,
accountIndices: instruction.accountIndices ?? [],
data: instruction.data ?? /* @__PURE__ */ new Uint8Array(0)
};
});
return memoizedGetInstructionEncoder;
}
var memoizedGetInstructionDecoder;
function getInstructionDecoder() {
if (!memoizedGetInstructionDecoder) memoizedGetInstructionDecoder = transformDecoder(getStructDecoder([
["programAddressIndex", getU8Decoder()],
["accountIndices", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],
["data", addDecoderSizePrefix(getBytesDecoder(), getShortU16Decoder())]
]), (instruction) => {
if (instruction.accountIndices.length && instruction.data.byteLength) return instruction;
const { accountIndices, data, ...rest } = instruction;
return {
...rest,
...accountIndices.length ? { accountIndices } : null,
...data.byteLength ? { data } : null
};
});
return memoizedGetInstructionDecoder;
}
function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
alphabet: alphabet4,
base: alphabet4.length,
value: givenValue
});
}
var getBaseXEncoder = (alphabet4) => {
return createEncoder({
getSizeFromValue: (value) => {
const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
if (!tailChars) return value.length;
const base10Number = getBigIntFromBaseX(tailChars, alphabet4);
return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
},
write(value, bytes, offset) {
assertValidBaseString(alphabet4, value);
if (value === "") return offset;
const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
if (!tailChars) {
bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
return offset + leadingZeroes.length;
}
let base10Number = getBigIntFromBaseX(tailChars, alphabet4);
const tailBytes = [];
while (base10Number > 0n) {
tailBytes.unshift(Number(base10Number % 256n));
base10Number /= 256n;
}
const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
bytes.set(bytesToAdd, offset);
return offset + bytesToAdd.length;
}
});
};
var getBaseXDecoder = (alphabet4) => {
return createDecoder({ read(rawBytes, offset) {
const bytes = offset === 0 || offset <= -rawBytes.byteLength ? rawBytes : rawBytes.slice(offset);
if (bytes.length === 0) return ["", rawBytes.length];
let trailIndex = bytes.findIndex((n) => n !== 0);
trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
const leadingZeroes = alphabet4[0].repeat(trailIndex);
if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];
return [leadingZeroes + getBaseXFromBigInt(bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n), alphabet4), rawBytes.length];
} });
};
function partitionLeadingZeroes(value, zeroCharacter) {
const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));
return [leadingZeros, tailChars];
}
function getBigIntFromBaseX(value, alphabet4) {
const base = BigInt(alphabet4.length);
let sum = 0n;
for (const char of value) {
sum *= base;
sum += BigInt(alphabet4.indexOf(char));
}
return sum;
}
function getBaseXFromBigInt(value, alphabet4) {
const base = BigInt(alphabet4.length);
const tailChars = [];
while (value > 0n) {
tailChars.unshift(alphabet4[Number(value % base)]);
value /= base;
}
return tailChars.join("");
}
var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
var getBase58Encoder = () => getBaseXEncoder(alphabet2);
var getBase58Decoder = () => getBaseXDecoder(alphabet2);
function getLifetimeTokenEncoder() {
return transformEncoder(getNullableEncoder(fixEncoderSize(getBase58Encoder(), 32), {
noneValue: "zeroes",
prefix: null
}), (token) => token ?? null);
}
function getLifetimeTokenDecoder() {
return fixDecoderSize(getBase58Decoder(), 32);
}
function getMessageEncoder() {
return transformEncoder(getStructEncoder([
["header", getMessageHeaderEncoder()],
["staticAccounts", getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],
["lifetimeToken", getLifetimeTokenEncoder()],
["instructions", getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })]
]), (value) => ({
...value,
lifetimeToken: "lifetimeToken" in value ? value.lifetimeToken : void 0
}));
}
function getMessageDecoder() {
return transformDecoder(getStructDecoder([
["header", getMessageHeaderDecoder()],
["staticAccounts", getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],
["lifetimeToken", getLifetimeTokenDecoder()],
["instructions", getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })]
]), (value) => ({
...value,
version: "legacy"
}));
}
var VERSION_FLAG_MASK = 128;
function getTransactionVersionEncoder() {
return createEncoder({
getSizeFromValue: (value) => value === "legacy" ? 0 : 1,
maxSize: 1,
write: (value, bytes, offset) => {
if (value === "legacy") return offset;
if (value < 0 || value > 127) throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, { actualVersion: value });
if (value > 1) throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, { unsupportedVersion: value });
bytes.set([value | VERSION_FLAG_MASK], offset);
return offset + 1;
}
});
}
function getTransactionVersionDecoder() {
return createDecoder({
maxSize: 1,
read: (bytes, offset) => {
const firstByte = bytes[offset];
if ((firstByte & VERSION_FLAG_MASK) === 0) return ["legacy", offset];
else {
const version = firstByte ^ VERSION_FLAG_MASK;
if (version > 1) throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, { unsupportedVersion: version });
return [version, offset + 1];
}
}
});
}
var memoizedAddressTableLookupEncoder;
function getAddressTableLookupEncoder() {
if (!memoizedAddressTableLookupEncoder) {
const indexEncoder = getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() });
memoizedAddressTableLookupEncoder = getStructEncoder([
["lookupTableAddress", getAddressEncoder()],
["writableIndexes", indexEncoder],
["readonlyIndexes", indexEncoder]
]);
}
return memoizedAddressTableLookupEncoder;
}
var memoizedAddressTableLookupDecoder;
function getAddressTableLookupDecoder() {
if (!memoizedAddressTableLookupDecoder) {
const indexEncoder = getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() });
memoizedAddressTableLookupDecoder = getStructDecoder([
["lookupTableAddress", getAddressDecoder()],
["writableIndexes", indexEncoder],
["readonlyIndexes", indexEncoder]
]);
}
return memoizedAddressTableLookupDecoder;
}
function getMessageEncoder2() {
return transformEncoder(getStructEncoder([
["version", getTransactionVersionEncoder()],
["header", getMessageHeaderEncoder()],
["staticAccounts", getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],
["lifetimeToken", getLifetimeTokenEncoder()],
["instructions", getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })],
["addressTableLookups", getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() })]
]), (value) => ({
...value,
addressTableLookups: value.addressTableLookups ?? [],
lifetimeToken: "lifetimeToken" in value ? value.lifetimeToken : void 0
}));
}
function getMessageDecoder2() {
return transformDecoder(getStructDecoder([
["version", getTransactionVersionDecoder()],
["header", getMessageHeaderDecoder()],
["staticAccounts", getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],
["lifetimeToken", getLifetimeTokenDecoder()],
["instructions", getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],
["addressTableLookups", getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() })]
]), ({ addressTableLookups, ...restOfMessage }) => {
if (!addressTableLookups?.length) return {
...restOfMessage,
version: 0
};
return {
...restOfMessage,
addressTableLookups,
version: 0
};
});
}
function isV1ConfigEmpty(config) {
return config.computeUnitLimit === void 0 && config.heapSize === void 0 && config.loadedAccountsDataSizeLimit === void 0 && config.priorityFeeLamports === void 0;
}
function transactionConfigMaskHasPriorityFee(mask) {
const priorityFeeBits = mask & 3;
if (priorityFeeBits === 1 || priorityFeeBits === 2) throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS, { mask });
return priorityFeeBits === 3;
}
function transactionConfigMaskHasComputeUnitLimit(mask) {
return (mask & 4) !== 0;
}
function transactionConfigMaskHasLoadedAccountsDataSizeLimit(mask) {
return (mask & 8) !== 0;
}
function transactionConfigMaskHasHeapSize(mask) {
return (mask & 16) !== 0;
}
function getCompiledTransactionConfigValueEncoder() {
return getPatternMatchEncoder([[(value) => value.kind === "u32", transformEncoder(getStructEncoder([["value", getU32Encoder()]]), (value) => value)], [(value) => value.kind === "u64", transformEncoder(getStructEncoder([["value", getU64Encoder()]]), (value) => value)]]);
}
function getCompiledTransactionConfigValuesEncoder() {
return getArrayEncoder(getCompiledTransactionConfigValueEncoder(), { size: "remainder" });
}
function getCompiledTransactionConfigValuesDecoder(mask) {
const hasPriorityFee = transactionConfigMaskHasPriorityFee(mask);
const hasComputeUnitLimit = transactionConfigMaskHasComputeUnitLimit(mask);
const hasLoadedAccountsDataSizeLimit = transactionConfigMaskHasLoadedAccountsDataSizeLimit(mask);
const hasHeapSize = transactionConfigMaskHasHeapSize(mask);
const u32Decoder = transformDecoder(getU32Decoder(), (value) => ({
kind: "u32",
value
}));
const u64Decoder = transformDecoder(getU64Decoder(), (value) => ({
kind: "u64",
value
}));
const unitDecoder = getUnitDecoder();
return transformDecoder(getTupleDecoder([
hasPriorityFee ? u64Decoder : unitDecoder,
hasComputeUnitLimit ? u32Decoder : unitDecoder,
hasLoadedAccountsDataSizeLimit ? u32Decoder : unitDecoder,
hasHeapSize ? u32Decoder : unitDecoder
]), (arr) => arr.filter(Boolean));
}
function getInstructionHeaderEncoder() {
return getStructEncoder([
["programAccountIndex", getU8Encoder()],
["numInstructionAccounts", getU8Encoder()],
["numInstructionDataBytes", getU16Encoder()]
]);
}
function getInstructionHeaderDecoder() {
return getStructDecoder([
["programAccountIndex", getU8Decoder()],
["numInstructionAccounts", getU8Decoder()],
["numInstructionDataBytes", getU16Decoder()]
]);
}
function getInstructionPayloadEncoder() {
return getStructEncoder([["instructionAccountIndices", getArrayEncoder(getU8Encoder(), { size: "remainder" })], ["instructionData", getBytesEncoder()]]);
}
function getInstructionPayloadDecoder(instructionHeader) {
return getStructDecoder([["instructionAccountIndices", getArrayDecoder(getU8Decoder(), { size: instructionHeader.numInstructionAccounts })], ["instructionData", fixDecoderSize(getBytesDecoder(), instructionHeader.numInstructionDataBytes)]]);
}
function getMessageEncoder3() {
return transformEncoder(getStructEncoder([
["version", getTransactionVersionEncoder()],
["header", getMessageHeaderEncoder()],
["configMask", getU32Encoder()],
["lifetimeToken", getLifetimeTokenEncoder()],
["numInstructions", getU8Encoder()],
["numStaticAccounts", getU8Encoder()],
["staticAccounts", getArrayEncoder(getAddressEncoder(), { size: "remainder" })],
["configValues", getCompiledTransactionConfigValuesEncoder()],
["instructionHeaders", getArrayEncoder(getInstructionHeaderEncoder(), { size: "remainder" })],
["instructionPayloads", getArrayEncoder(getInstructionPayloadEncoder(), { size: "remainder" })]
]), (value) => ({
...value,
lifetimeToken: "lifetimeToken" in value ? value.lifetimeToken : void 0
}));
}
function getMessageDecoder3() {
return createDecoder({ read(bytes, offset) {
const [{ header, configMask, lifetimeToken, numInstructions, numStaticAccounts }, afterFixedFields] = getStructDecoder([
["version", getTransactionVersionDecoder()],
["header", getMessageHeaderDecoder()],
["configMask", getU32Decoder()],
["lifetimeToken", getLifetimeTokenDecoder()],
["numInstructions", getU8Decoder()],
["numStaticAccounts", getU8Decoder()]
]).read(bytes, offset);
let nextOffset = afterFixedFields;
const [staticAccounts, afterAddresses] = getArrayDecoder(getAddressDecoder(), { size: numStaticAccounts }).read(bytes, nextOffset);
nextOffset = afterAddresses;
const [configValues, afterConfig] = getCompiledTransactionConfigValuesDecoder(configMask).read(bytes, nextOffset);
nextOffset = afterConfig;
const [instructionHeaders, afterHeaders] = getArrayDecoder(getInstructionHeaderDecoder(), { size: numInstructions }).read(bytes, nextOffset);
nextOffset = afterHeaders;
const instructionPayloads = [];
for (const header2 of instructionHeaders) {
const [payload, next] = getInstructionPayloadDecoder(header2).read(bytes, nextOffset);
instructionPayloads.push(payload);
nextOffset = next;
}
return [{
configMask,
configValues,
header,
instructionHeaders,
instructionPayloads,
lifetimeToken,
numInstructions,
numStaticAccounts,
staticAccounts,
version: 1
}, nextOffset];
} });
}
function getCompiledTransactionMessageEncoder() {
return transformEncoder(getPatternMatchEncoder([
[(m) => m.version === "legacy", getMessageEncoder()],
[(m) => m.version === 0, getMessageEncoder2()],
[(m) => m.version === 1, getMessageEncoder3()]
]), (value) => {
if (value.version !== "legacy" && value.version > 1) throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, { unsupportedVersion: value.version });
return value;
});
}
function getCompiledTransactionMessageDecoder() {
return createDecoder({ read(bytes, offset) {
const [version] = getTransactionVersionDecoder().read(bytes, offset);
return getPatternMatchDecoder([
[() => version === "legacy", getMessageDecoder()],
[() => version === 0, getMessageDecoder2()],
[() => version === 1, getMessageDecoder3()]
]).read(bytes, offset);
} });
}
function getTransactionConfigMask(config) {
let mask = 0;
if (config.priorityFeeLamports !== void 0) mask |= 3;
if (config.computeUnitLimit !== void 0) mask |= 4;
if (config.loadedAccountsDataSizeLimit !== void 0) mask |= 8;
if (config.heapSize !== void 0) mask |= 16;
return mask;
}
function getTransactionConfigValues(config) {
const values = [];
if (config.priorityFeeLamports !== void 0) values.push({
kind: "u64",
value: config.priorityFeeLamports
});
if (config.computeUnitLimit !== void 0) values.push({
kind: "u32",
value: config.computeUnitLimit
});
if (config.loadedAccountsDataSizeLimit !== void 0) values.push({
kind: "u32",
value: config.loadedAccountsDataSizeLimit
});
if (config.heapSize !== void 0) values.push({
kind: "u32",
value: config.heapSize
});
return values;
}
function decompileTransactionConfig(configMask, configValues) {
const [config] = [
[
"priorityFeeLamports",
"u64",
transactionConfigMaskHasPriorityFee
],
[
"computeUnitLimit",
"u32",
transactionConfigMaskHasComputeUnitLimit
],
[
"loadedAccountsDataSizeLimit",
"u32",
transactionConfigMaskHasLoadedAccountsDataSizeLimit
],
[
"heapSize",
"u32",
transactionConfigMaskHasHeapSize
]
].reduce(([acc, index], [name, kind, predicate]) => {
if (!predicate(configMask)) return [acc, index];
const configValue = configValues[index];
if (configValue.kind !== kind) throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND, {
actualKind: configValue.kind,
configName: name,
expectedKind: kind
});
return [{
...acc,
[name]: configValue.value
}, index + 1];
}, [{}, 0]);
return config;
}
// ../../node_modules/.pnpm/@solana+promises@8.6.0_typescript@5.9.3/node_modules/@solana/promises/dist/index.browser.mjs
function isObject(value) {
return value !== null && (typeof value === "object" || typeof value === "function");
}
function addRaceContender(contender) {
const deferreds = /* @__PURE__ */ new Set();
const record = {
deferreds,
settled: false
};
Promise.resolve(contender).then((value) => {
for (const { resolve } of deferreds) resolve(value);
deferreds.clear();
record.settled = true;
}, (err) => {
for (const { reject } of deferreds) reject(err);
deferreds.clear();
record.settled = true;
});
return record;
}
var wm = /* @__PURE__ */ new WeakMap();
async function safeRace(contenders) {
let deferred;
return await new Promise((resolve, reject) => {
deferred = {
reject,
resolve
};
for (const contender of contenders) {
if (!isObject(contender)) {
Promise.resolve(contender).then(resolve, reject);
continue;
}
let record = wm.get(contender);
if (record === void 0) {
record = addRaceContender(contender);
record.deferreds.add(deferred);
wm.set(contender, record);
} else if (record.settled) Promise.resolve(contender).then(resolve, reject);
else record.deferreds.add(deferred);
}
}).finally(() => {
for (const contender of contenders) if (isObject(contender)) wm.get(contender).deferreds.delete(deferred);
});
}
function getAbortablePromise(promise, abortSignal) {
if (!abortSignal) return promise;
else return safeRace([new Promise((_, reject) => {
if (abortSignal.aborted) reject(abortSignal.reason);
else abortSignal.addEventListener("abort", function() {
reject(this.reason);
});
}), promise]);
}
// ../../node_modules/.pnpm/@solana+keys@8.6.0_typescript@5.9.3/node_modules/@solana/keys/dist/index.browser.mjs
var ED25519_ALGORITHM_IDENTIFIER = Object.freeze({ name: "Ed25519" });
function addPkcs8Header(bytes) {
return new Uint8Array([
48,
46,
2,
1,
0,
48,
5,
6,
3,
43,
101,
112,
4,
34,
4,
32,
...bytes
]);
}
async function createPrivateKeyFromBytes(bytes, extractable = false) {
const actualLength = bytes.byteLength;
if (actualLength !== 32) throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, { actualLength });
const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, ED25519_ALGORITHM_IDENTIFIER, extractable, ["sign"]);
}
async function getPublicKeyFromPrivateKey(privateKey, _extractable) {
assertKeyExporterIsAvailable();
if (privateKey.extractable === false) throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, { key: privateKey });
const jwk = await crypto.subtle.exportKey("jwk", privateKey);
return await crypto.subtle.importKey("jwk", {
crv: "Ed25519",
ext: true,
key_ops: ["verify"],
kty: "OKP",
x: jwk.x
}, "Ed25519", true, ["verify"]);
}
var P = 2n ** 255n - 19n;
var SMALL_ORDER_Y_COORDINATES = /* @__PURE__ */ new Set([
0n,
1n,
P - 1n,
2707385501144840649318225287225658788936804267575313519463743609750303402022n,
55188659117513257062467267217118295137698188065244968500265048394206261417927n
]);
function isSmallOrderPointEncoding(bytes) {
if (bytes.byteLength !== 32) return false;
let y = 0n;
for (let ii = 31; ii >= 0; ii--) y = y << 8n | BigInt(ii === 31 ? bytes[ii] & 127 : bytes[ii]);
return SMALL_ORDER_Y_COORDINATES.has(y % P);
}
var base58Encoder;
function assertIsSignature(putativeSignature) {
if (!base58Encoder) base58Encoder = getBase58Encoder$1();
if (putativeSignature.length < 64 || putativeSignature.length > 88) throw new SolanaError(SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, { actualLength: putativeSignature.length });
assertIsSignatureBytes(base58Encoder.encode(putativeSignature));
}
function assertIsSignatureBytes(putativeSignatureBytes) {
const numBytes = putativeSignatureBytes.byteLength;
if (numBytes !== 64) throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, { actualLength: numBytes });
}
async function signBytes(key, data) {
assertSigningCapabilityIsAvailable();
const signedData = await crypto.subtle.sign(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(data));
return new Uint8Array(signedData);
}
function signatureBytes(putativeSignatureBytes) {
assertIsSignatureBytes(putativeSignatureBytes);
return putativeSignatureBytes;
}
async function verifySignature(key, signature2, data) {
assertVerificationCapabilityIsAvailable();
assertKeyExporterIsAvailable();
if (key.type !== "public" || !key.extractable) throw new SolanaError(SOLANA_ERROR__KEYS__VERIFICATION_REQUIRES_EXTRACTABLE_PUBLIC_KEY);
if (isSmallOrderPointEncoding(new Uint8Array(await crypto.subtle.exportKey("raw", key)))) return false;
if (isSmallOrderPointEncoding(signature2.subarray(0, 32))) return false;
return await crypto.subtle.verify(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(signature2), toArrayBuffer(data));
}
async function createKeyPairFromBytes(bytes, extractable = false) {
assertPRNGIsAvailable();
if (bytes.byteLength !== 64) throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH, { byteLength: bytes.byteLength });
const [publicKey, privateKey] = await Promise.all([crypto.subtle.importKey("raw", bytes.slice(32), ED25519_ALGORITHM_IDENTIFIER, true, ["verify"]), createPrivateKeyFromBytes(bytes.slice(0, 32), extractable)]);
const randomBytes = /* @__PURE__ */ new Uint8Array(32);
crypto.getRandomValues(randomBytes);
if (!await verifySignature(publicKey, await signBytes(privateKey, randomBytes), randomBytes)) throw new SolanaError(SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY);
return {
privateKey,
publicKey
};
}
async function createKeyPairFromPrivateKeyBytes(bytes, extractable = false) {
const privateKeyPromise = createPrivateKeyFromBytes(bytes, extractable);
const [publicKey, privateKey] = await Promise.all([(extractable ? privateKeyPromise : createPrivateKeyFromBytes(bytes, true)).then(async (privateKey2) => await getPublicKeyFromPrivateKey(privateKey2)), privateKeyPromise]);
return {
privateKey,
publicKey
};
}
// ../../node_modules/.pnpm/@solana+transactions@8.6.0_typescript@5.9.3/node_modules/@solana/transactions/dist/index.browser.mjs
function getSignaturesToEncode(signaturesMap) {
const signatures = Object.values(signaturesMap);
if (signatures.length === 0) throw new SolanaError(SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES);
return signatures.map((signature) => {
if (!signature) return (/* @__PURE__ */ new Uint8Array(64)).fill(0);
return signature;
});
}
function getSignaturesEncoderWithSizePrefix() {
return transformEncoder(getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getShortU16Encoder() }), getSignaturesToEncode);
}
function getSignaturesEncoderWithLength(size) {
return transformEncoder(getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), {
description: "signatures",
size
}), getSignaturesToEncode);
}
function getEnvelopeShapeFromMessageBytes(messageBytes) {
if (messageBytes.length === 0) throw new SolanaError(SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES);
return getTransactionVersionDecoder().decode(messageBytes) === 1 ? "messageFirst" : "signaturesFirst";
}
function getTransactionEncoder() {
return getPredicateEncoder((transaction) => getEnvelopeShapeFromMessageBytes(transaction.messageBytes) === "signaturesFirst", getTransactionEncoderWithSignaturesFirst(), getTransactionEncoderWithMessageFirst());
}
function getTransactionEncoderWithSignaturesFirst() {
return getStructEncoder([["signatures", getSignaturesEncoderWithSizePrefix()], ["messageBytes", getBytesEncoder()]]);
}
function getSignatureCountForVersionedOrThrow(messageBytes, offset) {
if (messageBytes.length < offset + 2) throw new SolanaError(SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES, { messageBytes });
return messageBytes[offset + 1];
}
function getTransactionEncoderWithMessageFirst() {
const bytesEncoder = getBytesEncoder();
return createEncoder({
getSizeFromValue: (transaction) => {
const signatureCount = getSignatureCountForVersionedOrThrow(transaction.messageBytes, 0);
return transaction.messageBytes.length + signatureCount * 64;
},
write: (transaction, bytes, offset) => {
offset = bytesEncoder.write(transaction.messageBytes, bytes, offset);
offset = getSignaturesEncoderWithLength(getSignatureCountForVersionedOrThrow(transaction.messageBytes, 0)).write(transaction.signatures, bytes, offset);
return offset;
}
});
}
var SYSTEM_PROGRAM_ADDRESS$1 = "11111111111111111111111111111111";
function compiledV1InstructionIsAdvanceNonceInstruction(instructionHeader, instructionPayload, staticAddresses) {
return staticAddresses[instructionHeader.programAccountIndex] === SYSTEM_PROGRAM_ADDRESS$1 && isAdvanceNonceAccountInstructionData(instructionPayload.instructionData) && instructionHeader.numInstructionAccounts === 3;
}
function compiledLegacyInstructionIsAdvanceNonceInstruction(instruction, staticAddresses) {
return staticAddresses[instruction.programAddressIndex] === SYSTEM_PROGRAM_ADDRESS$1 && instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && instruction.accountIndices?.length === 3;
}
function isAdvanceNonceAccountInstructionData(data) {
return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
}
async function getTransactionLifetimeConstraintFromCompiledTransactionMessage(compiledTransactionMessage) {
const { version } = compiledTransactionMessage;
if (version === "legacy" || version === 0) {
const firstInstruction = compiledTransactionMessage.instructions[0];
const { staticAccounts } = compiledTransactionMessage;
if (firstInstruction && compiledLegacyInstructionIsAdvanceNonceInstruction(firstInstruction, staticAccounts)) {
const nonceAccountAddress = staticAccounts[firstInstruction.accountIndices[0]];
if (!nonceAccountAddress) throw new SolanaError(SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE, { nonce: compiledTransactionMessage.lifetimeToken });
return {
nonce: compiledTransactionMessage.lifetimeToken,
nonceAccountAddress
};
} else return {
blockhash: compiledTransactionMessage.lifetimeToken,
lastValidBlockHeight: 18446744073709551615n
};
}
if (version === 1) {
const firstInstructionHeader = compiledTransactionMessage.instructionHeaders[0];
const firstInstructionPayload = compiledTransactionMessage.instructionPayloads[0];
const { staticAccounts } = compiledTransactionMessage;
if (firstInstructionHeader && firstInstructionPayload && compiledV1InstructionIsAdvanceNonceInstruction(firstInstructionHeader, firstInstructionPayload, staticAccounts)) {
const nonceAccountAddress = staticAccounts[firstInstructionPayload.instructionAccountIndices[0]];
if (!nonceAccountAddress) throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX, {
nonce: compiledTransactionMessage.lifetimeToken,
nonceAccountIndex: firstInstructionPayload.instructionAccountIndices[0],
numberOfStaticAccounts: staticAccounts.length
});
return {
nonce: compiledTransactionMessage.lifetimeToken,
nonceAccountAddress
};
} else return {
blockhash: compiledTransactionMessage.lifetimeToken,
lastValidBlockHeight: 18446744073709551615n
};
}
throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, { unsupportedVersion: version });
}
async function partiallySignTransaction(keyPairs, transaction) {
let newSignatures;
let unexpectedSigners;
await Promise.all(keyPairs.map(async (keyPair) => {
const address = await getAddressFromPublicKey(keyPair.publicKey);
const existingSignature = transaction.signatures[address];
if (existingSignature === void 0) {
unexpectedSigners ||= /* @__PURE__ */ new Set();
unexpectedSigners.add(address);
return;
}
if (unexpectedSigners) return;
const newSignature = await signBytes(keyPair.privateKey, transaction.messageBytes);
if (existingSignature !== null && bytesEqual(newSignature, existingSignature)) return;
newSignatures ||= {};
newSignatures[address] = newSignature;
}));
if (unexpectedSigners && unexpectedSigners.size > 0) throw new SolanaError(SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, {
expectedAddresses: Object.keys(transaction.signatures),
unexpectedAddresses: [...unexpectedSigners]
});
if (!newSignatures) return transaction;
return Object.freeze({
...transaction,
signatures: Object.freeze({
...transaction.signatures,
...newSignatures
})
});
}
var LEGACY_TRANSACTION_SIZE_LIMIT = 1232;
var V1_TRANSACTION_SIZE_LIMIT = 4096;
function getTransactionSize(transaction) {
return getTransactionEncoder().getSizeFromValue(transaction);
}
function getTransactionSizeLimit(transaction) {
const VERSION_FLAG_MASK2 = 128;
const VERSION_NUMBER_MASK = 127;
const firstByte = transaction.messageBytes[0];
return (firstByte & VERSION_FLAG_MASK2) !== 0 && (firstByte & VERSION_NUMBER_MASK) === 1 ? V1_TRANSACTION_SIZE_LIMIT : LEGACY_TRANSACTION_SIZE_LIMIT;
}
function assertIsTransactionWithinSizeLimit(transaction) {
if (transaction.messageBytes.length === 0) return;
const sizeLimit = getTransactionSizeLimit(transaction);
const transactionSize = getTransactionSize(transaction);
if (transactionSize > sizeLimit) throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {
transactionSize,
transactionSizeLimit: sizeLimit
});
}
// ../../node_modules/.pnpm/@solana+instruction-plans@8.6.0_typescript@5.9.3/node_modules/@solana/instruction-plans/dist/index.browser.mjs
function isInstructionPlan(value) {
return typeof value === "object" && value !== null && "planType" in value && typeof value.planType === "string" && value.planType === "instructionPlan";
}
function isSingleInstructionPlan(plan) {
return plan.kind === "single";
}
function flattenInstructionPlan(instructionPlan) {
if (instructionPlan.kind === "single" || instructionPlan.kind === "messagePacker") return [instructionPlan];
return instructionPlan.plans.flatMap(flattenInstructionPlan);
}
// ../../node_modules/.pnpm/@solana+rpc-spec-types@8.6.0_typescript@5.9.3/node_modules/@solana/rpc-spec-types/dist/index.browser.mjs
var JAVASCRIPT_PROTOCOL_PROPERTY_NAMES = /* @__PURE__ */ new Set([
"then",
"toJSON",
/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"),
Symbol.asyncIterator,
Symbol.iterator,
Symbol.toPrimitive,
Symbol.toStringTag,
Symbol.asyncDispose,
Symbol.dispose
].filter((propertyName) => propertyName != null));
var OBJECT_PROTOTYPE_PROPERTY_NAMES = /* @__PURE__ */ new Set([
"__defineGetter__",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__",
"__proto__",
"constructor",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"valueOf"
]);
function getNonRpcPropertyValue(propertyName, receiver) {
if (JAVASCRIPT_PROTOCOL_PROPERTY_NAMES.has(propertyName)) return;
return Reflect.get(Object.prototype, propertyName, receiver);
}
function isNonRpcPropertyName(propertyName) {
return JAVASCRIPT_PROTOCOL_PROPERTY_NAMES.has(propertyName) || OBJECT_PROTOTYPE_PROPERTY_NAMES.has(propertyName);
}
var BIGINT_VALUE_OBJECT_PATTERN = /^(-?)(\d+)(?:[eE]\+?(\d+))?$/;
var MAX_BIGINT_DIGITS = 1e3;
function parseJsonWithBigInts(json) {
return JSON.parse(wrapIntegersInBigIntValueObject(json), (_, value) => {
return isBigIntValueObject(value) ? unwrapBigIntValueObject(value) : value;
});
}
function wrapIntegersInBigIntValueObject(json) {
const out = [];
let inQuote = false;
for (let ii = 0; ii < json.length; ii++) {
let isEscaped = false;
if (json[ii] === "\\") {
out.push(json[ii++]);
isEscaped = !isEscaped;
}
if (json[ii] === "\"") {
out.push(json[ii]);
if (!isEscaped) inQuote = !inQuote;
continue;
}
if (!inQuote) {
const consumedNumber = consumeNumber(json, ii);
if (consumedNumber?.length) {
ii += consumedNumber.length - 1;
if (consumedNumber.match(/\.|[eE]-/)) out.push(consumedNumber);
else out.push(wrapBigIntValueObject(consumedNumber));
continue;
}
}
out.push(json[ii]);
}
return out.join("");
}
function consumeNumber(json, ii) {
const JSON_NUMBER_REGEX = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/;
if (!json[ii]?.match(/[-\d]/)) return null;
const numberMatch = json.slice(ii).match(JSON_NUMBER_REGEX);
return numberMatch ? numberMatch[0] : null;
}
function wrapBigIntValueObject(value) {
return `{"$n":"${value}"}`;
}
function unwrapBigIntValueObject({ $n }) {
const match = $n.match(BIGINT_VALUE_OBJECT_PATTERN);
if (match) {
const [, sign, mantissa, exponent] = match;
if (mantissa.length + (exponent ? Number(exponent) : 0) <= MAX_BIGINT_DIGITS) return exponent ? BigInt(`${sign}${mantissa}`) * 10n ** BigInt(exponent) : BigInt($n);
}
throw new SolanaError(7, { value: $n });
}
function isBigIntValueObject(value) {
return !!value && typeof value === "object" && "$n" in value && typeof value.$n === "string";
}
var _nextMessageId = 0n;
function getNextMessageId() {
const id = _nextMessageId;
_nextMessageId++;
return id.toString();
}
function createRpcMessage(request) {
return {
id: getNextMessageId(),
jsonrpc: "2.0",
method: request.methodName,
params: request.params
};
}
function stringifyJsonWithBigInts(value, space) {
return unwrapBigIntValueObject2(JSON.stringify(value, (_, v) => typeof v === "bigint" ? wrapBigIntValueObject2(v) : v, space));
}
function wrapBigIntValueObject2(value) {
return { $n: `${value}` };
}
function unwrapBigIntValueObject2(value) {
return value.replace(/\{\s*"\$n"\s*:\s*"(-?\d+)"\s*\}/g, "$1");
}
// ../../node_modules/.pnpm/@solana+subscribable@8.6.0_typescript@5.9.3/node_modules/@solana/subscribable/dist/index.browser.mjs
var o$4 = globalThis.AbortController;
var t$1 = globalThis.EventTarget;
var IDLE_STATE = Object.freeze({
data: void 0,
error: void 0,
status: "idle"
});
function createReactiveActionStore(fn) {
let state = IDLE_STATE;
let currentController;
const listeners = /* @__PURE__ */ new Set();
function setState(next) {
if (state.status === next.status && state.data === next.data && state.error === next.error) return;
state = next;
listeners.forEach((listener) => listener());
}
const dispatchAsyncWithSignal = async (userSignal, ...args) => {
currentController?.abort();
if (userSignal?.aborted) {
setState({
data: state.data,
error: userSignal.reason,
status: "error"
});
throw userSignal.reason;
}
const controller = new o$4();
currentController = controller;
const signal = userSignal ? AbortSignal.any([controller.signal, userSignal]) : controller.signal;
const previousData = state.data;
const previousError = state.error;
setState({
data: previousData,
error: previousError,
status: "running"
});
try {
const result = await getAbortablePromise(fn(signal, ...args), signal);
if (signal.aborted) throw signal.reason;
setState({
data: result,
error: void 0,
status: "success"
});
return result;
} catch (error) {
if (controller.signal.aborted) throw controller.signal.reason;
setState({
data: previousData,
error,
status: "error"
});
throw error;
}
};
const dispatchAsync = (...args) => dispatchAsyncWithSignal(void 0, ...args);
const dispatch = (...args) => {
dispatchAsync(...args).catch(() => {});
};
return {
dispatch,
dispatchAsync,
getState: () => state,
reset: () => {
currentController?.abort();
currentController = void 0;
setState(IDLE_STATE);
},
subscribe: (listener) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
withSignal: (signal) => ({
dispatch: (...args) => {
dispatchAsyncWithSignal(signal, ...args).catch(() => {});
},
dispatchAsync: (...args) => dispatchAsyncWithSignal(signal, ...args)
})
};
}
var EXPLICIT_ABORT_TOKEN;
function createExplicitAbortToken() {
return Symbol(void 0);
}
var UNINITIALIZED = Symbol();
function createAsyncIterableFromDataPublisher({ abortSignal, dataChannelName, dataPublisher, errorChannelName }) {
const iteratorState = /* @__PURE__ */ new Map();
function publishErrorToAllIterators(reason) {
for (const [iteratorKey, state] of iteratorState.entries()) if (state.__hasPolled) {
iteratorState.delete(iteratorKey);
state.onError(reason);
} else state.publishQueue.push({
__type: 1,
err: reason
});
}
const abortController = new o$4();
abortSignal.addEventListener("abort", () => {
abortController.abort();
publishErrorToAllIterators(EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken());
});
const options = { signal: abortController.signal };
let firstError = UNINITIALIZED;
dataPublisher.on(errorChannelName, (err) => {
if (firstError === UNINITIALIZED) {
firstError = err;
abortController.abort();
publishErrorToAllIterators(err);
}
}, options);
dataPublisher.on(dataChannelName, (data) => {
iteratorState.forEach((state, iteratorKey) => {
if (state.__hasPolled) {
const { onData } = state;
iteratorState.set(iteratorKey, {
__hasPolled: false,
publishQueue: []
});
onData(data);
} else state.publishQueue.push({
__type: 0,
data
});
});
}, options);
return { async *[Symbol.asyncIterator]() {
if (abortSignal.aborted) return;
if (firstError !== UNINITIALIZED) throw firstError;
const iteratorKey = Symbol();
iteratorState.set(iteratorKey, {
__hasPolled: false,
publishQueue: []
});
try {
while (true) {
const state = iteratorState.get(iteratorKey);
if (!state) throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);
if (state.__hasPolled) throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE);
const publishQueue = state.publishQueue;
try {
if (publishQueue.length) {
state.publishQueue = [];
for (const item of publishQueue) if (item.__type === 0) yield item.data;
else throw item.err;
} else yield await new Promise((resolve, reject) => {
iteratorState.set(iteratorKey, {
__hasPolled: true,
onData: resolve,
onError: reject
});
});
} catch (e) {
if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) return;
else throw e;
}
}
} finally {
iteratorState.delete(iteratorKey);
}
} };
}
function getDataPublisherFromEventEmitter(eventEmitter) {
return { on(channelName, subscriber, options) {
function innerListener(ev) {
if (ev instanceof CustomEvent) {
const data = ev.detail;
subscriber(data);
} else subscriber();
}
eventEmitter.addEventListener(channelName, innerListener, options);
return () => {
eventEmitter.removeEventListener(channelName, innerListener);
};
} };
}
function demultiplexDataPublisher(publisher, sourceChannelName, messageTransformer) {
let innerPublisherState;
const eventTarget = new t$1();
const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);
return {
...demultiplexedDataPublisher,
on(channelName, subscriber, options) {
if (!innerPublisherState) innerPublisherState = {
dispose: publisher.on(sourceChannelName, (sourceMessage) => {
const transformResult = messageTransformer(sourceMessage);
if (!transformResult) return;
const [destinationChannelName, message] = transformResult;
eventTarget.dispatchEvent(new CustomEvent(destinationChannelName, { detail: message }));
}),
numSubscribers: 0
};
innerPublisherState.numSubscribers++;
const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);
let isActive = true;
function handleUnsubscribe() {
if (!isActive) return;
isActive = false;
options?.signal.removeEventListener("abort", handleUnsubscribe);
innerPublisherState.numSubscribers--;
if (innerPublisherState.numSubscribers === 0) {
innerPublisherState.dispose();
innerPublisherState = void 0;
}
unsubscribe();
}
options?.signal.addEventListener("abort", handleUnsubscribe);
return handleUnsubscribe;
}
};
}
var IDLE_STATE2 = Object.freeze({
data: void 0,
error: void 0,
status: "idle"
});
function createReactiveStoreFromDataPublisherFactory({ createDataPublisher, dataChannelName, errorChannelName }) {
let currentState = IDLE_STATE2;
let currentInnerController;
const subscribers = /* @__PURE__ */ new Set();
function notify() {
subscribers.forEach((cb) => cb());
}
function setState(next) {
if (currentState.status === next.status && currentState.data === next.data && currentState.error === next.error) return;
currentState = next;
notify();
}
function performConnect(callerSignal) {
currentInnerController?.abort();
if (callerSignal?.aborted) {
setState({
data: currentState.data,
error: callerSignal.reason,
status: "error"
});
return;
}
setState({
data: currentState.data,
error: currentState.error,
status: "loading"
});
const innerController = new o$4();
currentInnerController = innerController;
const signal = callerSignal ? AbortSignal.any([innerController.signal, callerSignal]) : innerController.signal;
if (callerSignal) callerSignal.addEventListener("abort", () => {
if (innerController.signal.aborted) return;
setState({
data: currentState.data,
error: callerSignal.reason,
status: "error"
});
innerController.abort(callerSignal.reason);
}, { signal: innerController.signal });
createDataPublisher(signal).then((publisher) => {
if (signal.aborted) return;
publisher.on(dataChannelName, (data) => {
setState({
data,
error: void 0,
status: "loaded"
});
}, { signal });
publisher.on(errorChannelName, (err) => {
if (currentState.status === "error") return;
setState({
data: currentState.data,
error: err,
status: "error"
});
innerController.abort(err);
}, { signal });
}, (err) => {
if (signal.aborted) return;
setState({
data: currentState.data,
error: err,
status: "error"
});
innerController.abort(err);
});
}
function performReset() {
currentInnerController?.abort();
currentInnerController = void 0;
setState(IDLE_STATE2);
}
return {
connect() {
performConnect(void 0);
},
getState() {
return currentState;
},
reset: performReset,
subscribe(callback) {
subscribers.add(callback);
return () => {
subscribers.delete(callback);
};
},
withSignal(signal) {
return { connect() {
performConnect(signal);
} };
}
};
}
// ../../node_modules/.pnpm/@solana+rpc-spec@8.6.0_typescript@5.9.3/node_modules/@solana/rpc-spec/dist/index.browser.mjs
function createRpc(rpcConfig) {
return makeProxy(rpcConfig);
}
function makeProxy(rpcConfig) {
return new Proxy(rpcConfig.api, {
defineProperty() {
return false;
},
deleteProperty() {
return false;
},
get(target, p, receiver) {
if (isNonRpcPropertyName(p)) return getNonRpcPropertyValue(p, receiver);
return function(...rawParams) {
const methodName = p.toString();
const getApiPlan = Reflect.get(target, methodName, receiver);
if (!getApiPlan) throw new SolanaError(SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, {
method: methodName,
params: rawParams
});
return createPendingRpcRequest(rpcConfig, getApiPlan(...rawParams));
};
}
});
}
function createPendingRpcRequest({ transport }, plan) {
return {
reactiveStore() {
return createReactiveActionStore((signal) => plan.execute({
signal,
transport
}));
},
async send(options) {
return await plan.execute({
signal: options?.abortSignal,
transport
});
}
};
}
function createJsonRpcApi(config) {
return new Proxy({}, {
defineProperty() {
return false;
},
deleteProperty() {
return false;
},
get(...args) {
const [_, p] = args;
if (isNonRpcPropertyName(p)) return getNonRpcPropertyValue(p, args[2]);
const methodName = p.toString();
return function(...rawParams) {
const rawRequest = Object.freeze({
methodName,
params: rawParams
});
const request = config?.requestTransformer ? config?.requestTransformer(rawRequest) : rawRequest;
return Object.freeze({ execute: async ({ signal, transport }) => {
const response = await transport({
payload: createRpcMessage(request),
signal
});
if (!config?.responseTransformer) return response;
return config.responseTransformer(response, request);
} });
};
}
});
}
// ../../node_modules/.pnpm/@solana+rpc-transformers@8.6.0_typescript@5.9.3/node_modules/@solana/rpc-transformers/dist/index.browser.mjs
function applyDefaultCommitment({ commitmentPropertyName, params, optionsObjectPositionInParams, overrideCommitment }) {
const paramInTargetPosition = params[optionsObjectPositionInParams];
if (paramInTargetPosition === void 0 || paramInTargetPosition && typeof paramInTargetPosition === "object" && !Array.isArray(paramInTargetPosition)) {
if (paramInTargetPosition && commitmentPropertyName in paramInTargetPosition) {
if (!paramInTargetPosition[commitmentPropertyName] || paramInTargetPosition[commitmentPropertyName] === "finalized") {
const nextParams = [...params];
const { [commitmentPropertyName]: _, ...rest } = paramInTargetPosition;
if (Object.keys(rest).length > 0) nextParams[optionsObjectPositionInParams] = rest;
else if (optionsObjectPositionInParams === nextParams.length - 1) nextParams.length--;
else nextParams[optionsObjectPositionInParams] = void 0;
return nextParams;
}
} else if (overrideCommitment !== "finalized") {
const nextParams = [...params];
nextParams[optionsObjectPositionInParams] = {
...paramInTargetPosition,
[commitmentPropertyName]: overrideCommitment
};
return nextParams;
}
}
return params;
}
function getDefaultCommitmentRequestTransformer({ defaultCommitment, optionsObjectPositionByMethod }) {
return (request) => {
const { params, methodName } = request;
if (!Array.isArray(params)) return request;
const optionsObjectPositionInParams = optionsObjectPositionByMethod[methodName];
if (optionsObjectPositionInParams == null) return request;
return Object.freeze({
methodName,
params: applyDefaultCommitment({
commitmentPropertyName: methodName === "sendTransaction" ? "preflightCommitment" : "commitment",
optionsObjectPositionInParams,
overrideCommitment: defaultCommitment,
params
})
});
};
}
function getIntegerOverflowNodeVisitor(onIntegerOverflow) {
return (value, { keyPath }) => {
if (typeof value === "bigint") {
if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) onIntegerOverflow(keyPath, value);
}
return value;
};
}
var KEYPATH_WILDCARD = {};
function getTreeWalker(visitors) {
return function traverse(node, state) {
if (Array.isArray(node)) return node.map((element, ii) => {
return traverse(element, {
...state,
keyPath: [...state.keyPath, ii]
});
});
else if (typeof node === "object" && node !== null) {
const out = {};
for (const propName in node) {
if (!Object.prototype.hasOwnProperty.call(node, propName)) continue;
const nextState = {
...state,
keyPath: [...state.keyPath, propName]
};
out[propName] = traverse(node[propName], nextState);
}
return out;
} else return visitors.reduce((acc, visitNode) => visitNode(acc, state), node);
};
}
function getTreeWalkerRequestTransformer(visitors, initialState) {
return (request) => {
const traverse = getTreeWalker(visitors);
return Object.freeze({
...request,
params: traverse(request.params, initialState)
});
};
}
function getTreeWalkerResponseTransformer(visitors, initialState) {
return (json) => getTreeWalker(visitors)(json, initialState);
}
function getIntegerOverflowRequestTransformer(onIntegerOverflow) {
return (request) => {
return getTreeWalkerRequestTransformer([getIntegerOverflowNodeVisitor((...args) => onIntegerOverflow(request, ...args))], { keyPath: [] })(request);
};
}
var OPTIONS_OBJECT_POSITION_BY_METHOD = {
accountNotifications: 1,
blockNotifications: 1,
getAccountInfo: 1,
getBalance: 1,
getBlock: 1,
getBlockHeight: 0,
getBlockProduction: 0,
getBlocks: 2,
getBlocksWithLimit: 2,
getEpochInfo: 0,
getFeeForMessage: 1,
getInflationGovernor: 0,
getInflationReward: 1,
getLargestAccounts: 0,
getLatestBlockhash: 0,
getLeaderSchedule: 1,
getMinimumBalanceForRentExemption: 1,
getMultipleAccounts: 1,
getProgramAccounts: 1,
getSignaturesForAddress: 1,
getSlot: 0,
getSlotLeader: 0,
getStakeMinimumDelegation: 0,
getSupply: 0,
getTokenAccountBalance: 1,
getTokenAccountsByDelegate: 2,
getTokenAccountsByOwner: 2,
getTokenLargestAccounts: 1,
getTokenSupply: 1,
getTransaction: 1,
getTransactionCount: 0,
getVoteAccounts: 0,
isBlockhashValid: 1,
logsNotifications: 1,
programNotifications: 1,
requestAirdrop: 2,
sendTransaction: 1,
signatureNotifications: 1,
simulateTransaction: 1
};
function getDefaultRequestTransformerForSolanaRpc(config) {
const handleIntegerOverflow = config?.onIntegerOverflow;
return (request) => {
return pipe(request, handleIntegerOverflow ? getIntegerOverflowRequestTransformer(handleIntegerOverflow) : (r) => r, getDefaultCommitmentRequestTransformer({
defaultCommitment: config?.defaultCommitment,
optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD
}));
};
}
function getBigIntUpcastVisitor(allowedNumericKeyPaths) {
return function upcastNodeToBigIntIfNumber(value, { keyPath }) {
if (!(typeof value === "number" && Number.isInteger(value) || typeof value === "bigint")) return value;
if (keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths)) return Number(value);
else return BigInt(value);
};
}
function keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths) {
return allowedNumericKeyPaths.some((prohibitedKeyPath) => {
if (prohibitedKeyPath.length !== keyPath.length) return false;
for (let ii = keyPath.length - 1; ii >= 0; ii--) {
const keyPathPart = keyPath[ii];
const prohibitedKeyPathPart = prohibitedKeyPath[ii];
if (prohibitedKeyPathPart !== keyPathPart && (prohibitedKeyPathPart !== KEYPATH_WILDCARD || typeof keyPathPart !== "number")) return false;
}
return true;
});
}
function getBigIntUpcastResponseTransformer(allowedNumericKeyPaths) {
return getTreeWalkerResponseTransformer([getBigIntUpcastVisitor(allowedNumericKeyPaths)], { keyPath: [] });
}
function getResultResponseTransformer() {
return (json) => json.result;
}
var jsonParsedTokenAccountsConfigs = [
[
"data",
"parsed",
"info",
"tokenAmount",
"decimals"
],
[
"data",
"parsed",
"info",
"tokenAmount",
"uiAmount"
],
[
"data",
"parsed",
"info",
"rentExemptReserve",
"decimals"
],
[
"data",
"parsed",
"info",
"rentExemptReserve",
"uiAmount"
],
[
"data",
"parsed",
"info",
"delegatedAmount",
"decimals"
],
[
"data",
"parsed",
"info",
"delegatedAmount",
"uiAmount"
],
[
"data",
"parsed",
"info",
"extensions",
KEYPATH_WILDCARD,
"state",
"olderTransferFee",
"transferFeeBasisPoints"
],
[
"data",
"parsed",
"info",
"extensions",
KEYPATH_WILDCARD,
"state",
"newerTransferFee",
"transferFeeBasisPoints"
],
[
"data",
"parsed",
"info",
"extensions",
KEYPATH_WILDCARD,
"state",
"preUpdateAverageRate"
],
[
"data",
"parsed",
"info",
"extensions",
KEYPATH_WILDCARD,
"state",
"currentRate"
]
];
var jsonParsedAccountsConfigs = [
...jsonParsedTokenAccountsConfigs,
[
"data",
"parsed",
"info",
"lastExtendedSlotStartIndex"
],
[
"data",
"parsed",
"info",
"slashPenalty"
],
[
"data",
"parsed",
"info",
"warmupCooldownRate"
],
[
"data",
"parsed",
"info",
"decimals"
],
[
"data",
"parsed",
"info",
"numRequiredSigners"
],
[
"data",
"parsed",
"info",
"numValidSigners"
],
[
"data",
"parsed",
"info",
"stake",
"delegation",
"warmupCooldownRate"
],
[
"data",
"parsed",
"info",
"exemptionThreshold"
],
[
"data",
"parsed",
"info",
"burnPercent"
],
[
"data",
"parsed",
"info",
"blockRevenueCommissionBps"
],
[
"data",
"parsed",
"info",
"commission"
],
[
"data",
"parsed",
"info",
"inflationRewardsCommissionBps"
],
[
"data",
"parsed",
"info",
"votes",
KEYPATH_WILDCARD,
"confirmationCount"
],
[
"data",
"parsed",
"info",
"votes",
KEYPATH_WILDCARD,
"latency"
]
];
var innerInstructionsConfigs = [
["index"],
[
"instructions",
KEYPATH_WILDCARD,
"accounts",
KEYPATH_WILDCARD
],
[
"instructions",
KEYPATH_WILDCARD,
"programIdIndex"
],
[
"instructions",
KEYPATH_WILDCARD,
"stackHeight"
]
];
var tokenBalancesConfigs = [
["accountIndex"],
["uiTokenAmount", "decimals"],
["uiTokenAmount", "uiAmount"]
];
var messageConfig = [
[
"addressTableLookups",
KEYPATH_WILDCARD,
"writableIndexes",
KEYPATH_WILDCARD
],
[
"addressTableLookups",
KEYPATH_WILDCARD,
"readonlyIndexes",
KEYPATH_WILDCARD
],
["header", "numReadonlySignedAccounts"],
["header", "numReadonlyUnsignedAccounts"],
["header", "numRequiredSignatures"],
[
"instructions",
KEYPATH_WILDCARD,
"accounts",
KEYPATH_WILDCARD
],
[
"instructions",
KEYPATH_WILDCARD,
"programIdIndex"
],
[
"instructions",
KEYPATH_WILDCARD,
"stackHeight"
],
["transactionConfig", "computeUnitLimit"],
["transactionConfig", "heapSize"],
["transactionConfig", "loadedAccountsDataSizeLimit"]
];
function getSimulateTransactionAllowedNumericKeypaths() {
return [
["loadedAccountsDataSize"],
...jsonParsedAccountsConfigs.map((c) => [
"accounts",
KEYPATH_WILDCARD,
...c
]),
...innerInstructionsConfigs.map((c) => [
"innerInstructions",
KEYPATH_WILDCARD,
...c
])
];
}
function getThrowSolanaErrorResponseTransformer() {
return (json, request) => {
const jsonRpcResponse = json;
if ("error" in jsonRpcResponse) {
const { error } = jsonRpcResponse;
if (error && typeof error === "object" && "code" in error && (error.code === -32002 || error.code === -32002n) && "data" in error && error.data) {
const transformedData = getTreeWalkerResponseTransformer([getBigIntUpcastVisitor(getSimulateTransactionAllowedNumericKeypaths())], { keyPath: [] })(error.data, request);
throw getSolanaErrorFromJsonRpcError({
...error,
data: transformedData
});
}
throw getSolanaErrorFromJsonRpcError(jsonRpcResponse.error);
}
return jsonRpcResponse;
};
}
function getDefaultResponseTransformerForSolanaRpc(config) {
return (response, request) => {
const methodName = request.methodName;
const keyPaths = config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : void 0;
return pipe(response, (r) => getThrowSolanaErrorResponseTransformer()(r, request), (r) => getResultResponseTransformer()(r, request), (r) => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request));
};
}
function toAllowedNumericMethodName(methodName) {
if (methodName.endsWith("Subscribe")) return `${methodName.slice(0, -9)}Notifications`;
if (methodName.endsWith("Notification") && !methodName.endsWith("Notifications")) return `${methodName}s`;
return methodName;
}
function getDefaultResponseTransformerForSolanaRpcSubscriptions(config) {
return (response, request) => {
const methodName = toAllowedNumericMethodName(request.methodName);
const keyPaths = config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : void 0;
return pipe(response, (r) => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request));
};
}
// ../../node_modules/.pnpm/@solana+rpc-api@8.6.0_typescript@5.9.3/node_modules/@solana/rpc-api/dist/index.browser.mjs
function createSolanaRpcApi(config) {
return createJsonRpcApi({
requestTransformer: getDefaultRequestTransformerForSolanaRpc(config),
responseTransformer: getDefaultResponseTransformerForSolanaRpc({ allowedNumericKeyPaths: getAllowedNumericKeypaths$1() })
});
}
var memoizedKeypaths$1;
function getAllowedNumericKeypaths$1() {
if (!memoizedKeypaths$1) memoizedKeypaths$1 = {
getAccountInfo: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
getAgGenesisCert: [
[
"block",
"blockId",
KEYPATH_WILDCARD
],
[
"signature",
"bitmap",
KEYPATH_WILDCARD
],
[
"signature",
"signature",
KEYPATH_WILDCARD
]
],
getBlock: [
...tokenBalancesConfigs.flatMap((c) => [[
"transactions",
KEYPATH_WILDCARD,
"meta",
"preTokenBalances",
KEYPATH_WILDCARD,
...c
], [
"transactions",
KEYPATH_WILDCARD,
"meta",
"postTokenBalances",
KEYPATH_WILDCARD,
...c
]]),
[
"transactions",
KEYPATH_WILDCARD,
"meta",
"rewards",
KEYPATH_WILDCARD,
"commission"
],
...innerInstructionsConfigs.map((c) => [
"transactions",
KEYPATH_WILDCARD,
"meta",
"innerInstructions",
KEYPATH_WILDCARD,
...c
]),
...messageConfig.map((c) => [
"transactions",
KEYPATH_WILDCARD,
"transaction",
"message",
...c
]),
[
"transactions",
KEYPATH_WILDCARD,
"version"
],
[
"rewards",
KEYPATH_WILDCARD,
"commission"
]
],
getClusterNodes: [[KEYPATH_WILDCARD, "featureSet"], [KEYPATH_WILDCARD, "shredVersion"]],
getInflationGovernor: [
["initial"],
["foundation"],
["foundationTerm"],
["taper"],
["terminal"]
],
getInflationRate: [
["foundation"],
["total"],
["validator"]
],
getInflationReward: [[KEYPATH_WILDCARD, "commission"]],
getMultipleAccounts: jsonParsedAccountsConfigs.map((c) => [
"value",
KEYPATH_WILDCARD,
...c
]),
getProgramAccounts: jsonParsedAccountsConfigs.flatMap((c) => [[
"value",
KEYPATH_WILDCARD,
"account",
...c
], [
KEYPATH_WILDCARD,
"account",
...c
]]),
getRecentPerformanceSamples: [[KEYPATH_WILDCARD, "samplePeriodSecs"]],
getSignaturesForAddress: [[KEYPATH_WILDCARD, "transactionIndex"]],
getTokenAccountBalance: [["value", "decimals"], ["value", "uiAmount"]],
getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map((c) => [
"value",
KEYPATH_WILDCARD,
"account",
...c
]),
getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map((c) => [
"value",
KEYPATH_WILDCARD,
"account",
...c
]),
getTokenLargestAccounts: [[
"value",
KEYPATH_WILDCARD,
"decimals"
], [
"value",
KEYPATH_WILDCARD,
"uiAmount"
]],
getTokenSupply: [["value", "decimals"], ["value", "uiAmount"]],
getTransaction: [
...tokenBalancesConfigs.flatMap((c) => [[
"meta",
"preTokenBalances",
KEYPATH_WILDCARD,
...c
], [
"meta",
"postTokenBalances",
KEYPATH_WILDCARD,
...c
]]),
[
"meta",
"rewards",
KEYPATH_WILDCARD,
"commission"
],
...innerInstructionsConfigs.map((c) => [
"meta",
"innerInstructions",
KEYPATH_WILDCARD,
...c
]),
...messageConfig.map((c) => [
"transaction",
"message",
...c
]),
["version"]
],
getTransactionsForAddress: [
[
"data",
KEYPATH_WILDCARD,
"transactionIndex"
],
...tokenBalancesConfigs.flatMap((c) => [[
"data",
KEYPATH_WILDCARD,
"meta",
"preTokenBalances",
KEYPATH_WILDCARD,
...c
], [
"data",
KEYPATH_WILDCARD,
"meta",
"postTokenBalances",
KEYPATH_WILDCARD,
...c
]]),
[
"data",
KEYPATH_WILDCARD,
"meta",
"rewards",
KEYPATH_WILDCARD,
"commission"
],
...innerInstructionsConfigs.map((c) => [
"data",
KEYPATH_WILDCARD,
"meta",
"innerInstructions",
KEYPATH_WILDCARD,
...c
]),
...messageConfig.map((c) => [
"data",
KEYPATH_WILDCARD,
"transaction",
"message",
...c
]),
[
"data",
KEYPATH_WILDCARD,
"version"
]
],
getVersion: [["feature-set"]],
getVoteAccounts: [
[
"current",
KEYPATH_WILDCARD,
"commission"
],
[
"current",
KEYPATH_WILDCARD,
"inflationRewardsCommissionBps"
],
[
"delinquent",
KEYPATH_WILDCARD,
"commission"
],
[
"delinquent",
KEYPATH_WILDCARD,
"inflationRewardsCommissionBps"
]
],
simulateTransaction: [
["value", "loadedAccountsDataSize"],
...jsonParsedAccountsConfigs.map((c) => [
"value",
"accounts",
KEYPATH_WILDCARD,
...c
]),
...innerInstructionsConfigs.map((c) => [
"value",
"innerInstructions",
KEYPATH_WILDCARD,
...c
]),
...tokenBalancesConfigs.flatMap((c) => [[
"value",
"preTokenBalances",
KEYPATH_WILDCARD,
...c
], [
"value",
"postTokenBalances",
KEYPATH_WILDCARD,
...c
]])
]
};
return memoizedKeypaths$1;
}
// ../../node_modules/.pnpm/@solana+fast-stable-stringify@8.6.0_typescript@5.9.3/node_modules/@solana/fast-stable-stringify/dist/index.browser.mjs
var objToString = Object.prototype.toString;
var objKeys = Object.keys || function(obj) {
const keys = [];
for (const name in obj) keys.push(name);
return keys;
};
function stringify(val, isArrayProp) {
let i, max, str, keys, key, propVal, toStr;
if (val === true) return "true";
if (val === false) return "false";
switch (typeof val) {
case "object": if (val === null) return null;
else if ("toJSON" in val && typeof val.toJSON === "function") return stringify(val.toJSON(), isArrayProp);
else {
toStr = objToString.call(val);
if (toStr === "[object Array]") {
str = "[";
max = val.length - 1;
for (i = 0; i < max; i++) str += stringify(val[i], true) + ",";
if (max > -1) str += stringify(val[i], true);
return str + "]";
} else if (toStr === "[object Object]") {
keys = objKeys(val).sort();
max = keys.length;
str = "";
i = 0;
while (i < max) {
key = keys[i];
propVal = stringify(val[key], false);
if (propVal !== void 0) {
if (str) str += ",";
str += JSON.stringify(key) + ":" + propVal;
}
i++;
}
return "{" + str + "}";
} else return JSON.stringify(val);
}
case "function":
case "undefined": return isArrayProp ? null : void 0;
case "bigint": return `${val.toString()}n`;
case "string": return JSON.stringify(val);
default: return isFinite(val) ? val : null;
}
}
function index_default(val) {
const returnVal = stringify(val, false);
if (returnVal !== void 0) return "" + returnVal;
}
// ../../node_modules/.pnpm/@solana+rpc@8.6.0_typescript@5.9.3/node_modules/@solana/rpc/dist/index.browser.mjs
function createSolanaJsonRpcIntegerOverflowError$1(methodName, keyPath, value) {
let argumentLabel = "";
if (typeof keyPath[0] === "number") {
const argPosition = keyPath[0] + 1;
const lastDigit = argPosition % 10;
const lastTwoDigits = argPosition % 100;
if (lastDigit == 1 && lastTwoDigits != 11) argumentLabel = argPosition + "st";
else if (lastDigit == 2 && lastTwoDigits != 12) argumentLabel = argPosition + "nd";
else if (lastDigit == 3 && lastTwoDigits != 13) argumentLabel = argPosition + "rd";
else argumentLabel = argPosition + "th";
} else argumentLabel = `\`${keyPath[0].toString()}\``;
const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : void 0;
const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {
argumentLabel,
keyPath,
methodName,
optionalPathLabel: path ? ` at path \`${path}\`` : "",
value,
...path !== void 0 ? { path } : void 0
});
safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError$1);
return error;
}
var DEFAULT_RPC_CONFIG = {
defaultCommitment: "confirmed",
onIntegerOverflow(request, keyPath, value) {
throw createSolanaJsonRpcIntegerOverflowError$1(request.methodName, keyPath, value);
}
};
globalThis.AbortController;
// ../../node_modules/.pnpm/@solana+rpc-subscriptions-spec@8.6.0_typescript@5.9.3/node_modules/@solana/rpc-subscriptions-spec/dist/index.browser.mjs
function createSubscriptionRpc(rpcConfig) {
return new Proxy(rpcConfig.api, {
defineProperty() {
return false;
},
deleteProperty() {
return false;
},
get(target, p, receiver) {
if (isNonRpcPropertyName(p)) return getNonRpcPropertyValue(p, receiver);
return function(...rawParams) {
const notificationName = p.toString();
const createRpcSubscriptionPlan = Reflect.get(target, notificationName, receiver);
if (!createRpcSubscriptionPlan) throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, { notificationName });
const subscriptionPlan = createRpcSubscriptionPlan(...rawParams);
return createPendingRpcSubscription(rpcConfig.transport, subscriptionPlan);
};
}
});
}
function createPendingRpcSubscription(transport, subscriptionsPlan) {
return {
reactiveStore() {
return createReactiveStoreFromDataPublisherFactory({
createDataPublisher(signal) {
return transport({
signal,
...subscriptionsPlan
});
},
dataChannelName: "notification",
errorChannelName: "error"
});
},
async subscribe({ abortSignal }) {
return createAsyncIterableFromDataPublisher({
abortSignal,
dataChannelName: "notification",
dataPublisher: await transport({
signal: abortSignal,
...subscriptionsPlan
}),
errorChannelName: "error"
});
}
};
}
function createRpcSubscriptionsApi(config) {
return new Proxy({}, {
defineProperty() {
return false;
},
deleteProperty() {
return false;
},
get(...args) {
const [_, p] = args;
if (isNonRpcPropertyName(p)) return getNonRpcPropertyValue(p, args[2]);
const methodName = p.toString();
return function(...params) {
const rawRequest = {
methodName,
params
};
const request = config.requestTransformer ? config.requestTransformer(rawRequest) : rawRequest;
return {
execute(planConfig) {
return config.planExecutor({
...planConfig,
request
});
},
request
};
};
}
});
}
function transformChannelInboundMessages(channel, transform) {
return Object.freeze({
...channel,
on(type, subscriber, options) {
if (type !== "message") return channel.on(type, subscriber, options);
return channel.on("message", (message) => subscriber(transform(message)), options);
}
});
}
function transformChannelOutboundMessages(channel, transform) {
return Object.freeze({
...channel,
send: (message) => channel.send(transform(message))
});
}
var o$2 = globalThis.AbortController;
function getApiMethodNameFromNotificationMethod(notificationMethod) {
if (notificationMethod.endsWith("Notification") && !notificationMethod.endsWith("Notifications")) return `${notificationMethod}s`;
return notificationMethod;
}
var subscriberCountBySubscriptionIdByChannel = /* @__PURE__ */ new WeakMap();
function decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) {
return augmentSubscriberCountAndReturnNewCount(-1, channel, subscriptionId);
}
function incrementSubscriberCount(channel, subscriptionId) {
augmentSubscriberCountAndReturnNewCount(1, channel, subscriptionId);
}
function getSubscriberCountBySubscriptionIdForChannel(channel) {
let subscriberCountBySubscriptionId = subscriberCountBySubscriptionIdByChannel.get(channel);
if (!subscriberCountBySubscriptionId) subscriberCountBySubscriptionIdByChannel.set(channel, subscriberCountBySubscriptionId = {});
return subscriberCountBySubscriptionId;
}
function augmentSubscriberCountAndReturnNewCount(amount, channel, subscriptionId) {
if (subscriptionId === void 0) return;
const subscriberCountBySubscriptionId = getSubscriberCountBySubscriptionIdForChannel(channel);
if (!subscriberCountBySubscriptionId[subscriptionId] && amount > 0) subscriberCountBySubscriptionId[subscriptionId] = 0;
const newCount = amount + subscriberCountBySubscriptionId[subscriptionId];
if (newCount <= 0) delete subscriberCountBySubscriptionId[subscriptionId];
else subscriberCountBySubscriptionId[subscriptionId] = newCount;
return newCount;
}
var cache = /* @__PURE__ */ new WeakMap();
function getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(channel, subscribeRequest, responseTransformer) {
let publisherByResponseTransformer = cache.get(channel);
if (!publisherByResponseTransformer) cache.set(channel, publisherByResponseTransformer = /* @__PURE__ */ new WeakMap());
const responseTransformerKey = responseTransformer ?? channel;
let publisher = publisherByResponseTransformer.get(responseTransformerKey);
if (!publisher) publisherByResponseTransformer.set(responseTransformerKey, publisher = demultiplexDataPublisher(channel, "message", (rawMessage) => {
const message = rawMessage;
if (!("method" in message)) return;
const transformedNotification = responseTransformer ? responseTransformer(message.params.result, {
methodName: getApiMethodNameFromNotificationMethod(message.method),
params: subscribeRequest.params
}) : message.params.result;
return [`notification:${message.params.subscription}`, transformedNotification];
}));
return publisher;
}
async function executeRpcPubSubSubscriptionPlan({ channel, responseTransformer, signal, subscribeRequest, unsubscribeMethodName }) {
let subscriptionId;
channel.on("error", () => {
subscriptionId = void 0;
subscriberCountBySubscriptionIdByChannel.delete(channel);
}, { signal });
const abortPromise = new Promise((_, reject) => {
function handleAbort() {
if (decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) === 0) {
const unsubscribePayload = createRpcMessage({
methodName: unsubscribeMethodName,
params: [subscriptionId]
});
subscriptionId = void 0;
channel.send(unsubscribePayload).catch(() => {});
}
reject(this.reason);
}
if (signal.aborted) handleAbort.call(signal);
else signal.addEventListener("abort", handleAbort);
});
const subscribePayload = createRpcMessage(subscribeRequest);
await channel.send(subscribePayload);
subscriptionId = await safeRace([abortPromise, new Promise((resolve, reject) => {
const abortController = new o$2();
signal.addEventListener("abort", abortController.abort.bind(abortController));
const options = { signal: abortController.signal };
channel.on("error", (err) => {
abortController.abort();
reject(err);
}, options);
channel.on("message", (message) => {
if (message && typeof message === "object" && "id" in message && message.id === subscribePayload.id) {
abortController.abort();
if ("error" in message) reject(getSolanaErrorFromJsonRpcError(message.error));
else resolve(message.result);
}
}, options);
})]);
if (subscriptionId == null) throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID);
incrementSubscriberCount(channel, subscriptionId);
const notificationPublisher = getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(channel, subscribeRequest, responseTransformer);
const notificationKey = `notification:${subscriptionId}`;
return { on(type, listener, options) {
switch (type) {
case "notification": return notificationPublisher.on(notificationKey, listener, options);
case "error": return channel.on("error", listener, options);
default: throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, {
channelName: type,
supportedChannelNames: ["notification", "error"]
});
}
} };
}
// ../../node_modules/.pnpm/@solana+rpc-subscriptions-api@8.6.0_typescript@5.9.3/node_modules/@solana/rpc-subscriptions-api/dist/index.browser.mjs
function createSolanaRpcSubscriptionsApi_INTERNAL(config) {
const requestTransformer = getDefaultRequestTransformerForSolanaRpc(config);
const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({ allowedNumericKeyPaths: getAllowedNumericKeypaths() });
return createRpcSubscriptionsApi({
planExecutor({ request, ...rest }) {
return executeRpcPubSubSubscriptionPlan({
...rest,
responseTransformer,
subscribeRequest: {
...request,
methodName: request.methodName.replace(/Notifications$/, "Subscribe")
},
unsubscribeMethodName: request.methodName.replace(/Notifications$/, "Unsubscribe")
});
},
requestTransformer
});
}
function createSolanaRpcSubscriptionsApi(config) {
return createSolanaRpcSubscriptionsApi_INTERNAL(config);
}
var memoizedKeypaths;
function getAllowedNumericKeypaths() {
if (!memoizedKeypaths) memoizedKeypaths = {
accountNotifications: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
blockNotifications: [
...tokenBalancesConfigs.flatMap((c) => [[
"value",
"block",
"transactions",
KEYPATH_WILDCARD,
"meta",
"preTokenBalances",
KEYPATH_WILDCARD,
...c
], [
"value",
"block",
"transactions",
KEYPATH_WILDCARD,
"meta",
"postTokenBalances",
KEYPATH_WILDCARD,
...c
]]),
[
"value",
"block",
"transactions",
KEYPATH_WILDCARD,
"meta",
"rewards",
KEYPATH_WILDCARD,
"commission"
],
...innerInstructionsConfigs.map((c) => [
"value",
"block",
"transactions",
KEYPATH_WILDCARD,
"meta",
"innerInstructions",
KEYPATH_WILDCARD,
...c
]),
...messageConfig.map((c) => [
"value",
"block",
"transactions",
KEYPATH_WILDCARD,
"transaction",
"message",
...c
]),
[
"value",
"block",
"transactions",
KEYPATH_WILDCARD,
"version"
],
[
"value",
"block",
"rewards",
KEYPATH_WILDCARD,
"commission"
]
],
programNotifications: jsonParsedAccountsConfigs.flatMap((c) => [[
"value",
KEYPATH_WILDCARD,
"account",
...c
], [
KEYPATH_WILDCARD,
"account",
...c
]])
};
return memoizedKeypaths;
}
// ../../node_modules/.pnpm/@solana+rpc-subscriptions-channel-websocket@8.6.0_bufferutil@4.0.8_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@solana/rpc-subscriptions-channel-websocket/dist/index.browser.mjs
var t = globalThis.EventTarget;
var e = globalThis.WebSocket;
var NORMAL_CLOSURE_CODE = 1e3;
function createWebSocketChannel({ sendBufferHighWatermark, signal, url }) {
if (signal.aborted) return Promise.reject(signal.reason);
let bufferDrainWatcher;
let hasConnected = false;
const listenerRemovers = /* @__PURE__ */ new Set();
function cleanupListeners() {
listenerRemovers.forEach((r) => {
r();
});
listenerRemovers.clear();
}
function handleAbort() {
cleanupListeners();
if (!hasConnected) rejectOpen(signal.reason);
if (webSocket.readyState !== e.CLOSED && webSocket.readyState !== e.CLOSING) webSocket.close(NORMAL_CLOSURE_CODE);
}
function handleClose(ev) {
cleanupListeners();
bufferDrainWatcher?.onCancel();
signal.removeEventListener("abort", handleAbort);
webSocket.removeEventListener("close", handleClose);
webSocket.removeEventListener("error", handleError);
webSocket.removeEventListener("message", handleMessage);
webSocket.removeEventListener("open", handleOpen);
if (!signal.aborted && !(ev.wasClean && ev.code === NORMAL_CLOSURE_CODE)) eventTarget.dispatchEvent(new CustomEvent("error", { detail: new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, { cause: ev }) }));
}
function handleError(ev) {
if (signal.aborted) return;
if (!hasConnected) {
const failedToConnectError = new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, { errorEvent: ev });
rejectOpen(failedToConnectError);
eventTarget.dispatchEvent(new CustomEvent("error", { detail: failedToConnectError }));
}
}
function handleMessage(ev) {
if (signal.aborted) return;
eventTarget.dispatchEvent(new CustomEvent("message", { detail: ev.data }));
}
const eventTarget = new t();
const dataPublisher = getDataPublisherFromEventEmitter(eventTarget);
function handleOpen() {
hasConnected = true;
resolveOpen({
...dataPublisher,
async send(message) {
if (webSocket.readyState !== e.OPEN) throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED);
if (!bufferDrainWatcher && webSocket.bufferedAmount > sendBufferHighWatermark) {
let onCancel;
const promise = new Promise((resolve, reject) => {
const intervalId = setInterval(() => {
if (webSocket.readyState !== e.OPEN || !(webSocket.bufferedAmount > sendBufferHighWatermark)) {
clearInterval(intervalId);
bufferDrainWatcher = void 0;
resolve();
}
}, 16);
onCancel = () => {
bufferDrainWatcher = void 0;
clearInterval(intervalId);
reject(new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED));
};
});
bufferDrainWatcher = {
onCancel,
promise
};
}
if (bufferDrainWatcher) {
if (ArrayBuffer.isView(message) && !(message instanceof DataView)) {
const TypedArrayConstructor = message.constructor;
message = new TypedArrayConstructor(message);
}
await bufferDrainWatcher.promise;
}
webSocket.send(message);
}
});
}
const webSocket = new e(url);
signal.addEventListener("abort", handleAbort);
webSocket.addEventListener("close", handleClose);
webSocket.addEventListener("error", handleError);
webSocket.addEventListener("message", handleMessage);
webSocket.addEventListener("open", handleOpen);
let rejectOpen;
let resolveOpen;
return new Promise((resolve, reject) => {
rejectOpen = reject;
resolveOpen = resolve;
});
}
// ../../node_modules/.pnpm/@solana+rpc-subscriptions@8.6.0_bufferutil@4.0.8_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@solana/rpc-subscriptions/dist/index.browser.mjs
function createSolanaJsonRpcIntegerOverflowError(methodName, keyPath, value) {
let argumentLabel = "";
if (typeof keyPath[0] === "number") {
const argPosition = keyPath[0] + 1;
const lastDigit = argPosition % 10;
const lastTwoDigits = argPosition % 100;
if (lastDigit == 1 && lastTwoDigits != 11) argumentLabel = argPosition + "st";
else if (lastDigit == 2 && lastTwoDigits != 12) argumentLabel = argPosition + "nd";
else if (lastDigit == 3 && lastTwoDigits != 13) argumentLabel = argPosition + "rd";
else argumentLabel = argPosition + "th";
} else argumentLabel = `\`${keyPath[0].toString()}\``;
const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : void 0;
const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {
argumentLabel,
keyPath,
methodName,
optionalPathLabel: path ? ` at path \`${path}\`` : "",
value,
...path !== void 0 ? { path } : void 0
});
safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);
return error;
}
var DEFAULT_RPC_SUBSCRIPTIONS_CONFIG = {
defaultCommitment: "confirmed",
onIntegerOverflow(request, keyPath, value) {
throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);
}
};
var o$1 = globalThis.AbortController;
var PING_PAYLOAD = {
jsonrpc: "2.0",
method: "ping"
};
function getRpcSubscriptionsChannelWithAutoping({ abortSignal: callerAbortSignal, channel, intervalMs }) {
let intervalId;
function sendPing() {
channel.send(PING_PAYLOAD).catch((e) => {
if (isSolanaError(e, 8190003)) pingerAbortController.abort();
});
}
function restartPingTimer() {
clearInterval(intervalId);
intervalId = setInterval(sendPing, intervalMs);
}
const pingerAbortController = new o$1();
pingerAbortController.signal.addEventListener("abort", () => {
clearInterval(intervalId);
});
callerAbortSignal.addEventListener("abort", () => {
pingerAbortController.abort();
});
channel.on("error", () => {
pingerAbortController.abort();
}, { signal: pingerAbortController.signal });
channel.on("message", restartPingTimer, { signal: pingerAbortController.signal });
if (globalThis.navigator.onLine) restartPingTimer();
globalThis.addEventListener("offline", function handleOffline() {
clearInterval(intervalId);
}, { signal: pingerAbortController.signal });
globalThis.addEventListener("online", function handleOnline() {
sendPing();
restartPingTimer();
}, { signal: pingerAbortController.signal });
return {
...channel,
send(...args) {
if (!pingerAbortController.signal.aborted) restartPingTimer();
return channel.send(...args);
}
};
}
function createChannelPool() {
return {
entries: [],
freeChannelIndex: -1
};
}
function getChannelPoolingChannelCreator(createChannel, { maxSubscriptionsPerChannel, minChannels }) {
const pool = createChannelPool();
function recomputeFreeChannelIndex() {
if (pool.entries.length < minChannels) {
pool.freeChannelIndex = -1;
return;
}
let mostFreeChannel;
for (let ii = 0; ii < pool.entries.length; ii++) {
const nextPoolIndex = (pool.freeChannelIndex + ii + 2) % pool.entries.length;
const nextPoolEntry = pool.entries[nextPoolIndex];
if (nextPoolEntry.subscriptionCount < maxSubscriptionsPerChannel && (!mostFreeChannel || mostFreeChannel.subscriptionCount >= nextPoolEntry.subscriptionCount)) mostFreeChannel = {
poolIndex: nextPoolIndex,
subscriptionCount: nextPoolEntry.subscriptionCount
};
}
pool.freeChannelIndex = mostFreeChannel?.poolIndex ?? -1;
}
return function getExistingChannelWithMostCapacityOrCreateChannel({ abortSignal }) {
let poolEntry;
function destroyPoolEntry() {
const index = pool.entries.findIndex((entry) => entry === poolEntry);
if (index === -1) return;
pool.entries.splice(index, 1);
poolEntry.dispose();
recomputeFreeChannelIndex();
}
if (pool.freeChannelIndex === -1) {
const abortController = new o$1();
const newChannelPromise = createChannel({ abortSignal: abortController.signal });
newChannelPromise.then((newChannel) => {
newChannel.on("error", destroyPoolEntry, { signal: abortController.signal });
}).catch(destroyPoolEntry);
poolEntry = {
channel: newChannelPromise,
dispose() {
abortController.abort();
},
subscriptionCount: 0
};
pool.entries.push(poolEntry);
} else poolEntry = pool.entries[pool.freeChannelIndex];
poolEntry.subscriptionCount++;
abortSignal.addEventListener("abort", function destroyConsumer() {
poolEntry.subscriptionCount--;
if (poolEntry.subscriptionCount === 0) destroyPoolEntry();
else if (pool.freeChannelIndex !== -1) {
pool.freeChannelIndex--;
recomputeFreeChannelIndex();
}
});
recomputeFreeChannelIndex();
return poolEntry.channel;
};
}
function getRpcSubscriptionsChannelWithBigIntJSONSerialization(channel) {
return pipe(channel, (c) => transformChannelInboundMessages(c, parseJsonWithBigInts), (c) => transformChannelOutboundMessages(c, stringifyJsonWithBigInts));
}
function createDefaultSolanaRpcSubscriptionsChannelCreator(config) {
return createDefaultRpcSubscriptionsChannelCreatorImpl({
...config,
jsonSerializer: getRpcSubscriptionsChannelWithBigIntJSONSerialization
});
}
function createDefaultRpcSubscriptionsChannelCreatorImpl(config) {
if (/^wss?:/i.test(config.url) === false) {
const protocolMatch = config.url.match(/^([^:]+):/);
throw new DOMException(protocolMatch ? `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${protocolMatch[1]}:' is not allowed.` : `Failed to construct 'WebSocket': The URL '${config.url}' is invalid.`);
}
const { intervalMs, ...rest } = config;
const createDefaultRpcSubscriptionsChannel = (({ abortSignal }) => {
return createWebSocketChannel({
...rest,
sendBufferHighWatermark: config.sendBufferHighWatermark ?? 131072,
signal: abortSignal
}).then(config.jsonSerializer).then((channel) => getRpcSubscriptionsChannelWithAutoping({
abortSignal,
channel,
intervalMs: intervalMs ?? 5e3
}));
});
return getChannelPoolingChannelCreator(createDefaultRpcSubscriptionsChannel, {
maxSubscriptionsPerChannel: config.maxSubscriptionsPerChannel ?? 100,
minChannels: config.minChannels ?? 1
});
}
function getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport) {
const cache = /* @__PURE__ */ new Map();
return function rpcSubscriptionsTransportWithSubscriptionCoalescing(config) {
const { request, signal } = config;
const subscriptionConfigurationHash = index_default([request.methodName, request.params]);
let cachedDataPublisherPromise = cache.get(subscriptionConfigurationHash);
if (!cachedDataPublisherPromise) {
const abortController = new o$1();
const dataPublisherPromise = transport({
...config,
signal: abortController.signal
});
dataPublisherPromise.then((dataPublisher) => {
dataPublisher.on("error", () => {
cache.delete(subscriptionConfigurationHash);
abortController.abort();
}, { signal: abortController.signal });
}).catch(() => {});
cache.set(subscriptionConfigurationHash, cachedDataPublisherPromise = {
abortController,
dataPublisherPromise,
numSubscribers: 0
});
}
cachedDataPublisherPromise.numSubscribers++;
signal.addEventListener("abort", () => {
cachedDataPublisherPromise.numSubscribers--;
if (cachedDataPublisherPromise.numSubscribers === 0) queueMicrotask(() => {
if (cachedDataPublisherPromise.numSubscribers === 0) {
cache.delete(subscriptionConfigurationHash);
cachedDataPublisherPromise.abortController.abort();
}
});
}, { signal: cachedDataPublisherPromise.abortController.signal });
return cachedDataPublisherPromise.dataPublisherPromise;
};
}
function createDefaultRpcSubscriptionsTransport({ createChannel }) {
return pipe(createRpcSubscriptionsTransportFromChannelCreator(createChannel), (transport) => getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport));
}
function createRpcSubscriptionsTransportFromChannelCreator(createChannel) {
return (async ({ execute, signal }) => {
return await execute({
channel: await createChannel({ abortSignal: signal }),
signal
});
});
}
// ../../node_modules/.pnpm/@solana+signers@8.6.0_typescript@5.9.3/node_modules/@solana/signers/dist/index.browser.mjs
function isTransactionModifyingSigner(value) {
return "modifyAndSignTransactions" in value && typeof value.modifyAndSignTransactions === "function";
}
function isTransactionPartialSigner(value) {
return "signTransactions" in value && typeof value.signTransactions === "function";
}
function assertIsTransactionPartialSigner(value) {
if (!isTransactionPartialSigner(value)) throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, { address: value.address });
}
function isTransactionSendingSigner(value) {
return "signAndSendTransactions" in value && typeof value.signAndSendTransactions === "function";
}
function isTransactionSigner(value) {
return isTransactionPartialSigner(value) || isTransactionModifyingSigner(value) || isTransactionSendingSigner(value);
}
async function createSignerFromKeyPair(keyPair) {
const address = await getAddressFromPublicKey(keyPair.publicKey);
return Object.freeze({
address,
keyPair,
signMessages: (messages) => Promise.all(messages.map(async (message) => Object.freeze({ [address]: await signBytes(keyPair.privateKey, message.content) }))),
signTransactions: (transactions) => Promise.all(transactions.map(async (transaction) => {
const signedTransaction = await partiallySignTransaction([keyPair], transaction);
return Object.freeze({ [address]: signedTransaction.signatures[address] });
}))
});
}
async function createKeyPairSignerFromBytes(bytes, extractable) {
return await createSignerFromKeyPair(await createKeyPairFromBytes(bytes, extractable));
}
async function createKeyPairSignerFromPrivateKeyBytes(bytes, extractable) {
return await createSignerFromKeyPair(await createKeyPairFromPrivateKeyBytes(bytes, extractable));
}
function createNoopSigner(address) {
return Object.freeze({
address,
signMessages: (messages) => Promise.resolve(messages.map(() => Object.freeze({}))),
signTransactions: (transactions) => Promise.resolve(transactions.map(() => Object.freeze({})))
});
}
globalThis.TextEncoder;
// src/utils/assert.ts
function assert_default(condition, message) {
if (!condition) throw new Error(message || "Assertion failed");
}
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/crypto.js
const crypto$1 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
/**
* Utilities for hex, bytes, CSPRNG.
* @module
*/
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
function isBytes(a) {
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
/** Asserts something is positive integer. */
function anumber(n) {
if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n);
}
/** Asserts something is Uint8Array. */
function abytes(b, ...lengths) {
if (!isBytes(b)) throw new Error("Uint8Array expected");
if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
}
/** Asserts something is hash */
function ahash(h) {
if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher");
anumber(h.outputLen);
anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
function aexists(instance, checkFinished = true) {
if (instance.destroyed) throw new Error("Hash instance has been destroyed");
if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
}
/** Asserts output is properly-sized byte array */
function aoutput(out, instance) {
abytes(out);
const min = instance.outputLen;
if (out.length < min) throw new Error("digestInto() expects output buffer of length at least " + min);
}
/** Cast u8 / u16 / u32 to u32. */
function u32(arr) {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
function clean(...arrays) {
for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
}
/** Create DataView of an array for easy byte-level manipulation. */
function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
function rotr(word, shift) {
return word << 32 - shift | word >>> shift;
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
/** The byte swap operation for uint32 */
function byteSwap(word) {
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
}
/** In place byte swap for Uint32Array */
function byteSwap32(arr) {
for (let i = 0; i < arr.length; i++) arr[i] = byteSwap(arr[i]);
return arr;
}
const swap32IfBE = isLE ? (u) => u : byteSwap32;
const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
/**
* Convert byte array to hex string. Uses built-in function, when available.
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
function bytesToHex(bytes) {
abytes(bytes);
if (hasHexBuiltin) return bytes.toHex();
let hex = "";
for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
return hex;
}
const asciis = {
_0: 48,
_9: 57,
A: 65,
F: 70,
a: 97,
f: 102
};
function asciiToBase16(ch) {
if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0;
if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10);
if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10);
}
/**
* Convert hex string to byte array. Uses built-in function, when available.
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
function hexToBytes(hex) {
if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
if (hasHexBuiltin) return Uint8Array.fromHex(hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === void 0 || n2 === void 0) {
const char = hex[hi] + hex[hi + 1];
throw new Error("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
/**
* Converts string to bytes using UTF8 encoding.
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
*/
function utf8ToBytes(str) {
if (typeof str !== "string") throw new Error("string expected");
return new Uint8Array(new TextEncoder().encode(str));
}
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
function toBytes(data) {
if (typeof data === "string") data = utf8ToBytes(data);
abytes(data);
return data;
}
/** Copies several Uint8Arrays into one. */
function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
/** For runtime check if class implements interface */
var Hash = class {};
/** Wraps hash function, creating an interface on top of it */
function createHasher(hashCons) {
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
function randomBytes(bytesLength = 32) {
if (crypto$1 && typeof crypto$1.getRandomValues === "function") return crypto$1.getRandomValues(new Uint8Array(bytesLength));
if (crypto$1 && typeof crypto$1.randomBytes === "function") return Uint8Array.from(crypto$1.randomBytes(bytesLength));
throw new Error("crypto.getRandomValues must be defined");
}
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
/**
* Internal Merkle-Damgard hash utils.
* @module
*/
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(4294967295);
const wh = Number(value >> _32n & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
function Chi(a, b, c) {
return a & b ^ ~a & c;
}
/** Majority function, true if any two inputs is true. */
function Maj(a, b, c) {
return a & b ^ a & c ^ b & c;
}
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
*/
var HashMD = class extends Hash {
constructor(blockLen, outputLen, padOffset, isLE) {
super();
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data) {
aexists(this);
data = toBytes(data);
abytes(data);
const { view, buffer, blockLen } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
const dataView = createView(data);
for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
aexists(this);
aoutput(out, this);
this.finished = true;
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
buffer[pos++] = 128;
clean(this.buffer.subarray(pos));
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++) buffer[i] = 0;
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = createView(out);
const len = this.outputLen;
if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
if (length % blockLen) to.buffer.set(buffer);
return to;
}
clone() {
return this._cloneInto();
}
};
/**
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
*/
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1779033703,
4089235720,
3144134277,
2227873595,
1013904242,
4271175723,
2773480762,
1595750129,
1359893119,
2917565137,
2600822924,
725511199,
528734635,
4215389547,
1541459225,
327033209
]);
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js
/**
* Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
* @todo re-check https://issues.chromium.org/issues/42212588
* @module
*/
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
if (le) return {
h: Number(n & U32_MASK64),
l: Number(n >> _32n & U32_MASK64)
};
return {
h: Number(n >> _32n & U32_MASK64) | 0,
l: Number(n & U32_MASK64) | 0
};
}
function split(lst, le = false) {
const len = lst.length;
let Ah = new Uint32Array(len);
let Al = new Uint32Array(len);
for (let i = 0; i < len; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => h << 32 - s | l >>> s;
const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
const rotlSH = (h, l, s) => h << s | l >>> 32 - s;
const rotlSL = (h, l, s) => l << s | h >>> 32 - s;
const rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
const rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return {
h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
l: l | 0
};
}
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
/**
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
* Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
* [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
* @module
*/
/**
* Round constants:
* First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
*/
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
1116352408,
1899447441,
3049323471,
3921009573,
961987163,
1508970993,
2453635748,
2870763221,
3624381080,
310598401,
607225278,
1426881987,
1925078388,
2162078206,
2614888103,
3248222580,
3835390401,
4022224774,
264347078,
604807628,
770255983,
1249150122,
1555081692,
1996064986,
2554220882,
2821834349,
2952996808,
3210313671,
3336571891,
3584528711,
113926993,
338241895,
666307205,
773529912,
1294757372,
1396182291,
1695183700,
1986661051,
2177026350,
2456956037,
2730485921,
2820302411,
3259730800,
3345764771,
3516065817,
3600352804,
4094571909,
275423344,
430227734,
506948616,
659060556,
883997877,
958139571,
1322822218,
1537002063,
1747873779,
1955562222,
2024104815,
2227730452,
2361852424,
2428436474,
2756734187,
3204031479,
3329325298
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
var SHA256 = class extends HashMD {
constructor(outputLen = 32) {
super(64, outputLen, 8, false);
this.A = SHA256_IV[0] | 0;
this.B = SHA256_IV[1] | 0;
this.C = SHA256_IV[2] | 0;
this.D = SHA256_IV[3] | 0;
this.E = SHA256_IV[4] | 0;
this.F = SHA256_IV[5] | 0;
this.G = SHA256_IV[6] | 0;
this.H = SHA256_IV[7] | 0;
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [
A,
B,
C,
D,
E,
F,
G,
H
];
}
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W[i - 15];
const W2 = SHA256_W[i - 2];
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
}
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
H = G;
G = F;
F = E;
E = D + T1 | 0;
D = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D = D + this.D | 0;
E = E + this.E | 0;
F = F + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
clean(SHA256_W);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
clean(this.buffer);
}
};
const K512 = /* @__PURE__ */ (() => split([
"0x428a2f98d728ae22",
"0x7137449123ef65cd",
"0xb5c0fbcfec4d3b2f",
"0xe9b5dba58189dbbc",
"0x3956c25bf348b538",
"0x59f111f1b605d019",
"0x923f82a4af194f9b",
"0xab1c5ed5da6d8118",
"0xd807aa98a3030242",
"0x12835b0145706fbe",
"0x243185be4ee4b28c",
"0x550c7dc3d5ffb4e2",
"0x72be5d74f27b896f",
"0x80deb1fe3b1696b1",
"0x9bdc06a725c71235",
"0xc19bf174cf692694",
"0xe49b69c19ef14ad2",
"0xefbe4786384f25e3",
"0x0fc19dc68b8cd5b5",
"0x240ca1cc77ac9c65",
"0x2de92c6f592b0275",
"0x4a7484aa6ea6e483",
"0x5cb0a9dcbd41fbd4",
"0x76f988da831153b5",
"0x983e5152ee66dfab",
"0xa831c66d2db43210",
"0xb00327c898fb213f",
"0xbf597fc7beef0ee4",
"0xc6e00bf33da88fc2",
"0xd5a79147930aa725",
"0x06ca6351e003826f",
"0x142929670a0e6e70",
"0x27b70a8546d22ffc",
"0x2e1b21385c26c926",
"0x4d2c6dfc5ac42aed",
"0x53380d139d95b3df",
"0x650a73548baf63de",
"0x766a0abb3c77b2a8",
"0x81c2c92e47edaee6",
"0x92722c851482353b",
"0xa2bfe8a14cf10364",
"0xa81a664bbc423001",
"0xc24b8b70d0f89791",
"0xc76c51a30654be30",
"0xd192e819d6ef5218",
"0xd69906245565a910",
"0xf40e35855771202a",
"0x106aa07032bbd1b8",
"0x19a4c116b8d2d0c8",
"0x1e376c085141ab53",
"0x2748774cdf8eeb99",
"0x34b0bcb5e19b48a8",
"0x391c0cb3c5c95a63",
"0x4ed8aa4ae3418acb",
"0x5b9cca4f7763e373",
"0x682e6ff3d6b2b8a3",
"0x748f82ee5defb2fc",
"0x78a5636f43172f60",
"0x84c87814a1f0ab72",
"0x8cc702081a6439ec",
"0x90befffa23631e28",
"0xa4506cebde82bde9",
"0xbef9a3f7b2c67915",
"0xc67178f2e372532b",
"0xca273eceea26619c",
"0xd186b8c721c0c207",
"0xeada7dd6cde0eb1e",
"0xf57d4f7fee6ed178",
"0x06f067aa72176fba",
"0x0a637dc5a2c898a6",
"0x113f9804bef90dae",
"0x1b710b35131c471b",
"0x28db77f523047d84",
"0x32caab7b40c72493",
"0x3c9ebe0a15c9bebc",
"0x431d67c49c100d4c",
"0x4cc5d4becb3e42b6",
"0x597f299cfc657e2a",
"0x5fcb6fab3ad6faec",
"0x6c44198c4a475817"
].map((n) => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
var SHA512 = class extends HashMD {
constructor(outputLen = 64) {
super(128, outputLen, 16, false);
this.Ah = SHA512_IV[0] | 0;
this.Al = SHA512_IV[1] | 0;
this.Bh = SHA512_IV[2] | 0;
this.Bl = SHA512_IV[3] | 0;
this.Ch = SHA512_IV[4] | 0;
this.Cl = SHA512_IV[5] | 0;
this.Dh = SHA512_IV[6] | 0;
this.Dl = SHA512_IV[7] | 0;
this.Eh = SHA512_IV[8] | 0;
this.El = SHA512_IV[9] | 0;
this.Fh = SHA512_IV[10] | 0;
this.Fl = SHA512_IV[11] | 0;
this.Gh = SHA512_IV[12] | 0;
this.Gl = SHA512_IV[13] | 0;
this.Hh = SHA512_IV[14] | 0;
this.Hl = SHA512_IV[15] | 0;
}
get() {
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
return [
Ah,
Al,
Bh,
Bl,
Ch,
Cl,
Dh,
Dl,
Eh,
El,
Fh,
Fl,
Gh,
Gl,
Hh,
Hl
];
}
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
this.Ah = Ah | 0;
this.Al = Al | 0;
this.Bh = Bh | 0;
this.Bl = Bl | 0;
this.Ch = Ch | 0;
this.Cl = Cl | 0;
this.Dh = Dh | 0;
this.Dl = Dl | 0;
this.Eh = Eh | 0;
this.El = El | 0;
this.Fh = Fh | 0;
this.Fl = Fl | 0;
this.Gh = Gh | 0;
this.Gl = Gl | 0;
this.Hh = Hh | 0;
this.Hl = Hl | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4) {
SHA512_W_H[i] = view.getUint32(offset);
SHA512_W_L[i] = view.getUint32(offset += 4);
}
for (let i = 16; i < 80; i++) {
const W15h = SHA512_W_H[i - 15] | 0;
const W15l = SHA512_W_L[i - 15] | 0;
const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
const W2h = SHA512_W_H[i - 2] | 0;
const W2l = SHA512_W_L[i - 2] | 0;
const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
SHA512_W_H[i] = SUMh | 0;
SHA512_W_L[i] = SUMl | 0;
}
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
for (let i = 0; i < 80; i++) {
const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
const CHIh = Eh & Fh ^ ~Eh & Gh;
const CHIl = El & Fl ^ ~El & Gl;
const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
const T1l = T1ll | 0;
const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
Hh = Gh | 0;
Hl = Gl | 0;
Gh = Fh | 0;
Gl = Fl | 0;
Fh = Eh | 0;
Fl = El | 0;
({h: Eh, l: El} = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
Dh = Ch | 0;
Dl = Cl | 0;
Ch = Bh | 0;
Cl = Bl | 0;
Bh = Ah | 0;
Bl = Al | 0;
const All = add3L(T1l, sigma0l, MAJl);
Ah = add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
({h: Ah, l: Al} = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({h: Bh, l: Bl} = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({h: Ch, l: Cl} = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({h: Dh, l: Dl} = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({h: Eh, l: El} = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({h: Fh, l: Fl} = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({h: Gh, l: Gl} = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({h: Hh, l: Hl} = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
}
roundClean() {
clean(SHA512_W_H, SHA512_W_L);
}
destroy() {
clean(this.buffer);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
};
/**
* SHA2-256 hash function from RFC 4634.
*
* It is the fastest JS hash, even faster than Blake3.
* To break sha256 using birthday attack, attackers need to try 2^128 hashes.
* BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
*/
const sha256$1 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-512 hash function from RFC 4634. */
const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
// ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/utils.js
/**
* Hex, bytes and number utilities.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$6 = /* @__PURE__ */ BigInt(0);
const _1n$6 = /* @__PURE__ */ BigInt(1);
function _abool2(value, title = "") {
if (typeof value !== "boolean") {
const prefix = title && `"${title}"`;
throw new Error(prefix + "expected boolean, got type=" + typeof value);
}
return value;
}
/** Asserts something is Uint8Array. */
function _abytes2(value, length, title = "") {
const bytes = isBytes(value);
const len = value?.length;
const needsLen = length !== void 0;
if (!bytes || needsLen && len !== length) {
const prefix = title && `"${title}" `;
const ofLen = needsLen ? ` of length ${length}` : "";
const got = bytes ? `length=${len}` : `type=${typeof value}`;
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
}
return value;
}
function numberToHexUnpadded(num) {
const hex = num.toString(16);
return hex.length & 1 ? "0" + hex : hex;
}
function hexToNumber(hex) {
if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
return hex === "" ? _0n$6 : BigInt("0x" + hex);
}
function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
function bytesToNumberLE(bytes) {
abytes(bytes);
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE(n, len) {
return hexToBytes(n.toString(16).padStart(len * 2, "0"));
}
function numberToBytesLE(n, len) {
return numberToBytesBE(n, len).reverse();
}
/**
* Takes hex string or Uint8Array, converts to Uint8Array.
* Validates output length.
* Will throw error for other types.
* @param title descriptive title for an error e.g. 'secret key'
* @param hex hex string or Uint8Array
* @param expectedLength optional, will compare to result array's length
* @returns
*/
function ensureBytes(title, hex, expectedLength) {
let res;
if (typeof hex === "string") try {
res = hexToBytes(hex);
} catch (e) {
throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
}
else if (isBytes(hex)) res = Uint8Array.from(hex);
else throw new Error(title + " must be hex string or Uint8Array");
const len = res.length;
if (typeof expectedLength === "number" && len !== expectedLength) throw new Error(title + " of length " + expectedLength + " expected, got " + len);
return res;
}
function equalBytes(a, b) {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
return diff === 0;
}
/**
* Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
* and Buffer#slice creates mutable copy. Never use Buffers!
*/
function copyBytes(bytes) {
return Uint8Array.from(bytes);
}
/**
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
/**
* Converts bytes to string using UTF8 encoding.
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
*/
const isPosBig = (n) => typeof n === "bigint" && _0n$6 <= n;
function inRange(n, min, max) {
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
* Asserts min <= n < max. NOTE: It's < max and not <= max.
* @example
* aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
*/
function aInRange(title, n, min, max) {
if (!inRange(n, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
}
/**
* Calculates amount of bits in a bigint.
* Same as `n.toString(2).length`
* TODO: merge with nLength in modular
*/
function bitLen(n) {
let len = 0;
for (; n > _0n$6; n >>= _1n$6, len += 1);
return len;
}
/**
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
*/
const bitMask = (n) => (_1n$6 << BigInt(n)) - _1n$6;
/**
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
* @returns function that will call DRBG until 2nd arg returns something meaningful
* @example
* const drbg = createHmacDRBG<Key>(32, 32, hmac);
* drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
*/
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number");
if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number");
if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function");
const u8n = (len) => new Uint8Array(len);
const u8of = (byte) => Uint8Array.of(byte);
let v = u8n(hashLen);
let k = u8n(hashLen);
let i = 0;
const reset = () => {
v.fill(1);
k.fill(0);
i = 0;
};
const h = (...b) => hmacFn(k, v, ...b);
const reseed = (seed = u8n(0)) => {
k = h(u8of(0), seed);
v = h();
if (seed.length === 0) return;
k = h(u8of(1), seed);
v = h();
};
const gen = () => {
if (i++ >= 1e3) throw new Error("drbg: tried 1000 values");
let len = 0;
const out = [];
while (len < qByteLen) {
v = h();
const sl = v.slice();
out.push(sl);
len += v.length;
}
return concatBytes(...out);
};
const genUntil = (seed, pred) => {
reset();
reseed(seed);
let res = void 0;
while (!(res = pred(gen()))) reseed();
reset();
return res;
};
return genUntil;
}
function _validateObject(object, fields, optFields = {}) {
if (!object || typeof object !== "object") throw new Error("expected valid options object");
function checkField(fieldName, expectedType, isOpt) {
const val = object[fieldName];
if (isOpt && val === void 0) return;
const current = typeof val;
if (current !== expectedType || val === null) throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
}
Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
* throws not implemented error
*/
const notImplemented = () => {
throw new Error("not implemented");
};
/**
* Memoizes (caches) computation result.
* Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
*/
function memoized(fn) {
const map = /* @__PURE__ */ new WeakMap();
return (arg, ...args) => {
const val = map.get(arg);
if (val !== void 0) return val;
const computed = fn(arg, ...args);
map.set(arg, computed);
return computed;
};
}
// ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js
/**
* Utils for modular division and fields.
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
* There is no division: it is replaced by modular multiplicative inverse.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$5 = BigInt(0);
const _1n$5 = BigInt(1);
const _2n$5 = /* @__PURE__ */ BigInt(2);
const _3n$1 = /* @__PURE__ */ BigInt(3);
const _4n$1 = /* @__PURE__ */ BigInt(4);
const _5n$1 = /* @__PURE__ */ BigInt(5);
const _7n$1 = /* @__PURE__ */ BigInt(7);
const _8n$2 = /* @__PURE__ */ BigInt(8);
const _9n = /* @__PURE__ */ BigInt(9);
const _16n = /* @__PURE__ */ BigInt(16);
function mod(a, b) {
const result = a % b;
return result >= _0n$5 ? result : b + result;
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
function pow2(x, power, modulo) {
let res = x;
while (power-- > _0n$5) {
res *= res;
res %= modulo;
}
return res;
}
/**
* Inverses number over modulo.
* Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
*/
function invert(number, modulo) {
if (number === _0n$5) throw new Error("invert: expected non-zero number");
if (modulo <= _0n$5) throw new Error("invert: expected positive modulus, got " + modulo);
let a = mod(number, modulo);
let b = modulo;
let x = _0n$5, y = _1n$5, u = _1n$5, v = _0n$5;
while (a !== _0n$5) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
b = a, a = r, x = u, y = v, u = m, v = n;
}
if (b !== _1n$5) throw new Error("invert: does not exist");
return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
}
function sqrt3mod4(Fp, n) {
const p1div4 = (Fp.ORDER + _1n$5) / _4n$1;
const root = Fp.pow(n, p1div4);
assertIsSquare(Fp, root, n);
return root;
}
function sqrt5mod8(Fp, n) {
const p5div8 = (Fp.ORDER - _5n$1) / _8n$2;
const n2 = Fp.mul(n, _2n$5);
const v = Fp.pow(n2, p5div8);
const nv = Fp.mul(n, v);
const i = Fp.mul(Fp.mul(nv, _2n$5), v);
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
assertIsSquare(Fp, root, n);
return root;
}
function sqrt9mod16(P) {
const Fp_ = Field(P);
const tn = tonelliShanks(P);
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
const c2 = tn(Fp_, c1);
const c3 = tn(Fp_, Fp_.neg(c1));
const c4 = (P + _7n$1) / _16n;
return (Fp, n) => {
let tv1 = Fp.pow(n, c4);
let tv2 = Fp.mul(tv1, c1);
const tv3 = Fp.mul(tv1, c2);
const tv4 = Fp.mul(tv1, c3);
const e1 = Fp.eql(Fp.sqr(tv2), n);
const e2 = Fp.eql(Fp.sqr(tv3), n);
tv1 = Fp.cmov(tv1, tv2, e1);
tv2 = Fp.cmov(tv4, tv3, e2);
const e3 = Fp.eql(Fp.sqr(tv2), n);
const root = Fp.cmov(tv1, tv2, e3);
assertIsSquare(Fp, root, n);
return root;
};
}
/**
* Tonelli-Shanks square root search algorithm.
* 1. https://eprint.iacr.org/2012/685.pdf (page 12)
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
* @param P field order
* @returns function that takes field Fp (created from P) and number n
*/
function tonelliShanks(P) {
if (P < _3n$1) throw new Error("sqrt is not defined for small field");
let Q = P - _1n$5;
let S = 0;
while (Q % _2n$5 === _0n$5) {
Q /= _2n$5;
S++;
}
let Z = _2n$5;
const _Fp = Field(P);
while (FpLegendre(_Fp, Z) === 1) if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P");
if (S === 1) return sqrt3mod4;
let cc = _Fp.pow(Z, Q);
const Q1div2 = (Q + _1n$5) / _2n$5;
return function tonelliSlow(Fp, n) {
if (Fp.is0(n)) return n;
if (FpLegendre(Fp, n) !== 1) throw new Error("Cannot find square root");
let M = S;
let c = Fp.mul(Fp.ONE, cc);
let t = Fp.pow(n, Q);
let R = Fp.pow(n, Q1div2);
while (!Fp.eql(t, Fp.ONE)) {
if (Fp.is0(t)) return Fp.ZERO;
let i = 1;
let t_tmp = Fp.sqr(t);
while (!Fp.eql(t_tmp, Fp.ONE)) {
i++;
t_tmp = Fp.sqr(t_tmp);
if (i === M) throw new Error("Cannot find square root");
}
const exponent = _1n$5 << BigInt(M - i - 1);
const b = Fp.pow(c, exponent);
M = i;
c = Fp.sqr(b);
t = Fp.mul(t, c);
R = Fp.mul(R, b);
}
return R;
};
}
/**
* Square root for a finite field. Will try optimized versions first:
*
* 1. P ≡ 3 (mod 4)
* 2. P ≡ 5 (mod 8)
* 3. P ≡ 9 (mod 16)
* 4. Tonelli-Shanks algorithm
*
* Different algorithms can give different roots, it is up to user to decide which one they want.
* For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
*/
function FpSqrt(P) {
if (P % _4n$1 === _3n$1) return sqrt3mod4;
if (P % _8n$2 === _5n$1) return sqrt5mod8;
if (P % _16n === _9n) return sqrt9mod16(P);
return tonelliShanks(P);
}
const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n$5) === _1n$5;
const FIELD_FIELDS = [
"create",
"isValid",
"is0",
"neg",
"inv",
"sqrt",
"sqr",
"eql",
"add",
"sub",
"mul",
"pow",
"div",
"addN",
"subN",
"mulN",
"sqrN"
];
function validateField(field) {
_validateObject(field, FIELD_FIELDS.reduce((map, val) => {
map[val] = "function";
return map;
}, {
ORDER: "bigint",
MASK: "bigint",
BYTES: "number",
BITS: "number"
}));
return field;
}
/**
* Same as `pow` but for Fp: non-constant-time.
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
*/
function FpPow(Fp, num, power) {
if (power < _0n$5) throw new Error("invalid exponent, negatives unsupported");
if (power === _0n$5) return Fp.ONE;
if (power === _1n$5) return num;
let p = Fp.ONE;
let d = num;
while (power > _0n$5) {
if (power & _1n$5) p = Fp.mul(p, d);
d = Fp.sqr(d);
power >>= _1n$5;
}
return p;
}
/**
* Efficiently invert an array of Field elements.
* Exception-free. Will return `undefined` for 0 elements.
* @param passZero map 0 to 0 (instead of undefined)
*/
function FpInvertBatch(Fp, nums, passZero = false) {
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
const multipliedAcc = nums.reduce((acc, num, i) => {
if (Fp.is0(num)) return acc;
inverted[i] = acc;
return Fp.mul(acc, num);
}, Fp.ONE);
const invertedAcc = Fp.inv(multipliedAcc);
nums.reduceRight((acc, num, i) => {
if (Fp.is0(num)) return acc;
inverted[i] = Fp.mul(acc, inverted[i]);
return Fp.mul(acc, num);
}, invertedAcc);
return inverted;
}
/**
* Legendre symbol.
* Legendre constant is used to calculate Legendre symbol (a | p)
* which denotes the value of a^((p-1)/2) (mod p).
*
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
*/
function FpLegendre(Fp, n) {
const p1mod2 = (Fp.ORDER - _1n$5) / _2n$5;
const powered = Fp.pow(n, p1mod2);
const yes = Fp.eql(powered, Fp.ONE);
const zero = Fp.eql(powered, Fp.ZERO);
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
return yes ? 1 : zero ? 0 : -1;
}
function nLength(n, nBitLength) {
if (nBitLength !== void 0) anumber(nBitLength);
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
return {
nBitLength: _nBitLength,
nByteLength: Math.ceil(_nBitLength / 8)
};
}
/**
* Creates a finite field. Major performance optimizations:
* * 1. Denormalized operations like mulN instead of mul.
* * 2. Identical object shape: never add or remove keys.
* * 3. `Object.freeze`.
* Fragile: always run a benchmark on a change.
* Security note: operations don't check 'isValid' for all elements for performance reasons,
* it is caller responsibility to check this.
* This is low-level code, please make sure you know what you're doing.
*
* Note about field properties:
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
*
* @param ORDER field order, probably prime, or could be composite
* @param bitLen how many bits the field consumes
* @param isLE (default: false) if encoding / decoding should be in little-endian
* @param redef optional faster redefinitions of sqrt and other methods
*/
function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) {
if (ORDER <= _0n$5) throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
let _nbitLength = void 0;
let _sqrt = void 0;
let modFromBytes = false;
let allowedLengths = void 0;
if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
if (opts.sqrt || isLE) throw new Error("cannot specify opts in two arguments");
const _opts = bitLenOrOpts;
if (_opts.BITS) _nbitLength = _opts.BITS;
if (_opts.sqrt) _sqrt = _opts.sqrt;
if (typeof _opts.isLE === "boolean") isLE = _opts.isLE;
if (typeof _opts.modFromBytes === "boolean") modFromBytes = _opts.modFromBytes;
allowedLengths = _opts.allowedLengths;
} else {
if (typeof bitLenOrOpts === "number") _nbitLength = bitLenOrOpts;
if (opts.sqrt) _sqrt = opts.sqrt;
}
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
if (BYTES > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes");
let sqrtP;
const f = Object.freeze({
ORDER,
isLE,
BITS,
BYTES,
MASK: bitMask(BITS),
ZERO: _0n$5,
ONE: _1n$5,
allowedLengths,
create: (num) => mod(num, ORDER),
isValid: (num) => {
if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num);
return _0n$5 <= num && num < ORDER;
},
is0: (num) => num === _0n$5,
isValidNot0: (num) => !f.is0(num) && f.isValid(num),
isOdd: (num) => (num & _1n$5) === _1n$5,
neg: (num) => mod(-num, ORDER),
eql: (lhs, rhs) => lhs === rhs,
sqr: (num) => mod(num * num, ORDER),
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
pow: (num, power) => FpPow(f, num, power),
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
sqrN: (num) => num * num,
addN: (lhs, rhs) => lhs + rhs,
subN: (lhs, rhs) => lhs - rhs,
mulN: (lhs, rhs) => lhs * rhs,
inv: (num) => invert(num, ORDER),
sqrt: _sqrt || ((n) => {
if (!sqrtP) sqrtP = FpSqrt(ORDER);
return sqrtP(f, n);
}),
toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
fromBytes: (bytes, skipValidation = true) => {
if (allowedLengths) {
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
const padded = new Uint8Array(BYTES);
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
bytes = padded;
}
if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
if (modFromBytes) scalar = mod(scalar, ORDER);
if (!skipValidation) {
if (!f.isValid(scalar)) throw new Error("invalid field element: outside of range 0..ORDER");
}
return scalar;
},
invertBatch: (lst) => FpInvertBatch(f, lst),
cmov: (a, b, c) => c ? b : a
});
return Object.freeze(f);
}
/**
* Returns total number of bytes consumed by the field element.
* For example, 32 bytes for usual 256-bit weierstrass curve.
* @param fieldOrder number of field elements, usually CURVE.n
* @returns byte length of field
*/
function getFieldBytesLength(fieldOrder) {
if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint");
const bitLength = fieldOrder.toString(2).length;
return Math.ceil(bitLength / 8);
}
/**
* Returns minimal amount of bytes that can be safely reduced
* by field order.
* Should be 2^-128 for 128-bit curve such as P256.
* @param fieldOrder number of field elements, usually CURVE.n
* @returns byte length of target hash
*/
function getMinHashLength(fieldOrder) {
const length = getFieldBytesLength(fieldOrder);
return length + Math.ceil(length / 2);
}
/**
* "Constant-time" private key generation utility.
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
* and convert them into private scalar, with the modulo bias being negligible.
* Needs at least 48 bytes of input for 32-byte private key.
* https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
* FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
* RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
* @param hash hash output from SHA3 or a similar function
* @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
* @param isLE interpret hash bytes as LE num
* @returns valid private scalar
*/
function mapHashToField(key, fieldOrder, isLE = false) {
const len = key.length;
const fieldLen = getFieldBytesLength(fieldOrder);
const minLen = getMinHashLength(fieldOrder);
if (len < 16 || len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
const reduced = mod(isLE ? bytesToNumberLE(key) : bytesToNumberBE(key), fieldOrder - _1n$5) + _1n$5;
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
// ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js
/**
* Methods for elliptic curve multiplication by scalars.
* Contains wNAF, pippenger.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$4 = BigInt(0);
const _1n$4 = BigInt(1);
function negateCt(condition, item) {
const neg = item.negate();
return condition ? neg : item;
}
/**
* Takes a bunch of Projective Points but executes only one
* inversion on all of them. Inversion is very slow operation,
* so this improves performance massively.
* Optimization: converts a list of projective points to a list of identical points with Z=1.
*/
function normalizeZ(c, points) {
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
}
function calcWOpts(W, scalarBits) {
validateW(W, scalarBits);
const windows = Math.ceil(scalarBits / W) + 1;
const windowSize = 2 ** (W - 1);
const maxNumber = 2 ** W;
return {
windows,
windowSize,
mask: bitMask(W),
maxNumber,
shiftBy: BigInt(W)
};
}
function calcOffsets(n, window, wOpts) {
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
let wbits = Number(n & mask);
let nextN = n >> shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
nextN += _1n$4;
}
const offsetStart = window * windowSize;
const offset = offsetStart + Math.abs(wbits) - 1;
const isZero = wbits === 0;
const isNeg = wbits < 0;
const isNegF = window % 2 !== 0;
return {
nextN,
offset,
isZero,
isNeg,
isNegF,
offsetF: offsetStart
};
}
function validateMSMPoints(points, c) {
if (!Array.isArray(points)) throw new Error("array expected");
points.forEach((p, i) => {
if (!(p instanceof c)) throw new Error("invalid point at index " + i);
});
}
function validateMSMScalars(scalars, field) {
if (!Array.isArray(scalars)) throw new Error("array of scalars expected");
scalars.forEach((s, i) => {
if (!field.isValid(s)) throw new Error("invalid scalar at index " + i);
});
}
const pointPrecomputes = /* @__PURE__ */ new WeakMap();
const pointWindowSizes = /* @__PURE__ */ new WeakMap();
function getW(P) {
return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
if (n !== _0n$4) throw new Error("invalid wNAF");
}
/**
* Elliptic curve multiplication of Point by scalar. Fragile.
* Table generation takes **30MB of ram and 10ms on high-end CPU**,
* but may take much longer on slow devices. Actual generation will happen on
* first call of `multiply()`. By default, `BASE` point is precomputed.
*
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
* Creates precomputation tables for fast multiplication:
* - private scalar is split by fixed size windows of W bits
* - every window point is collected from window's table & added to accumulator
* - since windows are different, same point inside tables won't be accessed more than once per calc
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
* - +1 window is neccessary for wNAF
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
*
* @todo Research returning 2d JS array of windows, instead of a single window.
* This would allow windows to be in different memory locations
*/
var wNAF = class {
constructor(Point, bits) {
this.BASE = Point.BASE;
this.ZERO = Point.ZERO;
this.Fn = Point.Fn;
this.bits = bits;
}
_unsafeLadder(elm, n, p = this.ZERO) {
let d = elm;
while (n > _0n$4) {
if (n & _1n$4) p = p.add(d);
d = d.double();
n >>= _1n$4;
}
return p;
}
/**
* Creates a wNAF precomputation window. Used for caching.
* Default window size is set by `utils.precompute()` and is equal to 8.
* Number of precomputed points depends on the curve size:
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
* - 𝑊 is the window size
* - 𝑛 is the bitlength of the curve order.
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
* @param point Point instance
* @param W window size
* @returns precomputed point tables flattened to a single array
*/
precomputeWindow(point, W) {
const { windows, windowSize } = calcWOpts(W, this.bits);
const points = [];
let p = point;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < windowSize; i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
}
/**
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
* More compact implementation:
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
* @returns real and fake (for const-time) points
*/
wNAF(W, precomputes, n) {
if (!this.Fn.isValid(n)) throw new Error("invalid scalar");
let p = this.ZERO;
let f = this.BASE;
const wo = calcWOpts(W, this.bits);
for (let window = 0; window < wo.windows; window++) {
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
n = nextN;
if (isZero) f = f.add(negateCt(isNegF, precomputes[offsetF]));
else p = p.add(negateCt(isNeg, precomputes[offset]));
}
assert0(n);
return {
p,
f
};
}
/**
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
* @param acc accumulator point to add result of multiplication
* @returns point
*/
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
const wo = calcWOpts(W, this.bits);
for (let window = 0; window < wo.windows; window++) {
if (n === _0n$4) break;
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
n = nextN;
if (isZero) continue;
else {
const item = precomputes[offset];
acc = acc.add(isNeg ? item.negate() : item);
}
}
assert0(n);
return acc;
}
getPrecomputes(W, point, transform) {
let comp = pointPrecomputes.get(point);
if (!comp) {
comp = this.precomputeWindow(point, W);
if (W !== 1) {
if (typeof transform === "function") comp = transform(comp);
pointPrecomputes.set(point, comp);
}
}
return comp;
}
cached(point, scalar, transform) {
const W = getW(point);
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
}
unsafe(point, scalar, transform, prev) {
const W = getW(point);
if (W === 1) return this._unsafeLadder(point, scalar, prev);
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
}
createCache(P, W) {
validateW(W, this.bits);
pointWindowSizes.set(P, W);
pointPrecomputes.delete(P);
}
hasCache(elm) {
return getW(elm) !== 1;
}
};
/**
* Endomorphism-specific multiplication for Koblitz curves.
* Cost: 128 dbl, 0-256 adds.
*/
function mulEndoUnsafe(Point, point, k1, k2) {
let acc = point;
let p1 = Point.ZERO;
let p2 = Point.ZERO;
while (k1 > _0n$4 || k2 > _0n$4) {
if (k1 & _1n$4) p1 = p1.add(acc);
if (k2 & _1n$4) p2 = p2.add(acc);
acc = acc.double();
k1 >>= _1n$4;
k2 >>= _1n$4;
}
return {
p1,
p2
};
}
/**
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
* 30x faster vs naive addition on L=4096, 10x faster than precomputes.
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
* @param c Curve Point constructor
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
* @param points array of L curve points
* @param scalars array of L scalars (aka secret keys / bigints)
*/
function pippenger(c, fieldN, points, scalars) {
validateMSMPoints(points, c);
validateMSMScalars(scalars, fieldN);
const plength = points.length;
const slength = scalars.length;
if (plength !== slength) throw new Error("arrays of points and scalars must have equal length");
const zero = c.ZERO;
const wbits = bitLen(BigInt(plength));
let windowSize = 1;
if (wbits > 12) windowSize = wbits - 3;
else if (wbits > 4) windowSize = wbits - 2;
else if (wbits > 0) windowSize = 2;
const MASK = bitMask(windowSize);
const buckets = new Array(Number(MASK) + 1).fill(zero);
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
let sum = zero;
for (let i = lastBits; i >= 0; i -= windowSize) {
buckets.fill(zero);
for (let j = 0; j < slength; j++) {
const scalar = scalars[j];
const wbits = Number(scalar >> BigInt(i) & MASK);
buckets[wbits] = buckets[wbits].add(points[j]);
}
let resI = zero;
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
sumI = sumI.add(buckets[j]);
resI = resI.add(sumI);
}
sum = sum.add(resI);
if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();
}
return sum;
}
function createField(order, field, isLE) {
if (field) {
if (field.ORDER !== order) throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
validateField(field);
return field;
} else return Field(order, { isLE });
}
/** Validates CURVE opts and creates fields */
function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
if (FpFnLE === void 0) FpFnLE = type === "edwards";
if (!CURVE || typeof CURVE !== "object") throw new Error(`expected valid ${type} CURVE object`);
for (const p of [
"p",
"n",
"h"
]) {
const val = CURVE[p];
if (!(typeof val === "bigint" && val > _0n$4)) throw new Error(`CURVE.${p} must be positive bigint`);
}
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
const params = [
"Gx",
"Gy",
"a",
type === "weierstrass" ? "b" : "d"
];
for (const p of params) if (!Fp.isValid(CURVE[p])) throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
CURVE = Object.freeze(Object.assign({}, CURVE));
return {
CURVE,
Fp,
Fn
};
}
// ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js
/**
* Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
* For design rationale of types / exports, see weierstrass module documentation.
* Untwisted Edwards curves exist, but they aren't used in real-world protocols.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$3 = BigInt(0);
const _1n$3 = BigInt(1);
const _2n$4 = BigInt(2);
const _8n$1 = BigInt(8);
function isEdValidXY(Fp, CURVE, x, y) {
const x2 = Fp.sqr(x);
const y2 = Fp.sqr(y);
const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
return Fp.eql(left, right);
}
function edwards(params, extraOpts = {}) {
const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
const { Fp, Fn } = validated;
let CURVE = validated.CURVE;
const { h: cofactor } = CURVE;
_validateObject(extraOpts, {}, { uvRatio: "function" });
const MASK = _2n$4 << BigInt(Fn.BYTES * 8) - _1n$3;
const modP = (n) => Fp.create(n);
const uvRatio = extraOpts.uvRatio || ((u, v) => {
try {
return {
isValid: true,
value: Fp.sqrt(Fp.div(u, v))
};
} catch (e) {
return {
isValid: false,
value: _0n$3
};
}
});
if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
/**
* Asserts coordinate is valid: 0 <= n < MASK.
* Coordinates >= Fp.ORDER are allowed for zip215.
*/
function acoord(title, n, banZero = false) {
const min = banZero ? _1n$3 : _0n$3;
aInRange("coordinate " + title, n, min, MASK);
return n;
}
function aextpoint(other) {
if (!(other instanceof Point)) throw new Error("ExtendedPoint expected");
}
const toAffineMemo = memoized((p, iz) => {
const { X, Y, Z } = p;
const is0 = p.is0();
if (iz == null) iz = is0 ? _8n$1 : Fp.inv(Z);
const x = modP(X * iz);
const y = modP(Y * iz);
const zz = Fp.mul(Z, iz);
if (is0) return {
x: _0n$3,
y: _1n$3
};
if (zz !== _1n$3) throw new Error("invZ was invalid");
return {
x,
y
};
});
const assertValidMemo = memoized((p) => {
const { a, d } = CURVE;
if (p.is0()) throw new Error("bad point: ZERO");
const { X, Y, Z, T } = p;
const X2 = modP(X * X);
const Y2 = modP(Y * Y);
const Z2 = modP(Z * Z);
const Z4 = modP(Z2 * Z2);
const aX2 = modP(X2 * a);
if (modP(Z2 * modP(aX2 + Y2)) !== modP(Z4 + modP(d * modP(X2 * Y2)))) throw new Error("bad point: equation left != right (1)");
if (modP(X * Y) !== modP(Z * T)) throw new Error("bad point: equation left != right (2)");
return true;
});
class Point {
constructor(X, Y, Z, T) {
this.X = acoord("x", X);
this.Y = acoord("y", Y);
this.Z = acoord("z", Z, true);
this.T = acoord("t", T);
Object.freeze(this);
}
static CURVE() {
return CURVE;
}
static fromAffine(p) {
if (p instanceof Point) throw new Error("extended point not allowed");
const { x, y } = p || {};
acoord("x", x);
acoord("y", y);
return new Point(x, y, _1n$3, modP(x * y));
}
static fromBytes(bytes, zip215 = false) {
const len = Fp.BYTES;
const { a, d } = CURVE;
bytes = copyBytes(_abytes2(bytes, len, "point"));
_abool2(zip215, "zip215");
const normed = copyBytes(bytes);
const lastByte = bytes[len - 1];
normed[len - 1] = lastByte & -129;
const y = bytesToNumberLE(normed);
const max = zip215 ? MASK : Fp.ORDER;
aInRange("point.y", y, _0n$3, max);
const y2 = modP(y * y);
const u = modP(y2 - _1n$3);
const v = modP(d * y2 - a);
let { isValid, value: x } = uvRatio(u, v);
if (!isValid) throw new Error("bad point: invalid y coordinate");
const isXOdd = (x & _1n$3) === _1n$3;
const isLastByteOdd = (lastByte & 128) !== 0;
if (!zip215 && x === _0n$3 && isLastByteOdd) throw new Error("bad point: x=0 and x_0=1");
if (isLastByteOdd !== isXOdd) x = modP(-x);
return Point.fromAffine({
x,
y
});
}
static fromHex(bytes, zip215 = false) {
return Point.fromBytes(ensureBytes("point", bytes), zip215);
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
precompute(windowSize = 8, isLazy = true) {
wnaf.createCache(this, windowSize);
if (!isLazy) this.multiply(_2n$4);
return this;
}
assertValidity() {
assertValidMemo(this);
}
equals(other) {
aextpoint(other);
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = other;
const X1Z2 = modP(X1 * Z2);
const X2Z1 = modP(X2 * Z1);
const Y1Z2 = modP(Y1 * Z2);
const Y2Z1 = modP(Y2 * Z1);
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
}
is0() {
return this.equals(Point.ZERO);
}
negate() {
return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
}
double() {
const { a } = CURVE;
const { X: X1, Y: Y1, Z: Z1 } = this;
const A = modP(X1 * X1);
const B = modP(Y1 * Y1);
const C = modP(_2n$4 * modP(Z1 * Z1));
const D = modP(a * A);
const x1y1 = X1 + Y1;
const E = modP(modP(x1y1 * x1y1) - A - B);
const G = D + B;
const F = G - C;
const H = D - B;
const X3 = modP(E * F);
const Y3 = modP(G * H);
const T3 = modP(E * H);
const Z3 = modP(F * G);
return new Point(X3, Y3, Z3, T3);
}
add(other) {
aextpoint(other);
const { a, d } = CURVE;
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
const A = modP(X1 * X2);
const B = modP(Y1 * Y2);
const C = modP(T1 * d * T2);
const D = modP(Z1 * Z2);
const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
const F = D - C;
const G = D + C;
const H = modP(B - a * A);
const X3 = modP(E * F);
const Y3 = modP(G * H);
const T3 = modP(E * H);
const Z3 = modP(F * G);
return new Point(X3, Y3, Z3, T3);
}
subtract(other) {
return this.add(other.negate());
}
multiply(scalar) {
if (!Fn.isValidNot0(scalar)) throw new Error("invalid scalar: expected 1 <= sc < curve.n");
const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));
return normalizeZ(Point, [p, f])[0];
}
multiplyUnsafe(scalar, acc = Point.ZERO) {
if (!Fn.isValid(scalar)) throw new Error("invalid scalar: expected 0 <= sc < curve.n");
if (scalar === _0n$3) return Point.ZERO;
if (this.is0() || scalar === _1n$3) return this;
return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
}
isSmallOrder() {
return this.multiplyUnsafe(cofactor).is0();
}
isTorsionFree() {
return wnaf.unsafe(this, CURVE.n).is0();
}
toAffine(invertedZ) {
return toAffineMemo(this, invertedZ);
}
clearCofactor() {
if (cofactor === _1n$3) return this;
return this.multiplyUnsafe(cofactor);
}
toBytes() {
const { x, y } = this.toAffine();
const bytes = Fp.toBytes(y);
bytes[bytes.length - 1] |= x & _1n$3 ? 128 : 0;
return bytes;
}
toHex() {
return bytesToHex(this.toBytes());
}
toString() {
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
}
get ex() {
return this.X;
}
get ey() {
return this.Y;
}
get ez() {
return this.Z;
}
get et() {
return this.T;
}
static normalizeZ(points) {
return normalizeZ(Point, points);
}
static msm(points, scalars) {
return pippenger(Point, Fn, points, scalars);
}
_setWindowSize(windowSize) {
this.precompute(windowSize);
}
toRawBytes() {
return this.toBytes();
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$3, modP(CURVE.Gx * CURVE.Gy));
Point.ZERO = new Point(_0n$3, _1n$3, _1n$3, _0n$3);
Point.Fp = Fp;
Point.Fn = Fn;
const wnaf = new wNAF(Point, Fn.BITS);
Point.BASE.precompute(8);
return Point;
}
/**
* Base class for prime-order points like Ristretto255 and Decaf448.
* These points eliminate cofactor issues by representing equivalence classes
* of Edwards curve points.
*/
var PrimeEdwardsPoint = class {
constructor(ep) {
this.ep = ep;
}
static fromBytes(_bytes) {
notImplemented();
}
static fromHex(_hex) {
notImplemented();
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
clearCofactor() {
return this;
}
assertValidity() {
this.ep.assertValidity();
}
toAffine(invertedZ) {
return this.ep.toAffine(invertedZ);
}
toHex() {
return bytesToHex(this.toBytes());
}
toString() {
return this.toHex();
}
isTorsionFree() {
return true;
}
isSmallOrder() {
return false;
}
add(other) {
this.assertSame(other);
return this.init(this.ep.add(other.ep));
}
subtract(other) {
this.assertSame(other);
return this.init(this.ep.subtract(other.ep));
}
multiply(scalar) {
return this.init(this.ep.multiply(scalar));
}
multiplyUnsafe(scalar) {
return this.init(this.ep.multiplyUnsafe(scalar));
}
double() {
return this.init(this.ep.double());
}
negate() {
return this.init(this.ep.negate());
}
precompute(windowSize, isLazy) {
return this.init(this.ep.precompute(windowSize, isLazy));
}
/** @deprecated use `toBytes` */
toRawBytes() {
return this.toBytes();
}
};
/**
* Initializes EdDSA signatures over given Edwards curve.
*/
function eddsa(Point, cHash, eddsaOpts = {}) {
if (typeof cHash !== "function") throw new Error("\"hash\" function param is required");
_validateObject(eddsaOpts, {}, {
adjustScalarBytes: "function",
randomBytes: "function",
domain: "function",
prehash: "function",
mapToCurve: "function"
});
const { prehash } = eddsaOpts;
const { BASE, Fp, Fn } = Point;
const randomBytes$2 = eddsaOpts.randomBytes || randomBytes;
const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
_abool2(phflag, "phflag");
if (ctx.length || phflag) throw new Error("Contexts/pre-hash are not supported");
return data;
});
function modN_LE(hash) {
return Fn.create(bytesToNumberLE(hash));
}
function getPrivateScalar(key) {
const len = lengths.secretKey;
key = ensureBytes("private key", key, len);
const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
const head = adjustScalarBytes(hashed.slice(0, len));
return {
head,
prefix: hashed.slice(len, 2 * len),
scalar: modN_LE(head)
};
}
/** Convenience method that creates public key from scalar. RFC8032 5.1.5 */
function getExtendedPublicKey(secretKey) {
const { head, prefix, scalar } = getPrivateScalar(secretKey);
const point = BASE.multiply(scalar);
return {
head,
prefix,
scalar,
point,
pointBytes: point.toBytes()
};
}
/** Calculates EdDSA pub key. RFC8032 5.1.5. */
function getPublicKey(secretKey) {
return getExtendedPublicKey(secretKey).pointBytes;
}
function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
const msg = concatBytes(...msgs);
return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
}
/** Signs message with privateKey. RFC8032 5.1.6 */
function sign(msg, secretKey, options = {}) {
msg = ensureBytes("message", msg);
if (prehash) msg = prehash(msg);
const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
const r = hashDomainToScalar(options.context, prefix, msg);
const R = BASE.multiply(r).toBytes();
const k = hashDomainToScalar(options.context, R, pointBytes, msg);
const s = Fn.create(r + k * scalar);
if (!Fn.isValid(s)) throw new Error("sign failed: invalid s");
return _abytes2(concatBytes(R, Fn.toBytes(s)), lengths.signature, "result");
}
const verifyOpts = { zip215: true };
/**
* Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
* An extended group equation is checked.
*/
function verify(sig, msg, publicKey, options = verifyOpts) {
const { context, zip215 } = options;
const len = lengths.signature;
sig = ensureBytes("signature", sig, len);
msg = ensureBytes("message", msg);
publicKey = ensureBytes("publicKey", publicKey, lengths.publicKey);
if (zip215 !== void 0) _abool2(zip215, "zip215");
if (prehash) msg = prehash(msg);
const mid = len / 2;
const r = sig.subarray(0, mid);
const s = bytesToNumberLE(sig.subarray(mid, len));
let A, R, SB;
try {
A = Point.fromBytes(publicKey, zip215);
R = Point.fromBytes(r, zip215);
SB = BASE.multiplyUnsafe(s);
} catch (error) {
return false;
}
if (!zip215 && A.isSmallOrder()) return false;
const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
return R.add(A.multiplyUnsafe(k)).subtract(SB).clearCofactor().is0();
}
const _size = Fp.BYTES;
const lengths = {
secretKey: _size,
publicKey: _size,
signature: 2 * _size,
seed: _size
};
function randomSecretKey(seed = randomBytes$2(lengths.seed)) {
return _abytes2(seed, lengths.seed, "seed");
}
function keygen(seed) {
const secretKey = utils.randomSecretKey(seed);
return {
secretKey,
publicKey: getPublicKey(secretKey)
};
}
function isValidSecretKey(key) {
return isBytes(key) && key.length === Fn.BYTES;
}
function isValidPublicKey(key, zip215) {
try {
return !!Point.fromBytes(key, zip215);
} catch (error) {
return false;
}
}
const utils = {
getExtendedPublicKey,
randomSecretKey,
isValidSecretKey,
isValidPublicKey,
/**
* Converts ed public key to x public key. Uses formula:
* - ed25519:
* - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
* - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
* - ed448:
* - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
* - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
*/
toMontgomery(publicKey) {
const { y } = Point.fromBytes(publicKey);
const size = lengths.publicKey;
const is25519 = size === 32;
if (!is25519 && size !== 57) throw new Error("only defined for 25519 and 448");
const u = is25519 ? Fp.div(_1n$3 + y, _1n$3 - y) : Fp.div(y - _1n$3, y + _1n$3);
return Fp.toBytes(u);
},
toMontgomerySecret(secretKey) {
const size = lengths.secretKey;
_abytes2(secretKey, size);
const hashed = cHash(secretKey.subarray(0, size));
return adjustScalarBytes(hashed).subarray(0, size);
},
/** @deprecated */
randomPrivateKey: randomSecretKey,
/** @deprecated */
precompute(windowSize = 8, point = Point.BASE) {
return point.precompute(windowSize, false);
}
};
return Object.freeze({
keygen,
getPublicKey,
sign,
verify,
utils,
Point,
lengths
});
}
function _eddsa_legacy_opts_to_new(c) {
const CURVE = {
a: c.a,
d: c.d,
p: c.Fp.ORDER,
n: c.n,
h: c.h,
Gx: c.Gx,
Gy: c.Gy
};
const curveOpts = {
Fp: c.Fp,
Fn: Field(CURVE.n, c.nBitLength, true),
uvRatio: c.uvRatio
};
const eddsaOpts = {
randomBytes: c.randomBytes,
adjustScalarBytes: c.adjustScalarBytes,
domain: c.domain,
prehash: c.prehash,
mapToCurve: c.mapToCurve
};
return {
CURVE,
curveOpts,
hash: c.hash,
eddsaOpts
};
}
function _eddsa_new_output_to_legacy(c, eddsa) {
const Point = eddsa.Point;
return Object.assign({}, eddsa, {
ExtendedPoint: Point,
CURVE: c,
nBitLength: Point.Fn.BITS,
nByteLength: Point.Fn.BYTES
});
}
function twistedEdwards(c) {
const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
return _eddsa_new_output_to_legacy(c, eddsa(edwards(CURVE, curveOpts), hash, eddsaOpts));
}
// ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js
/**
* ed25519 Twisted Edwards curve with following addons:
* - X25519 ECDH
* - Ristretto cofactor elimination
* - Elligator hash-to-group / point indistinguishability
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$2 = /* @__PURE__ */ BigInt(0);
const _1n$2 = BigInt(1);
const _2n$3 = BigInt(2);
const _5n = BigInt(5);
const _8n = BigInt(8);
const ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
const ed25519_CURVE = /* @__PURE__ */ (() => ({
p: ed25519_CURVE_p,
n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
h: _8n,
a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
}))();
function ed25519_pow_2_252_3(x) {
const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
const P = ed25519_CURVE_p;
const b2 = x * x % P * x % P;
const b5 = pow2(pow2(b2, _2n$3, P) * b2 % P, _1n$2, P) * x % P;
const b10 = pow2(b5, _5n, P) * b5 % P;
const b20 = pow2(b10, _10n, P) * b10 % P;
const b40 = pow2(b20, _20n, P) * b20 % P;
const b80 = pow2(b40, _40n, P) * b40 % P;
return {
pow_p_5_8: pow2(pow2(pow2(pow2(b80, _80n, P) * b80 % P, _80n, P) * b80 % P, _10n, P) * b10 % P, _2n$3, P) * x % P,
b2
};
}
function adjustScalarBytes(bytes) {
bytes[0] &= 248;
bytes[31] &= 127;
bytes[31] |= 64;
return bytes;
}
const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
function uvRatio(u, v) {
const P = ed25519_CURVE_p;
const v3 = mod(v * v * v, P);
const pow = ed25519_pow_2_252_3(u * mod(v3 * v3 * v, P)).pow_p_5_8;
let x = mod(u * v3 * pow, P);
const vx2 = mod(v * x * x, P);
const root1 = x;
const root2 = mod(x * ED25519_SQRT_M1, P);
const useRoot1 = vx2 === u;
const useRoot2 = vx2 === mod(-u, P);
const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
if (useRoot1) x = root1;
if (useRoot2 || noRoot) x = root2;
if (isNegativeLE(x, P)) x = mod(-x, P);
return {
isValid: useRoot1 || useRoot2,
value: x
};
}
const Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
const Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();
const ed25519Defaults = /* @__PURE__ */ (() => ({
...ed25519_CURVE,
Fp,
hash: sha512,
adjustScalarBytes,
uvRatio
}))();
/**
* ed25519 curve with EdDSA signatures.
* @example
* import { ed25519 } from '@noble/curves/ed25519';
* const { secretKey, publicKey } = ed25519.keygen();
* const msg = new TextEncoder().encode('hello');
* const sig = ed25519.sign(msg, priv);
* ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215
* ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5
*/
const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
const SQRT_M1 = ED25519_SQRT_M1;
const SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
const INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
const ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
const D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
const invertSqrt = (number) => uvRatio(_1n$2, number);
const MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
const bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);
/**
* Computes Elligator map for Ristretto255.
* Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on
* the [website](https://ristretto.group/formulas/elligator.html).
*/
function calcElligatorRistrettoMap(r0) {
const { d } = ed25519_CURVE;
const P = ed25519_CURVE_p;
const mod = (n) => Fp.create(n);
const r = mod(SQRT_M1 * r0 * r0);
const Ns = mod((r + _1n$2) * ONE_MINUS_D_SQ);
let c = BigInt(-1);
const D = mod((c - d * r) * mod(r + d));
let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
let s_ = mod(s * r0);
if (!isNegativeLE(s_, P)) s_ = mod(-s_);
if (!Ns_D_is_sq) s = s_;
if (!Ns_D_is_sq) c = r;
const Nt = mod(c * (r - _1n$2) * D_MINUS_ONE_SQ - D);
const s2 = s * s;
const W0 = mod((s + s) * D);
const W1 = mod(Nt * SQRT_AD_MINUS_ONE);
const W2 = mod(_1n$2 - s2);
const W3 = mod(_1n$2 + s2);
return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
}
function ristretto255_map(bytes) {
abytes(bytes, 64);
const R1 = calcElligatorRistrettoMap(bytes255ToNumberLE(bytes.subarray(0, 32)));
const R2 = calcElligatorRistrettoMap(bytes255ToNumberLE(bytes.subarray(32, 64)));
return new _RistrettoPoint(R1.add(R2));
}
/**
* Wrapper over Edwards Point for ristretto255.
*
* Each ed25519/ExtendedPoint has 8 different equivalent points. This can be
* a source of bugs for protocols like ring signatures. Ristretto was created to solve this.
* Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,
* but it should work in its own namespace: do not combine those two.
* See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).
*/
var _RistrettoPoint = class _RistrettoPoint extends PrimeEdwardsPoint {
constructor(ep) {
super(ep);
}
static fromAffine(ap) {
return new _RistrettoPoint(ed25519.Point.fromAffine(ap));
}
assertSame(other) {
if (!(other instanceof _RistrettoPoint)) throw new Error("RistrettoPoint expected");
}
init(ep) {
return new _RistrettoPoint(ep);
}
/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
static hashToCurve(hex) {
return ristretto255_map(ensureBytes("ristrettoHash", hex, 64));
}
static fromBytes(bytes) {
abytes(bytes, 32);
const { a, d } = ed25519_CURVE;
const P = ed25519_CURVE_p;
const mod = (n) => Fp.create(n);
const s = bytes255ToNumberLE(bytes);
if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P)) throw new Error("invalid ristretto255 encoding 1");
const s2 = mod(s * s);
const u1 = mod(_1n$2 + a * s2);
const u2 = mod(_1n$2 - a * s2);
const u1_2 = mod(u1 * u1);
const u2_2 = mod(u2 * u2);
const v = mod(a * d * u1_2 - u2_2);
const { isValid, value: I } = invertSqrt(mod(v * u2_2));
const Dx = mod(I * u2);
const Dy = mod(I * Dx * v);
let x = mod((s + s) * Dx);
if (isNegativeLE(x, P)) x = mod(-x);
const y = mod(u1 * Dy);
const t = mod(x * y);
if (!isValid || isNegativeLE(t, P) || y === _0n$2) throw new Error("invalid ristretto255 encoding 2");
return new _RistrettoPoint(new ed25519.Point(x, y, _1n$2, t));
}
/**
* Converts ristretto-encoded string to ristretto point.
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
* @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
*/
static fromHex(hex) {
return _RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex, 32));
}
static msm(points, scalars) {
return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);
}
/**
* Encodes ristretto point to Uint8Array.
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
*/
toBytes() {
let { X, Y, Z, T } = this.ep;
const P = ed25519_CURVE_p;
const mod = (n) => Fp.create(n);
const u1 = mod(mod(Z + Y) * mod(Z - Y));
const u2 = mod(X * Y);
const u2sq = mod(u2 * u2);
const { value: invsqrt } = invertSqrt(mod(u1 * u2sq));
const D1 = mod(invsqrt * u1);
const D2 = mod(invsqrt * u2);
const zInv = mod(D1 * D2 * T);
let D;
if (isNegativeLE(T * zInv, P)) {
let _x = mod(Y * SQRT_M1);
let _y = mod(X * SQRT_M1);
X = _x;
Y = _y;
D = mod(D1 * INVSQRT_A_MINUS_D);
} else D = D2;
if (isNegativeLE(X * zInv, P)) Y = mod(-Y);
let s = mod((Z - Y) * D);
if (isNegativeLE(s, P)) s = mod(-s);
return Fp.toBytes(s);
}
/**
* Compares two Ristretto points.
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
*/
equals(other) {
this.assertSame(other);
const { X: X1, Y: Y1 } = this.ep;
const { X: X2, Y: Y2 } = other.ep;
const mod = (n) => Fp.create(n);
const one = mod(X1 * Y2) === mod(Y1 * X2);
const two = mod(Y1 * Y2) === mod(X1 * X2);
return one || two;
}
is0() {
return this.equals(_RistrettoPoint.ZERO);
}
};
_RistrettoPoint.BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();
_RistrettoPoint.ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();
_RistrettoPoint.Fp = /* @__PURE__ */ (() => Fp)();
_RistrettoPoint.Fn = /* @__PURE__ */ (() => Fn)();
// 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) {
return await signBytes((await createKeyPairFromBytes(Uint8Array.from(secretKey))).privateKey, toPackedUint8Array(message));
}
async function verify(signature, message, publicKey) {
const signatureSnapshot = Uint8Array.from(signature);
const messageSnapshot = Uint8Array.from(message);
return await verifySignature(await globalThis.crypto.subtle.importKey("raw", Uint8Array.from(publicKey), { name: "Ed25519" }, true, ["verify"]), 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);
return await verifySignature(await globalThis.crypto.subtle.importKey("raw", publicKeyBytes, { name: "Ed25519" }, true, ["verify"]), 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");
// ../../node_modules/.pnpm/@solana+program-client-core@8.6.0_typescript@5.9.3/node_modules/@solana/program-client-core/dist/index.browser.mjs
function getNonNullResolvedInstructionInput(inputName, value) {
if (value === null || value === void 0) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL, { inputName });
return value;
}
function getAddressFromResolvedInstructionAccount(inputName, value) {
const nonNullValue = getNonNullResolvedInstructionInput(inputName, value);
if (typeof value === "object" && "address" in nonNullValue) return nonNullValue.address;
if (Array.isArray(nonNullValue)) return nonNullValue[0];
return nonNullValue;
}
function getResolvedInstructionAccountAsProgramDerivedAddress(inputName, value) {
if (!isProgramDerivedAddress(value)) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE, {
expectedType: "ProgramDerivedAddress",
inputName
});
return value;
}
function getAccountMetaFactory(programAddress, optionalAccountStrategy) {
return (inputName, account) => {
if (!account.value) {
if (optionalAccountStrategy === "omitted") return;
return Object.freeze({
address: programAddress,
role: AccountRole.READONLY
});
}
if (hasExplicitRole(account.value)) return Object.freeze({
address: account.value.address,
role: account.value.role,
..."signer" in account.value && account.value.signer ? { signer: account.value.signer } : {}
});
const idlIsSigner = account.isSigner ?? "either";
const isSigner = idlIsSigner !== false && isResolvedInstructionAccountSigner(account.value);
if (!isSigner && idlIsSigner === true) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_SIGNER, { inputName });
const writableRole = account.isWritable ? AccountRole.WRITABLE : AccountRole.READONLY;
return Object.freeze({
address: getAddressFromResolvedInstructionAccount(inputName, account.value),
role: isSigner ? upgradeRoleToSigner(writableRole) : writableRole,
...isSigner ? { signer: account.value } : {}
});
};
}
function hasExplicitRole(value) {
return typeof value === "object" && "role" in value && typeof value.role === "number";
}
function isResolvedInstructionAccountSigner(value) {
return !!value && typeof value === "object" && "address" in value && typeof value.address === "string" && isTransactionSigner(value);
}
// ../../node_modules/.pnpm/@solana-program+system@0.16.0_@solana+kit@8.6.0_bufferutil@4.0.8_typescript@5.9.3_utf-8-validate@5.0.10_/node_modules/@solana-program/system/dist/src/index.mjs
var NonceState = /* @__PURE__ */ ((NonceState2) => {
NonceState2[NonceState2["Uninitialized"] = 0] = "Uninitialized";
NonceState2[NonceState2["Initialized"] = 1] = "Initialized";
return NonceState2;
})(NonceState || {});
function getNonceStateDecoder() {
return getEnumDecoder(NonceState, { size: getU32Decoder() });
}
var NonceVersion = /* @__PURE__ */ ((NonceVersion2) => {
NonceVersion2[NonceVersion2["Legacy"] = 0] = "Legacy";
NonceVersion2[NonceVersion2["Current"] = 1] = "Current";
return NonceVersion2;
})(NonceVersion || {});
function getNonceVersionDecoder() {
return getEnumDecoder(NonceVersion, { size: getU32Decoder() });
}
function getNonceDecoder() {
return getStructDecoder([
["version", getNonceVersionDecoder()],
["state", getNonceStateDecoder()],
["authority", getAddressDecoder()],
["blockhash", getAddressDecoder()],
["lamportsPerSignature", getU64Decoder()]
]);
}
function getNonceSize() {
return 80;
}
function getAdvanceNonceAccountInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 4
}));
}
function getAdvanceNonceAccountInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getAdvanceNonceAccountInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
nonceAccount: {
value: input.nonceAccount ?? null,
isSigner: false,
isWritable: true
},
recentBlockhashesSysvar: {
value: input.recentBlockhashesSysvar ?? null,
isSigner: false,
isWritable: false
},
nonceAuthority: {
value: input.nonceAuthority ?? null,
isSigner: true,
isWritable: false
}
};
if (!accounts.recentBlockhashesSysvar.value) accounts.recentBlockhashesSysvar.value = "SysvarRecentB1ockHashes11111111111111111111";
return Object.freeze({
accounts: [
getAccountMeta("nonceAccount", accounts.nonceAccount),
getAccountMeta("recentBlockhashesSysvar", accounts.recentBlockhashesSysvar),
getAccountMeta("nonceAuthority", accounts.nonceAuthority)
],
data: getAdvanceNonceAccountInstructionDataEncoder().encode({}),
programAddress
});
}
function parseAdvanceNonceAccountInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
nonceAccount: getNextAccount(),
recentBlockhashesSysvar: getNextAccount(),
nonceAuthority: getNextAccount()
},
data: getAdvanceNonceAccountInstructionDataDecoder().decode(instruction.data)
};
}
function getAllocateInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["space", getU64Encoder()]]), (value) => ({
...value,
discriminator: 8
}));
}
function getAllocateInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["space", getU64Decoder()]]);
}
function getAllocateInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = { newAccount: {
value: input.newAccount ?? null,
isSigner: true,
isWritable: true
} };
const args = { ...input };
return Object.freeze({
accounts: [getAccountMeta("newAccount", accounts.newAccount)],
data: getAllocateInstructionDataEncoder().encode(args),
programAddress
});
}
function parseAllocateInstruction(instruction) {
if (instruction.accounts.length < 1) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 1
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: { newAccount: getNextAccount() },
data: getAllocateInstructionDataDecoder().decode(instruction.data)
};
}
function getAllocateWithSeedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["base", getAddressEncoder()],
["seed", addEncoderSizePrefix(getUtf8Encoder(), getU64Encoder())],
["space", getU64Encoder()],
["programAddress", getAddressEncoder()]
]), (value) => ({
...value,
discriminator: 9
}));
}
function getAllocateWithSeedInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["base", getAddressDecoder()],
["seed", addDecoderSizePrefix(getUtf8Decoder(), getU64Decoder())],
["space", getU64Decoder()],
["programAddress", getAddressDecoder()]
]);
}
function getAllocateWithSeedInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
newAccount: {
value: input.newAccount ?? null,
isSigner: false,
isWritable: true
},
baseAccount: {
value: input.baseAccount ?? null,
isSigner: true,
isWritable: false
}
};
const args = { ...input };
return Object.freeze({
accounts: [getAccountMeta("newAccount", accounts.newAccount), getAccountMeta("baseAccount", accounts.baseAccount)],
data: getAllocateWithSeedInstructionDataEncoder().encode(args),
programAddress
});
}
function parseAllocateWithSeedInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
newAccount: getNextAccount(),
baseAccount: getNextAccount()
},
data: getAllocateWithSeedInstructionDataDecoder().decode(instruction.data)
};
}
function getAssignInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["programAddress", getAddressEncoder()]]), (value) => ({
...value,
discriminator: 1
}));
}
function getAssignInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["programAddress", getAddressDecoder()]]);
}
function getAssignInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = { account: {
value: input.account ?? null,
isSigner: true,
isWritable: true
} };
const args = { ...input };
return Object.freeze({
accounts: [getAccountMeta("account", accounts.account)],
data: getAssignInstructionDataEncoder().encode(args),
programAddress
});
}
function parseAssignInstruction(instruction) {
if (instruction.accounts.length < 1) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 1
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: { account: getNextAccount() },
data: getAssignInstructionDataDecoder().decode(instruction.data)
};
}
function getAssignWithSeedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["base", getAddressEncoder()],
["seed", addEncoderSizePrefix(getUtf8Encoder(), getU64Encoder())],
["programAddress", getAddressEncoder()]
]), (value) => ({
...value,
discriminator: 10
}));
}
function getAssignWithSeedInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["base", getAddressDecoder()],
["seed", addDecoderSizePrefix(getUtf8Decoder(), getU64Decoder())],
["programAddress", getAddressDecoder()]
]);
}
function getAssignWithSeedInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
account: {
value: input.account ?? null,
isSigner: false,
isWritable: true
},
baseAccount: {
value: input.baseAccount ?? null,
isSigner: true,
isWritable: false
}
};
const args = { ...input };
return Object.freeze({
accounts: [getAccountMeta("account", accounts.account), getAccountMeta("baseAccount", accounts.baseAccount)],
data: getAssignWithSeedInstructionDataEncoder().encode(args),
programAddress
});
}
function parseAssignWithSeedInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
account: getNextAccount(),
baseAccount: getNextAccount()
},
data: getAssignWithSeedInstructionDataDecoder().decode(instruction.data)
};
}
function getAuthorizeNonceAccountInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["newNonceAuthority", getAddressEncoder()]]), (value) => ({
...value,
discriminator: 7
}));
}
function getAuthorizeNonceAccountInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["newNonceAuthority", getAddressDecoder()]]);
}
function getAuthorizeNonceAccountInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
nonceAccount: {
value: input.nonceAccount ?? null,
isSigner: false,
isWritable: true
},
nonceAuthority: {
value: input.nonceAuthority ?? null,
isSigner: true,
isWritable: false
}
};
const args = { ...input };
return Object.freeze({
accounts: [getAccountMeta("nonceAccount", accounts.nonceAccount), getAccountMeta("nonceAuthority", accounts.nonceAuthority)],
data: getAuthorizeNonceAccountInstructionDataEncoder().encode(args),
programAddress
});
}
function parseAuthorizeNonceAccountInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
nonceAccount: getNextAccount(),
nonceAuthority: getNextAccount()
},
data: getAuthorizeNonceAccountInstructionDataDecoder().decode(instruction.data)
};
}
function getCreateAccountInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["lamports", getU64Encoder()],
["space", getU64Encoder()],
["programAddress", getAddressEncoder()]
]), (value) => ({
...value,
discriminator: 0
}));
}
function getCreateAccountInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["lamports", getU64Decoder()],
["space", getU64Decoder()],
["programAddress", getAddressDecoder()]
]);
}
function getCreateAccountInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
payer: {
value: input.payer ?? null,
isSigner: true,
isWritable: true
},
newAccount: {
value: input.newAccount ?? null,
isSigner: true,
isWritable: true
}
};
const args = { ...input };
const byteDelta = [Number(args.space) + 128].reduce((a, b) => a + b, 0);
return Object.freeze({
accounts: [getAccountMeta("payer", accounts.payer), getAccountMeta("newAccount", accounts.newAccount)],
byteDelta,
data: getCreateAccountInstructionDataEncoder().encode(args),
programAddress
});
}
function parseCreateAccountInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
payer: getNextAccount(),
newAccount: getNextAccount()
},
data: getCreateAccountInstructionDataDecoder().decode(instruction.data)
};
}
function getCreateAccountAllowPrefundInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["lamports", getU64Decoder()],
["space", getU64Decoder()],
["programAddress", getAddressDecoder()]
]);
}
function parseCreateAccountAllowPrefundInstruction(instruction) {
if (instruction.accounts.length < 1) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 1
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
let optionalAccountsRemaining = instruction.accounts.length - 1;
const getNextOptionalAccount = () => {
if (optionalAccountsRemaining === 0) return void 0;
optionalAccountsRemaining -= 1;
return getNextAccount();
};
return {
programAddress: instruction.programAddress,
accounts: {
newAccount: getNextAccount(),
payer: getNextOptionalAccount()
},
data: getCreateAccountAllowPrefundInstructionDataDecoder().decode(instruction.data)
};
}
function getCreateAccountWithSeedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["base", getAddressEncoder()],
["seed", addEncoderSizePrefix(getUtf8Encoder(), getU64Encoder())],
["amount", getU64Encoder()],
["space", getU64Encoder()],
["programAddress", getAddressEncoder()]
]), (value) => ({
...value,
discriminator: 3
}));
}
function getCreateAccountWithSeedInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["base", getAddressDecoder()],
["seed", addDecoderSizePrefix(getUtf8Decoder(), getU64Decoder())],
["amount", getU64Decoder()],
["space", getU64Decoder()],
["programAddress", getAddressDecoder()]
]);
}
function getCreateAccountWithSeedInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
payer: {
value: input.payer ?? null,
isSigner: true,
isWritable: true
},
newAccount: {
value: input.newAccount ?? null,
isSigner: false,
isWritable: true
},
baseAccount: {
value: input.baseAccount ?? null,
isSigner: true,
isWritable: false
}
};
const args = { ...input };
return Object.freeze({
accounts: [
getAccountMeta("payer", accounts.payer),
getAccountMeta("newAccount", accounts.newAccount),
getAccountMeta("baseAccount", accounts.baseAccount)
].filter((x) => x !== void 0),
data: getCreateAccountWithSeedInstructionDataEncoder().encode(args),
programAddress
});
}
function parseCreateAccountWithSeedInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
let optionalAccountsRemaining = instruction.accounts.length - 2;
const getNextOptionalAccount = () => {
if (optionalAccountsRemaining === 0) return void 0;
optionalAccountsRemaining -= 1;
return getNextAccount();
};
return {
programAddress: instruction.programAddress,
accounts: {
payer: getNextAccount(),
newAccount: getNextAccount(),
baseAccount: getNextOptionalAccount()
},
data: getCreateAccountWithSeedInstructionDataDecoder().decode(instruction.data)
};
}
function getInitializeNonceAccountInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["nonceAuthority", getAddressEncoder()]]), (value) => ({
...value,
discriminator: 6
}));
}
function getInitializeNonceAccountInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["nonceAuthority", getAddressDecoder()]]);
}
function getInitializeNonceAccountInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
nonceAccount: {
value: input.nonceAccount ?? null,
isSigner: false,
isWritable: true
},
recentBlockhashesSysvar: {
value: input.recentBlockhashesSysvar ?? null,
isSigner: false,
isWritable: false
},
rentSysvar: {
value: input.rentSysvar ?? null,
isSigner: false,
isWritable: false
}
};
const args = { ...input };
if (!accounts.recentBlockhashesSysvar.value) accounts.recentBlockhashesSysvar.value = "SysvarRecentB1ockHashes11111111111111111111";
if (!accounts.rentSysvar.value) accounts.rentSysvar.value = "SysvarRent111111111111111111111111111111111";
return Object.freeze({
accounts: [
getAccountMeta("nonceAccount", accounts.nonceAccount),
getAccountMeta("recentBlockhashesSysvar", accounts.recentBlockhashesSysvar),
getAccountMeta("rentSysvar", accounts.rentSysvar)
],
data: getInitializeNonceAccountInstructionDataEncoder().encode(args),
programAddress
});
}
function parseInitializeNonceAccountInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
nonceAccount: getNextAccount(),
recentBlockhashesSysvar: getNextAccount(),
rentSysvar: getNextAccount()
},
data: getInitializeNonceAccountInstructionDataDecoder().decode(instruction.data)
};
}
function getTransferSolInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["amount", getU64Encoder()]]), (value) => ({
...value,
discriminator: 2
}));
}
function getTransferSolInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["amount", getU64Decoder()]]);
}
function getTransferSolInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
source: {
value: input.source ?? null,
isSigner: true,
isWritable: true
},
destination: {
value: input.destination ?? null,
isSigner: false,
isWritable: true
}
};
const args = { ...input };
return Object.freeze({
accounts: [getAccountMeta("source", accounts.source), getAccountMeta("destination", accounts.destination)],
data: getTransferSolInstructionDataEncoder().encode(args),
programAddress
});
}
function parseTransferSolInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
source: getNextAccount(),
destination: getNextAccount()
},
data: getTransferSolInstructionDataDecoder().decode(instruction.data)
};
}
function getTransferSolWithSeedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["amount", getU64Encoder()],
["fromSeed", addEncoderSizePrefix(getUtf8Encoder(), getU64Encoder())],
["fromOwner", getAddressEncoder()]
]), (value) => ({
...value,
discriminator: 11
}));
}
function getTransferSolWithSeedInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["amount", getU64Decoder()],
["fromSeed", addDecoderSizePrefix(getUtf8Decoder(), getU64Decoder())],
["fromOwner", getAddressDecoder()]
]);
}
function getTransferSolWithSeedInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
source: {
value: input.source ?? null,
isSigner: false,
isWritable: true
},
baseAccount: {
value: input.baseAccount ?? null,
isSigner: true,
isWritable: false
},
destination: {
value: input.destination ?? null,
isSigner: false,
isWritable: true
}
};
const args = { ...input };
return Object.freeze({
accounts: [
getAccountMeta("source", accounts.source),
getAccountMeta("baseAccount", accounts.baseAccount),
getAccountMeta("destination", accounts.destination)
],
data: getTransferSolWithSeedInstructionDataEncoder().encode(args),
programAddress
});
}
function parseTransferSolWithSeedInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
source: getNextAccount(),
baseAccount: getNextAccount(),
destination: getNextAccount()
},
data: getTransferSolWithSeedInstructionDataDecoder().decode(instruction.data)
};
}
function getUpgradeNonceAccountInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function parseUpgradeNonceAccountInstruction(instruction) {
if (instruction.accounts.length < 1) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 1
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: { nonceAccount: getNextAccount() },
data: getUpgradeNonceAccountInstructionDataDecoder().decode(instruction.data)
};
}
function getWithdrawNonceAccountInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["withdrawAmount", getU64Encoder()]]), (value) => ({
...value,
discriminator: 5
}));
}
function getWithdrawNonceAccountInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["withdrawAmount", getU64Decoder()]]);
}
function getWithdrawNonceAccountInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "11111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
const accounts = {
nonceAccount: {
value: input.nonceAccount ?? null,
isSigner: false,
isWritable: true
},
recipientAccount: {
value: input.recipientAccount ?? null,
isSigner: false,
isWritable: true
},
recentBlockhashesSysvar: {
value: input.recentBlockhashesSysvar ?? null,
isSigner: false,
isWritable: false
},
rentSysvar: {
value: input.rentSysvar ?? null,
isSigner: false,
isWritable: false
},
nonceAuthority: {
value: input.nonceAuthority ?? null,
isSigner: true,
isWritable: false
}
};
const args = { ...input };
if (!accounts.recentBlockhashesSysvar.value) accounts.recentBlockhashesSysvar.value = "SysvarRecentB1ockHashes11111111111111111111";
if (!accounts.rentSysvar.value) accounts.rentSysvar.value = "SysvarRent111111111111111111111111111111111";
return Object.freeze({
accounts: [
getAccountMeta("nonceAccount", accounts.nonceAccount),
getAccountMeta("recipientAccount", accounts.recipientAccount),
getAccountMeta("recentBlockhashesSysvar", accounts.recentBlockhashesSysvar),
getAccountMeta("rentSysvar", accounts.rentSysvar),
getAccountMeta("nonceAuthority", accounts.nonceAuthority)
],
data: getWithdrawNonceAccountInstructionDataEncoder().encode(args),
programAddress
});
}
function parseWithdrawNonceAccountInstruction(instruction) {
if (instruction.accounts.length < 5) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 5
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
nonceAccount: getNextAccount(),
recipientAccount: getNextAccount(),
recentBlockhashesSysvar: getNextAccount(),
rentSysvar: getNextAccount(),
nonceAuthority: getNextAccount()
},
data: getWithdrawNonceAccountInstructionDataDecoder().decode(instruction.data)
};
}
var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111";
var SystemInstruction$1 = /* @__PURE__ */ ((SystemInstruction2) => {
SystemInstruction2[SystemInstruction2["CreateAccount"] = 0] = "CreateAccount";
SystemInstruction2[SystemInstruction2["Assign"] = 1] = "Assign";
SystemInstruction2[SystemInstruction2["TransferSol"] = 2] = "TransferSol";
SystemInstruction2[SystemInstruction2["CreateAccountWithSeed"] = 3] = "CreateAccountWithSeed";
SystemInstruction2[SystemInstruction2["AdvanceNonceAccount"] = 4] = "AdvanceNonceAccount";
SystemInstruction2[SystemInstruction2["WithdrawNonceAccount"] = 5] = "WithdrawNonceAccount";
SystemInstruction2[SystemInstruction2["InitializeNonceAccount"] = 6] = "InitializeNonceAccount";
SystemInstruction2[SystemInstruction2["AuthorizeNonceAccount"] = 7] = "AuthorizeNonceAccount";
SystemInstruction2[SystemInstruction2["Allocate"] = 8] = "Allocate";
SystemInstruction2[SystemInstruction2["AllocateWithSeed"] = 9] = "AllocateWithSeed";
SystemInstruction2[SystemInstruction2["AssignWithSeed"] = 10] = "AssignWithSeed";
SystemInstruction2[SystemInstruction2["TransferSolWithSeed"] = 11] = "TransferSolWithSeed";
SystemInstruction2[SystemInstruction2["UpgradeNonceAccount"] = 12] = "UpgradeNonceAccount";
SystemInstruction2[SystemInstruction2["CreateAccountAllowPrefund"] = 13] = "CreateAccountAllowPrefund";
return SystemInstruction2;
})(SystemInstruction$1 || {});
function identifySystemInstruction(instruction) {
const data = "data" in instruction ? instruction.data : instruction;
if (containsBytes(data, getU32Encoder().encode(0), 0)) return 0;
if (containsBytes(data, getU32Encoder().encode(1), 0)) return 1;
if (containsBytes(data, getU32Encoder().encode(2), 0)) return 2;
if (containsBytes(data, getU32Encoder().encode(3), 0)) return 3;
if (containsBytes(data, getU32Encoder().encode(4), 0)) return 4;
if (containsBytes(data, getU32Encoder().encode(5), 0)) return 5;
if (containsBytes(data, getU32Encoder().encode(6), 0)) return 6;
if (containsBytes(data, getU32Encoder().encode(7), 0)) return 7;
if (containsBytes(data, getU32Encoder().encode(8), 0)) return 8;
if (containsBytes(data, getU32Encoder().encode(9), 0)) return 9;
if (containsBytes(data, getU32Encoder().encode(10), 0)) return 10;
if (containsBytes(data, getU32Encoder().encode(11), 0)) return 11;
if (containsBytes(data, getU32Encoder().encode(12), 0)) return 12;
if (containsBytes(data, getU32Encoder().encode(13), 0)) return 13;
throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {
instructionData: data,
programName: "system"
});
}
function parseSystemInstruction(instruction) {
const instructionType = identifySystemInstruction(instruction);
switch (instructionType) {
case 0:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 0,
...parseCreateAccountInstruction(instruction)
};
case 1:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 1,
...parseAssignInstruction(instruction)
};
case 2:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 2,
...parseTransferSolInstruction(instruction)
};
case 3:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 3,
...parseCreateAccountWithSeedInstruction(instruction)
};
case 4:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 4,
...parseAdvanceNonceAccountInstruction(instruction)
};
case 5:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 5,
...parseWithdrawNonceAccountInstruction(instruction)
};
case 6:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 6,
...parseInitializeNonceAccountInstruction(instruction)
};
case 7:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 7,
...parseAuthorizeNonceAccountInstruction(instruction)
};
case 8:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 8,
...parseAllocateInstruction(instruction)
};
case 9:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 9,
...parseAllocateWithSeedInstruction(instruction)
};
case 10:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 10,
...parseAssignWithSeedInstruction(instruction)
};
case 11:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 11,
...parseTransferSolWithSeedInstruction(instruction)
};
case 12:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 12,
...parseUpgradeNonceAccountInstruction(instruction)
};
case 13:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 13,
...parseCreateAccountAllowPrefundInstruction(instruction)
};
default: throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {
instructionType,
programName: "system"
});
}
}
// 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$1();
const BASE58_DECODER = getBase58Decoder$1();
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();
/**
* 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 & -32) !== 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 TRANSACTION_WIRE_DECODER = getStructDecoder([["signatures", getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { 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$1();
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$1();
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
}
};
}
// ../../node_modules/.pnpm/@solana-program+address-lookup-table@0.16.0_@solana+kit@8.6.0_bufferutil@4.0.8_typescript@5.9.3_utf-8-validate@5.0.10_/node_modules/@solana-program/address-lookup-table/dist/src/index.mjs
function getAddressLookupTableDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["deactivationSlot", getU64Decoder()],
["lastExtendedSlot", getU64Decoder()],
["lastExtendedSlotStartIndex", getU8Decoder()],
["authority", getOptionDecoder(getAddressDecoder(), { noneValue: "zeroes" })],
["padding", getU16Decoder()],
["addresses", getArrayDecoder(getAddressDecoder(), { size: "remainder" })]
]);
}
var ADDRESS_LOOKUP_TABLE_PROGRAM_ADDRESS = "AddressLookupTab1e1111111111111111111111111";
var AddressLookupTableInstruction$1 = /* @__PURE__ */ ((AddressLookupTableInstruction2) => {
AddressLookupTableInstruction2[AddressLookupTableInstruction2["CreateLookupTable"] = 0] = "CreateLookupTable";
AddressLookupTableInstruction2[AddressLookupTableInstruction2["FreezeLookupTable"] = 1] = "FreezeLookupTable";
AddressLookupTableInstruction2[AddressLookupTableInstruction2["ExtendLookupTable"] = 2] = "ExtendLookupTable";
AddressLookupTableInstruction2[AddressLookupTableInstruction2["DeactivateLookupTable"] = 3] = "DeactivateLookupTable";
AddressLookupTableInstruction2[AddressLookupTableInstruction2["CloseLookupTable"] = 4] = "CloseLookupTable";
return AddressLookupTableInstruction2;
})(AddressLookupTableInstruction$1 || {});
function identifyAddressLookupTableInstruction(instruction) {
const data = "data" in instruction ? instruction.data : instruction;
if (containsBytes(data, getU32Encoder().encode(0), 0)) return 0;
if (containsBytes(data, getU32Encoder().encode(1), 0)) return 1;
if (containsBytes(data, getU32Encoder().encode(2), 0)) return 2;
if (containsBytes(data, getU32Encoder().encode(3), 0)) return 3;
if (containsBytes(data, getU32Encoder().encode(4), 0)) return 4;
throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {
instructionData: data,
programName: "addressLookupTable"
});
}
function parseAddressLookupTableInstruction(instruction) {
const instructionType = identifyAddressLookupTableInstruction(instruction);
switch (instructionType) {
case 0:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 0,
...parseCreateLookupTableInstruction(instruction)
};
case 1:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 1,
...parseFreezeLookupTableInstruction(instruction)
};
case 2:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 2,
...parseExtendLookupTableInstruction(instruction)
};
case 3:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 3,
...parseDeactivateLookupTableInstruction(instruction)
};
case 4:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 4,
...parseCloseLookupTableInstruction(instruction)
};
default: throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {
instructionType,
programName: "addressLookupTable"
});
}
}
function getCloseLookupTableInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 4
}));
}
function getCloseLookupTableInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getCloseLookupTableInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "AddressLookupTab1e1111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
address: {
value: input.address ?? null,
isSigner: false,
isWritable: true
},
authority: {
value: input.authority ?? null,
isSigner: true,
isWritable: false
},
recipient: {
value: input.recipient ?? null,
isSigner: false,
isWritable: true
}
};
return Object.freeze({
accounts: [
getAccountMeta("address", accounts.address),
getAccountMeta("authority", accounts.authority),
getAccountMeta("recipient", accounts.recipient)
],
data: getCloseLookupTableInstructionDataEncoder().encode({}),
programAddress
});
}
function parseCloseLookupTableInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
address: getNextAccount(),
authority: getNextAccount(),
recipient: getNextAccount()
},
data: getCloseLookupTableInstructionDataDecoder().decode(instruction.data)
};
}
function getCreateLookupTableInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["recentSlot", getU64Encoder()],
["bump", getU8Encoder()]
]), (value) => ({
...value,
discriminator: 0
}));
}
function getCreateLookupTableInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["recentSlot", getU64Decoder()],
["bump", getU8Decoder()]
]);
}
function getCreateLookupTableInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "AddressLookupTab1e1111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
address: {
value: input.address ?? null,
isSigner: false,
isWritable: true
},
authority: {
value: input.authority ?? null,
isSigner: false,
isWritable: false
},
payer: {
value: input.payer ?? null,
isSigner: "either",
isWritable: true
},
systemProgram: {
value: input.systemProgram ?? null,
isSigner: false,
isWritable: false
}
};
const args = { ...input };
if (!accounts.payer.value) accounts.payer.value = getNonNullResolvedInstructionInput("authority", accounts.authority.value);
if (!accounts.systemProgram.value) accounts.systemProgram.value = "11111111111111111111111111111111";
if (!args.bump) args.bump = getResolvedInstructionAccountAsProgramDerivedAddress("address", accounts.address.value)[1];
const byteDelta = [184].reduce((a, b) => a + b, 0);
return Object.freeze({
accounts: [
getAccountMeta("address", accounts.address),
getAccountMeta("authority", accounts.authority),
getAccountMeta("payer", accounts.payer),
getAccountMeta("systemProgram", accounts.systemProgram)
],
byteDelta,
data: getCreateLookupTableInstructionDataEncoder().encode(args),
programAddress
});
}
function parseCreateLookupTableInstruction(instruction) {
if (instruction.accounts.length < 4) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 4
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
address: getNextAccount(),
authority: getNextAccount(),
payer: getNextAccount(),
systemProgram: getNextAccount()
},
data: getCreateLookupTableInstructionDataDecoder().decode(instruction.data)
};
}
function getDeactivateLookupTableInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 3
}));
}
function getDeactivateLookupTableInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getDeactivateLookupTableInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "AddressLookupTab1e1111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
address: {
value: input.address ?? null,
isSigner: false,
isWritable: true
},
authority: {
value: input.authority ?? null,
isSigner: true,
isWritable: false
}
};
return Object.freeze({
accounts: [getAccountMeta("address", accounts.address), getAccountMeta("authority", accounts.authority)],
data: getDeactivateLookupTableInstructionDataEncoder().encode({}),
programAddress
});
}
function parseDeactivateLookupTableInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
address: getNextAccount(),
authority: getNextAccount()
},
data: getDeactivateLookupTableInstructionDataDecoder().decode(instruction.data)
};
}
var resolveExtendLookupTableBytes = (scope) => 32 * scope.args.addresses.length;
function getExtendLookupTableInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["addresses", getArrayEncoder(getAddressEncoder(), { size: getU64Encoder() })]]), (value) => ({
...value,
discriminator: 2
}));
}
function getExtendLookupTableInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["addresses", getArrayDecoder(getAddressDecoder(), { size: getU64Decoder() })]]);
}
function getExtendLookupTableInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "AddressLookupTab1e1111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
address: {
value: input.address ?? null,
isSigner: false,
isWritable: true
},
authority: {
value: input.authority ?? null,
isSigner: true,
isWritable: false
},
payer: {
value: input.payer ?? null,
isSigner: true,
isWritable: true
},
systemProgram: {
value: input.systemProgram ?? null,
isSigner: false,
isWritable: false
}
};
const args = { ...input };
const resolverScope = { args };
if (!accounts.systemProgram.value) accounts.systemProgram.value = "11111111111111111111111111111111";
const byteDelta = [resolveExtendLookupTableBytes(resolverScope)].reduce((a, b) => a + b, 0);
return Object.freeze({
accounts: [
getAccountMeta("address", accounts.address),
getAccountMeta("authority", accounts.authority),
getAccountMeta("payer", accounts.payer),
getAccountMeta("systemProgram", accounts.systemProgram)
],
byteDelta,
data: getExtendLookupTableInstructionDataEncoder().encode(args),
programAddress
});
}
function parseExtendLookupTableInstruction(instruction) {
if (instruction.accounts.length < 4) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 4
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
address: getNextAccount(),
authority: getNextAccount(),
payer: getNextAccount(),
systemProgram: getNextAccount()
},
data: getExtendLookupTableInstructionDataDecoder().decode(instruction.data)
};
}
function getFreezeLookupTableInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 1
}));
}
function getFreezeLookupTableInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getFreezeLookupTableInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "AddressLookupTab1e1111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
address: {
value: input.address ?? null,
isSigner: false,
isWritable: true
},
authority: {
value: input.authority ?? null,
isSigner: true,
isWritable: false
}
};
return Object.freeze({
accounts: [getAccountMeta("address", accounts.address), getAccountMeta("authority", accounts.authority)],
data: getFreezeLookupTableInstructionDataEncoder().encode({}),
programAddress
});
}
function parseFreezeLookupTableInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
address: getNextAccount(),
authority: getNextAccount()
},
data: getFreezeLookupTableInstructionDataDecoder().decode(instruction.data)
};
}
// 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 !== 1) 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$1();
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$1();
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, 8100002) || 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, -32002)) {
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) => index_default(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");
return lamports(await this.getMinimumBalanceForRentExemption(0) / BigInt(128) * 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 = index_default({
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));
}
};
// ../../node_modules/.pnpm/@solana-program+compute-budget@0.20.0_@solana+kit@8.6.0_bufferutil@4.0.8_typescript@5.9.3_utf-8-validate@5.0.10_/node_modules/@solana-program/compute-budget/dist/src/index.mjs
var COMPUTE_BUDGET_PROGRAM_ADDRESS = "ComputeBudget111111111111111111111111111111";
var ComputeBudgetInstruction$1 = /* @__PURE__ */ ((ComputeBudgetInstruction2) => {
ComputeBudgetInstruction2[ComputeBudgetInstruction2["RequestUnits"] = 0] = "RequestUnits";
ComputeBudgetInstruction2[ComputeBudgetInstruction2["RequestHeapFrame"] = 1] = "RequestHeapFrame";
ComputeBudgetInstruction2[ComputeBudgetInstruction2["SetComputeUnitLimit"] = 2] = "SetComputeUnitLimit";
ComputeBudgetInstruction2[ComputeBudgetInstruction2["SetComputeUnitPrice"] = 3] = "SetComputeUnitPrice";
ComputeBudgetInstruction2[ComputeBudgetInstruction2["SetLoadedAccountsDataSizeLimit"] = 4] = "SetLoadedAccountsDataSizeLimit";
return ComputeBudgetInstruction2;
})(ComputeBudgetInstruction$1 || {});
function identifyComputeBudgetInstruction(instruction) {
const data = "data" in instruction ? instruction.data : instruction;
if (containsBytes(data, getU8Encoder().encode(0), 0)) return 0;
if (containsBytes(data, getU8Encoder().encode(1), 0)) return 1;
if (containsBytes(data, getU8Encoder().encode(2), 0)) return 2;
if (containsBytes(data, getU8Encoder().encode(3), 0)) return 3;
if (containsBytes(data, getU8Encoder().encode(4), 0)) return 4;
throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {
instructionData: data,
programName: "computeBudget"
});
}
function parseComputeBudgetInstruction(instruction) {
const instructionType = identifyComputeBudgetInstruction(instruction);
switch (instructionType) {
case 0: return {
instructionType: 0,
...parseRequestUnitsInstruction(instruction)
};
case 1: return {
instructionType: 1,
...parseRequestHeapFrameInstruction(instruction)
};
case 2: return {
instructionType: 2,
...parseSetComputeUnitLimitInstruction(instruction)
};
case 3: return {
instructionType: 3,
...parseSetComputeUnitPriceInstruction(instruction)
};
case 4: return {
instructionType: 4,
...parseSetLoadedAccountsDataSizeLimitInstruction(instruction)
};
default: throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {
instructionType,
programName: "computeBudget"
});
}
}
function getRequestHeapFrameInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()], ["bytes", getU32Encoder()]]), (value) => ({
...value,
discriminator: 1
}));
}
function getRequestHeapFrameInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU8Decoder()], ["bytes", getU32Decoder()]]);
}
function getRequestHeapFrameInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "ComputeBudget111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const args = { ...input };
return Object.freeze({
data: getRequestHeapFrameInstructionDataEncoder().encode(args),
programAddress
});
}
function parseRequestHeapFrameInstruction(instruction) {
return {
programAddress: instruction.programAddress,
data: getRequestHeapFrameInstructionDataDecoder().decode(instruction.data)
};
}
function getRequestUnitsInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU8Encoder()],
["units", getU32Encoder()],
["additionalFee", getU32Encoder()]
]), (value) => ({
...value,
discriminator: 0
}));
}
function getRequestUnitsInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU8Decoder()],
["units", getU32Decoder()],
["additionalFee", getU32Decoder()]
]);
}
function getRequestUnitsInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "ComputeBudget111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const args = { ...input };
return Object.freeze({
data: getRequestUnitsInstructionDataEncoder().encode(args),
programAddress
});
}
function parseRequestUnitsInstruction(instruction) {
return {
programAddress: instruction.programAddress,
data: getRequestUnitsInstructionDataDecoder().decode(instruction.data)
};
}
function getSetComputeUnitLimitInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()], ["units", getU32Encoder()]]), (value) => ({
...value,
discriminator: 2
}));
}
function getSetComputeUnitLimitInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU8Decoder()], ["units", getU32Decoder()]]);
}
function getSetComputeUnitLimitInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "ComputeBudget111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const args = { ...input };
return Object.freeze({
data: getSetComputeUnitLimitInstructionDataEncoder().encode(args),
programAddress
});
}
function parseSetComputeUnitLimitInstruction(instruction) {
return {
programAddress: instruction.programAddress,
data: getSetComputeUnitLimitInstructionDataDecoder().decode(instruction.data)
};
}
function getSetComputeUnitPriceInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()], ["microLamports", getU64Encoder()]]), (value) => ({
...value,
discriminator: 3
}));
}
function getSetComputeUnitPriceInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU8Decoder()], ["microLamports", getU64Decoder()]]);
}
function getSetComputeUnitPriceInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "ComputeBudget111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const args = { ...input };
return Object.freeze({
data: getSetComputeUnitPriceInstructionDataEncoder().encode(args),
programAddress
});
}
function parseSetComputeUnitPriceInstruction(instruction) {
return {
programAddress: instruction.programAddress,
data: getSetComputeUnitPriceInstructionDataDecoder().decode(instruction.data)
};
}
function getSetLoadedAccountsDataSizeLimitInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()], ["accountDataSizeLimit", getU32Encoder()]]), (value) => ({
...value,
discriminator: 4
}));
}
function getSetLoadedAccountsDataSizeLimitInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU8Decoder()], ["accountDataSizeLimit", getU32Decoder()]]);
}
function getSetLoadedAccountsDataSizeLimitInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "ComputeBudget111111111111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const args = { ...input };
return Object.freeze({
data: getSetLoadedAccountsDataSizeLimitInstructionDataEncoder().encode(args),
programAddress
});
}
function parseSetLoadedAccountsDataSizeLimitInstruction(instruction) {
return {
programAddress: instruction.programAddress,
data: getSetLoadedAccountsDataSizeLimitInstructionDataDecoder().decode(instruction.data)
};
}
// 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));
}
};
// ../../node_modules/.pnpm/@solana-program+loader-v3@0.8.0_@solana+kit@8.6.0_bufferutil@4.0.8_typescript@5.9.3_utf-8-validate@5.0.10_/node_modules/@solana-program/loader-v3/dist/src/index.mjs
var LOADER_V3_PROGRAM_ADDRESS = "BPFLoaderUpgradeab1e11111111111111111111111";
var LoaderV3Instruction$1 = /* @__PURE__ */ ((LoaderV3Instruction2) => {
LoaderV3Instruction2[LoaderV3Instruction2["InitializeBuffer"] = 0] = "InitializeBuffer";
LoaderV3Instruction2[LoaderV3Instruction2["Write"] = 1] = "Write";
LoaderV3Instruction2[LoaderV3Instruction2["DeployWithMaxDataLen"] = 2] = "DeployWithMaxDataLen";
LoaderV3Instruction2[LoaderV3Instruction2["Upgrade"] = 3] = "Upgrade";
LoaderV3Instruction2[LoaderV3Instruction2["SetAuthority"] = 4] = "SetAuthority";
LoaderV3Instruction2[LoaderV3Instruction2["Close"] = 5] = "Close";
LoaderV3Instruction2[LoaderV3Instruction2["ExtendProgram"] = 6] = "ExtendProgram";
LoaderV3Instruction2[LoaderV3Instruction2["SetAuthorityChecked"] = 7] = "SetAuthorityChecked";
return LoaderV3Instruction2;
})(LoaderV3Instruction$1 || {});
function identifyLoaderV3Instruction(instruction) {
const data = "data" in instruction ? instruction.data : instruction;
if (containsBytes(data, getU32Encoder().encode(0), 0)) return 0;
if (containsBytes(data, getU32Encoder().encode(1), 0)) return 1;
if (containsBytes(data, getU32Encoder().encode(2), 0)) return 2;
if (containsBytes(data, getU32Encoder().encode(3), 0)) return 3;
if (containsBytes(data, getU32Encoder().encode(4), 0)) return 4;
if (containsBytes(data, getU32Encoder().encode(5), 0)) return 5;
if (containsBytes(data, getU32Encoder().encode(6), 0)) return 6;
if (containsBytes(data, getU32Encoder().encode(7), 0)) return 7;
throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {
instructionData: data,
programName: "loaderV3"
});
}
function parseLoaderV3Instruction(instruction) {
const instructionType = identifyLoaderV3Instruction(instruction);
switch (instructionType) {
case 0:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 0,
...parseInitializeBufferInstruction(instruction)
};
case 1:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 1,
...parseWriteInstruction(instruction)
};
case 2:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 2,
...parseDeployWithMaxDataLenInstruction(instruction)
};
case 3:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 3,
...parseUpgradeInstruction(instruction)
};
case 4:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 4,
...parseSetAuthorityInstruction(instruction)
};
case 5:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 5,
...parseCloseInstruction(instruction)
};
case 6:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 6,
...parseExtendProgramInstruction(instruction)
};
case 7:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 7,
...parseSetAuthorityCheckedInstruction(instruction)
};
default: throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {
instructionType,
programName: "loaderV3"
});
}
}
function getCloseInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 5
}));
}
function getCloseInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getCloseInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "BPFLoaderUpgradeab1e11111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
bufferOrProgramDataAccount: {
value: input.bufferOrProgramDataAccount ?? null,
isSigner: false,
isWritable: true
},
destinationAccount: {
value: input.destinationAccount ?? null,
isSigner: false,
isWritable: true
},
authority: {
value: input.authority ?? null,
isSigner: true,
isWritable: false
},
programAccount: {
value: input.programAccount ?? null,
isSigner: false,
isWritable: false
}
};
return Object.freeze({
accounts: [
getAccountMeta("bufferOrProgramDataAccount", accounts.bufferOrProgramDataAccount),
getAccountMeta("destinationAccount", accounts.destinationAccount),
getAccountMeta("authority", accounts.authority),
getAccountMeta("programAccount", accounts.programAccount)
],
data: getCloseInstructionDataEncoder().encode({}),
programAddress
});
}
function parseCloseInstruction(instruction) {
if (instruction.accounts.length < 4) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 4
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
const getNextOptionalAccount = () => {
const accountMeta = getNextAccount();
return accountMeta.address === "BPFLoaderUpgradeab1e11111111111111111111111" ? void 0 : accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
bufferOrProgramDataAccount: getNextAccount(),
destinationAccount: getNextAccount(),
authority: getNextOptionalAccount(),
programAccount: getNextOptionalAccount()
},
data: getCloseInstructionDataDecoder().decode(instruction.data)
};
}
function getDeployWithMaxDataLenInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["maxDataLen", getU64Encoder()]]), (value) => ({
...value,
discriminator: 2
}));
}
function getDeployWithMaxDataLenInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["maxDataLen", getU64Decoder()]]);
}
function getDeployWithMaxDataLenInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "BPFLoaderUpgradeab1e11111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
payerAccount: {
value: input.payerAccount ?? null,
isSigner: true,
isWritable: true
},
programDataAccount: {
value: input.programDataAccount ?? null,
isSigner: false,
isWritable: true
},
programAccount: {
value: input.programAccount ?? null,
isSigner: false,
isWritable: true
},
bufferAccount: {
value: input.bufferAccount ?? null,
isSigner: false,
isWritable: true
},
rentSysvar: {
value: input.rentSysvar ?? null,
isSigner: false,
isWritable: false
},
clockSysvar: {
value: input.clockSysvar ?? null,
isSigner: false,
isWritable: false
},
systemProgram: {
value: input.systemProgram ?? null,
isSigner: false,
isWritable: false
},
authority: {
value: input.authority ?? null,
isSigner: true,
isWritable: false
}
};
const args = { ...input };
if (!accounts.rentSysvar.value) accounts.rentSysvar.value = "SysvarRent111111111111111111111111111111111";
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
if (!accounts.systemProgram.value) accounts.systemProgram.value = "11111111111111111111111111111111";
return Object.freeze({
accounts: [
getAccountMeta("payerAccount", accounts.payerAccount),
getAccountMeta("programDataAccount", accounts.programDataAccount),
getAccountMeta("programAccount", accounts.programAccount),
getAccountMeta("bufferAccount", accounts.bufferAccount),
getAccountMeta("rentSysvar", accounts.rentSysvar),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("systemProgram", accounts.systemProgram),
getAccountMeta("authority", accounts.authority)
],
data: getDeployWithMaxDataLenInstructionDataEncoder().encode(args),
programAddress
});
}
function parseDeployWithMaxDataLenInstruction(instruction) {
if (instruction.accounts.length < 8) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 8
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
payerAccount: getNextAccount(),
programDataAccount: getNextAccount(),
programAccount: getNextAccount(),
bufferAccount: getNextAccount(),
rentSysvar: getNextAccount(),
clockSysvar: getNextAccount(),
systemProgram: getNextAccount(),
authority: getNextAccount()
},
data: getDeployWithMaxDataLenInstructionDataDecoder().decode(instruction.data)
};
}
function getExtendProgramInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["additionalBytes", getU32Encoder()]]), (value) => ({
...value,
discriminator: 6
}));
}
function getExtendProgramInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["additionalBytes", getU32Decoder()]]);
}
function getExtendProgramInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "BPFLoaderUpgradeab1e11111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
programDataAccount: {
value: input.programDataAccount ?? null,
isSigner: false,
isWritable: true
},
programAccount: {
value: input.programAccount ?? null,
isSigner: false,
isWritable: true
},
systemProgram: {
value: input.systemProgram ?? null,
isSigner: false,
isWritable: false
},
payer: {
value: input.payer ?? null,
isSigner: true,
isWritable: true
}
};
const args = { ...input };
return Object.freeze({
accounts: [
getAccountMeta("programDataAccount", accounts.programDataAccount),
getAccountMeta("programAccount", accounts.programAccount),
getAccountMeta("systemProgram", accounts.systemProgram),
getAccountMeta("payer", accounts.payer)
],
data: getExtendProgramInstructionDataEncoder().encode(args),
programAddress
});
}
function parseExtendProgramInstruction(instruction) {
if (instruction.accounts.length < 4) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 4
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
const getNextOptionalAccount = () => {
const accountMeta = getNextAccount();
return accountMeta.address === "BPFLoaderUpgradeab1e11111111111111111111111" ? void 0 : accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
programDataAccount: getNextAccount(),
programAccount: getNextAccount(),
systemProgram: getNextOptionalAccount(),
payer: getNextOptionalAccount()
},
data: getExtendProgramInstructionDataDecoder().decode(instruction.data)
};
}
function getInitializeBufferInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 0
}));
}
function getInitializeBufferInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getInitializeBufferInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "BPFLoaderUpgradeab1e11111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
sourceAccount: {
value: input.sourceAccount ?? null,
isSigner: false,
isWritable: true
},
bufferAuthority: {
value: input.bufferAuthority ?? null,
isSigner: false,
isWritable: false
}
};
return Object.freeze({
accounts: [getAccountMeta("sourceAccount", accounts.sourceAccount), getAccountMeta("bufferAuthority", accounts.bufferAuthority)],
data: getInitializeBufferInstructionDataEncoder().encode({}),
programAddress
});
}
function parseInitializeBufferInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
sourceAccount: getNextAccount(),
bufferAuthority: getNextAccount()
},
data: getInitializeBufferInstructionDataDecoder().decode(instruction.data)
};
}
function getSetAuthorityInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 4
}));
}
function getSetAuthorityInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getSetAuthorityInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "BPFLoaderUpgradeab1e11111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
bufferOrProgramDataAccount: {
value: input.bufferOrProgramDataAccount ?? null,
isSigner: false,
isWritable: true
},
currentAuthority: {
value: input.currentAuthority ?? null,
isSigner: true,
isWritable: false
},
newAuthority: {
value: input.newAuthority ?? null,
isSigner: false,
isWritable: false
}
};
return Object.freeze({
accounts: [
getAccountMeta("bufferOrProgramDataAccount", accounts.bufferOrProgramDataAccount),
getAccountMeta("currentAuthority", accounts.currentAuthority),
getAccountMeta("newAuthority", accounts.newAuthority)
],
data: getSetAuthorityInstructionDataEncoder().encode({}),
programAddress
});
}
function parseSetAuthorityInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
const getNextOptionalAccount = () => {
const accountMeta = getNextAccount();
return accountMeta.address === "BPFLoaderUpgradeab1e11111111111111111111111" ? void 0 : accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
bufferOrProgramDataAccount: getNextAccount(),
currentAuthority: getNextAccount(),
newAuthority: getNextOptionalAccount()
},
data: getSetAuthorityInstructionDataDecoder().decode(instruction.data)
};
}
function getSetAuthorityCheckedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 7
}));
}
function getSetAuthorityCheckedInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getSetAuthorityCheckedInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "BPFLoaderUpgradeab1e11111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
bufferOrProgramDataAccount: {
value: input.bufferOrProgramDataAccount ?? null,
isSigner: false,
isWritable: true
},
currentAuthority: {
value: input.currentAuthority ?? null,
isSigner: true,
isWritable: false
},
newAuthority: {
value: input.newAuthority ?? null,
isSigner: true,
isWritable: false
}
};
return Object.freeze({
accounts: [
getAccountMeta("bufferOrProgramDataAccount", accounts.bufferOrProgramDataAccount),
getAccountMeta("currentAuthority", accounts.currentAuthority),
getAccountMeta("newAuthority", accounts.newAuthority)
],
data: getSetAuthorityCheckedInstructionDataEncoder().encode({}),
programAddress
});
}
function parseSetAuthorityCheckedInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
bufferOrProgramDataAccount: getNextAccount(),
currentAuthority: getNextAccount(),
newAuthority: getNextAccount()
},
data: getSetAuthorityCheckedInstructionDataDecoder().decode(instruction.data)
};
}
function getUpgradeInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 3
}));
}
function getUpgradeInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getUpgradeInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "BPFLoaderUpgradeab1e11111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
programDataAccount: {
value: input.programDataAccount ?? null,
isSigner: false,
isWritable: true
},
programAccount: {
value: input.programAccount ?? null,
isSigner: false,
isWritable: true
},
bufferAccount: {
value: input.bufferAccount ?? null,
isSigner: false,
isWritable: true
},
spillAccount: {
value: input.spillAccount ?? null,
isSigner: false,
isWritable: true
},
rentSysvar: {
value: input.rentSysvar ?? null,
isSigner: false,
isWritable: false
},
clockSysvar: {
value: input.clockSysvar ?? null,
isSigner: false,
isWritable: false
},
authority: {
value: input.authority ?? null,
isSigner: true,
isWritable: false
}
};
if (!accounts.rentSysvar.value) accounts.rentSysvar.value = "SysvarRent111111111111111111111111111111111";
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
return Object.freeze({
accounts: [
getAccountMeta("programDataAccount", accounts.programDataAccount),
getAccountMeta("programAccount", accounts.programAccount),
getAccountMeta("bufferAccount", accounts.bufferAccount),
getAccountMeta("spillAccount", accounts.spillAccount),
getAccountMeta("rentSysvar", accounts.rentSysvar),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("authority", accounts.authority)
],
data: getUpgradeInstructionDataEncoder().encode({}),
programAddress
});
}
function parseUpgradeInstruction(instruction) {
if (instruction.accounts.length < 7) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 7
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
programDataAccount: getNextAccount(),
programAccount: getNextAccount(),
bufferAccount: getNextAccount(),
spillAccount: getNextAccount(),
rentSysvar: getNextAccount(),
clockSysvar: getNextAccount(),
authority: getNextAccount()
},
data: getUpgradeInstructionDataDecoder().decode(instruction.data)
};
}
function getWriteInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["offset", getU32Encoder()],
["bytes", addEncoderSizePrefix(getBytesEncoder(), getU64Encoder())]
]), (value) => ({
...value,
discriminator: 1
}));
}
function getWriteInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["offset", getU32Decoder()],
["bytes", addDecoderSizePrefix(getBytesDecoder(), getU64Decoder())]
]);
}
function getWriteInstruction(input, config) {
const programAddressInput = config?.programAddress ?? "BPFLoaderUpgradeab1e11111111111111111111111";
const programAddress = typeof programAddressInput === "string" ? programAddressInput : programAddressInput.address;
const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
const accounts = {
bufferAccount: {
value: input.bufferAccount ?? null,
isSigner: false,
isWritable: true
},
bufferAuthority: {
value: input.bufferAuthority ?? null,
isSigner: true,
isWritable: false
}
};
const args = { ...input };
return Object.freeze({
accounts: [getAccountMeta("bufferAccount", accounts.bufferAccount), getAccountMeta("bufferAuthority", accounts.bufferAuthority)],
data: getWriteInstructionDataEncoder().encode(args),
programAddress
});
}
function parseWriteInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
bufferAccount: getNextAccount(),
bufferAuthority: getNextAccount()
},
data: getWriteInstructionDataDecoder().decode(instruction.data)
};
}
// 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)}`);
}
}
};
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js
/**
* SHA3 (keccak) hash function, based on a new "Sponge function" design.
* Different from older hashes, the internal state is bigger than output size.
*
* Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
* [Website](https://keccak.team/keccak.html),
* [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
*
* Check out `sha3-addons` module for cSHAKE, k12, and others.
* @module
*/
const _0n$1 = BigInt(0);
const _1n$1 = BigInt(1);
const _2n$2 = BigInt(2);
const _7n = BigInt(7);
const _256n = BigInt(256);
const _0x71n = BigInt(113);
const SHA3_PI = [];
const SHA3_ROTL = [];
const _SHA3_IOTA = [];
for (let round = 0, R = _1n$1, x = 1, y = 0; round < 24; round++) {
[x, y] = [y, (2 * x + 3 * y) % 5];
SHA3_PI.push(2 * (5 * y + x));
SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
let t = _0n$1;
for (let j = 0; j < 7; j++) {
R = (R << _1n$1 ^ (R >> _7n) * _0x71n) % _256n;
if (R & _2n$2) t ^= _1n$1 << (_1n$1 << /* @__PURE__ */ BigInt(j)) - _1n$1;
}
_SHA3_IOTA.push(t);
}
const IOTAS = split(_SHA3_IOTA, true);
const SHA3_IOTA_H = IOTAS[0];
const SHA3_IOTA_L = IOTAS[1];
const rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
const rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
/** `keccakf1600` internal function, additionally allows to adjust round count. */
function keccakP(s, rounds = 24) {
const B = /* @__PURE__ */ new Uint32Array(10);
for (let round = 24 - rounds; round < 24; round++) {
for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
for (let x = 0; x < 10; x += 2) {
const idx1 = (x + 8) % 10;
const idx0 = (x + 2) % 10;
const B0 = B[idx0];
const B1 = B[idx0 + 1];
const Th = rotlH(B0, B1, 1) ^ B[idx1];
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
for (let y = 0; y < 50; y += 10) {
s[x + y] ^= Th;
s[x + y + 1] ^= Tl;
}
}
let curH = s[2];
let curL = s[3];
for (let t = 0; t < 24; t++) {
const shift = SHA3_ROTL[t];
const Th = rotlH(curH, curL, shift);
const Tl = rotlL(curH, curL, shift);
const PI = SHA3_PI[t];
curH = s[PI];
curL = s[PI + 1];
s[PI] = Th;
s[PI + 1] = Tl;
}
for (let y = 0; y < 50; y += 10) {
for (let x = 0; x < 10; x++) B[x] = s[y + x];
for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
}
s[0] ^= SHA3_IOTA_H[round];
s[1] ^= SHA3_IOTA_L[round];
}
clean(B);
}
/** Keccak sponge function. */
var Keccak = class Keccak extends Hash {
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
super();
this.pos = 0;
this.posOut = 0;
this.finished = false;
this.destroyed = false;
this.enableXOF = false;
this.blockLen = blockLen;
this.suffix = suffix;
this.outputLen = outputLen;
this.enableXOF = enableXOF;
this.rounds = rounds;
anumber(outputLen);
if (!(0 < blockLen && blockLen < 200)) throw new Error("only keccak-f1600 function is supported");
this.state = /* @__PURE__ */ new Uint8Array(200);
this.state32 = u32(this.state);
}
clone() {
return this._cloneInto();
}
keccak() {
swap32IfBE(this.state32);
keccakP(this.state32, this.rounds);
swap32IfBE(this.state32);
this.posOut = 0;
this.pos = 0;
}
update(data) {
aexists(this);
data = toBytes(data);
abytes(data);
const { blockLen, state } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];
if (this.pos === blockLen) this.keccak();
}
return this;
}
finish() {
if (this.finished) return;
this.finished = true;
const { state, suffix, pos, blockLen } = this;
state[pos] ^= suffix;
if ((suffix & 128) !== 0 && pos === blockLen - 1) this.keccak();
state[blockLen - 1] ^= 128;
this.keccak();
}
writeInto(out) {
aexists(this, false);
abytes(out);
this.finish();
const bufferOut = this.state;
const { blockLen } = this;
for (let pos = 0, len = out.length; pos < len;) {
if (this.posOut >= blockLen) this.keccak();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
if (!this.enableXOF) throw new Error("XOF is not possible for this instance");
return this.writeInto(out);
}
xof(bytes) {
anumber(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
aoutput(out, this);
if (this.finished) throw new Error("digest() was already called");
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
destroy() {
this.destroyed = true;
clean(this.state);
}
_cloneInto(to) {
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
to.state32.set(this.state32);
to.pos = this.pos;
to.posOut = this.posOut;
to.finished = this.finished;
to.rounds = rounds;
to.suffix = suffix;
to.outputLen = outputLen;
to.enableXOF = enableXOF;
to.destroyed = this.destroyed;
return to;
}
};
const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
/** keccak-256 hash function. Different from SHA3-256. */
const keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 32))();
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
/**
* HMAC: RFC2104 message authentication code.
* @module
*/
var HMAC = class extends Hash {
constructor(hash, _key) {
super();
this.finished = false;
this.destroyed = false;
ahash(hash);
const key = toBytes(_key);
this.iHash = hash.create();
if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash.create();
for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
this.oHash.update(pad);
clean(pad);
}
update(buf) {
aexists(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
aexists(this);
abytes(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
clone() {
return this._cloneInto();
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
};
/**
* HMAC: RFC2104 message authentication code.
* @param hash - function that would be used e.g. sha256
* @param key - message key
* @param message - message data
* @example
* import { hmac } from '@noble/hashes/hmac';
* import { sha256 } from '@noble/hashes/sha2';
* const mac1 = hmac(sha256, 'key', 'message');
*/
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
// ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/weierstrass.js
/**
* Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
*
* ### Design rationale for types
*
* * Interaction between classes from different curves should fail:
* `k256.Point.BASE.add(p256.Point.BASE)`
* * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
* * Different calls of `curve()` would return different classes -
* `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
* it won't affect others
*
* TypeScript can't infer types for classes created inside a function. Classes is one instance
* of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
* unique type for every function call.
*
* We can use generic types via some param, like curve opts, but that would:
* 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
* which is hard to debug.
* 2. Params can be generic and we can't enforce them to be constant value:
* if somebody creates curve from non-constant params,
* it would be allowed to interact with other curves with non-constant params
*
* @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n$1) / den;
/**
* Splits scalar for GLV endomorphism.
*/
function _splitEndoScalar(k, basis, n) {
const [[a1, b1], [a2, b2]] = basis;
const c1 = divNearest(b2 * k, n);
const c2 = divNearest(-b1 * k, n);
let k1 = k - c1 * a1 - c2 * a2;
let k2 = -c1 * b1 - c2 * b2;
const k1neg = k1 < _0n;
const k2neg = k2 < _0n;
if (k1neg) k1 = -k1;
if (k2neg) k2 = -k2;
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n;
if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) throw new Error("splitScalar (endomorphism): failed, k=" + k);
return {
k1neg,
k1,
k2neg,
k2
};
}
function validateSigFormat(format) {
if (![
"compact",
"recovered",
"der"
].includes(format)) throw new Error("Signature format must be \"compact\", \"recovered\", or \"der\"");
return format;
}
function validateSigOpts(opts, def) {
const optsn = {};
for (let optName of Object.keys(def)) optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
_abool2(optsn.lowS, "lowS");
_abool2(optsn.prehash, "prehash");
if (optsn.format !== void 0) validateSigFormat(optsn.format);
return optsn;
}
var DERErr = class extends Error {
constructor(m = "") {
super(m);
}
};
/**
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
*
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
*
* Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
*/
const DER = {
Err: DERErr,
_tlv: {
encode: (tag, data) => {
const { Err: E } = DER;
if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
if (data.length & 1) throw new E("tlv.encode: unpadded data");
const dataLen = data.length / 2;
const len = numberToHexUnpadded(dataLen);
if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big");
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
return numberToHexUnpadded(tag) + lenLen + len + data;
},
decode(tag, data) {
const { Err: E } = DER;
let pos = 0;
if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv");
const first = data[pos++];
const isLong = !!(first & 128);
let length = 0;
if (!isLong) length = first;
else {
const lenLen = first & 127;
if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported");
if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big");
const lengthBytes = data.subarray(pos, pos + lenLen);
if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete");
if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte");
for (const b of lengthBytes) length = length << 8 | b;
pos += lenLen;
if (length < 128) throw new E("tlv.decode(long): not minimal encoding");
}
const v = data.subarray(pos, pos + length);
if (v.length !== length) throw new E("tlv.decode: wrong value length");
return {
v,
l: data.subarray(pos + length)
};
}
},
_int: {
encode(num) {
const { Err: E } = DER;
if (num < _0n) throw new E("integer: negative integers are not allowed");
let hex = numberToHexUnpadded(num);
if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex;
if (hex.length & 1) throw new E("unexpected DER parsing assertion: unpadded hex");
return hex;
},
decode(data) {
const { Err: E } = DER;
if (data[0] & 128) throw new E("invalid signature integer: negative");
if (data[0] === 0 && !(data[1] & 128)) throw new E("invalid signature integer: unnecessary leading zero");
return bytesToNumberBE(data);
}
},
toSig(hex) {
const { Err: E, _int: int, _tlv: tlv } = DER;
const data = ensureBytes("signature", hex);
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
if (seqLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
if (sLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
return {
r: int.decode(rBytes),
s: int.decode(sBytes)
};
},
hexFromSig(sig) {
const { _tlv: tlv, _int: int } = DER;
const seq = tlv.encode(2, int.encode(sig.r)) + tlv.encode(2, int.encode(sig.s));
return tlv.encode(48, seq);
}
};
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n$1 = BigInt(2);
const _3n = BigInt(3);
const _4n = BigInt(4);
function _normFnElement(Fn, key) {
const { BYTES: expected } = Fn;
let num;
if (typeof key === "bigint") num = key;
else {
let bytes = ensureBytes("private key", key);
try {
num = Fn.fromBytes(bytes);
} catch (error) {
throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
}
}
if (!Fn.isValidNot0(num)) throw new Error("invalid private key: out of range [1..N-1]");
return num;
}
/**
* Creates weierstrass Point constructor, based on specified curve options.
*
* @example
```js
const opts = {
p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
h: BigInt(1),
a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
*/
function weierstrassN(params, extraOpts = {}) {
const validated = _createCurveFields("weierstrass", params, extraOpts);
const { Fp, Fn } = validated;
let CURVE = validated.CURVE;
const { h: cofactor, n: CURVE_ORDER } = CURVE;
_validateObject(extraOpts, {}, {
allowInfinityPoint: "boolean",
clearCofactor: "function",
isTorsionFree: "function",
fromBytes: "function",
toBytes: "function",
endo: "object",
wrapPrivateKey: "boolean"
});
const { endo } = extraOpts;
if (endo) {
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) throw new Error("invalid endo: expected \"beta\": bigint and \"basises\": array");
}
const lengths = getWLengths(Fp, Fn);
function assertCompressionIsSupported() {
if (!Fp.isOdd) throw new Error("compression is not supported: Field does not have .isOdd()");
}
function pointToBytes(_c, point, isCompressed) {
const { x, y } = point.toAffine();
const bx = Fp.toBytes(x);
_abool2(isCompressed, "isCompressed");
if (isCompressed) {
assertCompressionIsSupported();
return concatBytes(pprefix(!Fp.isOdd(y)), bx);
} else return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
}
function pointFromBytes(bytes) {
_abytes2(bytes, void 0, "Point");
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
const length = bytes.length;
const head = bytes[0];
const tail = bytes.subarray(1);
if (length === comp && (head === 2 || head === 3)) {
const x = Fp.fromBytes(tail);
if (!Fp.isValid(x)) throw new Error("bad point: is not on curve, wrong x");
const y2 = weierstrassEquation(x);
let y;
try {
y = Fp.sqrt(y2);
} catch (sqrtError) {
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
throw new Error("bad point: is not on curve, sqrt error" + err);
}
assertCompressionIsSupported();
const isYOdd = Fp.isOdd(y);
if ((head & 1) === 1 !== isYOdd) y = Fp.neg(y);
return {
x,
y
};
} else if (length === uncomp && head === 4) {
const L = Fp.BYTES;
const x = Fp.fromBytes(tail.subarray(0, L));
const y = Fp.fromBytes(tail.subarray(L, L * 2));
if (!isValidXY(x, y)) throw new Error("bad point: is not on curve");
return {
x,
y
};
} else throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
}
const encodePoint = extraOpts.toBytes || pointToBytes;
const decodePoint = extraOpts.fromBytes || pointFromBytes;
function weierstrassEquation(x) {
const x2 = Fp.sqr(x);
const x3 = Fp.mul(x2, x);
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
}
/** Checks whether equation holds for given x, y: y² == x³ + ax + b */
function isValidXY(x, y) {
const left = Fp.sqr(y);
const right = weierstrassEquation(x);
return Fp.eql(left, right);
}
if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error("bad curve params: a or b");
/** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
function acoord(title, n, banZero = false) {
if (!Fp.isValid(n) || banZero && Fp.is0(n)) throw new Error(`bad point coordinate ${title}`);
return n;
}
function aprjpoint(other) {
if (!(other instanceof Point)) throw new Error("ProjectivePoint expected");
}
function splitEndoScalarN(k) {
if (!endo || !endo.basises) throw new Error("no endo");
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
}
const toAffineMemo = memoized((p, iz) => {
const { X, Y, Z } = p;
if (Fp.eql(Z, Fp.ONE)) return {
x: X,
y: Y
};
const is0 = p.is0();
if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);
const x = Fp.mul(X, iz);
const y = Fp.mul(Y, iz);
const zz = Fp.mul(Z, iz);
if (is0) return {
x: Fp.ZERO,
y: Fp.ZERO
};
if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid");
return {
x,
y
};
});
const assertValidMemo = memoized((p) => {
if (p.is0()) {
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) return;
throw new Error("bad point: ZERO");
}
const { x, y } = p.toAffine();
if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not field elements");
if (!isValidXY(x, y)) throw new Error("bad point: equation left != right");
if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup");
return true;
});
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
k1p = negateCt(k1neg, k1p);
k2p = negateCt(k2neg, k2p);
return k1p.add(k2p);
}
/**
* Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
* Default Point works in 2d / affine coordinates: (x, y).
* We're doing calculations in projective, because its operations don't require costly inversion.
*/
class Point {
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
constructor(X, Y, Z) {
this.X = acoord("x", X);
this.Y = acoord("y", Y, true);
this.Z = acoord("z", Z);
Object.freeze(this);
}
static CURVE() {
return CURVE;
}
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
static fromAffine(p) {
const { x, y } = p || {};
if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point");
if (p instanceof Point) throw new Error("projective point not allowed");
if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;
return new Point(x, y, Fp.ONE);
}
static fromBytes(bytes) {
const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
P.assertValidity();
return P;
}
static fromHex(hex) {
return Point.fromBytes(ensureBytes("pointHex", hex));
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
/**
*
* @param windowSize
* @param isLazy true will defer table computation until the first multiplication
* @returns
*/
precompute(windowSize = 8, isLazy = true) {
wnaf.createCache(this, windowSize);
if (!isLazy) this.multiply(_3n);
return this;
}
/** A point on curve is valid if it conforms to equation. */
assertValidity() {
assertValidMemo(this);
}
hasEvenY() {
const { y } = this.toAffine();
if (!Fp.isOdd) throw new Error("Field doesn't support isOdd");
return !Fp.isOdd(y);
}
/** Compare one point to another. */
equals(other) {
aprjpoint(other);
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = other;
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
return U1 && U2;
}
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
negate() {
return new Point(this.X, Fp.neg(this.Y), this.Z);
}
double() {
const { a, b } = CURVE;
const b3 = Fp.mul(b, _3n);
const { X: X1, Y: Y1, Z: Z1 } = this;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
let t0 = Fp.mul(X1, X1);
let t1 = Fp.mul(Y1, Y1);
let t2 = Fp.mul(Z1, Z1);
let t3 = Fp.mul(X1, Y1);
t3 = Fp.add(t3, t3);
Z3 = Fp.mul(X1, Z1);
Z3 = Fp.add(Z3, Z3);
X3 = Fp.mul(a, Z3);
Y3 = Fp.mul(b3, t2);
Y3 = Fp.add(X3, Y3);
X3 = Fp.sub(t1, Y3);
Y3 = Fp.add(t1, Y3);
Y3 = Fp.mul(X3, Y3);
X3 = Fp.mul(t3, X3);
Z3 = Fp.mul(b3, Z3);
t2 = Fp.mul(a, t2);
t3 = Fp.sub(t0, t2);
t3 = Fp.mul(a, t3);
t3 = Fp.add(t3, Z3);
Z3 = Fp.add(t0, t0);
t0 = Fp.add(Z3, t0);
t0 = Fp.add(t0, t2);
t0 = Fp.mul(t0, t3);
Y3 = Fp.add(Y3, t0);
t2 = Fp.mul(Y1, Z1);
t2 = Fp.add(t2, t2);
t0 = Fp.mul(t2, t3);
X3 = Fp.sub(X3, t0);
Z3 = Fp.mul(t2, t1);
Z3 = Fp.add(Z3, Z3);
Z3 = Fp.add(Z3, Z3);
return new Point(X3, Y3, Z3);
}
add(other) {
aprjpoint(other);
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = other;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
const a = CURVE.a;
const b3 = Fp.mul(CURVE.b, _3n);
let t0 = Fp.mul(X1, X2);
let t1 = Fp.mul(Y1, Y2);
let t2 = Fp.mul(Z1, Z2);
let t3 = Fp.add(X1, Y1);
let t4 = Fp.add(X2, Y2);
t3 = Fp.mul(t3, t4);
t4 = Fp.add(t0, t1);
t3 = Fp.sub(t3, t4);
t4 = Fp.add(X1, Z1);
let t5 = Fp.add(X2, Z2);
t4 = Fp.mul(t4, t5);
t5 = Fp.add(t0, t2);
t4 = Fp.sub(t4, t5);
t5 = Fp.add(Y1, Z1);
X3 = Fp.add(Y2, Z2);
t5 = Fp.mul(t5, X3);
X3 = Fp.add(t1, t2);
t5 = Fp.sub(t5, X3);
Z3 = Fp.mul(a, t4);
X3 = Fp.mul(b3, t2);
Z3 = Fp.add(X3, Z3);
X3 = Fp.sub(t1, Z3);
Z3 = Fp.add(t1, Z3);
Y3 = Fp.mul(X3, Z3);
t1 = Fp.add(t0, t0);
t1 = Fp.add(t1, t0);
t2 = Fp.mul(a, t2);
t4 = Fp.mul(b3, t4);
t1 = Fp.add(t1, t2);
t2 = Fp.sub(t0, t2);
t2 = Fp.mul(a, t2);
t4 = Fp.add(t4, t2);
t0 = Fp.mul(t1, t4);
Y3 = Fp.add(Y3, t0);
t0 = Fp.mul(t5, t4);
X3 = Fp.mul(t3, X3);
X3 = Fp.sub(X3, t0);
t0 = Fp.mul(t3, t1);
Z3 = Fp.mul(t5, Z3);
Z3 = Fp.add(Z3, t0);
return new Point(X3, Y3, Z3);
}
subtract(other) {
return this.add(other.negate());
}
is0() {
return this.equals(Point.ZERO);
}
/**
* Constant time multiplication.
* Uses wNAF method. Windowed method may be 10% faster,
* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @returns New point
*/
multiply(scalar) {
const { endo } = extraOpts;
if (!Fn.isValidNot0(scalar)) throw new Error("invalid scalar: out of range");
let point, fake;
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
/** See docs for {@link EndomorphismOpts} */
if (endo) {
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
const { p: k1p, f: k1f } = mul(k1);
const { p: k2p, f: k2f } = mul(k2);
fake = k1f.add(k2f);
point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
} else {
const { p, f } = mul(scalar);
point = p;
fake = f;
}
return normalizeZ(Point, [point, fake])[0];
}
/**
* Non-constant-time multiplication. Uses double-and-add algorithm.
* It's faster, but should only be used when you don't care about
* an exposed secret key e.g. sig verification, which works over *public* keys.
*/
multiplyUnsafe(sc) {
const { endo } = extraOpts;
const p = this;
if (!Fn.isValid(sc)) throw new Error("invalid scalar: out of range");
if (sc === _0n || p.is0()) return Point.ZERO;
if (sc === _1n) return p;
if (wnaf.hasCache(this)) return this.multiply(sc);
if (endo) {
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
} else return wnaf.unsafe(p, sc);
}
multiplyAndAddUnsafe(Q, a, b) {
const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
return sum.is0() ? void 0 : sum;
}
/**
* Converts Projective point to affine (x, y) coordinates.
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
*/
toAffine(invertedZ) {
return toAffineMemo(this, invertedZ);
}
/**
* Checks whether Point is free of torsion elements (is in prime subgroup).
* Always torsion-free for cofactor=1 curves.
*/
isTorsionFree() {
const { isTorsionFree } = extraOpts;
if (cofactor === _1n) return true;
if (isTorsionFree) return isTorsionFree(Point, this);
return wnaf.unsafe(this, CURVE_ORDER).is0();
}
clearCofactor() {
const { clearCofactor } = extraOpts;
if (cofactor === _1n) return this;
if (clearCofactor) return clearCofactor(Point, this);
return this.multiplyUnsafe(cofactor);
}
isSmallOrder() {
return this.multiplyUnsafe(cofactor).is0();
}
toBytes(isCompressed = true) {
_abool2(isCompressed, "isCompressed");
this.assertValidity();
return encodePoint(Point, this, isCompressed);
}
toHex(isCompressed = true) {
return bytesToHex(this.toBytes(isCompressed));
}
toString() {
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
}
get px() {
return this.X;
}
get py() {
return this.X;
}
get pz() {
return this.Z;
}
toRawBytes(isCompressed = true) {
return this.toBytes(isCompressed);
}
_setWindowSize(windowSize) {
this.precompute(windowSize);
}
static normalizeZ(points) {
return normalizeZ(Point, points);
}
static msm(points, scalars) {
return pippenger(Point, Fn, points, scalars);
}
static fromPrivateKey(privateKey) {
return Point.BASE.multiply(_normFnElement(Fn, privateKey));
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
Point.Fp = Fp;
Point.Fn = Fn;
const bits = Fn.BITS;
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
Point.BASE.precompute(8);
return Point;
}
function pprefix(hasEvenY) {
return Uint8Array.of(hasEvenY ? 2 : 3);
}
function getWLengths(Fp, Fn) {
return {
secretKey: Fn.BYTES,
publicKey: 1 + Fp.BYTES,
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
publicKeyHasPrefix: true,
signature: 2 * Fn.BYTES
};
}
/**
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
* This helper ensures no signature functionality is present. Less code, smaller bundle size.
*/
function ecdh(Point, ecdhOpts = {}) {
const { Fn } = Point;
const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
function isValidSecretKey(secretKey) {
try {
return !!_normFnElement(Fn, secretKey);
} catch (error) {
return false;
}
}
function isValidPublicKey(publicKey, isCompressed) {
const { publicKey: comp, publicKeyUncompressed } = lengths;
try {
const l = publicKey.length;
if (isCompressed === true && l !== comp) return false;
if (isCompressed === false && l !== publicKeyUncompressed) return false;
return !!Point.fromBytes(publicKey);
} catch (error) {
return false;
}
}
/**
* Produces cryptographically secure secret key from random of size
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
*/
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
}
/**
* Computes public key for a secret key. Checks for validity of the secret key.
* @param isCompressed whether to return compact (default), or full key
* @returns Public key, full when isCompressed=false; short when isCompressed=true
*/
function getPublicKey(secretKey, isCompressed = true) {
return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
}
function keygen(seed) {
const secretKey = randomSecretKey(seed);
return {
secretKey,
publicKey: getPublicKey(secretKey)
};
}
/**
* Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
*/
function isProbPub(item) {
if (typeof item === "bigint") return false;
if (item instanceof Point) return true;
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
if (Fn.allowedLengths || secretKey === publicKey) return void 0;
const l = ensureBytes("key", item).length;
return l === publicKey || l === publicKeyUncompressed;
}
/**
* ECDH (Elliptic Curve Diffie Hellman).
* Computes shared public key from secret key A and public key B.
* Checks: 1) secret key validity 2) shared key is on-curve.
* Does NOT hash the result.
* @param isCompressed whether to return compact (default), or full key
* @returns shared public key
*/
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
if (isProbPub(secretKeyA) === true) throw new Error("first arg must be private key");
if (isProbPub(publicKeyB) === false) throw new Error("second arg must be public key");
const s = _normFnElement(Fn, secretKeyA);
return Point.fromHex(publicKeyB).multiply(s).toBytes(isCompressed);
}
return Object.freeze({
getPublicKey,
getSharedSecret,
keygen,
Point,
utils: {
isValidSecretKey,
isValidPublicKey,
randomSecretKey,
isValidPrivateKey: isValidSecretKey,
randomPrivateKey: randomSecretKey,
normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
precompute(windowSize = 8, point = Point.BASE) {
return point.precompute(windowSize, false);
}
},
lengths
});
}
/**
* Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
* We need `hash` for 2 features:
* 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
* 2. k generation in `sign`, using HMAC-drbg(hash)
*
* ECDSAOpts are only rarely needed.
*
* @example
* ```js
* const p256_Point = weierstrass(...);
* const p256_sha256 = ecdsa(p256_Point, sha256);
* const p256_sha224 = ecdsa(p256_Point, sha224);
* const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
* ```
*/
function ecdsa(Point, hash, ecdsaOpts = {}) {
ahash(hash);
_validateObject(ecdsaOpts, {}, {
hmac: "function",
lowS: "boolean",
randomBytes: "function",
bits2int: "function",
bits2int_modN: "function"
});
const randomBytes$1 = ecdsaOpts.randomBytes || randomBytes;
const hmac$1 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
const { Fp, Fn } = Point;
const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
const defaultSigOpts = {
prehash: false,
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
format: void 0,
extraEntropy: false
};
const defaultSigOpts_format = "compact";
function isBiggerThanHalfOrder(number) {
return number > CURVE_ORDER >> _1n;
}
function validateRS(title, num) {
if (!Fn.isValidNot0(num)) throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
return num;
}
function validateSigLength(bytes, format) {
validateSigFormat(format);
const size = lengths.signature;
return _abytes2(bytes, format === "compact" ? size : format === "recovered" ? size + 1 : void 0, `${format} signature`);
}
/**
* ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
*/
class Signature {
constructor(r, s, recovery) {
this.r = validateRS("r", r);
this.s = validateRS("s", s);
if (recovery != null) this.recovery = recovery;
Object.freeze(this);
}
static fromBytes(bytes, format = defaultSigOpts_format) {
validateSigLength(bytes, format);
let recid;
if (format === "der") {
const { r, s } = DER.toSig(_abytes2(bytes));
return new Signature(r, s);
}
if (format === "recovered") {
recid = bytes[0];
format = "compact";
bytes = bytes.subarray(1);
}
const L = Fn.BYTES;
const r = bytes.subarray(0, L);
const s = bytes.subarray(L, L * 2);
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
}
static fromHex(hex, format) {
return this.fromBytes(hexToBytes(hex), format);
}
addRecoveryBit(recovery) {
return new Signature(this.r, this.s, recovery);
}
recoverPublicKey(messageHash) {
const FIELD_ORDER = Fp.ORDER;
const { r, s, recovery: rec } = this;
if (rec == null || ![
0,
1,
2,
3
].includes(rec)) throw new Error("recovery id invalid");
if (CURVE_ORDER * _2n$1 < FIELD_ORDER && rec > 1) throw new Error("recovery id is ambiguous for h>1 curve");
const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
if (!Fp.isValid(radj)) throw new Error("recovery id 2 or 3 invalid");
const x = Fp.toBytes(radj);
const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
const ir = Fn.inv(radj);
const h = bits2int_modN(ensureBytes("msgHash", messageHash));
const u1 = Fn.create(-h * ir);
const u2 = Fn.create(s * ir);
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
if (Q.is0()) throw new Error("point at infinify");
Q.assertValidity();
return Q;
}
hasHighS() {
return isBiggerThanHalfOrder(this.s);
}
toBytes(format = defaultSigOpts_format) {
validateSigFormat(format);
if (format === "der") return hexToBytes(DER.hexFromSig(this));
const r = Fn.toBytes(this.r);
const s = Fn.toBytes(this.s);
if (format === "recovered") {
if (this.recovery == null) throw new Error("recovery bit must be present");
return concatBytes(Uint8Array.of(this.recovery), r, s);
}
return concatBytes(r, s);
}
toHex(format) {
return bytesToHex(this.toBytes(format));
}
assertValidity() {}
static fromCompact(hex) {
return Signature.fromBytes(ensureBytes("sig", hex), "compact");
}
static fromDER(hex) {
return Signature.fromBytes(ensureBytes("sig", hex), "der");
}
normalizeS() {
return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
}
toDERRawBytes() {
return this.toBytes("der");
}
toDERHex() {
return bytesToHex(this.toBytes("der"));
}
toCompactRawBytes() {
return this.toBytes("compact");
}
toCompactHex() {
return bytesToHex(this.toBytes("compact"));
}
}
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
if (bytes.length > 8192) throw new Error("input is too large");
const num = bytesToNumberBE(bytes);
const delta = bytes.length * 8 - fnBits;
return delta > 0 ? num >> BigInt(delta) : num;
};
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
return Fn.create(bits2int(bytes));
};
const ORDER_MASK = bitMask(fnBits);
/** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
function int2octets(num) {
aInRange("num < 2^" + fnBits, num, _0n, ORDER_MASK);
return Fn.toBytes(num);
}
function validateMsgAndHash(message, prehash) {
_abytes2(message, void 0, "message");
return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
}
/**
* Steps A, D of RFC6979 3.2.
* Creates RFC6979 seed; converts msg/privKey to numbers.
* Used only in sign, not in verify.
*
* Warning: we cannot assume here that message has same amount of bytes as curve order,
* this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
*/
function prepSig(message, privateKey, opts) {
if (["recovered", "canonical"].some((k) => k in opts)) throw new Error("sign() legacy options not supported");
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
message = validateMsgAndHash(message, prehash);
const h1int = bits2int_modN(message);
const d = _normFnElement(Fn, privateKey);
const seedArgs = [int2octets(d), int2octets(h1int)];
if (extraEntropy != null && extraEntropy !== false) {
const e = extraEntropy === true ? randomBytes$1(lengths.secretKey) : extraEntropy;
seedArgs.push(ensureBytes("extraEntropy", e));
}
const seed = concatBytes(...seedArgs);
const m = h1int;
function k2sig(kBytes) {
const k = bits2int(kBytes);
if (!Fn.isValidNot0(k)) return;
const ik = Fn.inv(k);
const q = Point.BASE.multiply(k).toAffine();
const r = Fn.create(q.x);
if (r === _0n) return;
const s = Fn.create(ik * Fn.create(m + r * d));
if (s === _0n) return;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n);
let normS = s;
if (lowS && isBiggerThanHalfOrder(s)) {
normS = Fn.neg(s);
recovery ^= 1;
}
return new Signature(r, normS, recovery);
}
return {
seed,
k2sig
};
}
/**
* Signs message hash with a secret key.
*
* ```
* sign(m, d) where
* k = rfc6979_hmac_drbg(m, d)
* (x, y) = G × k
* r = x mod n
* s = (m + dr) / k mod n
* ```
*/
function sign(message, secretKey, opts = {}) {
message = ensureBytes("message", message);
const { seed, k2sig } = prepSig(message, secretKey, opts);
return createHmacDrbg(hash.outputLen, Fn.BYTES, hmac$1)(seed, k2sig);
}
function tryParsingSig(sg) {
let sig = void 0;
const isHex = typeof sg === "string" || isBytes(sg);
const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
if (!isHex && !isObj) throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
if (isObj) sig = new Signature(sg.r, sg.s);
else if (isHex) {
try {
sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
} catch (derError) {
if (!(derError instanceof DER.Err)) throw derError;
}
if (!sig) try {
sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
} catch (error) {
return false;
}
}
if (!sig) return false;
return sig;
}
/**
* Verifies a signature against message and public key.
* Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
* Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
*
* ```
* verify(r, s, h, P) where
* u1 = hs^-1 mod n
* u2 = rs^-1 mod n
* R = u1⋅G + u2⋅P
* mod(R.x, n) == r
* ```
*/
function verify(signature, message, publicKey, opts = {}) {
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
publicKey = ensureBytes("publicKey", publicKey);
message = validateMsgAndHash(ensureBytes("message", message), prehash);
if ("strict" in opts) throw new Error("options.strict was renamed to lowS");
const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
if (sig === false) return false;
try {
const P = Point.fromBytes(publicKey);
if (lowS && sig.hasHighS()) return false;
const { r, s } = sig;
const h = bits2int_modN(message);
const is = Fn.inv(s);
const u1 = Fn.create(h * is);
const u2 = Fn.create(r * is);
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
if (R.is0()) return false;
return Fn.create(R.x) === r;
} catch (e) {
return false;
}
}
function recoverPublicKey(signature, message, opts = {}) {
const { prehash } = validateSigOpts(opts, defaultSigOpts);
message = validateMsgAndHash(message, prehash);
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
}
return Object.freeze({
keygen,
getPublicKey,
getSharedSecret,
utils,
lengths,
Point,
sign,
verify,
recoverPublicKey,
Signature,
hash
});
}
function _weierstrass_legacy_opts_to_new(c) {
const CURVE = {
a: c.a,
b: c.b,
p: c.Fp.ORDER,
n: c.n,
h: c.h,
Gx: c.Gx,
Gy: c.Gy
};
const Fp = c.Fp;
let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
return {
CURVE,
curveOpts: {
Fp,
Fn: Field(CURVE.n, {
BITS: c.nBitLength,
allowedLengths,
modFromBytes: c.wrapPrivateKey
}),
allowInfinityPoint: c.allowInfinityPoint,
endo: c.endo,
isTorsionFree: c.isTorsionFree,
clearCofactor: c.clearCofactor,
fromBytes: c.fromBytes,
toBytes: c.toBytes
}
};
}
function _ecdsa_legacy_opts_to_new(c) {
const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
const ecdsaOpts = {
hmac: c.hmac,
randomBytes: c.randomBytes,
lowS: c.lowS,
bits2int: c.bits2int,
bits2int_modN: c.bits2int_modN
};
return {
CURVE,
curveOpts,
hash: c.hash,
ecdsaOpts
};
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
const Point = _ecdsa.Point;
return Object.assign({}, _ecdsa, {
ProjectivePoint: Point,
CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
});
}
function weierstrass(c) {
const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
return _ecdsa_new_output_to_legacy(c, ecdsa(weierstrassN(CURVE, curveOpts), hash, ecdsaOpts));
}
// ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/_shortw_utils.js
/**
* Utilities for short weierstrass curves, combined with noble-hashes.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
function createCurve(curveDef, defHash) {
const create = (hash) => weierstrass({
...curveDef,
hash
});
return {
...create(defHash),
create
};
}
// ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/secp256k1.js
/**
* SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
*
* Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
* check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const secp256k1_CURVE = {
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
h: BigInt(1),
a: BigInt(0),
b: BigInt(7),
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
};
const secp256k1_ENDO = {
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
basises: [[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")], [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]
};
const _2n = /* @__PURE__ */ BigInt(2);
/**
* √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
* (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
*/
function sqrtMod(y) {
const P = secp256k1_CURVE.p;
const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
const b2 = y * y * y % P;
const b3 = b2 * b2 * y % P;
const b11 = pow2(pow2(pow2(b3, _3n, P) * b3 % P, _3n, P) * b3 % P, _2n, P) * b2 % P;
const b22 = pow2(b11, _11n, P) * b11 % P;
const b44 = pow2(b22, _22n, P) * b22 % P;
const b88 = pow2(b44, _44n, P) * b44 % P;
const root = pow2(pow2(pow2(pow2(pow2(pow2(b88, _88n, P) * b88 % P, _44n, P) * b44 % P, _3n, P) * b3 % P, _23n, P) * b22 % P, _6n, P) * b2 % P, _2n, P);
if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error("Cannot find square root");
return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
* secp256k1 curve, ECDSA and ECDH methods.
*
* Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
*
* @example
* ```js
* import { secp256k1 } from '@noble/curves/secp256k1';
* const { secretKey, publicKey } = secp256k1.keygen();
* const msg = new TextEncoder().encode('hello');
* const sig = secp256k1.sign(msg, secretKey);
* const isValid = secp256k1.verify(sig, msg, publicKey) === true;
* ```
*/
const secp256k1 = createCurve({
...secp256k1_CURVE,
Fp: Fpk1,
lowS: true,
endo: secp256k1_ENDO
}, sha256$1);
// 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)}`);
}
}
};
// ../../node_modules/.pnpm/@solana-program+stake@0.9.0_@solana+kit@8.6.0_bufferutil@4.0.8_typescript@5.9.3_utf-8-validate@5.0.10_/node_modules/@solana-program/stake/dist/src/index.mjs
function getAuthorizedEncoder() {
return getStructEncoder([["staker", getAddressEncoder()], ["withdrawer", getAddressEncoder()]]);
}
function getAuthorizedDecoder() {
return getStructDecoder([["staker", getAddressDecoder()], ["withdrawer", getAddressDecoder()]]);
}
function getDelegationDecoder() {
return getStructDecoder([
["voterPubkey", getAddressDecoder()],
["stake", getU64Decoder()],
["activationEpoch", getEpochDecoder()],
["deactivationEpoch", getEpochDecoder()],
["reserved", getArrayDecoder(getU8Decoder(), { size: 8 })]
]);
}
function getEpochEncoder() {
return getU64Encoder();
}
function getEpochDecoder() {
return getU64Decoder();
}
function getLockupEncoder() {
return getStructEncoder([
["unixTimestamp", getUnixTimestampEncoder()],
["epoch", getEpochEncoder()],
["custodian", getAddressEncoder()]
]);
}
function getLockupDecoder() {
return getStructDecoder([
["unixTimestamp", getUnixTimestampDecoder()],
["epoch", getEpochDecoder()],
["custodian", getAddressDecoder()]
]);
}
function getMetaDecoder() {
return getStructDecoder([
["rentExemptReserve", getU64Decoder()],
["authorized", getAuthorizedDecoder()],
["lockup", getLockupDecoder()]
]);
}
function getStakeDecoder() {
return getStructDecoder([["delegation", getDelegationDecoder()], ["creditsObserved", getU64Decoder()]]);
}
var StakeAuthorize = /* @__PURE__ */ ((StakeAuthorize2) => {
StakeAuthorize2[StakeAuthorize2["Staker"] = 0] = "Staker";
StakeAuthorize2[StakeAuthorize2["Withdrawer"] = 1] = "Withdrawer";
return StakeAuthorize2;
})(StakeAuthorize || {});
function getStakeAuthorizeEncoder() {
return getEnumEncoder(StakeAuthorize, { size: getU32Encoder() });
}
function getStakeAuthorizeDecoder() {
return getEnumDecoder(StakeAuthorize, { size: getU32Decoder() });
}
function getStakeFlagsDecoder() {
return getStructDecoder([["bits", getU8Decoder()]]);
}
function getStakeStateV2Decoder() {
return getDiscriminatedUnionDecoder([
["Uninitialized", getUnitDecoder()],
["Initialized", getStructDecoder([["fields", getTupleDecoder([getMetaDecoder()])]])],
["Stake", getStructDecoder([["fields", getTupleDecoder([
getMetaDecoder(),
getStakeDecoder(),
getStakeFlagsDecoder()
])]])],
["RewardsPool", getUnitDecoder()]
], { size: getU32Decoder() });
}
function getUnixTimestampEncoder() {
return getI64Encoder();
}
function getUnixTimestampDecoder() {
return getI64Decoder();
}
function getStakeStateAccountDecoder() {
return getStructDecoder([["state", getStakeStateV2Decoder()]]);
}
function getAuthorizeInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["arg0", getAddressEncoder()],
["arg1", getStakeAuthorizeEncoder()]
]), (value) => ({
...value,
discriminator: 1
}));
}
function getAuthorizeInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["arg0", getAddressDecoder()],
["arg1", getStakeAuthorizeDecoder()]
]);
}
function getAuthorizeInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
clockSysvar: {
value: input.clockSysvar ?? null,
isWritable: false
},
authority: {
value: input.authority ?? null,
isWritable: false
},
lockupAuthority: {
value: input.lockupAuthority ?? null,
isWritable: false
}
};
const args = { ...input };
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("authority", accounts.authority),
getAccountMeta("lockupAuthority", accounts.lockupAuthority)
].filter((x) => x !== void 0),
data: getAuthorizeInstructionDataEncoder().encode(args),
programAddress
});
}
function parseAuthorizeInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
let optionalAccountsRemaining = instruction.accounts.length - 3;
const getNextOptionalAccount = () => {
if (optionalAccountsRemaining === 0) return void 0;
optionalAccountsRemaining -= 1;
return getNextAccount();
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
clockSysvar: getNextAccount(),
authority: getNextAccount(),
lockupAuthority: getNextOptionalAccount()
},
data: getAuthorizeInstructionDataDecoder().decode(instruction.data)
};
}
function getAuthorizeCheckedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["stakeAuthorize", getStakeAuthorizeEncoder()]]), (value) => ({
...value,
discriminator: 10
}));
}
function getAuthorizeCheckedInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["stakeAuthorize", getStakeAuthorizeDecoder()]]);
}
function getAuthorizeCheckedInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
clockSysvar: {
value: input.clockSysvar ?? null,
isWritable: false
},
authority: {
value: input.authority ?? null,
isWritable: false
},
newAuthority: {
value: input.newAuthority ?? null,
isWritable: false
},
lockupAuthority: {
value: input.lockupAuthority ?? null,
isWritable: false
}
};
const args = { ...input };
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("authority", accounts.authority),
getAccountMeta("newAuthority", accounts.newAuthority),
getAccountMeta("lockupAuthority", accounts.lockupAuthority)
].filter((x) => x !== void 0),
data: getAuthorizeCheckedInstructionDataEncoder().encode(args),
programAddress
});
}
function parseAuthorizeCheckedInstruction(instruction) {
if (instruction.accounts.length < 4) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 4
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
let optionalAccountsRemaining = instruction.accounts.length - 4;
const getNextOptionalAccount = () => {
if (optionalAccountsRemaining === 0) return void 0;
optionalAccountsRemaining -= 1;
return getNextAccount();
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
clockSysvar: getNextAccount(),
authority: getNextAccount(),
newAuthority: getNextAccount(),
lockupAuthority: getNextOptionalAccount()
},
data: getAuthorizeCheckedInstructionDataDecoder().decode(instruction.data)
};
}
function getAuthorizeCheckedWithSeedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["stakeAuthorize", getStakeAuthorizeEncoder()],
["authoritySeed", addEncoderSizePrefix(getUtf8Encoder(), getU64Encoder())],
["authorityOwner", getAddressEncoder()]
]), (value) => ({
...value,
discriminator: 11
}));
}
function getAuthorizeCheckedWithSeedInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["stakeAuthorize", getStakeAuthorizeDecoder()],
["authoritySeed", addDecoderSizePrefix(getUtf8Decoder(), getU64Decoder())],
["authorityOwner", getAddressDecoder()]
]);
}
function getAuthorizeCheckedWithSeedInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
base: {
value: input.base ?? null,
isWritable: false
},
clockSysvar: {
value: input.clockSysvar ?? null,
isWritable: false
},
newAuthority: {
value: input.newAuthority ?? null,
isWritable: false
},
lockupAuthority: {
value: input.lockupAuthority ?? null,
isWritable: false
}
};
const args = { ...input };
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("base", accounts.base),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("newAuthority", accounts.newAuthority),
getAccountMeta("lockupAuthority", accounts.lockupAuthority)
].filter((x) => x !== void 0),
data: getAuthorizeCheckedWithSeedInstructionDataEncoder().encode(args),
programAddress
});
}
function parseAuthorizeCheckedWithSeedInstruction(instruction) {
if (instruction.accounts.length < 4) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 4
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
let optionalAccountsRemaining = instruction.accounts.length - 4;
const getNextOptionalAccount = () => {
if (optionalAccountsRemaining === 0) return void 0;
optionalAccountsRemaining -= 1;
return getNextAccount();
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
base: getNextAccount(),
clockSysvar: getNextAccount(),
newAuthority: getNextAccount(),
lockupAuthority: getNextOptionalAccount()
},
data: getAuthorizeCheckedWithSeedInstructionDataDecoder().decode(instruction.data)
};
}
function getAuthorizeWithSeedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["newAuthorizedPubkey", getAddressEncoder()],
["stakeAuthorize", getStakeAuthorizeEncoder()],
["authoritySeed", addEncoderSizePrefix(getUtf8Encoder(), getU64Encoder())],
["authorityOwner", getAddressEncoder()]
]), (value) => ({
...value,
discriminator: 8
}));
}
function getAuthorizeWithSeedInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["newAuthorizedPubkey", getAddressDecoder()],
["stakeAuthorize", getStakeAuthorizeDecoder()],
["authoritySeed", addDecoderSizePrefix(getUtf8Decoder(), getU64Decoder())],
["authorityOwner", getAddressDecoder()]
]);
}
function getAuthorizeWithSeedInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
base: {
value: input.base ?? null,
isWritable: false
},
clockSysvar: {
value: input.clockSysvar ?? null,
isWritable: false
},
lockupAuthority: {
value: input.lockupAuthority ?? null,
isWritable: false
}
};
const args = { ...input };
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("base", accounts.base),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("lockupAuthority", accounts.lockupAuthority)
].filter((x) => x !== void 0),
data: getAuthorizeWithSeedInstructionDataEncoder().encode(args),
programAddress
});
}
function parseAuthorizeWithSeedInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
let optionalAccountsRemaining = instruction.accounts.length - 3;
const getNextOptionalAccount = () => {
if (optionalAccountsRemaining === 0) return void 0;
optionalAccountsRemaining -= 1;
return getNextAccount();
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
base: getNextAccount(),
clockSysvar: getNextAccount(),
lockupAuthority: getNextOptionalAccount()
},
data: getAuthorizeWithSeedInstructionDataDecoder().decode(instruction.data)
};
}
function getDeactivateInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 5
}));
}
function getDeactivateInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getDeactivateInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
clockSysvar: {
value: input.clockSysvar ?? null,
isWritable: false
},
stakeAuthority: {
value: input.stakeAuthority ?? null,
isWritable: false
}
};
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("stakeAuthority", accounts.stakeAuthority)
],
data: getDeactivateInstructionDataEncoder().encode({}),
programAddress
});
}
function parseDeactivateInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
clockSysvar: getNextAccount(),
stakeAuthority: getNextAccount()
},
data: getDeactivateInstructionDataDecoder().decode(instruction.data)
};
}
function getDeactivateDelinquentInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 14
}));
}
function getDeactivateDelinquentInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getDeactivateDelinquentInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
delinquentVote: {
value: input.delinquentVote ?? null,
isWritable: false
},
referenceVote: {
value: input.referenceVote ?? null,
isWritable: false
}
};
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("delinquentVote", accounts.delinquentVote),
getAccountMeta("referenceVote", accounts.referenceVote)
],
data: getDeactivateDelinquentInstructionDataEncoder().encode({}),
programAddress
});
}
function parseDeactivateDelinquentInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
delinquentVote: getNextAccount(),
referenceVote: getNextAccount()
},
data: getDeactivateDelinquentInstructionDataDecoder().decode(instruction.data)
};
}
function getDelegateStakeInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 2
}));
}
function getDelegateStakeInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getDelegateStakeInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
vote: {
value: input.vote ?? null,
isWritable: false
},
clockSysvar: {
value: input.clockSysvar ?? null,
isWritable: false
},
stakeHistory: {
value: input.stakeHistory ?? null,
isWritable: false
},
unused: {
value: input.unused ?? null,
isWritable: false
},
stakeAuthority: {
value: input.stakeAuthority ?? null,
isWritable: false
}
};
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
if (!accounts.stakeHistory.value) accounts.stakeHistory.value = "SysvarStakeHistory1111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("vote", accounts.vote),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("stakeHistory", accounts.stakeHistory),
getAccountMeta("unused", accounts.unused),
getAccountMeta("stakeAuthority", accounts.stakeAuthority)
],
data: getDelegateStakeInstructionDataEncoder().encode({}),
programAddress
});
}
function parseDelegateStakeInstruction(instruction) {
if (instruction.accounts.length < 6) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 6
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
vote: getNextAccount(),
clockSysvar: getNextAccount(),
stakeHistory: getNextAccount(),
unused: getNextAccount(),
stakeAuthority: getNextAccount()
},
data: getDelegateStakeInstructionDataDecoder().decode(instruction.data)
};
}
function getGetMinimumDelegationInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 13
}));
}
function getGetMinimumDelegationInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getGetMinimumDelegationInstruction(config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
return Object.freeze({
data: getGetMinimumDelegationInstructionDataEncoder().encode({}),
programAddress
});
}
function parseGetMinimumDelegationInstruction(instruction) {
return {
programAddress: instruction.programAddress,
data: getGetMinimumDelegationInstructionDataDecoder().decode(instruction.data)
};
}
function getInitializeInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["arg0", getAuthorizedEncoder()],
["arg1", getLockupEncoder()]
]), (value) => ({
...value,
discriminator: 0
}));
}
function getInitializeInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["arg0", getAuthorizedDecoder()],
["arg1", getLockupDecoder()]
]);
}
function getInitializeInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
rentSysvar: {
value: input.rentSysvar ?? null,
isWritable: false
}
};
const args = { ...input };
if (!accounts.rentSysvar.value) accounts.rentSysvar.value = "SysvarRent111111111111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [getAccountMeta("stake", accounts.stake), getAccountMeta("rentSysvar", accounts.rentSysvar)],
data: getInitializeInstructionDataEncoder().encode(args),
programAddress
});
}
function parseInitializeInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
rentSysvar: getNextAccount()
},
data: getInitializeInstructionDataDecoder().decode(instruction.data)
};
}
function getInitializeCheckedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 9
}));
}
function getInitializeCheckedInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getInitializeCheckedInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
rentSysvar: {
value: input.rentSysvar ?? null,
isWritable: false
},
stakeAuthority: {
value: input.stakeAuthority ?? null,
isWritable: false
},
withdrawAuthority: {
value: input.withdrawAuthority ?? null,
isWritable: false
}
};
if (!accounts.rentSysvar.value) accounts.rentSysvar.value = "SysvarRent111111111111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("rentSysvar", accounts.rentSysvar),
getAccountMeta("stakeAuthority", accounts.stakeAuthority),
getAccountMeta("withdrawAuthority", accounts.withdrawAuthority)
],
data: getInitializeCheckedInstructionDataEncoder().encode({}),
programAddress
});
}
function parseInitializeCheckedInstruction(instruction) {
if (instruction.accounts.length < 4) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 4
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
rentSysvar: getNextAccount(),
stakeAuthority: getNextAccount(),
withdrawAuthority: getNextAccount()
},
data: getInitializeCheckedInstructionDataDecoder().decode(instruction.data)
};
}
function getMergeInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()]]), (value) => ({
...value,
discriminator: 7
}));
}
function getMergeInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()]]);
}
function getMergeInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
destinationStake: {
value: input.destinationStake ?? null,
isWritable: true
},
sourceStake: {
value: input.sourceStake ?? null,
isWritable: true
},
clockSysvar: {
value: input.clockSysvar ?? null,
isWritable: false
},
stakeHistory: {
value: input.stakeHistory ?? null,
isWritable: false
},
stakeAuthority: {
value: input.stakeAuthority ?? null,
isWritable: false
}
};
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
if (!accounts.stakeHistory.value) accounts.stakeHistory.value = "SysvarStakeHistory1111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("destinationStake", accounts.destinationStake),
getAccountMeta("sourceStake", accounts.sourceStake),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("stakeHistory", accounts.stakeHistory),
getAccountMeta("stakeAuthority", accounts.stakeAuthority)
],
data: getMergeInstructionDataEncoder().encode({}),
programAddress
});
}
function parseMergeInstruction(instruction) {
if (instruction.accounts.length < 5) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 5
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
destinationStake: getNextAccount(),
sourceStake: getNextAccount(),
clockSysvar: getNextAccount(),
stakeHistory: getNextAccount(),
stakeAuthority: getNextAccount()
},
data: getMergeInstructionDataDecoder().decode(instruction.data)
};
}
function getMoveLamportsInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["args", getU64Encoder()]]), (value) => ({
...value,
discriminator: 17
}));
}
function getMoveLamportsInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["args", getU64Decoder()]]);
}
function getMoveLamportsInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
sourceStake: {
value: input.sourceStake ?? null,
isWritable: true
},
destinationStake: {
value: input.destinationStake ?? null,
isWritable: true
},
stakeAuthority: {
value: input.stakeAuthority ?? null,
isWritable: false
}
};
const args = { ...input };
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("sourceStake", accounts.sourceStake),
getAccountMeta("destinationStake", accounts.destinationStake),
getAccountMeta("stakeAuthority", accounts.stakeAuthority)
],
data: getMoveLamportsInstructionDataEncoder().encode(args),
programAddress
});
}
function parseMoveLamportsInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
sourceStake: getNextAccount(),
destinationStake: getNextAccount(),
stakeAuthority: getNextAccount()
},
data: getMoveLamportsInstructionDataDecoder().decode(instruction.data)
};
}
function getMoveStakeInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["args", getU64Encoder()]]), (value) => ({
...value,
discriminator: 16
}));
}
function getMoveStakeInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["args", getU64Decoder()]]);
}
function getMoveStakeInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
sourceStake: {
value: input.sourceStake ?? null,
isWritable: true
},
destinationStake: {
value: input.destinationStake ?? null,
isWritable: true
},
stakeAuthority: {
value: input.stakeAuthority ?? null,
isWritable: false
}
};
const args = { ...input };
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("sourceStake", accounts.sourceStake),
getAccountMeta("destinationStake", accounts.destinationStake),
getAccountMeta("stakeAuthority", accounts.stakeAuthority)
],
data: getMoveStakeInstructionDataEncoder().encode(args),
programAddress
});
}
function parseMoveStakeInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
sourceStake: getNextAccount(),
destinationStake: getNextAccount(),
stakeAuthority: getNextAccount()
},
data: getMoveStakeInstructionDataDecoder().decode(instruction.data)
};
}
function getSetLockupInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["unixTimestamp", getOptionEncoder(getUnixTimestampEncoder())],
["epoch", getOptionEncoder(getEpochEncoder())],
["custodian", getOptionEncoder(getAddressEncoder())]
]), (value) => ({
...value,
discriminator: 6
}));
}
function getSetLockupInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["unixTimestamp", getOptionDecoder(getUnixTimestampDecoder())],
["epoch", getOptionDecoder(getEpochDecoder())],
["custodian", getOptionDecoder(getAddressDecoder())]
]);
}
function getSetLockupInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
authority: {
value: input.authority ?? null,
isWritable: false
}
};
const args = { ...input };
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [getAccountMeta("stake", accounts.stake), getAccountMeta("authority", accounts.authority)],
data: getSetLockupInstructionDataEncoder().encode(args),
programAddress
});
}
function parseSetLockupInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
authority: getNextAccount()
},
data: getSetLockupInstructionDataDecoder().decode(instruction.data)
};
}
function getSetLockupCheckedInstructionDataEncoder() {
return transformEncoder(getStructEncoder([
["discriminator", getU32Encoder()],
["unixTimestamp", getOptionEncoder(getUnixTimestampEncoder())],
["epoch", getOptionEncoder(getEpochEncoder())]
]), (value) => ({
...value,
discriminator: 12
}));
}
function getSetLockupCheckedInstructionDataDecoder() {
return getStructDecoder([
["discriminator", getU32Decoder()],
["unixTimestamp", getOptionDecoder(getUnixTimestampDecoder())],
["epoch", getOptionDecoder(getEpochDecoder())]
]);
}
function getSetLockupCheckedInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
authority: {
value: input.authority ?? null,
isWritable: false
},
newAuthority: {
value: input.newAuthority ?? null,
isWritable: false
}
};
const args = { ...input };
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("authority", accounts.authority),
getAccountMeta("newAuthority", accounts.newAuthority)
].filter((x) => x !== void 0),
data: getSetLockupCheckedInstructionDataEncoder().encode(args),
programAddress
});
}
function parseSetLockupCheckedInstruction(instruction) {
if (instruction.accounts.length < 2) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 2
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
let optionalAccountsRemaining = instruction.accounts.length - 2;
const getNextOptionalAccount = () => {
if (optionalAccountsRemaining === 0) return void 0;
optionalAccountsRemaining -= 1;
return getNextAccount();
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
authority: getNextAccount(),
newAuthority: getNextOptionalAccount()
},
data: getSetLockupCheckedInstructionDataDecoder().decode(instruction.data)
};
}
function getSplitInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["args", getU64Encoder()]]), (value) => ({
...value,
discriminator: 3
}));
}
function getSplitInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["args", getU64Decoder()]]);
}
function getSplitInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
splitStake: {
value: input.splitStake ?? null,
isWritable: true
},
stakeAuthority: {
value: input.stakeAuthority ?? null,
isWritable: false
}
};
const args = { ...input };
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("splitStake", accounts.splitStake),
getAccountMeta("stakeAuthority", accounts.stakeAuthority)
],
data: getSplitInstructionDataEncoder().encode(args),
programAddress
});
}
function parseSplitInstruction(instruction) {
if (instruction.accounts.length < 3) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 3
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
splitStake: getNextAccount(),
stakeAuthority: getNextAccount()
},
data: getSplitInstructionDataDecoder().decode(instruction.data)
};
}
function getWithdrawInstructionDataEncoder() {
return transformEncoder(getStructEncoder([["discriminator", getU32Encoder()], ["args", getU64Encoder()]]), (value) => ({
...value,
discriminator: 4
}));
}
function getWithdrawInstructionDataDecoder() {
return getStructDecoder([["discriminator", getU32Decoder()], ["args", getU64Decoder()]]);
}
function getWithdrawInstruction(input, config) {
const programAddress = config?.programAddress ?? "Stake11111111111111111111111111111111111111";
const accounts = {
stake: {
value: input.stake ?? null,
isWritable: true
},
recipient: {
value: input.recipient ?? null,
isWritable: true
},
clockSysvar: {
value: input.clockSysvar ?? null,
isWritable: false
},
stakeHistory: {
value: input.stakeHistory ?? null,
isWritable: false
},
withdrawAuthority: {
value: input.withdrawAuthority ?? null,
isWritable: false
},
lockupAuthority: {
value: input.lockupAuthority ?? null,
isWritable: false
}
};
const args = { ...input };
if (!accounts.clockSysvar.value) accounts.clockSysvar.value = "SysvarC1ock11111111111111111111111111111111";
if (!accounts.stakeHistory.value) accounts.stakeHistory.value = "SysvarStakeHistory1111111111111111111111111";
const getAccountMeta = getAccountMetaFactory(programAddress, "omitted");
return Object.freeze({
accounts: [
getAccountMeta("stake", accounts.stake),
getAccountMeta("recipient", accounts.recipient),
getAccountMeta("clockSysvar", accounts.clockSysvar),
getAccountMeta("stakeHistory", accounts.stakeHistory),
getAccountMeta("withdrawAuthority", accounts.withdrawAuthority),
getAccountMeta("lockupAuthority", accounts.lockupAuthority)
].filter((x) => x !== void 0),
data: getWithdrawInstructionDataEncoder().encode(args),
programAddress
});
}
function parseWithdrawInstruction(instruction) {
if (instruction.accounts.length < 5) throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {
actualAccountMetas: instruction.accounts.length,
expectedAccountMetas: 5
});
let accountIndex = 0;
const getNextAccount = () => {
const accountMeta = instruction.accounts[accountIndex];
accountIndex += 1;
return accountMeta;
};
let optionalAccountsRemaining = instruction.accounts.length - 5;
const getNextOptionalAccount = () => {
if (optionalAccountsRemaining === 0) return void 0;
optionalAccountsRemaining -= 1;
return getNextAccount();
};
return {
programAddress: instruction.programAddress,
accounts: {
stake: getNextAccount(),
recipient: getNextAccount(),
clockSysvar: getNextAccount(),
stakeHistory: getNextAccount(),
withdrawAuthority: getNextAccount(),
lockupAuthority: getNextOptionalAccount()
},
data: getWithdrawInstructionDataDecoder().decode(instruction.data)
};
}
var STAKE_PROGRAM_ADDRESS = "Stake11111111111111111111111111111111111111";
var StakeInstruction$1 = /* @__PURE__ */ ((StakeInstruction2) => {
StakeInstruction2[StakeInstruction2["Initialize"] = 0] = "Initialize";
StakeInstruction2[StakeInstruction2["Authorize"] = 1] = "Authorize";
StakeInstruction2[StakeInstruction2["DelegateStake"] = 2] = "DelegateStake";
StakeInstruction2[StakeInstruction2["Split"] = 3] = "Split";
StakeInstruction2[StakeInstruction2["Withdraw"] = 4] = "Withdraw";
StakeInstruction2[StakeInstruction2["Deactivate"] = 5] = "Deactivate";
StakeInstruction2[StakeInstruction2["SetLockup"] = 6] = "SetLockup";
StakeInstruction2[StakeInstruction2["Merge"] = 7] = "Merge";
StakeInstruction2[StakeInstruction2["AuthorizeWithSeed"] = 8] = "AuthorizeWithSeed";
StakeInstruction2[StakeInstruction2["InitializeChecked"] = 9] = "InitializeChecked";
StakeInstruction2[StakeInstruction2["AuthorizeChecked"] = 10] = "AuthorizeChecked";
StakeInstruction2[StakeInstruction2["AuthorizeCheckedWithSeed"] = 11] = "AuthorizeCheckedWithSeed";
StakeInstruction2[StakeInstruction2["SetLockupChecked"] = 12] = "SetLockupChecked";
StakeInstruction2[StakeInstruction2["GetMinimumDelegation"] = 13] = "GetMinimumDelegation";
StakeInstruction2[StakeInstruction2["DeactivateDelinquent"] = 14] = "DeactivateDelinquent";
StakeInstruction2[StakeInstruction2["MoveStake"] = 15] = "MoveStake";
StakeInstruction2[StakeInstruction2["MoveLamports"] = 16] = "MoveLamports";
return StakeInstruction2;
})(StakeInstruction$1 || {});
function identifyStakeInstruction(instruction) {
const data = "data" in instruction ? instruction.data : instruction;
if (containsBytes(data, getU32Encoder().encode(0), 0)) return 0;
if (containsBytes(data, getU32Encoder().encode(1), 0)) return 1;
if (containsBytes(data, getU32Encoder().encode(2), 0)) return 2;
if (containsBytes(data, getU32Encoder().encode(3), 0)) return 3;
if (containsBytes(data, getU32Encoder().encode(4), 0)) return 4;
if (containsBytes(data, getU32Encoder().encode(5), 0)) return 5;
if (containsBytes(data, getU32Encoder().encode(6), 0)) return 6;
if (containsBytes(data, getU32Encoder().encode(7), 0)) return 7;
if (containsBytes(data, getU32Encoder().encode(8), 0)) return 8;
if (containsBytes(data, getU32Encoder().encode(9), 0)) return 9;
if (containsBytes(data, getU32Encoder().encode(10), 0)) return 10;
if (containsBytes(data, getU32Encoder().encode(11), 0)) return 11;
if (containsBytes(data, getU32Encoder().encode(12), 0)) return 12;
if (containsBytes(data, getU32Encoder().encode(13), 0)) return 13;
if (containsBytes(data, getU32Encoder().encode(14), 0)) return 14;
if (containsBytes(data, getU32Encoder().encode(16), 0)) return 15;
if (containsBytes(data, getU32Encoder().encode(17), 0)) return 16;
throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {
instructionData: data,
programName: "stake"
});
}
function parseStakeInstruction(instruction) {
const instructionType = identifyStakeInstruction(instruction);
switch (instructionType) {
case 0:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 0,
...parseInitializeInstruction(instruction)
};
case 1:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 1,
...parseAuthorizeInstruction(instruction)
};
case 2:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 2,
...parseDelegateStakeInstruction(instruction)
};
case 3:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 3,
...parseSplitInstruction(instruction)
};
case 4:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 4,
...parseWithdrawInstruction(instruction)
};
case 5:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 5,
...parseDeactivateInstruction(instruction)
};
case 6:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 6,
...parseSetLockupInstruction(instruction)
};
case 7:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 7,
...parseMergeInstruction(instruction)
};
case 8:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 8,
...parseAuthorizeWithSeedInstruction(instruction)
};
case 9:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 9,
...parseInitializeCheckedInstruction(instruction)
};
case 10:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 10,
...parseAuthorizeCheckedInstruction(instruction)
};
case 11:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 11,
...parseAuthorizeCheckedWithSeedInstruction(instruction)
};
case 12:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 12,
...parseSetLockupCheckedInstruction(instruction)
};
case 13: return {
instructionType: 13,
...parseGetMinimumDelegationInstruction(instruction)
};
case 14:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 14,
...parseDeactivateDelinquentInstruction(instruction)
};
case 15:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 15,
...parseMoveStakeInstruction(instruction)
};
case 16:
assertIsInstructionWithAccounts(instruction);
return {
instructionType: 16,
...parseMoveLamportsInstruction(instruction)
};
default: throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {
instructionType,
programName: "stake"
});
}
}
// 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_VOTERS_CODEC = getStructCodec([
["buf", getArrayCodec(getStructCodec([
["authorizedPubkey", PUBLIC_KEY_CODEC],
["epochOfLastAuthorizedSwitch", U64_BIGINT_CODEC],
["targetEpoch", U64_BIGINT_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;
exports.AddressLookupTableAccount = AddressLookupTableAccount;
exports.AddressLookupTableInstruction = AddressLookupTableInstruction;
exports.AddressLookupTableProgram = AddressLookupTableProgram;
exports.Authorized = Authorized;
exports.BLOCKHASH_CACHE_TIMEOUT_MS = BLOCKHASH_CACHE_TIMEOUT_MS;
exports.BPF_LOADER_DEPRECATED_PROGRAM_ID = BPF_LOADER_DEPRECATED_PROGRAM_ID;
exports.BPF_LOADER_PROGRAM_ID = BPF_LOADER_PROGRAM_ID;
exports.BpfLoader = BpfLoader;
exports.ComputeBudgetInstruction = ComputeBudgetInstruction;
exports.ComputeBudgetProgram = ComputeBudgetProgram;
exports.Connection = Connection;
exports.Ed25519Program = Ed25519Program;
exports.EpochSchedule = EpochSchedule;
exports.Keypair = Keypair;
exports.LAMPORTS_PER_SOL = LAMPORTS_PER_SOL;
exports.Loader = Loader;
exports.LoaderV3Instruction = LoaderV3Instruction;
exports.LoaderV3Program = LoaderV3Program;
exports.Lockup = Lockup;
exports.MAX_SEED_LENGTH = MAX_SEED_LENGTH;
exports.Message = Message;
exports.MessageAccountKeys = MessageAccountKeys;
exports.MessageV0 = MessageV0;
exports.MessageV1 = MessageV1;
exports.NONCE_ACCOUNT_LENGTH = NONCE_ACCOUNT_LENGTH;
exports.NonceAccount = NonceAccount;
exports.PACKET_DATA_SIZE = PACKET_DATA_SIZE;
exports.PUBLIC_KEY_LENGTH = PUBLIC_KEY_LENGTH;
exports.PublicKey = PublicKey;
exports.SIGNATURE_LENGTH_IN_BYTES = SIGNATURE_LENGTH_IN_BYTES;
exports.STAKE_CONFIG_ID = STAKE_CONFIG_ID;
exports.SYSVAR_CLOCK_PUBKEY = SYSVAR_CLOCK_PUBKEY;
exports.SYSVAR_EPOCH_SCHEDULE_PUBKEY = SYSVAR_EPOCH_SCHEDULE_PUBKEY;
exports.SYSVAR_INSTRUCTIONS_PUBKEY = SYSVAR_INSTRUCTIONS_PUBKEY;
exports.SYSVAR_RECENT_BLOCKHASHES_PUBKEY = SYSVAR_RECENT_BLOCKHASHES_PUBKEY;
exports.SYSVAR_RENT_PUBKEY = SYSVAR_RENT_PUBKEY;
exports.SYSVAR_REWARDS_PUBKEY = SYSVAR_REWARDS_PUBKEY;
exports.SYSVAR_SLOT_HASHES_PUBKEY = SYSVAR_SLOT_HASHES_PUBKEY;
exports.SYSVAR_SLOT_HISTORY_PUBKEY = SYSVAR_SLOT_HISTORY_PUBKEY;
exports.SYSVAR_STAKE_HISTORY_PUBKEY = SYSVAR_STAKE_HISTORY_PUBKEY;
exports.Secp256k1Program = Secp256k1Program;
exports.SendTransactionError = SendTransactionError;
exports.SolanaJSONRPCError = SolanaJSONRPCError;
exports.SolanaJSONRPCErrorCode = SolanaJSONRPCErrorCode;
exports.StakeAccount = StakeAccount;
exports.StakeAuthorizationLayout = StakeAuthorizationLayout;
exports.StakeInstruction = StakeInstruction;
exports.StakeProgram = StakeProgram;
exports.SystemInstruction = SystemInstruction;
exports.SystemProgram = SystemProgram;
exports.Transaction = Transaction;
exports.TransactionExpiredBlockheightExceededError = TransactionExpiredBlockheightExceededError;
exports.TransactionExpiredNonceInvalidError = TransactionExpiredNonceInvalidError;
exports.TransactionExpiredTimeoutError = TransactionExpiredTimeoutError;
exports.TransactionInstruction = TransactionInstruction;
exports.TransactionMessage = TransactionMessage;
exports.TransactionStatus = TransactionStatus;
exports.V1_MAX_INSTRUCTIONS = V1_MAX_INSTRUCTIONS;
exports.V1_MESSAGE_PREFIX = V1_MESSAGE_PREFIX;
exports.VALIDATOR_INFO_KEY = VALIDATOR_INFO_KEY;
exports.VERSION_PREFIX_MASK = VERSION_PREFIX_MASK;
exports.VOTE_PROGRAM_ID = VOTE_PROGRAM_ID;
exports.ValidatorInfo = ValidatorInfo;
exports.VersionedMessage = VersionedMessage;
exports.VersionedTransaction = VersionedTransaction;
exports.VoteAccount = VoteAccount;
exports.VoteAuthorizationLayout = VoteAuthorizationLayout;
exports.VoteInit = VoteInit;
exports.VoteInstruction = VoteInstruction;
exports.VoteProgram = VoteProgram;
exports.VoteStateVersion = VoteStateVersion;
exports.__TEST_ONLY__VOTE_ACCOUNT_V1_14_11_CODEC = __TEST_ONLY__VOTE_ACCOUNT_V1_14_11_CODEC;
exports.__TEST_ONLY__VOTE_ACCOUNT_V3_CODEC = __TEST_ONLY__VOTE_ACCOUNT_V3_CODEC;
exports.__TEST_ONLY__VOTE_ACCOUNT_V4_CODEC = __TEST_ONLY__VOTE_ACCOUNT_V4_CODEC;
exports.clusterApiUrl = clusterApiUrl;
exports.sendAndConfirmRawTransaction = sendAndConfirmRawTransaction;
exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
return exports;
})({});
//# sourceMappingURL=index.iife.js.map