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MAAM1lC,EAAAA,GAAAA,MACNs1C,SAAS/O,EAAAA,GAAAA,KAASvmC,EAAAA,GAAAA,OAClBu1C,SAAShP,EAAAA,GAAAA,KAASvmC,EAAAA,GAAAA,OAClBw1C,iBAAiBjP,EAAAA,GAAAA,KAASvmC,EAAAA,GAAAA,SCnCG,IAAI2wB,GACjC,+CAoEwB2D,GAAAA,OAAqC,CAC7Dtd,GAAiB,cACjBA,GAAiB,wBACjBsd,GAAAA,GAAgB,cAChBA,GAAAA,OACAA,GAAAA,IACEA,GAAAA,OAAoB,CAClBA,GAAAA,KAAkB,QAClBA,GAAAA,IAAiB,uBAEnBA,GAAAA,OAAoBA,GAAAA,OAAqB,GACzC,SAEFA,GAAAA,GAAgB,iBAChBA,GAAAA,KAAkB,YAClBA,GAAAA,OACAA,GAAAA,IACEA,GAAAA,OAAoB,CAClBA,GAAAA,KAAkB,SAClBtd,GAAiB,qBAEnBsd,GAAAA,OAAoBA,GAAAA,OAAqB,GACzC,oBAEFA,GAAAA,OACE,CACEA,GAAAA,IACEA,GAAAA,OAAoB,CAClBtd,GAAiB,oBACjBsd,GAAAA,KAAkB,+BAClBA,GAAAA,KAAkB,iBAEpB,GACA,OAEFA,GAAAA,KAAkB,OAClBA,GAAAA,GAAgB,YAElB,eAEFA,GAAAA,OACAA,GAAAA,IACEA,GAAAA,OAAoB,CAClBA,GAAAA,KAAkB,SAClBA,GAAAA,KAAkB,WAClBA,GAAAA,KAAkB,iBAEpBA,GAAAA,OAAoBA,GAAAA,OAAqB,GACzC,gBAEFA,GAAAA,OACE,CAACA,GAAAA,KAAkB,QAASA,GAAAA,KAAkB,cAC9C,mB","sources":["webpack://fluxbeam/./node_modules/@alphabatem/liquifynft-sdk/node_modules/base-x/src/index.js","webpack://fluxbeam/./node_modules/@alphabatem/liquifynft-sdk/node_modules/bs58/index.js","webpack://fluxbeam/./node_modules/@alphabatem/liquifynft-sdk/lib/esm/api/core.js","webpack://fluxbeam/./node_modules/@alphabatem/liquifynft-sdk/lib/esm/api/getCollections.js","webpack://fluxbeam/./node_modules/@alphabatem/liquifynft-sdk/lib/esm/api/getCollectionPricing.js","webpack://fluxbeam/./node_modules/@alphabatem/liquifynft-sdk/lib/esm/api/getNftStats.js","webpack://fluxbeam/../../src/abstract/utils.ts","webpack://fluxbeam/../../src/abstract/modular.ts","webpack://fluxbeam/../../src/abstract/curve.ts","webpack://fluxbeam/../../src/abstract/edwards.ts","webpack://fluxbeam/../../src/abstract/montgomery.ts","webpack://fluxbeam/../../src/abstract/hash-to-curve.ts","webpack://fluxbeam/../src/ed25519.ts","webpack://fluxbeam/../../src/abstract/weierstrass.ts","webpack://fluxbeam/../src/_shortw_utils.ts","webpack://fluxbeam/../src/secp256k1.ts","webpack://fluxbeam/../src/utils/ed25519.ts","webpack://fluxbeam/../src/utils/to-buffer.ts","webpack://fluxbeam/../src/utils/borsh-schema.ts","webpack://fluxbeam/../src/publickey.ts","webpack://fluxbeam/../src/bpf-loader-deprecated.ts","webpack://fluxbeam/../src/transaction/constants.ts","webpack://fluxbeam/../src/transaction/expiry-custom-errors.ts","webpack://fluxbeam/../src/message/account-keys.ts","webpack://fluxbeam/../src/layout.ts","webpack://fluxbeam/../src/utils/shortvec-encoding.ts","webpack://fluxbeam/../src/utils/assert.ts","webpack://fluxbeam/../src/message/compiled-keys.ts","webpack://fluxbeam/../src/message/legacy.ts","webpack://fluxbeam/../src/transaction/legacy.ts","webpack://fluxbeam/../src/timing.ts","webpack://fluxbeam/../src/sysvar.ts","webpack://fluxbeam/../src/utils/send-and-confirm-transaction.ts","webpack://fluxbeam/../src/utils/sleep.ts","webpack://fluxbeam/../src/instruction.ts","webpack://fluxbeam/../src/fee-calculator.ts","webpack://fluxbeam/../src/nonce-account.ts","webpack://fluxbeam/../src/utils/bigint.ts","webpack://fluxbeam/../src/programs/system.ts","webpack://fluxbeam/../src/loader.ts","webpack://fluxbeam/../src/bpf-loader.ts","webpack://fluxbeam/../../../node_modules/.pnpm/fast-stable-stringify@1.0.0/node_modules/fast-stable-stringify/index.js","webpack://fluxbeam/../src/errors.ts","webpack://fluxbeam/../src/__forks__/browser/fetch-impl.ts","webpack://fluxbeam/../src/programs/address-lookup-table/state.ts","webpack://fluxbeam/../src/connection.ts","webpack://fluxbeam/../src/keypair.ts","webpack://fluxbeam/../src/programs/address-lookup-table/index.ts","webpack://fluxbeam/../src/programs/compute-budget.ts","webpack://fluxbeam/../src/programs/ed25519.ts","webpack://fluxbeam/../src/utils/secp256k1.ts","webpack://fluxbeam/../src/programs/secp256k1.ts","webpack://fluxbeam/../src/programs/stake.ts","webpack://fluxbeam/../src/programs/vote.ts","webpack://fluxbeam/../src/validator-info.ts","webpack://fluxbeam/../src/vote-account.ts"],"sourcesContent":["'use strict'\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n// @ts-ignore\nvar _Buffer = require('safe-buffer').Buffer\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256)\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i)\n var xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n var BASE = ALPHABET.length\n var LEADER = ALPHABET.charAt(0)\n var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }\n if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0\n var length = 0\n var pbegin = 0\n var pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n var b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return _Buffer.alloc(0) }\n var psz = 0\n // Skip and count leading '1's.\n var zeroes = 0\n var length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size)\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)]\n // Invalid character\n if (carry === 255) { return }\n var i = 0\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n var it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n var vch = _Buffer.allocUnsafe(zeroes + (size - it4))\n vch.fill(0x00, 0, zeroes)\n var j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nmodule.exports = base\n","var basex = require('base-x')\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\n","let defaultURI = \"https://api.liquifynft.com/v1\";\nexport async function getApi(uri) {\n const resp = await fetch(fullUri(uri));\n return resp.json();\n}\nexport async function postApi(uri, data) {\n const resp = await fetch(fullUri(uri), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(data)\n });\n return resp.json();\n}\nexport function fullUri(path) {\n return `${baseURI()}/${path}`;\n}\nexport function baseURI() {\n return defaultURI;\n}\nexport function setBaseURI(base) {\n defaultURI = base;\n}\n","import { getApi } from \"./core\";\nexport async function getCollections(page = 0, limit = 500, search = \"\", onChainOnly = false) {\n let uri = `collections?page=${page}&limit=${limit}`;\n if (search !== \"\")\n uri = `${uri}&search=${search}`;\n if (onChainOnly)\n uri = `${uri}&onchain=true`;\n const resp = await getApi(uri);\n return resp;\n}\n","import { getApi } from \"./core\";\nexport async function getCollectionPricing() {\n const resp = await getApi(\"pricing/collections\");\n return resp;\n}\n","import { getApi } from \"./core\";\nexport async function getNftStats(id) {\n const resp = await getApi(`nfts/${id}/stats`);\n return resp;\n}\n",null,null,null,null,null,null,null,null,null,null,"import {ed25519} from '@noble/curves/ed25519';\n\n/**\n * A 64 byte secret key, the first 32 bytes of which is the\n * private scalar and the last 32 bytes is the public key.\n * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/\n */\ntype Ed25519SecretKey = Uint8Array;\n\n/**\n * Ed25519 Keypair\n */\nexport interface Ed25519Keypair {\n publicKey: Uint8Array;\n secretKey: Ed25519SecretKey;\n}\n\nexport const generatePrivateKey = ed25519.utils.randomPrivateKey;\nexport const generateKeypair = (): Ed25519Keypair => {\n const privateScalar = ed25519.utils.randomPrivateKey();\n const publicKey = getPublicKey(privateScalar);\n const secretKey = new Uint8Array(64);\n secretKey.set(privateScalar);\n secretKey.set(publicKey, 32);\n return {\n publicKey,\n secretKey,\n };\n};\nexport const getPublicKey = ed25519.getPublicKey;\nexport function isOnCurve(publicKey: Uint8Array): boolean {\n try {\n ed25519.ExtendedPoint.fromHex(publicKey);\n return true;\n } catch {\n return false;\n }\n}\nexport const sign = (\n message: Parameters[0],\n secretKey: Ed25519SecretKey,\n) => ed25519.sign(message, secretKey.slice(0, 32));\nexport const verify = ed25519.verify;\n","import {Buffer} from 'buffer';\n\nexport const toBuffer = (arr: Buffer | Uint8Array | Array): Buffer => {\n if (Buffer.isBuffer(arr)) {\n return arr;\n } else if (arr instanceof Uint8Array) {\n return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);\n } else {\n return Buffer.from(arr);\n }\n};\n","import {Buffer} from 'buffer';\nimport {serialize, deserialize, deserializeUnchecked} from 'borsh';\n\n// Class wrapping a plain object\nexport class Struct {\n constructor(properties: any) {\n Object.assign(this, properties);\n }\n\n encode(): Buffer {\n return Buffer.from(serialize(SOLANA_SCHEMA, this));\n }\n\n static decode(data: Buffer): any {\n return deserialize(SOLANA_SCHEMA, this, data);\n }\n\n static decodeUnchecked(data: Buffer): any {\n return deserializeUnchecked(SOLANA_SCHEMA, this, data);\n }\n}\n\n// Class representing a Rust-compatible enum, since enums are only strings or\n// numbers in pure JS\nexport class Enum extends Struct {\n enum: string = '';\n constructor(properties: any) {\n super(properties);\n if (Object.keys(properties).length !== 1) {\n throw new Error('Enum can only take single value');\n }\n Object.keys(properties).map(key => {\n this.enum = key;\n });\n }\n}\n\nexport const SOLANA_SCHEMA: Map = new Map();\n","import BN from 'bn.js';\nimport bs58 from 'bs58';\nimport {Buffer} from 'buffer';\nimport {sha256} from '@noble/hashes/sha256';\n\nimport {isOnCurve} from './utils/ed25519';\nimport {Struct, SOLANA_SCHEMA} from './utils/borsh-schema';\nimport {toBuffer} from './utils/to-buffer';\n\n/**\n * Maximum length of derived pubkey seed\n */\nexport const MAX_SEED_LENGTH = 32;\n\n/**\n * Size of public key in bytes\n */\nexport const PUBLIC_KEY_LENGTH = 32;\n\n/**\n * Value to be converted into public key\n */\nexport type PublicKeyInitData =\n | number\n | string\n | Uint8Array\n | Array\n | PublicKeyData;\n\n/**\n * JSON object representation of PublicKey class\n */\nexport type PublicKeyData = {\n /** @internal */\n _bn: BN;\n};\n\nfunction isPublicKeyData(value: PublicKeyInitData): value is PublicKeyData {\n return (value as PublicKeyData)._bn !== undefined;\n}\n\n// local counter used by PublicKey.unique()\nlet uniquePublicKeyCounter = 1;\n\n/**\n * A public key\n */\nexport class PublicKey extends Struct {\n /** @internal */\n _bn: BN;\n\n /**\n * Create a new PublicKey object\n * @param value ed25519 public key as buffer or base-58 encoded string\n */\n constructor(value: PublicKeyInitData) {\n super({});\n if (isPublicKeyData(value)) {\n this._bn = value._bn;\n } else {\n if (typeof value === 'string') {\n // assume base 58 encoding by default\n const decoded = bs58.decode(value);\n if (decoded.length != PUBLIC_KEY_LENGTH) {\n throw new Error(`Invalid public key input`);\n }\n this._bn = new BN(decoded);\n } else {\n this._bn = new BN(value);\n }\n\n if (this._bn.byteLength() > PUBLIC_KEY_LENGTH) {\n throw new Error(`Invalid public key input`);\n }\n }\n }\n\n /**\n * Returns a unique PublicKey for tests and benchmarks using a counter\n */\n static unique(): PublicKey {\n const key = new PublicKey(uniquePublicKeyCounter);\n uniquePublicKeyCounter += 1;\n return new PublicKey(key.toBuffer());\n }\n\n /**\n * Default public key value. The base58-encoded string representation is all ones (as seen below)\n * The underlying BN number is 32 bytes that are all zeros\n */\n static default: PublicKey = new PublicKey('11111111111111111111111111111111');\n\n /**\n * Checks if two publicKeys are equal\n */\n equals(publicKey: PublicKey): boolean {\n return this._bn.eq(publicKey._bn);\n }\n\n /**\n * Return the base-58 representation of the public key\n */\n toBase58(): string {\n return bs58.encode(this.toBytes());\n }\n\n toJSON(): string {\n return this.toBase58();\n }\n\n /**\n * Return the byte array representation of the public key in big endian\n */\n toBytes(): Uint8Array {\n const buf = this.toBuffer();\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n }\n\n /**\n * Return the Buffer representation of the public key in big endian\n */\n toBuffer(): Buffer {\n const b = this._bn.toArrayLike(Buffer);\n if (b.length === PUBLIC_KEY_LENGTH) {\n return b;\n }\n\n const zeroPad = Buffer.alloc(32);\n b.copy(zeroPad, 32 - b.length);\n return zeroPad;\n }\n\n get [Symbol.toStringTag](): string {\n return `PublicKey(${this.toString()})`;\n }\n\n /**\n * Return the base-58 representation of the public key\n */\n toString(): string {\n return this.toBase58();\n }\n\n /**\n * Derive a public key from another key, a seed, and a program ID.\n * The program ID will also serve as the owner of the public key, giving\n * it permission to write data to the account.\n */\n /* eslint-disable require-await */\n static async createWithSeed(\n fromPublicKey: PublicKey,\n seed: string,\n programId: PublicKey,\n ): Promise {\n const buffer = Buffer.concat([\n fromPublicKey.toBuffer(),\n Buffer.from(seed),\n programId.toBuffer(),\n ]);\n const publicKeyBytes = sha256(buffer);\n return new PublicKey(publicKeyBytes);\n }\n\n /**\n * Derive a program address from seeds and a program ID.\n */\n /* eslint-disable require-await */\n static createProgramAddressSync(\n seeds: Array,\n programId: PublicKey,\n ): PublicKey {\n let buffer = Buffer.alloc(0);\n seeds.forEach(function (seed) {\n if (seed.length > MAX_SEED_LENGTH) {\n throw new TypeError(`Max seed length exceeded`);\n }\n buffer = Buffer.concat([buffer, toBuffer(seed)]);\n });\n buffer = Buffer.concat([\n buffer,\n programId.toBuffer(),\n Buffer.from('ProgramDerivedAddress'),\n ]);\n const publicKeyBytes = sha256(buffer);\n if (isOnCurve(publicKeyBytes)) {\n throw new Error(`Invalid seeds, address must fall off the curve`);\n }\n return new PublicKey(publicKeyBytes);\n }\n\n /**\n * Async version of createProgramAddressSync\n * For backwards compatibility\n *\n * @deprecated Use {@link createProgramAddressSync} instead\n */\n /* eslint-disable require-await */\n static async createProgramAddress(\n seeds: Array,\n programId: PublicKey,\n ): Promise {\n return this.createProgramAddressSync(seeds, programId);\n }\n\n /**\n * Find a valid program address\n *\n * Valid program addresses must fall off the ed25519 curve. This function\n * iterates a nonce until it finds one that when combined with the seeds\n * results in a valid program address.\n */\n static findProgramAddressSync(\n seeds: Array,\n programId: PublicKey,\n ): [PublicKey, number] {\n let nonce = 255;\n let address;\n while (nonce != 0) {\n try {\n const seedsWithNonce = seeds.concat(Buffer.from([nonce]));\n address = this.createProgramAddressSync(seedsWithNonce, programId);\n } catch (err) {\n if (err instanceof TypeError) {\n throw err;\n }\n nonce--;\n continue;\n }\n return [address, nonce];\n }\n throw new Error(`Unable to find a viable program address nonce`);\n }\n\n /**\n * Async version of findProgramAddressSync\n * For backwards compatibility\n *\n * @deprecated Use {@link findProgramAddressSync} instead\n */\n static async findProgramAddress(\n seeds: Array,\n programId: PublicKey,\n ): Promise<[PublicKey, number]> {\n return this.findProgramAddressSync(seeds, programId);\n }\n\n /**\n * Check that a pubkey is on the ed25519 curve.\n */\n static isOnCurve(pubkeyData: PublicKeyInitData): boolean {\n const pubkey = new PublicKey(pubkeyData);\n return isOnCurve(pubkey.toBytes());\n }\n}\n\nSOLANA_SCHEMA.set(PublicKey, {\n kind: 'struct',\n fields: [['_bn', 'u256']],\n});\n","import {PublicKey} from './publickey';\n\nexport const BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey(\n 'BPFLoader1111111111111111111111111111111111',\n);\n","/**\n * Maximum over-the-wire size of a Transaction\n *\n * 1280 is IPv6 minimum MTU\n * 40 bytes is the size of the IPv6 header\n * 8 bytes is the size of the fragment header\n */\nexport const PACKET_DATA_SIZE = 1280 - 40 - 8;\n\nexport const VERSION_PREFIX_MASK = 0x7f;\n\nexport const SIGNATURE_LENGTH_IN_BYTES = 64;\n","export class TransactionExpiredBlockheightExceededError extends Error {\n signature: string;\n\n constructor(signature: string) {\n super(`Signature ${signature} has expired: block height exceeded.`);\n this.signature = signature;\n }\n}\n\nObject.defineProperty(\n TransactionExpiredBlockheightExceededError.prototype,\n 'name',\n {\n value: 'TransactionExpiredBlockheightExceededError',\n },\n);\n\nexport class TransactionExpiredTimeoutError extends Error {\n signature: string;\n\n constructor(signature: string, timeoutSeconds: number) {\n super(\n `Transaction was not confirmed in ${timeoutSeconds.toFixed(\n 2,\n )} seconds. It is ` +\n 'unknown if it succeeded or failed. Check signature ' +\n `${signature} using the Solana Explorer or CLI tools.`,\n );\n this.signature = signature;\n }\n}\n\nObject.defineProperty(TransactionExpiredTimeoutError.prototype, 'name', {\n value: 'TransactionExpiredTimeoutError',\n});\n\nexport class TransactionExpiredNonceInvalidError extends Error {\n signature: string;\n\n constructor(signature: string) {\n super(`Signature ${signature} has expired: the nonce is no longer valid.`);\n this.signature = signature;\n }\n}\n\nObject.defineProperty(TransactionExpiredNonceInvalidError.prototype, 'name', {\n value: 'TransactionExpiredNonceInvalidError',\n});\n","import {LoadedAddresses} from '../connection';\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport {MessageCompiledInstruction} from './index';\n\nexport type AccountKeysFromLookups = LoadedAddresses;\n\nexport class MessageAccountKeys {\n staticAccountKeys: Array;\n accountKeysFromLookups?: AccountKeysFromLookups;\n\n constructor(\n staticAccountKeys: Array,\n accountKeysFromLookups?: AccountKeysFromLookups,\n ) {\n this.staticAccountKeys = staticAccountKeys;\n this.accountKeysFromLookups = accountKeysFromLookups;\n }\n\n keySegments(): Array> {\n const keySegments = [this.staticAccountKeys];\n if (this.accountKeysFromLookups) {\n keySegments.push(this.accountKeysFromLookups.writable);\n keySegments.push(this.accountKeysFromLookups.readonly);\n }\n return keySegments;\n }\n\n get(index: number): PublicKey | undefined {\n for (const keySegment of this.keySegments()) {\n if (index < keySegment.length) {\n return keySegment[index];\n } else {\n index -= keySegment.length;\n }\n }\n return;\n }\n\n get length(): number {\n return this.keySegments().flat().length;\n }\n\n compileInstructions(\n instructions: Array,\n ): Array {\n // Bail early if any account indexes would overflow a u8\n const U8_MAX = 255;\n if (this.length > U8_MAX + 1) {\n throw new Error('Account index overflow encountered during compilation');\n }\n\n const keyIndexMap = new Map();\n this.keySegments()\n .flat()\n .forEach((key, index) => {\n keyIndexMap.set(key.toBase58(), index);\n });\n\n const findKeyIndex = (key: PublicKey) => {\n const keyIndex = keyIndexMap.get(key.toBase58());\n if (keyIndex === undefined)\n throw new Error(\n 'Encountered an unknown instruction account key during compilation',\n );\n return keyIndex;\n };\n\n return instructions.map((instruction): MessageCompiledInstruction => {\n return {\n programIdIndex: findKeyIndex(instruction.programId),\n accountKeyIndexes: instruction.keys.map(meta =>\n findKeyIndex(meta.pubkey),\n ),\n data: instruction.data,\n };\n });\n }\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {VoteAuthorizeWithSeedArgs} from './programs/vote';\n\n/**\n * Layout for a public key\n */\nexport const publicKey = (property: string = 'publicKey') => {\n return BufferLayout.blob(32, property);\n};\n\n/**\n * Layout for a signature\n */\nexport const signature = (property: string = 'signature') => {\n return BufferLayout.blob(64, property);\n};\n\n/**\n * Layout for a 64bit unsigned value\n */\nexport const uint64 = (property: string = 'uint64') => {\n return BufferLayout.blob(8, property);\n};\n\ninterface IRustStringShim\n extends Omit<\n BufferLayout.Structure<\n Readonly<{\n length: number;\n lengthPadding: number;\n chars: Uint8Array;\n }>\n >,\n 'decode' | 'encode' | 'replicate'\n > {\n alloc: (str: string) => number;\n decode: (b: Uint8Array, offset?: number) => string;\n encode: (str: string, b: Uint8Array, offset?: number) => number;\n replicate: (property: string) => this;\n}\n\n/**\n * Layout for a Rust String type\n */\nexport const rustString = (\n property: string = 'string',\n): BufferLayout.Layout => {\n const rsl = BufferLayout.struct<\n Readonly<{\n length?: number;\n lengthPadding?: number;\n chars: Uint8Array;\n }>\n >(\n [\n BufferLayout.u32('length'),\n BufferLayout.u32('lengthPadding'),\n BufferLayout.blob(BufferLayout.offset(BufferLayout.u32(), -8), 'chars'),\n ],\n property,\n );\n const _decode = rsl.decode.bind(rsl);\n const _encode = rsl.encode.bind(rsl);\n\n const rslShim = rsl as unknown as IRustStringShim;\n\n rslShim.decode = (b: Uint8Array, offset?: number) => {\n const data = _decode(b, offset);\n return data['chars'].toString();\n };\n\n rslShim.encode = (str: string, b: Uint8Array, offset?: number) => {\n const data = {\n chars: Buffer.from(str, 'utf8'),\n };\n return _encode(data, b, offset);\n };\n\n rslShim.alloc = (str: string) => {\n return (\n BufferLayout.u32().span +\n BufferLayout.u32().span +\n Buffer.from(str, 'utf8').length\n );\n };\n\n return rslShim;\n};\n\n/**\n * Layout for an Authorized object\n */\nexport const authorized = (property: string = 'authorized') => {\n return BufferLayout.struct<\n Readonly<{\n staker: Uint8Array;\n withdrawer: Uint8Array;\n }>\n >([publicKey('staker'), publicKey('withdrawer')], property);\n};\n\n/**\n * Layout for a Lockup object\n */\nexport const lockup = (property: string = 'lockup') => {\n return BufferLayout.struct<\n Readonly<{\n custodian: Uint8Array;\n epoch: number;\n unixTimestamp: number;\n }>\n >(\n [\n BufferLayout.ns64('unixTimestamp'),\n BufferLayout.ns64('epoch'),\n publicKey('custodian'),\n ],\n property,\n );\n};\n\n/**\n * Layout for a VoteInit object\n */\nexport const voteInit = (property: string = 'voteInit') => {\n return BufferLayout.struct<\n Readonly<{\n authorizedVoter: Uint8Array;\n authorizedWithdrawer: Uint8Array;\n commission: number;\n nodePubkey: Uint8Array;\n }>\n >(\n [\n publicKey('nodePubkey'),\n publicKey('authorizedVoter'),\n publicKey('authorizedWithdrawer'),\n BufferLayout.u8('commission'),\n ],\n property,\n );\n};\n\n/**\n * Layout for a VoteAuthorizeWithSeedArgs object\n */\nexport const voteAuthorizeWithSeedArgs = (\n property: string = 'voteAuthorizeWithSeedArgs',\n) => {\n return BufferLayout.struct(\n [\n BufferLayout.u32('voteAuthorizationType'),\n publicKey('currentAuthorityDerivedKeyOwnerPubkey'),\n rustString('currentAuthorityDerivedKeySeed'),\n publicKey('newAuthorized'),\n ],\n property,\n );\n};\n\nexport function getAlloc(type: any, fields: any): number {\n const getItemAlloc = (item: any): number => {\n if (item.span >= 0) {\n return item.span;\n } else if (typeof item.alloc === 'function') {\n return item.alloc(fields[item.property]);\n } else if ('count' in item && 'elementLayout' in item) {\n const field = fields[item.property];\n if (Array.isArray(field)) {\n return field.length * getItemAlloc(item.elementLayout);\n }\n } else if ('fields' in item) {\n // This is a `Structure` whose size needs to be recursively measured.\n return getAlloc({layout: item}, fields[item.property]);\n }\n // Couldn't determine allocated size of layout\n return 0;\n };\n\n let alloc = 0;\n type.layout.fields.forEach((item: any) => {\n alloc += getItemAlloc(item);\n });\n\n return alloc;\n}\n","export function decodeLength(bytes: Array): number {\n let len = 0;\n let size = 0;\n for (;;) {\n let elem = bytes.shift() as number;\n len |= (elem & 0x7f) << (size * 7);\n size += 1;\n if ((elem & 0x80) === 0) {\n break;\n }\n }\n return len;\n}\n\nexport function encodeLength(bytes: Array, len: number) {\n let rem_len = len;\n for (;;) {\n let elem = rem_len & 0x7f;\n rem_len >>= 7;\n if (rem_len == 0) {\n bytes.push(elem);\n break;\n } else {\n elem |= 0x80;\n bytes.push(elem);\n }\n }\n}\n","export default function (\n condition: unknown,\n message?: string,\n): asserts condition {\n if (!condition) {\n throw new Error(message || 'Assertion failed');\n }\n}\n","import {MessageHeader, MessageAddressTableLookup} from './index';\nimport {AccountKeysFromLookups} from './account-keys';\nimport {AddressLookupTableAccount} from '../programs';\nimport {TransactionInstruction} from '../transaction';\nimport assert from '../utils/assert';\nimport {PublicKey} from '../publickey';\n\nexport type CompiledKeyMeta = {\n isSigner: boolean;\n isWritable: boolean;\n isInvoked: boolean;\n};\n\ntype KeyMetaMap = Map;\n\nexport class CompiledKeys {\n payer: PublicKey;\n keyMetaMap: KeyMetaMap;\n\n constructor(payer: PublicKey, keyMetaMap: KeyMetaMap) {\n this.payer = payer;\n this.keyMetaMap = keyMetaMap;\n }\n\n static compile(\n instructions: Array,\n payer: PublicKey,\n ): CompiledKeys {\n const keyMetaMap: KeyMetaMap = new Map();\n const getOrInsertDefault = (pubkey: PublicKey): CompiledKeyMeta => {\n const address = pubkey.toBase58();\n let keyMeta = keyMetaMap.get(address);\n if (keyMeta === undefined) {\n keyMeta = {\n isSigner: false,\n isWritable: false,\n isInvoked: false,\n };\n keyMetaMap.set(address, keyMeta);\n }\n return keyMeta;\n };\n\n const payerKeyMeta = getOrInsertDefault(payer);\n payerKeyMeta.isSigner = true;\n payerKeyMeta.isWritable = true;\n\n for (const ix of instructions) {\n getOrInsertDefault(ix.programId).isInvoked = true;\n for (const accountMeta of ix.keys) {\n const keyMeta = getOrInsertDefault(accountMeta.pubkey);\n keyMeta.isSigner ||= accountMeta.isSigner;\n keyMeta.isWritable ||= accountMeta.isWritable;\n }\n }\n\n return new CompiledKeys(payer, keyMetaMap);\n }\n\n getMessageComponents(): [MessageHeader, Array] {\n const mapEntries = [...this.keyMetaMap.entries()];\n assert(mapEntries.length <= 256, 'Max static account keys length exceeded');\n\n const writableSigners = mapEntries.filter(\n ([, meta]) => meta.isSigner && meta.isWritable,\n );\n const readonlySigners = mapEntries.filter(\n ([, meta]) => meta.isSigner && !meta.isWritable,\n );\n const writableNonSigners = mapEntries.filter(\n ([, meta]) => !meta.isSigner && meta.isWritable,\n );\n const readonlyNonSigners = mapEntries.filter(\n ([, meta]) => !meta.isSigner && !meta.isWritable,\n );\n\n const header: MessageHeader = {\n numRequiredSignatures: writableSigners.length + readonlySigners.length,\n numReadonlySignedAccounts: readonlySigners.length,\n numReadonlyUnsignedAccounts: readonlyNonSigners.length,\n };\n\n // sanity checks\n {\n assert(\n writableSigners.length > 0,\n 'Expected at least one writable signer key',\n );\n const [payerAddress] = writableSigners[0];\n assert(\n payerAddress === this.payer.toBase58(),\n 'Expected first writable signer key to be the fee payer',\n );\n }\n\n const staticAccountKeys = [\n ...writableSigners.map(([address]) => new PublicKey(address)),\n ...readonlySigners.map(([address]) => new PublicKey(address)),\n ...writableNonSigners.map(([address]) => new PublicKey(address)),\n ...readonlyNonSigners.map(([address]) => new PublicKey(address)),\n ];\n\n return [header, staticAccountKeys];\n }\n\n extractTableLookup(\n lookupTable: AddressLookupTableAccount,\n ): [MessageAddressTableLookup, AccountKeysFromLookups] | undefined {\n const [writableIndexes, drainedWritableKeys] =\n this.drainKeysFoundInLookupTable(\n lookupTable.state.addresses,\n keyMeta =>\n !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable,\n );\n const [readonlyIndexes, drainedReadonlyKeys] =\n this.drainKeysFoundInLookupTable(\n lookupTable.state.addresses,\n keyMeta =>\n !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable,\n );\n\n // Don't extract lookup if no keys were found\n if (writableIndexes.length === 0 && readonlyIndexes.length === 0) {\n return;\n }\n\n return [\n {\n accountKey: lookupTable.key,\n writableIndexes,\n readonlyIndexes,\n },\n {\n writable: drainedWritableKeys,\n readonly: drainedReadonlyKeys,\n },\n ];\n }\n\n /** @internal */\n private drainKeysFoundInLookupTable(\n lookupTableEntries: Array,\n keyMetaFilter: (keyMeta: CompiledKeyMeta) => boolean,\n ): [Array, Array] {\n const lookupTableIndexes = new Array();\n const drainedKeys = new Array();\n\n for (const [address, keyMeta] of this.keyMetaMap.entries()) {\n if (keyMetaFilter(keyMeta)) {\n const key = new PublicKey(address);\n const lookupTableIndex = lookupTableEntries.findIndex(entry =>\n entry.equals(key),\n );\n if (lookupTableIndex >= 0) {\n assert(lookupTableIndex < 256, 'Max lookup table index exceeded');\n lookupTableIndexes.push(lookupTableIndex);\n drainedKeys.push(key);\n this.keyMetaMap.delete(address);\n }\n }\n }\n\n return [lookupTableIndexes, drainedKeys];\n }\n}\n","import bs58 from 'bs58';\nimport {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {PublicKey, PUBLIC_KEY_LENGTH} from '../publickey';\nimport type {Blockhash} from '../blockhash';\nimport * as Layout from '../layout';\nimport {PACKET_DATA_SIZE, VERSION_PREFIX_MASK} from '../transaction/constants';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport {toBuffer} from '../utils/to-buffer';\nimport {\n MessageHeader,\n MessageAddressTableLookup,\n MessageCompiledInstruction,\n} from './index';\nimport {TransactionInstruction} from '../transaction';\nimport {CompiledKeys} from './compiled-keys';\nimport {MessageAccountKeys} from './account-keys';\n\n/**\n * An instruction to execute by a program\n *\n * @property {number} programIdIndex\n * @property {number[]} accounts\n * @property {string} data\n */\nexport type CompiledInstruction = {\n /** Index into the transaction keys array indicating the program account that executes this instruction */\n programIdIndex: number;\n /** Ordered indices into the transaction keys array indicating which accounts to pass to the program */\n accounts: number[];\n /** The program input data encoded as base 58 */\n data: string;\n};\n\n/**\n * Message constructor arguments\n */\nexport type MessageArgs = {\n /** The message header, identifying signed and read-only `accountKeys` */\n header: MessageHeader;\n /** All the account keys used by this transaction */\n accountKeys: string[] | PublicKey[];\n /** The hash of a recent ledger block */\n recentBlockhash: Blockhash;\n /** Instructions that will be executed in sequence and committed in one atomic transaction if all succeed. */\n instructions: CompiledInstruction[];\n};\n\nexport type CompileLegacyArgs = {\n payerKey: PublicKey;\n instructions: Array;\n recentBlockhash: Blockhash;\n};\n\n/**\n * List of instructions to be processed atomically\n */\nexport class Message {\n header: MessageHeader;\n accountKeys: PublicKey[];\n recentBlockhash: Blockhash;\n instructions: CompiledInstruction[];\n\n private indexToProgramIds: Map = new Map<\n number,\n PublicKey\n >();\n\n constructor(args: MessageArgs) {\n this.header = args.header;\n this.accountKeys = args.accountKeys.map(account => new PublicKey(account));\n this.recentBlockhash = args.recentBlockhash;\n this.instructions = args.instructions;\n this.instructions.forEach(ix =>\n this.indexToProgramIds.set(\n ix.programIdIndex,\n this.accountKeys[ix.programIdIndex],\n ),\n );\n }\n\n get version(): 'legacy' {\n return 'legacy';\n }\n\n get staticAccountKeys(): Array {\n return this.accountKeys;\n }\n\n get compiledInstructions(): Array {\n return this.instructions.map(\n (ix): MessageCompiledInstruction => ({\n programIdIndex: ix.programIdIndex,\n accountKeyIndexes: ix.accounts,\n data: bs58.decode(ix.data),\n }),\n );\n }\n\n get addressTableLookups(): Array {\n return [];\n }\n\n getAccountKeys(): MessageAccountKeys {\n return new MessageAccountKeys(this.staticAccountKeys);\n }\n\n static compile(args: CompileLegacyArgs): Message {\n const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);\n const [header, staticAccountKeys] = compiledKeys.getMessageComponents();\n const accountKeys = new MessageAccountKeys(staticAccountKeys);\n const instructions = accountKeys.compileInstructions(args.instructions).map(\n (ix: MessageCompiledInstruction): CompiledInstruction => ({\n programIdIndex: ix.programIdIndex,\n accounts: ix.accountKeyIndexes,\n data: bs58.encode(ix.data),\n }),\n );\n return new Message({\n header,\n accountKeys: staticAccountKeys,\n recentBlockhash: args.recentBlockhash,\n instructions,\n });\n }\n\n isAccountSigner(index: number): boolean {\n return index < this.header.numRequiredSignatures;\n }\n\n isAccountWritable(index: number): boolean {\n const numSignedAccounts = this.header.numRequiredSignatures;\n if (index >= this.header.numRequiredSignatures) {\n const unsignedAccountIndex = index - numSignedAccounts;\n const numUnsignedAccounts = this.accountKeys.length - numSignedAccounts;\n const numWritableUnsignedAccounts =\n numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts;\n return unsignedAccountIndex < numWritableUnsignedAccounts;\n } else {\n const numWritableSignedAccounts =\n numSignedAccounts - this.header.numReadonlySignedAccounts;\n return index < numWritableSignedAccounts;\n }\n }\n\n isProgramId(index: number): boolean {\n return this.indexToProgramIds.has(index);\n }\n\n programIds(): PublicKey[] {\n return [...this.indexToProgramIds.values()];\n }\n\n nonProgramIds(): PublicKey[] {\n return this.accountKeys.filter((_, index) => !this.isProgramId(index));\n }\n\n serialize(): Buffer {\n const numKeys = this.accountKeys.length;\n\n let keyCount: number[] = [];\n shortvec.encodeLength(keyCount, numKeys);\n\n const instructions = this.instructions.map(instruction => {\n const {accounts, programIdIndex} = instruction;\n const data = Array.from(bs58.decode(instruction.data));\n\n let keyIndicesCount: number[] = [];\n shortvec.encodeLength(keyIndicesCount, accounts.length);\n\n let dataCount: number[] = [];\n shortvec.encodeLength(dataCount, data.length);\n\n return {\n programIdIndex,\n keyIndicesCount: Buffer.from(keyIndicesCount),\n keyIndices: accounts,\n dataLength: Buffer.from(dataCount),\n data,\n };\n });\n\n let instructionCount: number[] = [];\n shortvec.encodeLength(instructionCount, instructions.length);\n let instructionBuffer = Buffer.alloc(PACKET_DATA_SIZE);\n Buffer.from(instructionCount).copy(instructionBuffer);\n let instructionBufferLength = instructionCount.length;\n\n instructions.forEach(instruction => {\n const instructionLayout = BufferLayout.struct<\n Readonly<{\n data: number[];\n dataLength: Uint8Array;\n keyIndices: number[];\n keyIndicesCount: Uint8Array;\n programIdIndex: number;\n }>\n >([\n BufferLayout.u8('programIdIndex'),\n\n BufferLayout.blob(\n instruction.keyIndicesCount.length,\n 'keyIndicesCount',\n ),\n BufferLayout.seq(\n BufferLayout.u8('keyIndex'),\n instruction.keyIndices.length,\n 'keyIndices',\n ),\n BufferLayout.blob(instruction.dataLength.length, 'dataLength'),\n BufferLayout.seq(\n BufferLayout.u8('userdatum'),\n instruction.data.length,\n 'data',\n ),\n ]);\n const length = instructionLayout.encode(\n instruction,\n instructionBuffer,\n instructionBufferLength,\n );\n instructionBufferLength += length;\n });\n instructionBuffer = instructionBuffer.slice(0, instructionBufferLength);\n\n const signDataLayout = BufferLayout.struct<\n Readonly<{\n keyCount: Uint8Array;\n keys: Uint8Array[];\n numReadonlySignedAccounts: Uint8Array;\n numReadonlyUnsignedAccounts: Uint8Array;\n numRequiredSignatures: Uint8Array;\n recentBlockhash: Uint8Array;\n }>\n >([\n BufferLayout.blob(1, 'numRequiredSignatures'),\n BufferLayout.blob(1, 'numReadonlySignedAccounts'),\n BufferLayout.blob(1, 'numReadonlyUnsignedAccounts'),\n BufferLayout.blob(keyCount.length, 'keyCount'),\n BufferLayout.seq(Layout.publicKey('key'), numKeys, 'keys'),\n Layout.publicKey('recentBlockhash'),\n ]);\n\n const transaction = {\n numRequiredSignatures: Buffer.from([this.header.numRequiredSignatures]),\n numReadonlySignedAccounts: Buffer.from([\n this.header.numReadonlySignedAccounts,\n ]),\n numReadonlyUnsignedAccounts: Buffer.from([\n this.header.numReadonlyUnsignedAccounts,\n ]),\n keyCount: Buffer.from(keyCount),\n keys: this.accountKeys.map(key => toBuffer(key.toBytes())),\n recentBlockhash: bs58.decode(this.recentBlockhash),\n };\n\n let signData = Buffer.alloc(2048);\n const length = signDataLayout.encode(transaction, signData);\n instructionBuffer.copy(signData, length);\n return signData.slice(0, length + instructionBuffer.length);\n }\n\n /**\n * Decode a compiled message into a Message object.\n */\n static from(buffer: Buffer | Uint8Array | Array): Message {\n // Slice up wire data\n let byteArray = [...buffer];\n\n const numRequiredSignatures = byteArray.shift()!;\n if (\n numRequiredSignatures !==\n (numRequiredSignatures & VERSION_PREFIX_MASK)\n ) {\n throw new Error(\n 'Versioned messages must be deserialized with VersionedMessage.deserialize()',\n );\n }\n\n const numReadonlySignedAccounts = byteArray.shift()!;\n const numReadonlyUnsignedAccounts = byteArray.shift()!;\n\n const accountCount = shortvec.decodeLength(byteArray);\n let accountKeys = [];\n for (let i = 0; i < accountCount; i++) {\n const account = byteArray.slice(0, PUBLIC_KEY_LENGTH);\n byteArray = byteArray.slice(PUBLIC_KEY_LENGTH);\n accountKeys.push(new PublicKey(Buffer.from(account)));\n }\n\n const recentBlockhash = byteArray.slice(0, PUBLIC_KEY_LENGTH);\n byteArray = byteArray.slice(PUBLIC_KEY_LENGTH);\n\n const instructionCount = shortvec.decodeLength(byteArray);\n let instructions: CompiledInstruction[] = [];\n for (let i = 0; i < instructionCount; i++) {\n const programIdIndex = byteArray.shift()!;\n const accountCount = shortvec.decodeLength(byteArray);\n const accounts = byteArray.slice(0, accountCount);\n byteArray = byteArray.slice(accountCount);\n const dataLength = shortvec.decodeLength(byteArray);\n const dataSlice = byteArray.slice(0, dataLength);\n const data = bs58.encode(Buffer.from(dataSlice));\n byteArray = byteArray.slice(dataLength);\n instructions.push({\n programIdIndex,\n accounts,\n data,\n });\n }\n\n const messageArgs = {\n header: {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts,\n },\n recentBlockhash: bs58.encode(Buffer.from(recentBlockhash)),\n accountKeys,\n instructions,\n };\n\n return new Message(messageArgs);\n }\n}\n","import bs58 from 'bs58';\nimport {Buffer} from 'buffer';\n\nimport {PACKET_DATA_SIZE, SIGNATURE_LENGTH_IN_BYTES} from './constants';\nimport {Connection} from '../connection';\nimport {Message} from '../message';\nimport {PublicKey} from '../publickey';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport {toBuffer} from '../utils/to-buffer';\nimport invariant from '../utils/assert';\nimport type {Signer} from '../keypair';\nimport type {Blockhash} from '../blockhash';\nimport type {CompiledInstruction} from '../message';\nimport {sign, verify} from '../utils/ed25519';\n\n/**\n * Transaction signature as base-58 encoded string\n */\nexport type TransactionSignature = string;\n\nexport const enum TransactionStatus {\n BLOCKHEIGHT_EXCEEDED,\n PROCESSED,\n TIMED_OUT,\n NONCE_INVALID,\n}\n\n/**\n * Default (empty) signature\n */\nconst DEFAULT_SIGNATURE = Buffer.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0);\n\n/**\n * Account metadata used to define instructions\n */\nexport type AccountMeta = {\n /** An account's public key */\n pubkey: PublicKey;\n /** True if an instruction requires a transaction signature matching `pubkey` */\n isSigner: boolean;\n /** True if the `pubkey` can be loaded as a read-write account. */\n isWritable: boolean;\n};\n\n/**\n * List of TransactionInstruction object fields that may be initialized at construction\n */\nexport type TransactionInstructionCtorFields = {\n keys: Array;\n programId: PublicKey;\n data?: Buffer;\n};\n\n/**\n * Configuration object for Transaction.serialize()\n */\nexport type SerializeConfig = {\n /** Require all transaction signatures be present (default: true) */\n requireAllSignatures?: boolean;\n /** Verify provided signatures (default: true) */\n verifySignatures?: boolean;\n};\n\n/**\n * @internal\n */\nexport interface TransactionInstructionJSON {\n keys: {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n }[];\n programId: string;\n data: number[];\n}\n\n/**\n * Transaction Instruction class\n */\nexport class TransactionInstruction {\n /**\n * Public keys to include in this transaction\n * Boolean represents whether this pubkey needs to sign the transaction\n */\n keys: Array;\n\n /**\n * Program Id to execute\n */\n programId: PublicKey;\n\n /**\n * Program input\n */\n data: Buffer = Buffer.alloc(0);\n\n constructor(opts: TransactionInstructionCtorFields) {\n this.programId = opts.programId;\n this.keys = opts.keys;\n if (opts.data) {\n this.data = opts.data;\n }\n }\n\n /**\n * @internal\n */\n toJSON(): TransactionInstructionJSON {\n return {\n keys: this.keys.map(({pubkey, isSigner, isWritable}) => ({\n pubkey: pubkey.toJSON(),\n isSigner,\n isWritable,\n })),\n programId: this.programId.toJSON(),\n data: [...this.data],\n };\n }\n}\n\n/**\n * Pair of signature and corresponding public key\n */\nexport type SignaturePubkeyPair = {\n signature: Buffer | null;\n publicKey: PublicKey;\n};\n\n/**\n * List of Transaction object fields that may be initialized at construction\n */\nexport type TransactionCtorFields_DEPRECATED = {\n /** Optional nonce information used for offline nonce'd transactions */\n nonceInfo?: NonceInformation | null;\n /** The transaction fee payer */\n feePayer?: PublicKey | null;\n /** One or more signatures */\n signatures?: Array;\n /** A recent blockhash */\n recentBlockhash?: Blockhash;\n};\n\n// For backward compatibility; an unfortunate consequence of being\n// forced to over-export types by the documentation generator.\n// See https://github.com/solana-labs/solana/pull/25820\nexport type TransactionCtorFields = TransactionCtorFields_DEPRECATED;\n\n/**\n * Blockhash-based transactions have a lifetime that are defined by\n * the blockhash they include. Any transaction whose blockhash is\n * too old will be rejected.\n */\nexport type TransactionBlockhashCtor = {\n /** The transaction fee payer */\n feePayer?: PublicKey | null;\n /** One or more signatures */\n signatures?: Array;\n /** A recent blockhash */\n blockhash: Blockhash;\n /** the last block chain can advance to before tx is declared expired */\n lastValidBlockHeight: number;\n};\n\n/**\n * Use these options to construct a durable nonce transaction.\n */\nexport type TransactionNonceCtor = {\n /** The transaction fee payer */\n feePayer?: PublicKey | null;\n minContextSlot: number;\n nonceInfo: NonceInformation;\n /** One or more signatures */\n signatures?: Array;\n};\n\n/**\n * Nonce information to be used to build an offline Transaction.\n */\nexport type NonceInformation = {\n /** The current blockhash stored in the nonce */\n nonce: Blockhash;\n /** AdvanceNonceAccount Instruction */\n nonceInstruction: TransactionInstruction;\n};\n\n/**\n * @internal\n */\nexport interface TransactionJSON {\n recentBlockhash: string | null;\n feePayer: string | null;\n nonceInfo: {\n nonce: string;\n nonceInstruction: TransactionInstructionJSON;\n } | null;\n instructions: TransactionInstructionJSON[];\n signers: string[];\n}\n\n/**\n * Transaction class\n */\nexport class Transaction {\n /**\n * Signatures for the transaction. Typically created by invoking the\n * `sign()` method\n */\n signatures: Array = [];\n\n /**\n * The first (payer) Transaction signature\n */\n get signature(): Buffer | null {\n if (this.signatures.length > 0) {\n return this.signatures[0].signature;\n }\n return null;\n }\n\n /**\n * The transaction fee payer\n */\n feePayer?: PublicKey;\n\n /**\n * The instructions to atomically execute\n */\n instructions: Array = [];\n\n /**\n * A recent transaction id. Must be populated by the caller\n */\n recentBlockhash?: Blockhash;\n\n /**\n * the last block chain can advance to before tx is declared expired\n * */\n lastValidBlockHeight?: number;\n\n /**\n * Optional Nonce information. If populated, transaction will use a durable\n * Nonce hash instead of a recentBlockhash. Must be populated by the caller\n */\n nonceInfo?: NonceInformation;\n\n /**\n * If this is a nonce transaction this represents the minimum slot from which\n * to evaluate if the nonce has advanced when attempting to confirm the\n * transaction. This protects against a case where the transaction confirmation\n * logic loads the nonce account from an old slot and assumes the mismatch in\n * nonce value implies that the nonce has been advanced.\n */\n minNonceContextSlot?: number;\n\n /**\n * @internal\n */\n _message?: Message;\n\n /**\n * @internal\n */\n _json?: TransactionJSON;\n\n // Construct a transaction with a blockhash and lastValidBlockHeight\n constructor(opts?: TransactionBlockhashCtor);\n\n // Construct a transaction using a durable nonce\n constructor(opts?: TransactionNonceCtor);\n\n /**\n * @deprecated `TransactionCtorFields` has been deprecated and will be removed in a future version.\n * Please supply a `TransactionBlockhashCtor` instead.\n */\n constructor(opts?: TransactionCtorFields_DEPRECATED);\n\n /**\n * Construct an empty Transaction\n */\n constructor(\n opts?:\n | TransactionBlockhashCtor\n | TransactionNonceCtor\n | TransactionCtorFields_DEPRECATED,\n ) {\n if (!opts) {\n return;\n }\n if (opts.feePayer) {\n this.feePayer = opts.feePayer;\n }\n if (opts.signatures) {\n this.signatures = opts.signatures;\n }\n if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) {\n const {minContextSlot, nonceInfo} = opts as TransactionNonceCtor;\n this.minNonceContextSlot = minContextSlot;\n this.nonceInfo = nonceInfo;\n } else if (\n Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')\n ) {\n const {blockhash, lastValidBlockHeight} =\n opts as TransactionBlockhashCtor;\n this.recentBlockhash = blockhash;\n this.lastValidBlockHeight = lastValidBlockHeight;\n } else {\n const {recentBlockhash, nonceInfo} =\n opts as TransactionCtorFields_DEPRECATED;\n if (nonceInfo) {\n this.nonceInfo = nonceInfo;\n }\n this.recentBlockhash = recentBlockhash;\n }\n }\n\n /**\n * @internal\n */\n toJSON(): TransactionJSON {\n return {\n recentBlockhash: this.recentBlockhash || null,\n feePayer: this.feePayer ? this.feePayer.toJSON() : null,\n nonceInfo: this.nonceInfo\n ? {\n nonce: this.nonceInfo.nonce,\n nonceInstruction: this.nonceInfo.nonceInstruction.toJSON(),\n }\n : null,\n instructions: this.instructions.map(instruction => instruction.toJSON()),\n signers: this.signatures.map(({publicKey}) => {\n return publicKey.toJSON();\n }),\n };\n }\n\n /**\n * Add one or more instructions to this Transaction\n */\n add(\n ...items: Array<\n Transaction | TransactionInstruction | TransactionInstructionCtorFields\n >\n ): Transaction {\n if (items.length === 0) {\n throw new Error('No instructions');\n }\n\n items.forEach((item: any) => {\n if ('instructions' in item) {\n this.instructions = this.instructions.concat(item.instructions);\n } else if ('data' in item && 'programId' in item && 'keys' in item) {\n this.instructions.push(item);\n } else {\n this.instructions.push(new TransactionInstruction(item));\n }\n });\n return this;\n }\n\n /**\n * Compile transaction data\n */\n compileMessage(): Message {\n if (\n this._message &&\n JSON.stringify(this.toJSON()) === JSON.stringify(this._json)\n ) {\n return this._message;\n }\n\n let recentBlockhash;\n let instructions: TransactionInstruction[];\n if (this.nonceInfo) {\n recentBlockhash = this.nonceInfo.nonce;\n if (this.instructions[0] != this.nonceInfo.nonceInstruction) {\n instructions = [this.nonceInfo.nonceInstruction, ...this.instructions];\n } else {\n instructions = this.instructions;\n }\n } else {\n recentBlockhash = this.recentBlockhash;\n instructions = this.instructions;\n }\n if (!recentBlockhash) {\n throw new Error('Transaction recentBlockhash required');\n }\n\n if (instructions.length < 1) {\n console.warn('No instructions provided');\n }\n\n let feePayer: PublicKey;\n if (this.feePayer) {\n feePayer = this.feePayer;\n } else if (this.signatures.length > 0 && this.signatures[0].publicKey) {\n // Use implicit fee payer\n feePayer = this.signatures[0].publicKey;\n } else {\n throw new Error('Transaction fee payer required');\n }\n\n for (let i = 0; i < instructions.length; i++) {\n if (instructions[i].programId === undefined) {\n throw new Error(\n `Transaction instruction index ${i} has undefined program id`,\n );\n }\n }\n\n const programIds: string[] = [];\n const accountMetas: AccountMeta[] = [];\n instructions.forEach(instruction => {\n instruction.keys.forEach(accountMeta => {\n accountMetas.push({...accountMeta});\n });\n\n const programId = instruction.programId.toString();\n if (!programIds.includes(programId)) {\n programIds.push(programId);\n }\n });\n\n // Append programID account metas\n programIds.forEach(programId => {\n accountMetas.push({\n pubkey: new PublicKey(programId),\n isSigner: false,\n isWritable: false,\n });\n });\n\n // Cull duplicate account metas\n const uniqueMetas: AccountMeta[] = [];\n accountMetas.forEach(accountMeta => {\n const pubkeyString = accountMeta.pubkey.toString();\n const uniqueIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.toString() === pubkeyString;\n });\n if (uniqueIndex > -1) {\n uniqueMetas[uniqueIndex].isWritable =\n uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable;\n uniqueMetas[uniqueIndex].isSigner =\n uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner;\n } else {\n uniqueMetas.push(accountMeta);\n }\n });\n\n // Sort. Prioritizing first by signer, then by writable\n uniqueMetas.sort(function (x, y) {\n if (x.isSigner !== y.isSigner) {\n // Signers always come before non-signers\n return x.isSigner ? -1 : 1;\n }\n if (x.isWritable !== y.isWritable) {\n // Writable accounts always come before read-only accounts\n return x.isWritable ? -1 : 1;\n }\n // Otherwise, sort by pubkey, stringwise.\n const options = {\n localeMatcher: 'best fit',\n usage: 'sort',\n sensitivity: 'variant',\n ignorePunctuation: false,\n numeric: false,\n caseFirst: 'lower',\n };\n return x.pubkey\n .toBase58()\n .localeCompare(y.pubkey.toBase58(), 'en', options);\n });\n\n // Move fee payer to the front\n const feePayerIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.equals(feePayer);\n });\n if (feePayerIndex > -1) {\n const [payerMeta] = uniqueMetas.splice(feePayerIndex, 1);\n payerMeta.isSigner = true;\n payerMeta.isWritable = true;\n uniqueMetas.unshift(payerMeta);\n } else {\n uniqueMetas.unshift({\n pubkey: feePayer,\n isSigner: true,\n isWritable: true,\n });\n }\n\n // Disallow unknown signers\n for (const signature of this.signatures) {\n const uniqueIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.equals(signature.publicKey);\n });\n if (uniqueIndex > -1) {\n if (!uniqueMetas[uniqueIndex].isSigner) {\n uniqueMetas[uniqueIndex].isSigner = true;\n console.warn(\n 'Transaction references a signature that is unnecessary, ' +\n 'only the fee payer and instruction signer accounts should sign a transaction. ' +\n 'This behavior is deprecated and will throw an error in the next major version release.',\n );\n }\n } else {\n throw new Error(`unknown signer: ${signature.publicKey.toString()}`);\n }\n }\n\n let numRequiredSignatures = 0;\n let numReadonlySignedAccounts = 0;\n let numReadonlyUnsignedAccounts = 0;\n\n // Split out signing from non-signing keys and count header values\n const signedKeys: string[] = [];\n const unsignedKeys: string[] = [];\n uniqueMetas.forEach(({pubkey, isSigner, isWritable}) => {\n if (isSigner) {\n signedKeys.push(pubkey.toString());\n numRequiredSignatures += 1;\n if (!isWritable) {\n numReadonlySignedAccounts += 1;\n }\n } else {\n unsignedKeys.push(pubkey.toString());\n if (!isWritable) {\n numReadonlyUnsignedAccounts += 1;\n }\n }\n });\n\n const accountKeys = signedKeys.concat(unsignedKeys);\n const compiledInstructions: CompiledInstruction[] = instructions.map(\n instruction => {\n const {data, programId} = instruction;\n return {\n programIdIndex: accountKeys.indexOf(programId.toString()),\n accounts: instruction.keys.map(meta =>\n accountKeys.indexOf(meta.pubkey.toString()),\n ),\n data: bs58.encode(data),\n };\n },\n );\n\n compiledInstructions.forEach(instruction => {\n invariant(instruction.programIdIndex >= 0);\n instruction.accounts.forEach(keyIndex => invariant(keyIndex >= 0));\n });\n\n return new Message({\n header: {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts,\n },\n accountKeys,\n recentBlockhash,\n instructions: compiledInstructions,\n });\n }\n\n /**\n * @internal\n */\n _compile(): Message {\n const message = this.compileMessage();\n const signedKeys = message.accountKeys.slice(\n 0,\n message.header.numRequiredSignatures,\n );\n\n if (this.signatures.length === signedKeys.length) {\n const valid = this.signatures.every((pair, index) => {\n return signedKeys[index].equals(pair.publicKey);\n });\n\n if (valid) return message;\n }\n\n this.signatures = signedKeys.map(publicKey => ({\n signature: null,\n publicKey,\n }));\n\n return message;\n }\n\n /**\n * Get a buffer of the Transaction data that need to be covered by signatures\n */\n serializeMessage(): Buffer {\n return this._compile().serialize();\n }\n\n /**\n * Get the estimated fee associated with a transaction\n */\n async getEstimatedFee(connection: Connection): Promise {\n return (await connection.getFeeForMessage(this.compileMessage())).value;\n }\n\n /**\n * Specify the public keys which will be used to sign the Transaction.\n * The first signer will be used as the transaction fee payer account.\n *\n * Signatures can be added with either `partialSign` or `addSignature`\n *\n * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be\n * specified and it can be set in the Transaction constructor or with the\n * `feePayer` property.\n */\n setSigners(...signers: Array) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n const seen = new Set();\n this.signatures = signers\n .filter(publicKey => {\n const key = publicKey.toString();\n if (seen.has(key)) {\n return false;\n } else {\n seen.add(key);\n return true;\n }\n })\n .map(publicKey => ({signature: null, publicKey}));\n }\n\n /**\n * Sign the Transaction with the specified signers. Multiple signatures may\n * be applied to a Transaction. The first signature is considered \"primary\"\n * and is used identify and confirm transactions.\n *\n * If the Transaction `feePayer` is not set, the first signer will be used\n * as the transaction fee payer account.\n *\n * Transaction fields should not be modified after the first call to `sign`,\n * as doing so may invalidate the signature and cause the Transaction to be\n * rejected.\n *\n * The Transaction must be assigned a valid `recentBlockhash` before invoking this method\n */\n sign(...signers: Array) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n // Dedupe signers\n const seen = new Set();\n const uniqueSigners = [];\n for (const signer of signers) {\n const key = signer.publicKey.toString();\n if (seen.has(key)) {\n continue;\n } else {\n seen.add(key);\n uniqueSigners.push(signer);\n }\n }\n\n this.signatures = uniqueSigners.map(signer => ({\n signature: null,\n publicKey: signer.publicKey,\n }));\n\n const message = this._compile();\n this._partialSign(message, ...uniqueSigners);\n }\n\n /**\n * Partially sign a transaction with the specified accounts. All accounts must\n * correspond to either the fee payer or a signer account in the transaction\n * instructions.\n *\n * All the caveats from the `sign` method apply to `partialSign`\n */\n partialSign(...signers: Array) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n // Dedupe signers\n const seen = new Set();\n const uniqueSigners = [];\n for (const signer of signers) {\n const key = signer.publicKey.toString();\n if (seen.has(key)) {\n continue;\n } else {\n seen.add(key);\n uniqueSigners.push(signer);\n }\n }\n\n const message = this._compile();\n this._partialSign(message, ...uniqueSigners);\n }\n\n /**\n * @internal\n */\n _partialSign(message: Message, ...signers: Array) {\n const signData = message.serialize();\n signers.forEach(signer => {\n const signature = sign(signData, signer.secretKey);\n this._addSignature(signer.publicKey, toBuffer(signature));\n });\n }\n\n /**\n * Add an externally created signature to a transaction. The public key\n * must correspond to either the fee payer or a signer account in the transaction\n * instructions.\n */\n addSignature(pubkey: PublicKey, signature: Buffer) {\n this._compile(); // Ensure signatures array is populated\n this._addSignature(pubkey, signature);\n }\n\n /**\n * @internal\n */\n _addSignature(pubkey: PublicKey, signature: Buffer) {\n invariant(signature.length === 64);\n\n const index = this.signatures.findIndex(sigpair =>\n pubkey.equals(sigpair.publicKey),\n );\n if (index < 0) {\n throw new Error(`unknown signer: ${pubkey.toString()}`);\n }\n\n this.signatures[index].signature = Buffer.from(signature);\n }\n\n /**\n * Verify signatures of a Transaction\n * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one.\n * If no boolean is provided, we expect a fully signed Transaction by default.\n */\n verifySignatures(requireAllSignatures?: boolean): boolean {\n return this._verifySignatures(\n this.serializeMessage(),\n requireAllSignatures === undefined ? true : requireAllSignatures,\n );\n }\n\n /**\n * @internal\n */\n _verifySignatures(\n signData: Uint8Array,\n requireAllSignatures: boolean,\n ): boolean {\n for (const {signature, publicKey} of this.signatures) {\n if (signature === null) {\n if (requireAllSignatures) {\n return false;\n }\n } else {\n if (!verify(signature, signData, publicKey.toBytes())) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Serialize the Transaction in the wire format.\n */\n serialize(config?: SerializeConfig): Buffer {\n const {requireAllSignatures, verifySignatures} = Object.assign(\n {requireAllSignatures: true, verifySignatures: true},\n config,\n );\n\n const signData = this.serializeMessage();\n if (\n verifySignatures &&\n !this._verifySignatures(signData, requireAllSignatures)\n ) {\n throw new Error('Signature verification failed');\n }\n\n return this._serialize(signData);\n }\n\n /**\n * @internal\n */\n _serialize(signData: Buffer): Buffer {\n const {signatures} = this;\n const signatureCount: number[] = [];\n shortvec.encodeLength(signatureCount, signatures.length);\n const transactionLength =\n signatureCount.length + signatures.length * 64 + signData.length;\n const wireTransaction = Buffer.alloc(transactionLength);\n invariant(signatures.length < 256);\n Buffer.from(signatureCount).copy(wireTransaction, 0);\n signatures.forEach(({signature}, index) => {\n if (signature !== null) {\n invariant(signature.length === 64, `signature has invalid length`);\n Buffer.from(signature).copy(\n wireTransaction,\n signatureCount.length + index * 64,\n );\n }\n });\n signData.copy(\n wireTransaction,\n signatureCount.length + signatures.length * 64,\n );\n invariant(\n wireTransaction.length <= PACKET_DATA_SIZE,\n `Transaction too large: ${wireTransaction.length} > ${PACKET_DATA_SIZE}`,\n );\n return wireTransaction;\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get keys(): Array {\n invariant(this.instructions.length === 1);\n return this.instructions[0].keys.map(keyObj => keyObj.pubkey);\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get programId(): PublicKey {\n invariant(this.instructions.length === 1);\n return this.instructions[0].programId;\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get data(): Buffer {\n invariant(this.instructions.length === 1);\n return this.instructions[0].data;\n }\n\n /**\n * Parse a wire transaction into a Transaction object.\n */\n static from(buffer: Buffer | Uint8Array | Array): Transaction {\n // Slice up wire data\n let byteArray = [...buffer];\n\n const signatureCount = shortvec.decodeLength(byteArray);\n let signatures = [];\n for (let i = 0; i < signatureCount; i++) {\n const signature = byteArray.slice(0, SIGNATURE_LENGTH_IN_BYTES);\n byteArray = byteArray.slice(SIGNATURE_LENGTH_IN_BYTES);\n signatures.push(bs58.encode(Buffer.from(signature)));\n }\n\n return Transaction.populate(Message.from(byteArray), signatures);\n }\n\n /**\n * Populate Transaction object from message and signatures\n */\n static populate(\n message: Message,\n signatures: Array = [],\n ): Transaction {\n const transaction = new Transaction();\n transaction.recentBlockhash = message.recentBlockhash;\n if (message.header.numRequiredSignatures > 0) {\n transaction.feePayer = message.accountKeys[0];\n }\n signatures.forEach((signature, index) => {\n const sigPubkeyPair = {\n signature:\n signature == bs58.encode(DEFAULT_SIGNATURE)\n ? null\n : bs58.decode(signature),\n publicKey: message.accountKeys[index],\n };\n transaction.signatures.push(sigPubkeyPair);\n });\n\n message.instructions.forEach(instruction => {\n const keys = instruction.accounts.map(account => {\n const pubkey = message.accountKeys[account];\n return {\n pubkey,\n isSigner:\n transaction.signatures.some(\n keyObj => keyObj.publicKey.toString() === pubkey.toString(),\n ) || message.isAccountSigner(account),\n isWritable: message.isAccountWritable(account),\n };\n });\n\n transaction.instructions.push(\n new TransactionInstruction({\n keys,\n programId: message.accountKeys[instruction.programIdIndex],\n data: bs58.decode(instruction.data),\n }),\n );\n });\n\n transaction._message = message;\n transaction._json = transaction.toJSON();\n\n return transaction;\n }\n}\n","// TODO: These constants should be removed in favor of reading them out of a\n// Syscall account\n\n/**\n * @internal\n */\nexport const NUM_TICKS_PER_SECOND = 160;\n\n/**\n * @internal\n */\nexport const DEFAULT_TICKS_PER_SLOT = 64;\n\n/**\n * @internal\n */\nexport const NUM_SLOTS_PER_SECOND =\n NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT;\n\n/**\n * @internal\n */\nexport const MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND;\n","import {PublicKey} from './publickey';\n\nexport const SYSVAR_CLOCK_PUBKEY = new PublicKey(\n 'SysvarC1ock11111111111111111111111111111111',\n);\n\nexport const SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey(\n 'SysvarEpochSchedu1e111111111111111111111111',\n);\n\nexport const SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey(\n 'Sysvar1nstructions1111111111111111111111111',\n);\n\nexport const SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey(\n 'SysvarRecentB1ockHashes11111111111111111111',\n);\n\nexport const SYSVAR_RENT_PUBKEY = new PublicKey(\n 'SysvarRent111111111111111111111111111111111',\n);\n\nexport const SYSVAR_REWARDS_PUBKEY = new PublicKey(\n 'SysvarRewards111111111111111111111111111111',\n);\n\nexport const SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey(\n 'SysvarS1otHashes111111111111111111111111111',\n);\n\nexport const SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey(\n 'SysvarS1otHistory11111111111111111111111111',\n);\n\nexport const SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey(\n 'SysvarStakeHistory1111111111111111111111111',\n);\n","import {Connection, SignatureResult} from '../connection';\nimport {Transaction} from '../transaction';\nimport type {ConfirmOptions} from '../connection';\nimport type {Signer} from '../keypair';\nimport type {TransactionSignature} from '../transaction';\n\n/**\n * Sign, send and confirm a transaction.\n *\n * If `commitment` option is not specified, defaults to 'max' commitment.\n *\n * @param {Connection} connection\n * @param {Transaction} transaction\n * @param {Array} signers\n * @param {ConfirmOptions} [options]\n * @returns {Promise}\n */\nexport async function sendAndConfirmTransaction(\n connection: Connection,\n transaction: Transaction,\n signers: Array,\n options?: ConfirmOptions &\n Readonly<{\n // A signal that, when aborted, cancels any outstanding transaction confirmation operations\n abortSignal?: AbortSignal;\n }>,\n): Promise {\n const sendOptions = options && {\n skipPreflight: options.skipPreflight,\n preflightCommitment: options.preflightCommitment || options.commitment,\n maxRetries: options.maxRetries,\n minContextSlot: options.minContextSlot,\n };\n\n const signature = await connection.sendTransaction(\n transaction,\n signers,\n sendOptions,\n );\n\n let status: SignatureResult;\n if (\n transaction.recentBlockhash != null &&\n transaction.lastValidBlockHeight != null\n ) {\n status = (\n await connection.confirmTransaction(\n {\n abortSignal: options?.abortSignal,\n signature: signature,\n blockhash: transaction.recentBlockhash,\n lastValidBlockHeight: transaction.lastValidBlockHeight,\n },\n options && options.commitment,\n )\n ).value;\n } else if (\n transaction.minNonceContextSlot != null &&\n transaction.nonceInfo != null\n ) {\n const {nonceInstruction} = transaction.nonceInfo;\n const nonceAccountPubkey = nonceInstruction.keys[0].pubkey;\n status = (\n await connection.confirmTransaction(\n {\n abortSignal: options?.abortSignal,\n minContextSlot: transaction.minNonceContextSlot,\n nonceAccountPubkey,\n nonceValue: transaction.nonceInfo.nonce,\n signature,\n },\n options && options.commitment,\n )\n ).value;\n } else {\n if (options?.abortSignal != null) {\n console.warn(\n 'sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was ' +\n 'supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` ' +\n 'or a combination of `nonceInfo` and `minNonceContextSlot` are abortable.',\n );\n }\n status = (\n await connection.confirmTransaction(\n signature,\n options && options.commitment,\n )\n ).value;\n }\n\n if (status.err) {\n throw new Error(\n `Transaction ${signature} failed (${JSON.stringify(status)})`,\n );\n }\n\n return signature;\n}\n","// zzz\nexport function sleep(ms: number): Promise {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport * as Layout from './layout';\n\nexport interface IInstructionInputData {\n readonly instruction: number;\n}\n\n/**\n * @internal\n */\nexport type InstructionType = {\n /** The Instruction index (from solana upstream program) */\n index: number;\n /** The BufferLayout to use to build data */\n layout: BufferLayout.Layout;\n};\n\n/**\n * Populate a buffer of instruction data using an InstructionType\n * @internal\n */\nexport function encodeData(\n type: InstructionType,\n fields?: any,\n): Buffer {\n const allocLength =\n type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields);\n const data = Buffer.alloc(allocLength);\n const layoutFields = Object.assign({instruction: type.index}, fields);\n type.layout.encode(layoutFields, data);\n return data;\n}\n\n/**\n * Decode instruction data buffer using an InstructionType\n * @internal\n */\nexport function decodeData(\n type: InstructionType,\n buffer: Buffer,\n): TInputData {\n let data: TInputData;\n try {\n data = type.layout.decode(buffer);\n } catch (err) {\n throw new Error('invalid instruction; ' + err);\n }\n\n if (data.instruction !== type.index) {\n throw new Error(\n `invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`,\n );\n }\n\n return data;\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\n/**\n * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11\n *\n * @internal\n */\nexport const FeeCalculatorLayout = BufferLayout.nu64('lamportsPerSignature');\n\n/**\n * Calculator for transaction fees.\n *\n * @deprecated Deprecated since Solana v1.8.0.\n */\nexport interface FeeCalculator {\n /** Cost in lamports to validate a signature. */\n lamportsPerSignature: number;\n}\n","import * as BufferLayout from '@solana/buffer-layout';\nimport {Buffer} from 'buffer';\n\nimport * as Layout from './layout';\nimport {PublicKey} from './publickey';\nimport type {FeeCalculator} from './fee-calculator';\nimport {FeeCalculatorLayout} from './fee-calculator';\nimport {toBuffer} from './utils/to-buffer';\n\n/**\n * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32\n *\n * @internal\n */\nconst NonceAccountLayout = BufferLayout.struct<\n Readonly<{\n authorizedPubkey: Uint8Array;\n feeCalculator: Readonly<{\n lamportsPerSignature: number;\n }>;\n nonce: Uint8Array;\n state: number;\n version: number;\n }>\n>([\n BufferLayout.u32('version'),\n BufferLayout.u32('state'),\n Layout.publicKey('authorizedPubkey'),\n Layout.publicKey('nonce'),\n BufferLayout.struct>(\n [FeeCalculatorLayout],\n 'feeCalculator',\n ),\n]);\n\nexport const NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span;\n\n/**\n * A durable nonce is a 32 byte value encoded as a base58 string.\n */\nexport type DurableNonce = string;\n\ntype NonceAccountArgs = {\n authorizedPubkey: PublicKey;\n nonce: DurableNonce;\n feeCalculator: FeeCalculator;\n};\n\n/**\n * NonceAccount class\n */\nexport class NonceAccount {\n authorizedPubkey: PublicKey;\n nonce: DurableNonce;\n feeCalculator: FeeCalculator;\n\n /**\n * @internal\n */\n constructor(args: NonceAccountArgs) {\n this.authorizedPubkey = args.authorizedPubkey;\n this.nonce = args.nonce;\n this.feeCalculator = args.feeCalculator;\n }\n\n /**\n * Deserialize NonceAccount from the account data.\n *\n * @param buffer account data\n * @return NonceAccount\n */\n static fromAccountData(\n buffer: Buffer | Uint8Array | Array,\n ): NonceAccount {\n const nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0);\n return new NonceAccount({\n authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey),\n nonce: new PublicKey(nonceAccount.nonce).toString(),\n feeCalculator: nonceAccount.feeCalculator,\n });\n }\n}\n","import {Buffer} from 'buffer';\nimport {blob, Layout} from '@solana/buffer-layout';\nimport {toBigIntLE, toBufferLE} from 'bigint-buffer';\n\ninterface EncodeDecode {\n decode(buffer: Buffer, offset?: number): T;\n encode(src: T, buffer: Buffer, offset?: number): number;\n}\n\nconst encodeDecode = (layout: Layout): EncodeDecode => {\n const decode = layout.decode.bind(layout);\n const encode = layout.encode.bind(layout);\n return {decode, encode};\n};\n\nconst bigInt =\n (length: number) =>\n (property?: string): Layout => {\n const layout = blob(length, property);\n const {encode, decode} = encodeDecode(layout);\n\n const bigIntLayout = layout as Layout as Layout;\n\n bigIntLayout.decode = (buffer: Buffer, offset: number) => {\n const src = decode(buffer, offset);\n return toBigIntLE(Buffer.from(src));\n };\n\n bigIntLayout.encode = (bigInt: bigint, buffer: Buffer, offset: number) => {\n const src = toBufferLE(bigInt, length);\n return encode(src, buffer, offset);\n };\n\n return bigIntLayout;\n };\n\nexport const u64 = bigInt(8);\n\nexport const u128 = bigInt(16);\n\nexport const u192 = bigInt(24);\n\nexport const u256 = bigInt(32);\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n encodeData,\n decodeData,\n InstructionType,\n IInstructionInputData,\n} from '../instruction';\nimport * as Layout from '../layout';\nimport {NONCE_ACCOUNT_LENGTH} from '../nonce-account';\nimport {PublicKey} from '../publickey';\nimport {SYSVAR_RECENT_BLOCKHASHES_PUBKEY, SYSVAR_RENT_PUBKEY} from '../sysvar';\nimport {Transaction, TransactionInstruction} from '../transaction';\nimport {toBuffer} from '../utils/to-buffer';\nimport {u64} from '../utils/bigint';\n\n/**\n * Create account system transaction params\n */\nexport type CreateAccountParams = {\n /** The account that will transfer lamports to the created account */\n fromPubkey: PublicKey;\n /** Public key of the created account */\n newAccountPubkey: PublicKey;\n /** Amount of lamports to transfer to the created account */\n lamports: number;\n /** Amount of space in bytes to allocate to the created account */\n space: number;\n /** Public key of the program to assign as the owner of the created account */\n programId: PublicKey;\n};\n\n/**\n * Transfer system transaction params\n */\nexport type TransferParams = {\n /** Account that will transfer lamports */\n fromPubkey: PublicKey;\n /** Account that will receive transferred lamports */\n toPubkey: PublicKey;\n /** Amount of lamports to transfer */\n lamports: number | bigint;\n};\n\n/**\n * Assign system transaction params\n */\nexport type AssignParams = {\n /** Public key of the account which will be assigned a new owner */\n accountPubkey: PublicKey;\n /** Public key of the program to assign as the owner */\n programId: PublicKey;\n};\n\n/**\n * Create account with seed system transaction params\n */\nexport type CreateAccountWithSeedParams = {\n /** The account that will transfer lamports to the created account */\n fromPubkey: PublicKey;\n /** Public key of the created account. Must be pre-calculated with PublicKey.createWithSeed() */\n newAccountPubkey: PublicKey;\n /** Base public key to use to derive the address of the created account. Must be the same as the base key used to create `newAccountPubkey` */\n basePubkey: PublicKey;\n /** Seed to use to derive the address of the created account. Must be the same as the seed used to create `newAccountPubkey` */\n seed: string;\n /** Amount of lamports to transfer to the created account */\n lamports: number;\n /** Amount of space in bytes to allocate to the created account */\n space: number;\n /** Public key of the program to assign as the owner of the created account */\n programId: PublicKey;\n};\n\n/**\n * Create nonce account system transaction params\n */\nexport type CreateNonceAccountParams = {\n /** The account that will transfer lamports to the created nonce account */\n fromPubkey: PublicKey;\n /** Public key of the created nonce account */\n noncePubkey: PublicKey;\n /** Public key to set as authority of the created nonce account */\n authorizedPubkey: PublicKey;\n /** Amount of lamports to transfer to the created nonce account */\n lamports: number;\n};\n\n/**\n * Create nonce account with seed system transaction params\n */\nexport type CreateNonceAccountWithSeedParams = {\n /** The account that will transfer lamports to the created nonce account */\n fromPubkey: PublicKey;\n /** Public key of the created nonce account */\n noncePubkey: PublicKey;\n /** Public key to set as authority of the created nonce account */\n authorizedPubkey: PublicKey;\n /** Amount of lamports to transfer to the created nonce account */\n lamports: number;\n /** Base public key to use to derive the address of the nonce account */\n basePubkey: PublicKey;\n /** Seed to use to derive the address of the nonce account */\n seed: string;\n};\n\n/**\n * Initialize nonce account system instruction params\n */\nexport type InitializeNonceParams = {\n /** Nonce account which will be initialized */\n noncePubkey: PublicKey;\n /** Public key to set as authority of the initialized nonce account */\n authorizedPubkey: PublicKey;\n};\n\n/**\n * Advance nonce account system instruction params\n */\nexport type AdvanceNonceParams = {\n /** Nonce account */\n noncePubkey: PublicKey;\n /** Public key of the nonce authority */\n authorizedPubkey: PublicKey;\n};\n\n/**\n * Withdraw nonce account system transaction params\n */\nexport type WithdrawNonceParams = {\n /** Nonce account */\n noncePubkey: PublicKey;\n /** Public key of the nonce authority */\n authorizedPubkey: PublicKey;\n /** Public key of the account which will receive the withdrawn nonce account balance */\n toPubkey: PublicKey;\n /** Amount of lamports to withdraw from the nonce account */\n lamports: number;\n};\n\n/**\n * Authorize nonce account system transaction params\n */\nexport type AuthorizeNonceParams = {\n /** Nonce account */\n noncePubkey: PublicKey;\n /** Public key of the current nonce authority */\n authorizedPubkey: PublicKey;\n /** Public key to set as the new nonce authority */\n newAuthorizedPubkey: PublicKey;\n};\n\n/**\n * Allocate account system transaction params\n */\nexport type AllocateParams = {\n /** Account to allocate */\n accountPubkey: PublicKey;\n /** Amount of space in bytes to allocate */\n space: number;\n};\n\n/**\n * Allocate account with seed system transaction params\n */\nexport type AllocateWithSeedParams = {\n /** Account to allocate */\n accountPubkey: PublicKey;\n /** Base public key to use to derive the address of the allocated account */\n basePubkey: PublicKey;\n /** Seed to use to derive the address of the allocated account */\n seed: string;\n /** Amount of space in bytes to allocate */\n space: number;\n /** Public key of the program to assign as the owner of the allocated account */\n programId: PublicKey;\n};\n\n/**\n * Assign account with seed system transaction params\n */\nexport type AssignWithSeedParams = {\n /** Public key of the account which will be assigned a new owner */\n accountPubkey: PublicKey;\n /** Base public key to use to derive the address of the assigned account */\n basePubkey: PublicKey;\n /** Seed to use to derive the address of the assigned account */\n seed: string;\n /** Public key of the program to assign as the owner */\n programId: PublicKey;\n};\n\n/**\n * Transfer with seed system transaction params\n */\nexport type TransferWithSeedParams = {\n /** Account that will transfer lamports */\n fromPubkey: PublicKey;\n /** Base public key to use to derive the funding account address */\n basePubkey: PublicKey;\n /** Account that will receive transferred lamports */\n toPubkey: PublicKey;\n /** Amount of lamports to transfer */\n lamports: number | bigint;\n /** Seed to use to derive the funding account address */\n seed: string;\n /** Program id to use to derive the funding account address */\n programId: PublicKey;\n};\n\n/** Decoded transfer system transaction instruction */\nexport type DecodedTransferInstruction = {\n /** Account that will transfer lamports */\n fromPubkey: PublicKey;\n /** Account that will receive transferred lamports */\n toPubkey: PublicKey;\n /** Amount of lamports to transfer */\n lamports: bigint;\n};\n\n/** Decoded transferWithSeed system transaction instruction */\nexport type DecodedTransferWithSeedInstruction = {\n /** Account that will transfer lamports */\n fromPubkey: PublicKey;\n /** Base public key to use to derive the funding account address */\n basePubkey: PublicKey;\n /** Account that will receive transferred lamports */\n toPubkey: PublicKey;\n /** Amount of lamports to transfer */\n lamports: bigint;\n /** Seed to use to derive the funding account address */\n seed: string;\n /** Program id to use to derive the funding account address */\n programId: PublicKey;\n};\n\n/**\n * System Instruction class\n */\nexport class SystemInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a system instruction and retrieve the instruction type.\n */\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): SystemInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n let type: SystemInstructionType | undefined;\n for (const [ixType, layout] of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType as SystemInstructionType;\n break;\n }\n }\n\n if (!type) {\n throw new Error('Instruction type incorrect; not a SystemInstruction');\n }\n\n return type;\n }\n\n /**\n * Decode a create account system instruction and retrieve the instruction params.\n */\n static decodeCreateAccount(\n instruction: TransactionInstruction,\n ): CreateAccountParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {lamports, space, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.Create,\n instruction.data,\n );\n\n return {\n fromPubkey: instruction.keys[0].pubkey,\n newAccountPubkey: instruction.keys[1].pubkey,\n lamports,\n space,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode a transfer system instruction and retrieve the instruction params.\n */\n static decodeTransfer(\n instruction: TransactionInstruction,\n ): DecodedTransferInstruction {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {lamports} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.Transfer,\n instruction.data,\n );\n\n return {\n fromPubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n lamports,\n };\n }\n\n /**\n * Decode a transfer with seed system instruction and retrieve the instruction params.\n */\n static decodeTransferWithSeed(\n instruction: TransactionInstruction,\n ): DecodedTransferWithSeedInstruction {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {lamports, seed, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed,\n instruction.data,\n );\n\n return {\n fromPubkey: instruction.keys[0].pubkey,\n basePubkey: instruction.keys[1].pubkey,\n toPubkey: instruction.keys[2].pubkey,\n lamports,\n seed,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode an allocate system instruction and retrieve the instruction params.\n */\n static decodeAllocate(instruction: TransactionInstruction): AllocateParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n\n const {space} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.Allocate,\n instruction.data,\n );\n\n return {\n accountPubkey: instruction.keys[0].pubkey,\n space,\n };\n }\n\n /**\n * Decode an allocate with seed system instruction and retrieve the instruction params.\n */\n static decodeAllocateWithSeed(\n instruction: TransactionInstruction,\n ): AllocateWithSeedParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n\n const {base, seed, space, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed,\n instruction.data,\n );\n\n return {\n accountPubkey: instruction.keys[0].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n space,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode an assign system instruction and retrieve the instruction params.\n */\n static decodeAssign(instruction: TransactionInstruction): AssignParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n\n const {programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.Assign,\n instruction.data,\n );\n\n return {\n accountPubkey: instruction.keys[0].pubkey,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode an assign with seed system instruction and retrieve the instruction params.\n */\n static decodeAssignWithSeed(\n instruction: TransactionInstruction,\n ): AssignWithSeedParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n\n const {base, seed, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed,\n instruction.data,\n );\n\n return {\n accountPubkey: instruction.keys[0].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode a create account with seed system instruction and retrieve the instruction params.\n */\n static decodeCreateWithSeed(\n instruction: TransactionInstruction,\n ): CreateAccountWithSeedParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {base, seed, lamports, space, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed,\n instruction.data,\n );\n\n return {\n fromPubkey: instruction.keys[0].pubkey,\n newAccountPubkey: instruction.keys[1].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n lamports,\n space,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode a nonce initialize system instruction and retrieve the instruction params.\n */\n static decodeNonceInitialize(\n instruction: TransactionInstruction,\n ): InitializeNonceParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {authorized} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount,\n instruction.data,\n );\n\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: new PublicKey(authorized),\n };\n }\n\n /**\n * Decode a nonce advance system instruction and retrieve the instruction params.\n */\n static decodeNonceAdvance(\n instruction: TransactionInstruction,\n ): AdvanceNonceParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount,\n instruction.data,\n );\n\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n };\n }\n\n /**\n * Decode a nonce withdraw system instruction and retrieve the instruction params.\n */\n static decodeNonceWithdraw(\n instruction: TransactionInstruction,\n ): WithdrawNonceParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 5);\n\n const {lamports} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount,\n instruction.data,\n );\n\n return {\n noncePubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n lamports,\n };\n }\n\n /**\n * Decode a nonce authorize system instruction and retrieve the instruction params.\n */\n static decodeNonceAuthorize(\n instruction: TransactionInstruction,\n ): AuthorizeNonceParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {authorized} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount,\n instruction.data,\n );\n\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[1].pubkey,\n newAuthorizedPubkey: new PublicKey(authorized),\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(SystemProgram.programId)) {\n throw new Error('invalid instruction; programId is not SystemProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys: Array, expectedLength: number) {\n if (keys.length < expectedLength) {\n throw new Error(\n `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n );\n }\n }\n}\n\n/**\n * An enumeration of valid SystemInstructionType's\n */\nexport type SystemInstructionType =\n // FIXME\n // It would be preferable for this type to be `keyof SystemInstructionInputData`\n // but Typedoc does not transpile `keyof` expressions.\n // See https://github.com/TypeStrong/typedoc/issues/1894\n | 'AdvanceNonceAccount'\n | 'Allocate'\n | 'AllocateWithSeed'\n | 'Assign'\n | 'AssignWithSeed'\n | 'AuthorizeNonceAccount'\n | 'Create'\n | 'CreateWithSeed'\n | 'InitializeNonceAccount'\n | 'Transfer'\n | 'TransferWithSeed'\n | 'WithdrawNonceAccount'\n | 'UpgradeNonceAccount';\n\ntype SystemInstructionInputData = {\n AdvanceNonceAccount: IInstructionInputData;\n Allocate: IInstructionInputData & {\n space: number;\n };\n AllocateWithSeed: IInstructionInputData & {\n base: Uint8Array;\n programId: Uint8Array;\n seed: string;\n space: number;\n };\n Assign: IInstructionInputData & {\n programId: Uint8Array;\n };\n AssignWithSeed: IInstructionInputData & {\n base: Uint8Array;\n seed: string;\n programId: Uint8Array;\n };\n AuthorizeNonceAccount: IInstructionInputData & {\n authorized: Uint8Array;\n };\n Create: IInstructionInputData & {\n lamports: number;\n programId: Uint8Array;\n space: number;\n };\n CreateWithSeed: IInstructionInputData & {\n base: Uint8Array;\n lamports: number;\n programId: Uint8Array;\n seed: string;\n space: number;\n };\n InitializeNonceAccount: IInstructionInputData & {\n authorized: Uint8Array;\n };\n Transfer: IInstructionInputData & {\n lamports: bigint;\n };\n TransferWithSeed: IInstructionInputData & {\n lamports: bigint;\n programId: Uint8Array;\n seed: string;\n };\n WithdrawNonceAccount: IInstructionInputData & {\n lamports: number;\n };\n UpgradeNonceAccount: IInstructionInputData;\n};\n\n/**\n * An enumeration of valid system InstructionType's\n * @internal\n */\nexport const SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze<{\n [Instruction in SystemInstructionType]: InstructionType<\n SystemInstructionInputData[Instruction]\n >;\n}>({\n Create: {\n index: 0,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('lamports'),\n BufferLayout.ns64('space'),\n Layout.publicKey('programId'),\n ]),\n },\n Assign: {\n index: 1,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('programId'),\n ]),\n },\n Transfer: {\n index: 2,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n u64('lamports'),\n ]),\n },\n CreateWithSeed: {\n index: 3,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('base'),\n Layout.rustString('seed'),\n BufferLayout.ns64('lamports'),\n BufferLayout.ns64('space'),\n Layout.publicKey('programId'),\n ]),\n },\n AdvanceNonceAccount: {\n index: 4,\n layout: BufferLayout.struct<\n SystemInstructionInputData['AdvanceNonceAccount']\n >([BufferLayout.u32('instruction')]),\n },\n WithdrawNonceAccount: {\n index: 5,\n layout: BufferLayout.struct<\n SystemInstructionInputData['WithdrawNonceAccount']\n >([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')]),\n },\n InitializeNonceAccount: {\n index: 6,\n layout: BufferLayout.struct<\n SystemInstructionInputData['InitializeNonceAccount']\n >([BufferLayout.u32('instruction'), Layout.publicKey('authorized')]),\n },\n AuthorizeNonceAccount: {\n index: 7,\n layout: BufferLayout.struct<\n SystemInstructionInputData['AuthorizeNonceAccount']\n >([BufferLayout.u32('instruction'), Layout.publicKey('authorized')]),\n },\n Allocate: {\n index: 8,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('space'),\n ]),\n },\n AllocateWithSeed: {\n index: 9,\n layout: BufferLayout.struct(\n [\n BufferLayout.u32('instruction'),\n Layout.publicKey('base'),\n Layout.rustString('seed'),\n BufferLayout.ns64('space'),\n Layout.publicKey('programId'),\n ],\n ),\n },\n AssignWithSeed: {\n index: 10,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('base'),\n Layout.rustString('seed'),\n Layout.publicKey('programId'),\n ]),\n },\n TransferWithSeed: {\n index: 11,\n layout: BufferLayout.struct(\n [\n BufferLayout.u32('instruction'),\n u64('lamports'),\n Layout.rustString('seed'),\n Layout.publicKey('programId'),\n ],\n ),\n },\n UpgradeNonceAccount: {\n index: 12,\n layout: BufferLayout.struct<\n SystemInstructionInputData['UpgradeNonceAccount']\n >([BufferLayout.u32('instruction')]),\n },\n});\n\n/**\n * Factory class for transactions to interact with the System program\n */\nexport class SystemProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the System program\n */\n static programId: PublicKey = new PublicKey(\n '11111111111111111111111111111111',\n );\n\n /**\n * Generate a transaction instruction that creates a new account\n */\n static createAccount(params: CreateAccountParams): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Create;\n const data = encodeData(type, {\n lamports: params.lamports,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer()),\n });\n\n return new TransactionInstruction({\n keys: [\n {pubkey: params.fromPubkey, isSigner: true, isWritable: true},\n {pubkey: params.newAccountPubkey, isSigner: true, isWritable: true},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that transfers lamports from one account to another\n */\n static transfer(\n params: TransferParams | TransferWithSeedParams,\n ): TransactionInstruction {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;\n data = encodeData(type, {\n lamports: BigInt(params.lamports),\n seed: params.seed,\n programId: toBuffer(params.programId.toBuffer()),\n });\n keys = [\n {pubkey: params.fromPubkey, isSigner: false, isWritable: true},\n {pubkey: params.basePubkey, isSigner: true, isWritable: false},\n {pubkey: params.toPubkey, isSigner: false, isWritable: true},\n ];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;\n data = encodeData(type, {lamports: BigInt(params.lamports)});\n keys = [\n {pubkey: params.fromPubkey, isSigner: true, isWritable: true},\n {pubkey: params.toPubkey, isSigner: false, isWritable: true},\n ];\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that assigns an account to a program\n */\n static assign(\n params: AssignParams | AssignWithSeedParams,\n ): TransactionInstruction {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n programId: toBuffer(params.programId.toBuffer()),\n });\n keys = [\n {pubkey: params.accountPubkey, isSigner: false, isWritable: true},\n {pubkey: params.basePubkey, isSigner: true, isWritable: false},\n ];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Assign;\n data = encodeData(type, {\n programId: toBuffer(params.programId.toBuffer()),\n });\n keys = [{pubkey: params.accountPubkey, isSigner: true, isWritable: true}];\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that creates a new account at\n * an address generated with `from`, a seed, and programId\n */\n static createAccountWithSeed(\n params: CreateAccountWithSeedParams,\n ): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;\n const data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n lamports: params.lamports,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer()),\n });\n let keys = [\n {pubkey: params.fromPubkey, isSigner: true, isWritable: true},\n {pubkey: params.newAccountPubkey, isSigner: false, isWritable: true},\n ];\n if (params.basePubkey != params.fromPubkey) {\n keys.push({\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false,\n });\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction that creates a new Nonce account\n */\n static createNonceAccount(\n params: CreateNonceAccountParams | CreateNonceAccountWithSeedParams,\n ): Transaction {\n const transaction = new Transaction();\n if ('basePubkey' in params && 'seed' in params) {\n transaction.add(\n SystemProgram.createAccountWithSeed({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.noncePubkey,\n basePubkey: params.basePubkey,\n seed: params.seed,\n lamports: params.lamports,\n space: NONCE_ACCOUNT_LENGTH,\n programId: this.programId,\n }),\n );\n } else {\n transaction.add(\n SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.noncePubkey,\n lamports: params.lamports,\n space: NONCE_ACCOUNT_LENGTH,\n programId: this.programId,\n }),\n );\n }\n\n const initParams = {\n noncePubkey: params.noncePubkey,\n authorizedPubkey: params.authorizedPubkey,\n };\n\n transaction.add(this.nonceInitialize(initParams));\n return transaction;\n }\n\n /**\n * Generate an instruction to initialize a Nonce account\n */\n static nonceInitialize(\n params: InitializeNonceParams,\n ): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;\n const data = encodeData(type, {\n authorized: toBuffer(params.authorizedPubkey.toBuffer()),\n });\n const instructionData = {\n keys: [\n {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n ],\n programId: this.programId,\n data,\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate an instruction to advance the nonce in a Nonce account\n */\n static nonceAdvance(params: AdvanceNonceParams): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount;\n const data = encodeData(type);\n const instructionData = {\n keys: [\n {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a transaction instruction that withdraws lamports from a Nonce account\n */\n static nonceWithdraw(params: WithdrawNonceParams): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount;\n const data = encodeData(type, {lamports: params.lamports});\n\n return new TransactionInstruction({\n keys: [\n {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n {pubkey: params.toPubkey, isSigner: false, isWritable: true},\n {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that authorizes a new PublicKey as the authority\n * on a Nonce account.\n */\n static nonceAuthorize(params: AuthorizeNonceParams): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;\n const data = encodeData(type, {\n authorized: toBuffer(params.newAuthorizedPubkey.toBuffer()),\n });\n\n return new TransactionInstruction({\n keys: [\n {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that allocates space in an account without funding\n */\n static allocate(\n params: AllocateParams | AllocateWithSeedParams,\n ): TransactionInstruction {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer()),\n });\n keys = [\n {pubkey: params.accountPubkey, isSigner: false, isWritable: true},\n {pubkey: params.basePubkey, isSigner: true, isWritable: false},\n ];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;\n data = encodeData(type, {\n space: params.space,\n });\n keys = [{pubkey: params.accountPubkey, isSigner: true, isWritable: true}];\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data,\n });\n }\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {PublicKey} from './publickey';\nimport {Transaction, PACKET_DATA_SIZE} from './transaction';\nimport {MS_PER_SLOT} from './timing';\nimport {SYSVAR_RENT_PUBKEY} from './sysvar';\nimport {sendAndConfirmTransaction} from './utils/send-and-confirm-transaction';\nimport {sleep} from './utils/sleep';\nimport type {Connection} from './connection';\nimport type {Signer} from './keypair';\nimport {SystemProgram} from './programs/system';\nimport {IInstructionInputData} from './instruction';\n\n// Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the\n// rest of the Transaction fields\n//\n// TODO: replace 300 with a proper constant for the size of the other\n// Transaction fields\nconst CHUNK_SIZE = PACKET_DATA_SIZE - 300;\n\n/**\n * Program loader interface\n */\nexport class Loader {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Amount of program data placed in each load Transaction\n */\n static chunkSize: number = CHUNK_SIZE;\n\n /**\n * Minimum number of signatures required to load a program not including\n * retries\n *\n * Can be used to calculate transaction fees\n */\n static getMinNumSignatures(dataLength: number): number {\n return (\n 2 * // Every transaction requires two signatures (payer + program)\n (Math.ceil(dataLength / Loader.chunkSize) +\n 1 + // Add one for Create transaction\n 1) // Add one for Finalize transaction\n );\n }\n\n /**\n * Loads a generic program\n *\n * @param connection The connection to use\n * @param payer System account that pays to load the program\n * @param program Account to load the program into\n * @param programId Public key that identifies the loader\n * @param data Program octets\n * @return true if program was loaded successfully, false if program was already loaded\n */\n static async load(\n connection: Connection,\n payer: Signer,\n program: Signer,\n programId: PublicKey,\n data: Buffer | Uint8Array | Array,\n ): Promise {\n {\n const balanceNeeded = await connection.getMinimumBalanceForRentExemption(\n data.length,\n );\n\n // Fetch program account info to check if it has already been created\n const programInfo = await connection.getAccountInfo(\n program.publicKey,\n 'confirmed',\n );\n\n let transaction: Transaction | null = null;\n if (programInfo !== null) {\n if (programInfo.executable) {\n console.error('Program load failed, account is already executable');\n return false;\n }\n\n if (programInfo.data.length !== data.length) {\n transaction = transaction || new Transaction();\n transaction.add(\n SystemProgram.allocate({\n accountPubkey: program.publicKey,\n space: data.length,\n }),\n );\n }\n\n if (!programInfo.owner.equals(programId)) {\n transaction = transaction || new Transaction();\n transaction.add(\n SystemProgram.assign({\n accountPubkey: program.publicKey,\n programId,\n }),\n );\n }\n\n if (programInfo.lamports < balanceNeeded) {\n transaction = transaction || new Transaction();\n transaction.add(\n SystemProgram.transfer({\n fromPubkey: payer.publicKey,\n toPubkey: program.publicKey,\n lamports: balanceNeeded - programInfo.lamports,\n }),\n );\n }\n } else {\n transaction = new Transaction().add(\n SystemProgram.createAccount({\n fromPubkey: payer.publicKey,\n newAccountPubkey: program.publicKey,\n lamports: balanceNeeded > 0 ? balanceNeeded : 1,\n space: data.length,\n programId,\n }),\n );\n }\n\n // If the account is already created correctly, skip this step\n // and proceed directly to loading instructions\n if (transaction !== null) {\n await sendAndConfirmTransaction(\n connection,\n transaction,\n [payer, program],\n {\n commitment: 'confirmed',\n },\n );\n }\n }\n\n const dataLayout = BufferLayout.struct<\n Readonly<{\n bytes: number[];\n bytesLength: number;\n bytesLengthPadding: number;\n instruction: number;\n offset: number;\n }>\n >([\n BufferLayout.u32('instruction'),\n BufferLayout.u32('offset'),\n BufferLayout.u32('bytesLength'),\n BufferLayout.u32('bytesLengthPadding'),\n BufferLayout.seq(\n BufferLayout.u8('byte'),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'bytes',\n ),\n ]);\n\n const chunkSize = Loader.chunkSize;\n let offset = 0;\n let array = data;\n let transactions = [];\n while (array.length > 0) {\n const bytes = array.slice(0, chunkSize);\n const data = Buffer.alloc(chunkSize + 16);\n dataLayout.encode(\n {\n instruction: 0, // Load instruction\n offset,\n bytes: bytes as number[],\n bytesLength: 0,\n bytesLengthPadding: 0,\n },\n data,\n );\n\n const transaction = new Transaction().add({\n keys: [{pubkey: program.publicKey, isSigner: true, isWritable: true}],\n programId,\n data,\n });\n transactions.push(\n sendAndConfirmTransaction(connection, transaction, [payer, program], {\n commitment: 'confirmed',\n }),\n );\n\n // Delay between sends in an attempt to reduce rate limit errors\n if (connection._rpcEndpoint.includes('solana.com')) {\n const REQUESTS_PER_SECOND = 4;\n await sleep(1000 / REQUESTS_PER_SECOND);\n }\n\n offset += chunkSize;\n array = array.slice(chunkSize);\n }\n await Promise.all(transactions);\n\n // Finalize the account loaded with program data for execution\n {\n const dataLayout = BufferLayout.struct([\n BufferLayout.u32('instruction'),\n ]);\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode(\n {\n instruction: 1, // Finalize instruction\n },\n data,\n );\n\n const transaction = new Transaction().add({\n keys: [\n {pubkey: program.publicKey, isSigner: true, isWritable: true},\n {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n ],\n programId,\n data,\n });\n const deployCommitment = 'processed';\n const finalizeSignature = await connection.sendTransaction(\n transaction,\n [payer, program],\n {preflightCommitment: deployCommitment},\n );\n const {context, value} = await connection.confirmTransaction(\n {\n signature: finalizeSignature,\n lastValidBlockHeight: transaction.lastValidBlockHeight!,\n blockhash: transaction.recentBlockhash!,\n },\n deployCommitment,\n );\n if (value.err) {\n throw new Error(\n `Transaction ${finalizeSignature} failed (${JSON.stringify(value)})`,\n );\n }\n // We prevent programs from being usable until the slot after their deployment.\n // See https://github.com/solana-labs/solana/pull/29654\n while (\n true // eslint-disable-line no-constant-condition\n ) {\n try {\n const currentSlot = await connection.getSlot({\n commitment: deployCommitment,\n });\n if (currentSlot > context.slot) {\n break;\n }\n } catch {\n /* empty */\n }\n await new Promise(resolve =>\n setTimeout(resolve, Math.round(MS_PER_SLOT / 2)),\n );\n }\n }\n\n // success\n return true;\n }\n}\n","import type {Buffer} from 'buffer';\n\nimport {PublicKey} from './publickey';\nimport {Loader} from './loader';\nimport type {Connection} from './connection';\nimport type {Signer} from './keypair';\n\nexport const BPF_LOADER_PROGRAM_ID = new PublicKey(\n 'BPFLoader2111111111111111111111111111111111',\n);\n\n/**\n * Factory class for transactions to interact with a program loader\n */\nexport class BpfLoader {\n /**\n * Minimum number of signatures required to load a program not including\n * retries\n *\n * Can be used to calculate transaction fees\n */\n static getMinNumSignatures(dataLength: number): number {\n return Loader.getMinNumSignatures(dataLength);\n }\n\n /**\n * Load a SBF program\n *\n * @param connection The connection to use\n * @param payer Account that will pay program loading fees\n * @param program Account to load the program into\n * @param elf The entire ELF containing the SBF program\n * @param loaderProgramId The program id of the BPF loader to use\n * @return true if program was loaded successfully, false if program was already loaded\n */\n static load(\n connection: Connection,\n payer: Signer,\n program: Signer,\n elf: Buffer | Uint8Array | Array,\n loaderProgramId: PublicKey,\n ): Promise {\n return Loader.load(connection, payer, program, loaderProgramId, elf);\n }\n}\n","var objToString = Object.prototype.toString;\nvar objKeys = Object.keys || function(obj) {\n\t\tvar keys = [];\n\t\tfor (var name in obj) {\n\t\t\tkeys.push(name);\n\t\t}\n\t\treturn keys;\n\t};\n\nfunction stringify(val, isArrayProp) {\n\tvar i, max, str, keys, key, propVal, toStr;\n\tif (val === true) {\n\t\treturn \"true\";\n\t}\n\tif (val === false) {\n\t\treturn \"false\";\n\t}\n\tswitch (typeof val) {\n\t\tcase \"object\":\n\t\t\tif (val === null) {\n\t\t\t\treturn null;\n\t\t\t} else if (val.toJSON && typeof val.toJSON === \"function\") {\n\t\t\t\treturn stringify(val.toJSON(), isArrayProp);\n\t\t\t} else {\n\t\t\t\ttoStr = objToString.call(val);\n\t\t\t\tif (toStr === \"[object Array]\") {\n\t\t\t\t\tstr = '[';\n\t\t\t\t\tmax = val.length - 1;\n\t\t\t\t\tfor(i = 0; i < max; i++) {\n\t\t\t\t\t\tstr += stringify(val[i], true) + ',';\n\t\t\t\t\t}\n\t\t\t\t\tif (max > -1) {\n\t\t\t\t\t\tstr += stringify(val[i], true);\n\t\t\t\t\t}\n\t\t\t\t\treturn str + ']';\n\t\t\t\t} else if (toStr === \"[object Object]\") {\n\t\t\t\t\t// only object is left\n\t\t\t\t\tkeys = objKeys(val).sort();\n\t\t\t\t\tmax = keys.length;\n\t\t\t\t\tstr = \"\";\n\t\t\t\t\ti = 0;\n\t\t\t\t\twhile (i < max) {\n\t\t\t\t\t\tkey = keys[i];\n\t\t\t\t\t\tpropVal = stringify(val[key], false);\n\t\t\t\t\t\tif (propVal !== undefined) {\n\t\t\t\t\t\t\tif (str) {\n\t\t\t\t\t\t\t\tstr += ',';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstr += JSON.stringify(key) + ':' + propVal;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\treturn '{' + str + '}';\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON.stringify(val);\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"function\":\n\t\tcase \"undefined\":\n\t\t\treturn isArrayProp ? null : undefined;\n\t\tcase \"string\":\n\t\t\treturn JSON.stringify(val);\n\t\tdefault:\n\t\t\treturn isFinite(val) ? val : null;\n\t}\n}\n\nmodule.exports = function(val) {\n\tvar returnVal = stringify(val, false);\n\tif (returnVal !== undefined) {\n\t\treturn ''+ returnVal;\n\t}\n};\n","export class SendTransactionError extends Error {\n logs: string[] | undefined;\n\n constructor(message: string, logs?: string[]) {\n super(message);\n\n this.logs = logs;\n }\n}\n\n// Keep in sync with client/src/rpc_custom_errors.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nexport const SolanaJSONRPCErrorCode = {\n JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n JSON_RPC_SCAN_ERROR: -32012,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016,\n} as const;\nexport type SolanaJSONRPCErrorCodeEnum =\n (typeof SolanaJSONRPCErrorCode)[keyof typeof SolanaJSONRPCErrorCode];\n\nexport class SolanaJSONRPCError extends Error {\n code: SolanaJSONRPCErrorCodeEnum | unknown;\n data?: any;\n constructor(\n {\n code,\n message,\n data,\n }: Readonly<{code: unknown; message: string; data?: any}>,\n customMessage?: string,\n ) {\n super(customMessage != null ? `${customMessage}: ${message}` : message);\n this.code = code;\n this.data = data;\n this.name = 'SolanaJSONRPCError';\n }\n}\n","export const Headers = globalThis.Headers;\nexport const Request = globalThis.Request;\nexport const Response = globalThis.Response;\nexport default globalThis.fetch;\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport assert from '../../utils/assert';\nimport * as Layout from '../../layout';\nimport {PublicKey} from '../../publickey';\nimport {u64} from '../../utils/bigint';\nimport {decodeData} from '../../account-data';\n\nexport type AddressLookupTableState = {\n deactivationSlot: bigint;\n lastExtendedSlot: number;\n lastExtendedSlotStartIndex: number;\n authority?: PublicKey;\n addresses: Array;\n};\n\nexport type AddressLookupTableAccountArgs = {\n key: PublicKey;\n state: AddressLookupTableState;\n};\n\n/// The serialized size of lookup table metadata\nconst LOOKUP_TABLE_META_SIZE = 56;\n\nexport class AddressLookupTableAccount {\n key: PublicKey;\n state: AddressLookupTableState;\n\n constructor(args: AddressLookupTableAccountArgs) {\n this.key = args.key;\n this.state = args.state;\n }\n\n isActive(): boolean {\n const U64_MAX = BigInt('0xffffffffffffffff');\n return this.state.deactivationSlot === U64_MAX;\n }\n\n static deserialize(accountData: Uint8Array): AddressLookupTableState {\n const meta = decodeData(LookupTableMetaLayout, accountData);\n\n const serializedAddressesLen = accountData.length - LOOKUP_TABLE_META_SIZE;\n assert(serializedAddressesLen >= 0, 'lookup table is invalid');\n assert(serializedAddressesLen % 32 === 0, 'lookup table is invalid');\n\n const numSerializedAddresses = serializedAddressesLen / 32;\n const {addresses} = BufferLayout.struct<{addresses: Array}>([\n BufferLayout.seq(Layout.publicKey(), numSerializedAddresses, 'addresses'),\n ]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE));\n\n return {\n deactivationSlot: meta.deactivationSlot,\n lastExtendedSlot: meta.lastExtendedSlot,\n lastExtendedSlotStartIndex: meta.lastExtendedStartIndex,\n authority:\n meta.authority.length !== 0\n ? new PublicKey(meta.authority[0])\n : undefined,\n addresses: addresses.map(address => new PublicKey(address)),\n };\n }\n}\n\nconst LookupTableMetaLayout = {\n index: 1,\n layout: BufferLayout.struct<{\n typeIndex: number;\n deactivationSlot: bigint;\n lastExtendedSlot: number;\n lastExtendedStartIndex: number;\n authority: Array;\n }>([\n BufferLayout.u32('typeIndex'),\n u64('deactivationSlot'),\n BufferLayout.nu64('lastExtendedSlot'),\n BufferLayout.u8('lastExtendedStartIndex'),\n BufferLayout.u8(), // option\n BufferLayout.seq(\n Layout.publicKey(),\n BufferLayout.offset(BufferLayout.u8(), -1),\n 'authority',\n ),\n ]),\n};\n","import HttpKeepAliveAgent, {\n HttpsAgent as HttpsKeepAliveAgent,\n} from 'agentkeepalive';\nimport bs58 from 'bs58';\nimport {Buffer} from 'buffer';\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\nimport type {Agent as NodeHttpAgent} from 'http';\nimport {Agent as NodeHttpsAgent} from 'https';\nimport {\n type as pick,\n number,\n string,\n array,\n boolean,\n literal,\n record,\n union,\n optional,\n nullable,\n coerce,\n instance,\n create,\n tuple,\n unknown,\n any,\n} from 'superstruct';\nimport type {Struct} from 'superstruct';\nimport RpcClient from 'jayson/lib/client/browser';\nimport {JSONRPCError} from 'jayson';\n\nimport {EpochSchedule} from './epoch-schedule';\nimport {SendTransactionError, SolanaJSONRPCError} from './errors';\nimport fetchImpl, {Response} from './fetch-impl';\nimport {DurableNonce, NonceAccount} from './nonce-account';\nimport {PublicKey} from './publickey';\nimport {Signer} from './keypair';\nimport RpcWebSocketClient from './rpc-websocket';\nimport {MS_PER_SLOT} from './timing';\nimport {\n Transaction,\n TransactionStatus,\n TransactionVersion,\n VersionedTransaction,\n} from './transaction';\nimport {Message, MessageHeader, MessageV0, VersionedMessage} from './message';\nimport {AddressLookupTableAccount} from './programs/address-lookup-table/state';\nimport assert from './utils/assert';\nimport {sleep} from './utils/sleep';\nimport {toBuffer} from './utils/to-buffer';\nimport {\n TransactionExpiredBlockheightExceededError,\n TransactionExpiredNonceInvalidError,\n TransactionExpiredTimeoutError,\n} from './transaction/expiry-custom-errors';\nimport {makeWebsocketUrl} from './utils/makeWebsocketUrl';\nimport type {Blockhash} from './blockhash';\nimport type {FeeCalculator} from './fee-calculator';\nimport type {TransactionSignature} from './transaction';\nimport type {CompiledInstruction} from './message';\n\nconst PublicKeyFromString = coerce(\n instance(PublicKey),\n string(),\n value => new PublicKey(value),\n);\n\nconst RawAccountDataResult = tuple([string(), literal('base64')]);\n\nconst BufferFromRawAccountData = coerce(\n instance(Buffer),\n RawAccountDataResult,\n value => Buffer.from(value[0], 'base64'),\n);\n\n/**\n * Attempt to use a recent blockhash for up to 30 seconds\n * @internal\n */\nexport const BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000;\n\n/**\n * HACK.\n * Copied from rpc-websockets/dist/lib/client.\n * Otherwise, `yarn build` fails with:\n * https://gist.github.com/steveluscher/c057eca81d479ef705cdb53162f9971d\n */\ninterface IWSRequestParams {\n [x: string]: any;\n [x: number]: any;\n}\n\ntype ClientSubscriptionId = number;\n/** @internal */ type ServerSubscriptionId = number;\n/** @internal */ type SubscriptionConfigHash = string;\n/** @internal */ type SubscriptionDisposeFn = () => Promise;\n/** @internal */ type SubscriptionStateChangeCallback = (\n nextState: StatefulSubscription['state'],\n) => void;\n/** @internal */ type SubscriptionStateChangeDisposeFn = () => void;\n/**\n * @internal\n * Every subscription contains the args used to open the subscription with\n * the server, and a list of callers interested in notifications.\n */\ntype BaseSubscription = Readonly<{\n args: IWSRequestParams;\n callbacks: Set['callback']>;\n}>;\n/**\n * @internal\n * A subscription may be in various states of connectedness. Only when it is\n * fully connected will it have a server subscription id associated with it.\n * This id can be returned to the server to unsubscribe the client entirely.\n */\ntype StatefulSubscription = Readonly<\n // New subscriptions that have not yet been\n // sent to the server start in this state.\n | {\n state: 'pending';\n }\n // These subscriptions have been sent to the server\n // and are waiting for the server to acknowledge them.\n | {\n state: 'subscribing';\n }\n // These subscriptions have been acknowledged by the\n // server and have been assigned server subscription ids.\n | {\n serverSubscriptionId: ServerSubscriptionId;\n state: 'subscribed';\n }\n // These subscriptions are intended to be torn down and\n // are waiting on an acknowledgement from the server.\n | {\n serverSubscriptionId: ServerSubscriptionId;\n state: 'unsubscribing';\n }\n // The request to tear down these subscriptions has been\n // acknowledged by the server. The `serverSubscriptionId`\n // is the id of the now-dead subscription.\n | {\n serverSubscriptionId: ServerSubscriptionId;\n state: 'unsubscribed';\n }\n>;\n/**\n * A type that encapsulates a subscription's RPC method\n * names and notification (callback) signature.\n */\ntype SubscriptionConfig = Readonly<\n | {\n callback: AccountChangeCallback;\n method: 'accountSubscribe';\n unsubscribeMethod: 'accountUnsubscribe';\n }\n | {\n callback: LogsCallback;\n method: 'logsSubscribe';\n unsubscribeMethod: 'logsUnsubscribe';\n }\n | {\n callback: ProgramAccountChangeCallback;\n method: 'programSubscribe';\n unsubscribeMethod: 'programUnsubscribe';\n }\n | {\n callback: RootChangeCallback;\n method: 'rootSubscribe';\n unsubscribeMethod: 'rootUnsubscribe';\n }\n | {\n callback: SignatureSubscriptionCallback;\n method: 'signatureSubscribe';\n unsubscribeMethod: 'signatureUnsubscribe';\n }\n | {\n callback: SlotChangeCallback;\n method: 'slotSubscribe';\n unsubscribeMethod: 'slotUnsubscribe';\n }\n | {\n callback: SlotUpdateCallback;\n method: 'slotsUpdatesSubscribe';\n unsubscribeMethod: 'slotsUpdatesUnsubscribe';\n }\n>;\n/**\n * @internal\n * Utility type that keeps tagged unions intact while omitting properties.\n */\ntype DistributiveOmit = T extends unknown\n ? Omit\n : never;\n/**\n * @internal\n * This type represents a single subscribable 'topic.' It's made up of:\n *\n * - The args used to open the subscription with the server,\n * - The state of the subscription, in terms of its connectedness, and\n * - The set of callbacks to call when the server publishes notifications\n *\n * This record gets indexed by `SubscriptionConfigHash` and is used to\n * set up subscriptions, fan out notifications, and track subscription state.\n */\ntype Subscription = BaseSubscription &\n StatefulSubscription &\n DistributiveOmit;\n\ntype RpcRequest = (methodName: string, args: Array) => Promise;\n\ntype RpcBatchRequest = (requests: RpcParams[]) => Promise;\n\n/**\n * @internal\n */\nexport type RpcParams = {\n methodName: string;\n args: Array;\n};\n\nexport type TokenAccountsFilter =\n | {\n mint: PublicKey;\n }\n | {\n programId: PublicKey;\n };\n\n/**\n * Extra contextual information for RPC responses\n */\nexport type Context = {\n slot: number;\n};\n\n/**\n * Options for sending transactions\n */\nexport type SendOptions = {\n /** disable transaction verification step */\n skipPreflight?: boolean;\n /** preflight commitment level */\n preflightCommitment?: Commitment;\n /** Maximum number of times for the RPC node to retry sending the transaction to the leader. */\n maxRetries?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Options for confirming transactions\n */\nexport type ConfirmOptions = {\n /** disable transaction verification step */\n skipPreflight?: boolean;\n /** desired commitment level */\n commitment?: Commitment;\n /** preflight commitment level */\n preflightCommitment?: Commitment;\n /** Maximum number of times for the RPC node to retry sending the transaction to the leader. */\n maxRetries?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Options for getConfirmedSignaturesForAddress2\n */\nexport type ConfirmedSignaturesForAddress2Options = {\n /**\n * Start searching backwards from this transaction signature.\n * @remark If not provided the search starts from the highest max confirmed block.\n */\n before?: TransactionSignature;\n /** Search until this transaction signature is reached, if found before `limit`. */\n until?: TransactionSignature;\n /** Maximum transaction signatures to return (between 1 and 1,000, default: 1,000). */\n limit?: number;\n};\n\n/**\n * Options for getSignaturesForAddress\n */\nexport type SignaturesForAddressOptions = {\n /**\n * Start searching backwards from this transaction signature.\n * @remark If not provided the search starts from the highest max confirmed block.\n */\n before?: TransactionSignature;\n /** Search until this transaction signature is reached, if found before `limit`. */\n until?: TransactionSignature;\n /** Maximum transaction signatures to return (between 1 and 1,000, default: 1,000). */\n limit?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * RPC Response with extra contextual information\n */\nexport type RpcResponseAndContext = {\n /** response context */\n context: Context;\n /** response value */\n value: T;\n};\n\nexport type BlockhashWithExpiryBlockHeight = Readonly<{\n blockhash: Blockhash;\n lastValidBlockHeight: number;\n}>;\n\n/**\n * A strategy for confirming transactions that uses the last valid\n * block height for a given blockhash to check for transaction expiration.\n */\nexport type BlockheightBasedTransactionConfirmationStrategy =\n BaseTransactionConfirmationStrategy & BlockhashWithExpiryBlockHeight;\n\n/**\n * A strategy for confirming durable nonce transactions.\n */\nexport type DurableNonceTransactionConfirmationStrategy =\n BaseTransactionConfirmationStrategy & {\n /**\n * The lowest slot at which to fetch the nonce value from the\n * nonce account. This should be no lower than the slot at\n * which the last-known value of the nonce was fetched.\n */\n minContextSlot: number;\n /**\n * The account where the current value of the nonce is stored.\n */\n nonceAccountPubkey: PublicKey;\n /**\n * The nonce value that was used to sign the transaction\n * for which confirmation is being sought.\n */\n nonceValue: DurableNonce;\n };\n\n/**\n * Properties shared by all transaction confirmation strategies\n */\nexport type BaseTransactionConfirmationStrategy = Readonly<{\n /** A signal that, when aborted, cancels any outstanding transaction confirmation operations */\n abortSignal?: AbortSignal;\n signature: TransactionSignature;\n}>;\n\n/**\n * This type represents all transaction confirmation strategies\n */\nexport type TransactionConfirmationStrategy =\n | BlockheightBasedTransactionConfirmationStrategy\n | DurableNonceTransactionConfirmationStrategy;\n\n/* @internal */\nfunction assertEndpointUrl(putativeUrl: string) {\n if (/^https?:/.test(putativeUrl) === false) {\n throw new TypeError('Endpoint URL must start with `http:` or `https:`.');\n }\n return putativeUrl;\n}\n\n/** @internal */\nfunction extractCommitmentFromConfig(\n commitmentOrConfig?: Commitment | ({commitment?: Commitment} & TConfig),\n) {\n let commitment: Commitment | undefined;\n let config: Omit | undefined;\n if (typeof commitmentOrConfig === 'string') {\n commitment = commitmentOrConfig;\n } else if (commitmentOrConfig) {\n const {commitment: specifiedCommitment, ...specifiedConfig} =\n commitmentOrConfig;\n commitment = specifiedCommitment;\n config = specifiedConfig;\n }\n return {commitment, config};\n}\n\n/**\n * @internal\n */\nfunction createRpcResult(result: Struct) {\n return union([\n pick({\n jsonrpc: literal('2.0'),\n id: string(),\n result,\n }),\n pick({\n jsonrpc: literal('2.0'),\n id: string(),\n error: pick({\n code: unknown(),\n message: string(),\n data: optional(any()),\n }),\n }),\n ]);\n}\n\nconst UnknownRpcResult = createRpcResult(unknown());\n\n/**\n * @internal\n */\nfunction jsonRpcResult(schema: Struct) {\n return coerce(createRpcResult(schema), UnknownRpcResult, value => {\n if ('error' in value) {\n return value;\n } else {\n return {\n ...value,\n result: create(value.result, schema),\n };\n }\n });\n}\n\n/**\n * @internal\n */\nfunction jsonRpcResultAndContext(value: Struct) {\n return jsonRpcResult(\n pick({\n context: pick({\n slot: number(),\n }),\n value,\n }),\n );\n}\n\n/**\n * @internal\n */\nfunction notificationResultAndContext(value: Struct) {\n return pick({\n context: pick({\n slot: number(),\n }),\n value,\n });\n}\n\n/**\n * @internal\n */\nfunction versionedMessageFromResponse(\n version: TransactionVersion | undefined,\n response: MessageResponse,\n): VersionedMessage {\n if (version === 0) {\n return new MessageV0({\n header: response.header,\n staticAccountKeys: response.accountKeys.map(\n accountKey => new PublicKey(accountKey),\n ),\n recentBlockhash: response.recentBlockhash,\n compiledInstructions: response.instructions.map(ix => ({\n programIdIndex: ix.programIdIndex,\n accountKeyIndexes: ix.accounts,\n data: bs58.decode(ix.data),\n })),\n addressTableLookups: response.addressTableLookups!,\n });\n } else {\n return new Message(response);\n }\n}\n\n/**\n * The level of commitment desired when querying state\n *
\n *   'processed': Query the most recent block which has reached 1 confirmation by the connected node\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * 
\n */\nexport type Commitment =\n | 'processed'\n | 'confirmed'\n | 'finalized'\n | 'recent' // Deprecated as of v1.5.5\n | 'single' // Deprecated as of v1.5.5\n | 'singleGossip' // Deprecated as of v1.5.5\n | 'root' // Deprecated as of v1.5.5\n | 'max'; // Deprecated as of v1.5.5\n\n/**\n * A subset of Commitment levels, which are at least optimistically confirmed\n *
\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * 
\n */\nexport type Finality = 'confirmed' | 'finalized';\n\n/**\n * Filter for largest accounts query\n *
\n *   'circulating':    Return the largest accounts that are part of the circulating supply\n *   'nonCirculating': Return the largest accounts that are not part of the circulating supply\n * 
\n */\nexport type LargestAccountsFilter = 'circulating' | 'nonCirculating';\n\n/**\n * Configuration object for changing `getAccountInfo` query behavior\n */\nexport type GetAccountInfoConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n /** Optional data slice to limit the returned account data */\n dataSlice?: DataSlice;\n};\n\n/**\n * Configuration object for changing `getBalance` query behavior\n */\nexport type GetBalanceConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\nexport type GetBlockConfig = {\n /** The level of finality desired */\n commitment?: Finality;\n /**\n * Whether to populate the rewards array. If parameter not provided, the default includes rewards.\n */\n rewards?: boolean;\n /**\n * Level of transaction detail to return, either \"full\", \"accounts\", \"signatures\", or \"none\". If\n * parameter not provided, the default detail level is \"full\". If \"accounts\" are requested,\n * transaction details only include signatures and an annotated list of accounts in each\n * transaction. Transaction metadata is limited to only: fee, err, pre_balances, post_balances,\n * pre_token_balances, and post_token_balances.\n */\n transactionDetails?: 'accounts' | 'full' | 'none' | 'signatures';\n};\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\nexport type GetVersionedBlockConfig = {\n /** The level of finality desired */\n commitment?: Finality;\n /** The max transaction version to return in responses. If the requested transaction is a higher version, an error will be returned */\n maxSupportedTransactionVersion?: number;\n /**\n * Whether to populate the rewards array. If parameter not provided, the default includes rewards.\n */\n rewards?: boolean;\n /**\n * Level of transaction detail to return, either \"full\", \"accounts\", \"signatures\", or \"none\". If\n * parameter not provided, the default detail level is \"full\". If \"accounts\" are requested,\n * transaction details only include signatures and an annotated list of accounts in each\n * transaction. Transaction metadata is limited to only: fee, err, pre_balances, post_balances,\n * pre_token_balances, and post_token_balances.\n */\n transactionDetails?: 'accounts' | 'full' | 'none' | 'signatures';\n};\n\n/**\n * Configuration object for changing `getStakeMinimumDelegation` query behavior\n */\nexport type GetStakeMinimumDelegationConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n};\n\n/**\n * Configuration object for changing `getBlockHeight` query behavior\n */\nexport type GetBlockHeightConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getEpochInfo` query behavior\n */\nexport type GetEpochInfoConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getInflationReward` query behavior\n */\nexport type GetInflationRewardConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** An epoch for which the reward occurs. If omitted, the previous epoch will be used */\n epoch?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getLatestBlockhash` query behavior\n */\nexport type GetLatestBlockhashConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getSlot` query behavior\n */\nexport type GetSlotConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getSlotLeader` query behavior\n */\nexport type GetSlotLeaderConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\nexport type GetTransactionConfig = {\n /** The level of finality desired */\n commitment?: Finality;\n};\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\nexport type GetVersionedTransactionConfig = {\n /** The level of finality desired */\n commitment?: Finality;\n /** The max transaction version to return in responses. If the requested transaction is a higher version, an error will be returned */\n maxSupportedTransactionVersion?: number;\n};\n\n/**\n * Configuration object for changing `getLargestAccounts` query behavior\n */\nexport type GetLargestAccountsConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** Filter largest accounts by whether they are part of the circulating supply */\n filter?: LargestAccountsFilter;\n};\n\n/**\n * Configuration object for changing `getSupply` request behavior\n */\nexport type GetSupplyConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** Exclude non circulating accounts list from response */\n excludeNonCirculatingAccountsList?: boolean;\n};\n\n/**\n * Configuration object for changing query behavior\n */\nexport type SignatureStatusConfig = {\n /** enable searching status history, not needed for recent transactions */\n searchTransactionHistory: boolean;\n};\n\n/**\n * Information describing a cluster node\n */\nexport type ContactInfo = {\n /** Identity public key of the node */\n pubkey: string;\n /** Gossip network address for the node */\n gossip: string | null;\n /** TPU network address for the node (null if not available) */\n tpu: string | null;\n /** JSON RPC network address for the node (null if not available) */\n rpc: string | null;\n /** Software version of the node (null if not available) */\n version: string | null;\n};\n\n/**\n * Information describing a vote account\n */\nexport type VoteAccountInfo = {\n /** Public key of the vote account */\n votePubkey: string;\n /** Identity public key of the node voting with this account */\n nodePubkey: string;\n /** The stake, in lamports, delegated to this vote account and activated */\n activatedStake: number;\n /** Whether the vote account is staked for this epoch */\n epochVoteAccount: boolean;\n /** Recent epoch voting credit history for this voter */\n epochCredits: Array<[number, number, number]>;\n /** A percentage (0-100) of rewards payout owed to the voter */\n commission: number;\n /** Most recent slot voted on by this vote account */\n lastVote: number;\n};\n\n/**\n * A collection of cluster vote accounts\n */\nexport type VoteAccountStatus = {\n /** Active vote accounts */\n current: Array;\n /** Inactive vote accounts */\n delinquent: Array;\n};\n\n/**\n * Network Inflation\n * (see https://docs.solana.com/implemented-proposals/ed_overview)\n */\nexport type InflationGovernor = {\n foundation: number;\n foundationTerm: number;\n initial: number;\n taper: number;\n terminal: number;\n};\n\nconst GetInflationGovernorResult = pick({\n foundation: number(),\n foundationTerm: number(),\n initial: number(),\n taper: number(),\n terminal: number(),\n});\n\n/**\n * The inflation reward for an epoch\n */\nexport type InflationReward = {\n /** epoch for which the reward occurs */\n epoch: number;\n /** the slot in which the rewards are effective */\n effectiveSlot: number;\n /** reward amount in lamports */\n amount: number;\n /** post balance of the account in lamports */\n postBalance: number;\n /** vote account commission when the reward was credited */\n commission?: number | null;\n};\n\n/**\n * Expected JSON RPC response for the \"getInflationReward\" message\n */\nconst GetInflationRewardResult = jsonRpcResult(\n array(\n nullable(\n pick({\n epoch: number(),\n effectiveSlot: number(),\n amount: number(),\n postBalance: number(),\n commission: optional(nullable(number())),\n }),\n ),\n ),\n);\n\nexport type RecentPrioritizationFees = {\n /** slot in which the fee was observed */\n slot: number;\n /** the per-compute-unit fee paid by at least one successfully landed transaction, specified in increments of 0.000001 lamports*/\n prioritizationFee: number;\n};\n\n/**\n * Configuration object for changing `getRecentPrioritizationFees` query behavior\n */\nexport type GetRecentPrioritizationFeesConfig = {\n /**\n * If this parameter is provided, the response will reflect a fee to land a transaction locking\n * all of the provided accounts as writable.\n */\n lockedWritableAccounts?: PublicKey[];\n};\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesResult = array(\n pick({\n slot: number(),\n prioritizationFee: number(),\n }),\n);\n\nexport type InflationRate = {\n /** total inflation */\n total: number;\n /** inflation allocated to validators */\n validator: number;\n /** inflation allocated to the foundation */\n foundation: number;\n /** epoch for which these values are valid */\n epoch: number;\n};\n\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateResult = pick({\n total: number(),\n validator: number(),\n foundation: number(),\n epoch: number(),\n});\n\n/**\n * Information about the current epoch\n */\nexport type EpochInfo = {\n epoch: number;\n slotIndex: number;\n slotsInEpoch: number;\n absoluteSlot: number;\n blockHeight?: number;\n transactionCount?: number;\n};\n\nconst GetEpochInfoResult = pick({\n epoch: number(),\n slotIndex: number(),\n slotsInEpoch: number(),\n absoluteSlot: number(),\n blockHeight: optional(number()),\n transactionCount: optional(number()),\n});\n\nconst GetEpochScheduleResult = pick({\n slotsPerEpoch: number(),\n leaderScheduleSlotOffset: number(),\n warmup: boolean(),\n firstNormalEpoch: number(),\n firstNormalSlot: number(),\n});\n\n/**\n * Leader schedule\n * (see https://docs.solana.com/terminology#leader-schedule)\n */\nexport type LeaderSchedule = {\n [address: string]: number[];\n};\n\nconst GetLeaderScheduleResult = record(string(), array(number()));\n\n/**\n * Transaction error or null\n */\nconst TransactionErrorResult = nullable(union([pick({}), string()]));\n\n/**\n * Signature status for a transaction\n */\nconst SignatureStatusResult = pick({\n err: TransactionErrorResult,\n});\n\n/**\n * Transaction signature received notification\n */\nconst SignatureReceivedResult = literal('receivedSignature');\n\n/**\n * Version info for a node\n */\nexport type Version = {\n /** Version of solana-core */\n 'solana-core': string;\n 'feature-set'?: number;\n};\n\nconst VersionResult = pick({\n 'solana-core': string(),\n 'feature-set': optional(number()),\n});\n\nexport type SimulatedTransactionAccountInfo = {\n /** `true` if this account's data contains a loaded program */\n executable: boolean;\n /** Identifier of the program that owns the account */\n owner: string;\n /** Number of lamports assigned to the account */\n lamports: number;\n /** Optional data assigned to the account */\n data: string[];\n /** Optional rent epoch info for account */\n rentEpoch?: number;\n};\n\nexport type TransactionReturnDataEncoding = 'base64';\n\nexport type TransactionReturnData = {\n programId: string;\n data: [string, TransactionReturnDataEncoding];\n};\n\nexport type SimulateTransactionConfig = {\n /** Optional parameter used to enable signature verification before simulation */\n sigVerify?: boolean;\n /** Optional parameter used to replace the simulated transaction's recent blockhash with the latest blockhash */\n replaceRecentBlockhash?: boolean;\n /** Optional parameter used to set the commitment level when selecting the latest block */\n commitment?: Commitment;\n /** Optional parameter used to specify a list of account addresses to return post simulation state for */\n accounts?: {\n encoding: 'base64';\n addresses: string[];\n };\n /** Optional parameter used to specify the minimum block slot that can be used for simulation */\n minContextSlot?: number;\n};\n\nexport type SimulatedTransactionResponse = {\n err: TransactionError | string | null;\n logs: Array | null;\n accounts?: (SimulatedTransactionAccountInfo | null)[] | null;\n unitsConsumed?: number;\n returnData?: TransactionReturnData | null;\n};\nconst SimulatedTransactionResponseStruct = jsonRpcResultAndContext(\n pick({\n err: nullable(union([pick({}), string()])),\n logs: nullable(array(string())),\n accounts: optional(\n nullable(\n array(\n nullable(\n pick({\n executable: boolean(),\n owner: string(),\n lamports: number(),\n data: array(string()),\n rentEpoch: optional(number()),\n }),\n ),\n ),\n ),\n ),\n unitsConsumed: optional(number()),\n returnData: optional(\n nullable(\n pick({\n programId: string(),\n data: tuple([string(), literal('base64')]),\n }),\n ),\n ),\n }),\n);\n\nexport type ParsedInnerInstruction = {\n index: number;\n instructions: (ParsedInstruction | PartiallyDecodedInstruction)[];\n};\n\nexport type TokenBalance = {\n accountIndex: number;\n mint: string;\n owner?: string;\n uiTokenAmount: TokenAmount;\n};\n\n/**\n * Metadata for a parsed confirmed transaction on the ledger\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link ParsedTransactionMeta} instead.\n */\nexport type ParsedConfirmedTransactionMeta = ParsedTransactionMeta;\n\n/**\n * Collection of addresses loaded by a transaction using address table lookups\n */\nexport type LoadedAddresses = {\n writable: Array;\n readonly: Array;\n};\n\n/**\n * Metadata for a parsed transaction on the ledger\n */\nexport type ParsedTransactionMeta = {\n /** The fee charged for processing the transaction */\n fee: number;\n /** An array of cross program invoked parsed instructions */\n innerInstructions?: ParsedInnerInstruction[] | null;\n /** The balances of the transaction accounts before processing */\n preBalances: Array;\n /** The balances of the transaction accounts after processing */\n postBalances: Array;\n /** An array of program log messages emitted during a transaction */\n logMessages?: Array | null;\n /** The token balances of the transaction accounts before processing */\n preTokenBalances?: Array | null;\n /** The token balances of the transaction accounts after processing */\n postTokenBalances?: Array | null;\n /** The error result of transaction processing */\n err: TransactionError | null;\n /** The collection of addresses loaded using address lookup tables */\n loadedAddresses?: LoadedAddresses;\n /** The compute units consumed after processing the transaction */\n computeUnitsConsumed?: number;\n};\n\nexport type CompiledInnerInstruction = {\n index: number;\n instructions: CompiledInstruction[];\n};\n\n/**\n * Metadata for a confirmed transaction on the ledger\n */\nexport type ConfirmedTransactionMeta = {\n /** The fee charged for processing the transaction */\n fee: number;\n /** An array of cross program invoked instructions */\n innerInstructions?: CompiledInnerInstruction[] | null;\n /** The balances of the transaction accounts before processing */\n preBalances: Array;\n /** The balances of the transaction accounts after processing */\n postBalances: Array;\n /** An array of program log messages emitted during a transaction */\n logMessages?: Array | null;\n /** The token balances of the transaction accounts before processing */\n preTokenBalances?: Array | null;\n /** The token balances of the transaction accounts after processing */\n postTokenBalances?: Array | null;\n /** The error result of transaction processing */\n err: TransactionError | null;\n /** The collection of addresses loaded using address lookup tables */\n loadedAddresses?: LoadedAddresses;\n /** The compute units consumed after processing the transaction */\n computeUnitsConsumed?: number;\n};\n\n/**\n * A processed transaction from the RPC API\n */\nexport type TransactionResponse = {\n /** The slot during which the transaction was processed */\n slot: number;\n /** The transaction */\n transaction: {\n /** The transaction message */\n message: Message;\n /** The transaction signatures */\n signatures: string[];\n };\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n};\n\n/**\n * A processed transaction from the RPC API\n */\nexport type VersionedTransactionResponse = {\n /** The slot during which the transaction was processed */\n slot: number;\n /** The transaction */\n transaction: {\n /** The transaction message */\n message: VersionedMessage;\n /** The transaction signatures */\n signatures: string[];\n };\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n /** The transaction version */\n version?: TransactionVersion;\n};\n\n/**\n * A processed transaction message from the RPC API\n */\ntype MessageResponse = {\n accountKeys: string[];\n header: MessageHeader;\n instructions: CompiledInstruction[];\n recentBlockhash: string;\n addressTableLookups?: ParsedAddressTableLookup[];\n};\n\n/**\n * A confirmed transaction on the ledger\n *\n * @deprecated Deprecated since Solana v1.8.0.\n */\nexport type ConfirmedTransaction = {\n /** The slot during which the transaction was processed */\n slot: number;\n /** The details of the transaction */\n transaction: Transaction;\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n};\n\n/**\n * A partially decoded transaction instruction\n */\nexport type PartiallyDecodedInstruction = {\n /** Program id called by this instruction */\n programId: PublicKey;\n /** Public keys of accounts passed to this instruction */\n accounts: Array;\n /** Raw base-58 instruction data */\n data: string;\n};\n\n/**\n * A parsed transaction message account\n */\nexport type ParsedMessageAccount = {\n /** Public key of the account */\n pubkey: PublicKey;\n /** Indicates if the account signed the transaction */\n signer: boolean;\n /** Indicates if the account is writable for this transaction */\n writable: boolean;\n /** Indicates if the account key came from the transaction or a lookup table */\n source?: 'transaction' | 'lookupTable';\n};\n\n/**\n * A parsed transaction instruction\n */\nexport type ParsedInstruction = {\n /** Name of the program for this instruction */\n program: string;\n /** ID of the program for this instruction */\n programId: PublicKey;\n /** Parsed instruction info */\n parsed: any;\n};\n\n/**\n * A parsed address table lookup\n */\nexport type ParsedAddressTableLookup = {\n /** Address lookup table account key */\n accountKey: PublicKey;\n /** Parsed instruction info */\n writableIndexes: number[];\n /** Parsed instruction info */\n readonlyIndexes: number[];\n};\n\n/**\n * A parsed transaction message\n */\nexport type ParsedMessage = {\n /** Accounts used in the instructions */\n accountKeys: ParsedMessageAccount[];\n /** The atomically executed instructions for the transaction */\n instructions: (ParsedInstruction | PartiallyDecodedInstruction)[];\n /** Recent blockhash */\n recentBlockhash: string;\n /** Address table lookups used to load additional accounts */\n addressTableLookups?: ParsedAddressTableLookup[] | null;\n};\n\n/**\n * A parsed transaction\n */\nexport type ParsedTransaction = {\n /** Signatures for the transaction */\n signatures: Array;\n /** Message of the transaction */\n message: ParsedMessage;\n};\n\n/**\n * A parsed and confirmed transaction on the ledger\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link ParsedTransactionWithMeta} instead.\n */\nexport type ParsedConfirmedTransaction = ParsedTransactionWithMeta;\n\n/**\n * A parsed transaction on the ledger with meta\n */\nexport type ParsedTransactionWithMeta = {\n /** The slot during which the transaction was processed */\n slot: number;\n /** The details of the transaction */\n transaction: ParsedTransaction;\n /** Metadata produced from the transaction */\n meta: ParsedTransactionMeta | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n /** The version of the transaction message */\n version?: TransactionVersion;\n};\n\n/**\n * A processed block fetched from the RPC API\n */\nexport type BlockResponse = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of transactions with status meta and original message */\n transactions: Array<{\n /** The transaction */\n transaction: {\n /** The transaction message */\n message: Message;\n /** The transaction signatures */\n signatures: string[];\n };\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The transaction version */\n version?: TransactionVersion;\n }>;\n /** Vector of block rewards */\n rewards?: Array<{\n /** Public key of reward recipient */\n pubkey: string;\n /** Reward value in lamports */\n lamports: number;\n /** Account balance after reward is applied */\n postBalance: number | null;\n /** Type of reward received */\n rewardType: string | null;\n /** Vote account commission when the reward was credited, only present for voting and staking rewards */\n commission?: number | null;\n }>;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n};\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\nexport type AccountsModeBlockResponse = VersionedAccountsModeBlockResponse;\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\nexport type NoneModeBlockResponse = VersionedNoneModeBlockResponse;\n\n/**\n * A block with parsed transactions\n */\nexport type ParsedBlockResponse = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of transactions with status meta and original message */\n transactions: Array<{\n /** The details of the transaction */\n transaction: ParsedTransaction;\n /** Metadata produced from the transaction */\n meta: ParsedTransactionMeta | null;\n /** The transaction version */\n version?: TransactionVersion;\n }>;\n /** Vector of block rewards */\n rewards?: Array<{\n /** Public key of reward recipient */\n pubkey: string;\n /** Reward value in lamports */\n lamports: number;\n /** Account balance after reward is applied */\n postBalance: number | null;\n /** Type of reward received */\n rewardType: string | null;\n /** Vote account commission when the reward was credited, only present for voting and staking rewards */\n commission?: number | null;\n }>;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n /** The number of blocks beneath this block */\n blockHeight: number | null;\n};\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `accounts`\n */\nexport type ParsedAccountsModeBlockResponse = Omit<\n ParsedBlockResponse,\n 'transactions'\n> & {\n transactions: Array<\n Omit & {\n transaction: Pick<\n ParsedBlockResponse['transactions'][number]['transaction'],\n 'signatures'\n > & {\n accountKeys: ParsedMessageAccount[];\n };\n }\n >;\n};\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `none`\n */\nexport type ParsedNoneModeBlockResponse = Omit<\n ParsedBlockResponse,\n 'transactions'\n>;\n\n/**\n * A processed block fetched from the RPC API\n */\nexport type VersionedBlockResponse = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of transactions with status meta and original message */\n transactions: Array<{\n /** The transaction */\n transaction: {\n /** The transaction message */\n message: VersionedMessage;\n /** The transaction signatures */\n signatures: string[];\n };\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The transaction version */\n version?: TransactionVersion;\n }>;\n /** Vector of block rewards */\n rewards?: Array<{\n /** Public key of reward recipient */\n pubkey: string;\n /** Reward value in lamports */\n lamports: number;\n /** Account balance after reward is applied */\n postBalance: number | null;\n /** Type of reward received */\n rewardType: string | null;\n /** Vote account commission when the reward was credited, only present for voting and staking rewards */\n commission?: number | null;\n }>;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n};\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\nexport type VersionedAccountsModeBlockResponse = Omit<\n VersionedBlockResponse,\n 'transactions'\n> & {\n transactions: Array<\n Omit & {\n transaction: Pick<\n VersionedBlockResponse['transactions'][number]['transaction'],\n 'signatures'\n > & {\n accountKeys: ParsedMessageAccount[];\n };\n }\n >;\n};\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\nexport type VersionedNoneModeBlockResponse = Omit<\n VersionedBlockResponse,\n 'transactions'\n>;\n\n/**\n * A confirmed block on the ledger\n *\n * @deprecated Deprecated since Solana v1.8.0.\n */\nexport type ConfirmedBlock = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of transactions and status metas */\n transactions: Array<{\n transaction: Transaction;\n meta: ConfirmedTransactionMeta | null;\n }>;\n /** Vector of block rewards */\n rewards?: Array<{\n pubkey: string;\n lamports: number;\n postBalance: number | null;\n rewardType: string | null;\n commission?: number | null;\n }>;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n};\n\n/**\n * A Block on the ledger with signatures only\n */\nexport type BlockSignatures = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of signatures */\n signatures: Array;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n};\n\n/**\n * recent block production information\n */\nexport type BlockProduction = Readonly<{\n /** a dictionary of validator identities, as base-58 encoded strings. Value is a two element array containing the number of leader slots and the number of blocks produced */\n byIdentity: Readonly>>;\n /** Block production slot range */\n range: Readonly<{\n /** first slot of the block production information (inclusive) */\n firstSlot: number;\n /** last slot of block production information (inclusive) */\n lastSlot: number;\n }>;\n}>;\n\nexport type GetBlockProductionConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** Slot range to return block production for. If parameter not provided, defaults to current epoch. */\n range?: {\n /** first slot to return block production information for (inclusive) */\n firstSlot: number;\n /** last slot to return block production information for (inclusive). If parameter not provided, defaults to the highest slot */\n lastSlot?: number;\n };\n /** Only return results for this validator identity (base-58 encoded) */\n identity?: string;\n};\n\n/**\n * Expected JSON RPC response for the \"getBlockProduction\" message\n */\nconst BlockProductionResponseStruct = jsonRpcResultAndContext(\n pick({\n byIdentity: record(string(), array(number())),\n range: pick({\n firstSlot: number(),\n lastSlot: number(),\n }),\n }),\n);\n\n/**\n * A performance sample\n */\nexport type PerfSample = {\n /** Slot number of sample */\n slot: number;\n /** Number of transactions in a sample window */\n numTransactions: number;\n /** Number of slots in a sample window */\n numSlots: number;\n /** Sample window in seconds */\n samplePeriodSecs: number;\n};\n\nfunction createRpcClient(\n url: string,\n httpHeaders?: HttpHeaders,\n customFetch?: FetchFn,\n fetchMiddleware?: FetchMiddleware,\n disableRetryOnRateLimit?: boolean,\n httpAgent?: NodeHttpAgent | NodeHttpsAgent | false,\n): RpcClient {\n const fetch = customFetch ? customFetch : fetchImpl;\n let agent: NodeHttpAgent | NodeHttpsAgent | undefined;\n if (process.env.BROWSER) {\n if (httpAgent != null) {\n console.warn(\n 'You have supplied an `httpAgent` when creating a `Connection` in a browser environment.' +\n 'It has been ignored; `httpAgent` is only used in Node environments.',\n );\n }\n } else {\n if (httpAgent == null) {\n if (process.env.NODE_ENV !== 'test') {\n const agentOptions = {\n // One second fewer than the Solana RPC's keepalive timeout.\n // Read more: https://github.com/solana-labs/solana/issues/27859#issuecomment-1340097889\n freeSocketTimeout: 19000,\n keepAlive: true,\n maxSockets: 25,\n };\n if (url.startsWith('https:')) {\n agent = new HttpsKeepAliveAgent(agentOptions);\n } else {\n agent = new HttpKeepAliveAgent(agentOptions);\n }\n }\n } else {\n if (httpAgent !== false) {\n const isHttps = url.startsWith('https:');\n if (isHttps && !(httpAgent instanceof NodeHttpsAgent)) {\n throw new Error(\n 'The endpoint `' +\n url +\n '` can only be paired with an `https.Agent`. You have, instead, supplied an ' +\n '`http.Agent` through `httpAgent`.',\n );\n } else if (!isHttps && httpAgent instanceof NodeHttpsAgent) {\n throw new Error(\n 'The endpoint `' +\n url +\n '` can only be paired with an `http.Agent`. You have, instead, supplied an ' +\n '`https.Agent` through `httpAgent`.',\n );\n }\n agent = httpAgent;\n }\n }\n }\n\n let fetchWithMiddleware: FetchFn | undefined;\n\n if (fetchMiddleware) {\n fetchWithMiddleware = async (info, init) => {\n const modifiedFetchArgs = await new Promise>(\n (resolve, reject) => {\n try {\n fetchMiddleware(info, init, (modifiedInfo, modifiedInit) =>\n resolve([modifiedInfo, modifiedInit]),\n );\n } catch (error) {\n reject(error);\n }\n },\n );\n return await fetch(...modifiedFetchArgs);\n };\n }\n\n const clientBrowser = new RpcClient(async (request, callback) => {\n const options = {\n method: 'POST',\n body: request,\n agent,\n headers: Object.assign(\n {\n 'Content-Type': 'application/json',\n },\n httpHeaders || {},\n COMMON_HTTP_HEADERS,\n ),\n };\n\n try {\n let too_many_requests_retries = 5;\n let res: Response;\n let waitTime = 500;\n for (;;) {\n if (fetchWithMiddleware) {\n res = await fetchWithMiddleware(url, options);\n } else {\n res = await fetch(url, options);\n }\n\n if (res.status !== 429 /* Too many requests */) {\n break;\n }\n if (disableRetryOnRateLimit === true) {\n break;\n }\n too_many_requests_retries -= 1;\n if (too_many_requests_retries === 0) {\n break;\n }\n console.log(\n `Server responded with ${res.status} ${res.statusText}. Retrying after ${waitTime}ms delay...`,\n );\n await sleep(waitTime);\n waitTime *= 2;\n }\n\n const text = await res.text();\n if (res.ok) {\n callback(null, text);\n } else {\n callback(new Error(`${res.status} ${res.statusText}: ${text}`));\n }\n } catch (err) {\n if (err instanceof Error) callback(err);\n }\n }, {});\n\n return clientBrowser;\n}\n\nfunction createRpcRequest(client: RpcClient): RpcRequest {\n return (method, args) => {\n return new Promise((resolve, reject) => {\n client.request(method, args, (err: any, response: any) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(response);\n });\n });\n };\n}\n\nfunction createRpcBatchRequest(client: RpcClient): RpcBatchRequest {\n return (requests: RpcParams[]) => {\n return new Promise((resolve, reject) => {\n // Do nothing if requests is empty\n if (requests.length === 0) resolve([]);\n\n const batch = requests.map((params: RpcParams) => {\n return client.request(params.methodName, params.args);\n });\n\n client.request(batch, (err: any, response: any) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(response);\n });\n });\n };\n}\n\n/**\n * Expected JSON RPC response for the \"getInflationGovernor\" message\n */\nconst GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult);\n\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateRpcResult = jsonRpcResult(GetInflationRateResult);\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesRpcResult = jsonRpcResult(\n GetRecentPrioritizationFeesResult,\n);\n\n/**\n * Expected JSON RPC response for the \"getEpochInfo\" message\n */\nconst GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult);\n\n/**\n * Expected JSON RPC response for the \"getEpochSchedule\" message\n */\nconst GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"getLeaderSchedule\" message\n */\nconst GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"minimumLedgerSlot\" and \"getFirstAvailableBlock\" messages\n */\nconst SlotRpcResult = jsonRpcResult(number());\n\n/**\n * Supply\n */\nexport type Supply = {\n /** Total supply in lamports */\n total: number;\n /** Circulating supply in lamports */\n circulating: number;\n /** Non-circulating supply in lamports */\n nonCirculating: number;\n /** List of non-circulating account addresses */\n nonCirculatingAccounts: Array;\n};\n\n/**\n * Expected JSON RPC response for the \"getSupply\" message\n */\nconst GetSupplyRpcResult = jsonRpcResultAndContext(\n pick({\n total: number(),\n circulating: number(),\n nonCirculating: number(),\n nonCirculatingAccounts: array(PublicKeyFromString),\n }),\n);\n\n/**\n * Token amount object which returns a token amount in different formats\n * for various client use cases.\n */\nexport type TokenAmount = {\n /** Raw amount of tokens as string ignoring decimals */\n amount: string;\n /** Number of decimals configured for token's mint */\n decimals: number;\n /** Token amount as float, accounts for decimals */\n uiAmount: number | null;\n /** Token amount as string, accounts for decimals */\n uiAmountString?: string;\n};\n\n/**\n * Expected JSON RPC structure for token amounts\n */\nconst TokenAmountResult = pick({\n amount: string(),\n uiAmount: nullable(number()),\n decimals: number(),\n uiAmountString: optional(string()),\n});\n\n/**\n * Token address and balance.\n */\nexport type TokenAccountBalancePair = {\n /** Address of the token account */\n address: PublicKey;\n /** Raw amount of tokens as string ignoring decimals */\n amount: string;\n /** Number of decimals configured for token's mint */\n decimals: number;\n /** Token amount as float, accounts for decimals */\n uiAmount: number | null;\n /** Token amount as string, accounts for decimals */\n uiAmountString?: string;\n};\n\n/**\n * Expected JSON RPC response for the \"getTokenLargestAccounts\" message\n */\nconst GetTokenLargestAccountsResult = jsonRpcResultAndContext(\n array(\n pick({\n address: PublicKeyFromString,\n amount: string(),\n uiAmount: nullable(number()),\n decimals: number(),\n uiAmountString: optional(string()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message\n */\nconst GetTokenAccountsByOwner = jsonRpcResultAndContext(\n array(\n pick({\n pubkey: PublicKeyFromString,\n account: pick({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: BufferFromRawAccountData,\n rentEpoch: number(),\n }),\n }),\n ),\n);\n\nconst ParsedAccountDataResult = pick({\n program: string(),\n parsed: unknown(),\n space: number(),\n});\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message with parsed data\n */\nconst GetParsedTokenAccountsByOwner = jsonRpcResultAndContext(\n array(\n pick({\n pubkey: PublicKeyFromString,\n account: pick({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: ParsedAccountDataResult,\n rentEpoch: number(),\n }),\n }),\n ),\n);\n\n/**\n * Pair of an account address and its balance\n */\nexport type AccountBalancePair = {\n address: PublicKey;\n lamports: number;\n};\n\n/**\n * Expected JSON RPC response for the \"getLargestAccounts\" message\n */\nconst GetLargestAccountsRpcResult = jsonRpcResultAndContext(\n array(\n pick({\n lamports: number(),\n address: PublicKeyFromString,\n }),\n ),\n);\n\n/**\n * @internal\n */\nconst AccountInfoResult = pick({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: BufferFromRawAccountData,\n rentEpoch: number(),\n});\n\n/**\n * @internal\n */\nconst KeyedAccountInfoResult = pick({\n pubkey: PublicKeyFromString,\n account: AccountInfoResult,\n});\n\nconst ParsedOrRawAccountData = coerce(\n union([instance(Buffer), ParsedAccountDataResult]),\n union([RawAccountDataResult, ParsedAccountDataResult]),\n value => {\n if (Array.isArray(value)) {\n return create(value, BufferFromRawAccountData);\n } else {\n return value;\n }\n },\n);\n\n/**\n * @internal\n */\nconst ParsedAccountInfoResult = pick({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: ParsedOrRawAccountData,\n rentEpoch: number(),\n});\n\nconst KeyedParsedAccountInfoResult = pick({\n pubkey: PublicKeyFromString,\n account: ParsedAccountInfoResult,\n});\n\n/**\n * @internal\n */\nconst StakeActivationResult = pick({\n state: union([\n literal('active'),\n literal('inactive'),\n literal('activating'),\n literal('deactivating'),\n ]),\n active: number(),\n inactive: number(),\n});\n\n/**\n * Expected JSON RPC response for the \"getConfirmedSignaturesForAddress2\" message\n */\n\nconst GetConfirmedSignaturesForAddress2RpcResult = jsonRpcResult(\n array(\n pick({\n signature: string(),\n slot: number(),\n err: TransactionErrorResult,\n memo: nullable(string()),\n blockTime: optional(nullable(number())),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getSignaturesForAddress\" message\n */\nconst GetSignaturesForAddressRpcResult = jsonRpcResult(\n array(\n pick({\n signature: string(),\n slot: number(),\n err: TransactionErrorResult,\n memo: nullable(string()),\n blockTime: optional(nullable(number())),\n }),\n ),\n);\n\n/***\n * Expected JSON RPC response for the \"accountNotification\" message\n */\nconst AccountNotificationResult = pick({\n subscription: number(),\n result: notificationResultAndContext(AccountInfoResult),\n});\n\n/**\n * @internal\n */\nconst ProgramAccountInfoResult = pick({\n pubkey: PublicKeyFromString,\n account: AccountInfoResult,\n});\n\n/***\n * Expected JSON RPC response for the \"programNotification\" message\n */\nconst ProgramAccountNotificationResult = pick({\n subscription: number(),\n result: notificationResultAndContext(ProgramAccountInfoResult),\n});\n\n/**\n * @internal\n */\nconst SlotInfoResult = pick({\n parent: number(),\n slot: number(),\n root: number(),\n});\n\n/**\n * Expected JSON RPC response for the \"slotNotification\" message\n */\nconst SlotNotificationResult = pick({\n subscription: number(),\n result: SlotInfoResult,\n});\n\n/**\n * Slot updates which can be used for tracking the live progress of a cluster.\n * - `\"firstShredReceived\"`: connected node received the first shred of a block.\n * Indicates that a new block that is being produced.\n * - `\"completed\"`: connected node has received all shreds of a block. Indicates\n * a block was recently produced.\n * - `\"optimisticConfirmation\"`: block was optimistically confirmed by the\n * cluster. It is not guaranteed that an optimistic confirmation notification\n * will be sent for every finalized blocks.\n * - `\"root\"`: the connected node rooted this block.\n * - `\"createdBank\"`: the connected node has started validating this block.\n * - `\"frozen\"`: the connected node has validated this block.\n * - `\"dead\"`: the connected node failed to validate this block.\n */\nexport type SlotUpdate =\n | {\n type: 'firstShredReceived';\n slot: number;\n timestamp: number;\n }\n | {\n type: 'completed';\n slot: number;\n timestamp: number;\n }\n | {\n type: 'createdBank';\n slot: number;\n timestamp: number;\n parent: number;\n }\n | {\n type: 'frozen';\n slot: number;\n timestamp: number;\n stats: {\n numTransactionEntries: number;\n numSuccessfulTransactions: number;\n numFailedTransactions: number;\n maxTransactionsPerEntry: number;\n };\n }\n | {\n type: 'dead';\n slot: number;\n timestamp: number;\n err: string;\n }\n | {\n type: 'optimisticConfirmation';\n slot: number;\n timestamp: number;\n }\n | {\n type: 'root';\n slot: number;\n timestamp: number;\n };\n\n/**\n * @internal\n */\nconst SlotUpdateResult = union([\n pick({\n type: union([\n literal('firstShredReceived'),\n literal('completed'),\n literal('optimisticConfirmation'),\n literal('root'),\n ]),\n slot: number(),\n timestamp: number(),\n }),\n pick({\n type: literal('createdBank'),\n parent: number(),\n slot: number(),\n timestamp: number(),\n }),\n pick({\n type: literal('frozen'),\n slot: number(),\n timestamp: number(),\n stats: pick({\n numTransactionEntries: number(),\n numSuccessfulTransactions: number(),\n numFailedTransactions: number(),\n maxTransactionsPerEntry: number(),\n }),\n }),\n pick({\n type: literal('dead'),\n slot: number(),\n timestamp: number(),\n err: string(),\n }),\n]);\n\n/**\n * Expected JSON RPC response for the \"slotsUpdatesNotification\" message\n */\nconst SlotUpdateNotificationResult = pick({\n subscription: number(),\n result: SlotUpdateResult,\n});\n\n/**\n * Expected JSON RPC response for the \"signatureNotification\" message\n */\nconst SignatureNotificationResult = pick({\n subscription: number(),\n result: notificationResultAndContext(\n union([SignatureStatusResult, SignatureReceivedResult]),\n ),\n});\n\n/**\n * Expected JSON RPC response for the \"rootNotification\" message\n */\nconst RootNotificationResult = pick({\n subscription: number(),\n result: number(),\n});\n\nconst ContactInfoResult = pick({\n pubkey: string(),\n gossip: nullable(string()),\n tpu: nullable(string()),\n rpc: nullable(string()),\n version: nullable(string()),\n});\n\nconst VoteAccountInfoResult = pick({\n votePubkey: string(),\n nodePubkey: string(),\n activatedStake: number(),\n epochVoteAccount: boolean(),\n epochCredits: array(tuple([number(), number(), number()])),\n commission: number(),\n lastVote: number(),\n rootSlot: nullable(number()),\n});\n\n/**\n * Expected JSON RPC response for the \"getVoteAccounts\" message\n */\nconst GetVoteAccounts = jsonRpcResult(\n pick({\n current: array(VoteAccountInfoResult),\n delinquent: array(VoteAccountInfoResult),\n }),\n);\n\nconst ConfirmationStatus = union([\n literal('processed'),\n literal('confirmed'),\n literal('finalized'),\n]);\n\nconst SignatureStatusResponse = pick({\n slot: number(),\n confirmations: nullable(number()),\n err: TransactionErrorResult,\n confirmationStatus: optional(ConfirmationStatus),\n});\n\n/**\n * Expected JSON RPC response for the \"getSignatureStatuses\" message\n */\nconst GetSignatureStatusesRpcResult = jsonRpcResultAndContext(\n array(nullable(SignatureStatusResponse)),\n);\n\n/**\n * Expected JSON RPC response for the \"getMinimumBalanceForRentExemption\" message\n */\nconst GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number());\n\nconst AddressTableLookupStruct = pick({\n accountKey: PublicKeyFromString,\n writableIndexes: array(number()),\n readonlyIndexes: array(number()),\n});\n\nconst ConfirmedTransactionResult = pick({\n signatures: array(string()),\n message: pick({\n accountKeys: array(string()),\n header: pick({\n numRequiredSignatures: number(),\n numReadonlySignedAccounts: number(),\n numReadonlyUnsignedAccounts: number(),\n }),\n instructions: array(\n pick({\n accounts: array(number()),\n data: string(),\n programIdIndex: number(),\n }),\n ),\n recentBlockhash: string(),\n addressTableLookups: optional(array(AddressTableLookupStruct)),\n }),\n});\n\nconst AnnotatedAccountKey = pick({\n pubkey: PublicKeyFromString,\n signer: boolean(),\n writable: boolean(),\n source: optional(union([literal('transaction'), literal('lookupTable')])),\n});\n\nconst ConfirmedTransactionAccountsModeResult = pick({\n accountKeys: array(AnnotatedAccountKey),\n signatures: array(string()),\n});\n\nconst ParsedInstructionResult = pick({\n parsed: unknown(),\n program: string(),\n programId: PublicKeyFromString,\n});\n\nconst RawInstructionResult = pick({\n accounts: array(PublicKeyFromString),\n data: string(),\n programId: PublicKeyFromString,\n});\n\nconst InstructionResult = union([\n RawInstructionResult,\n ParsedInstructionResult,\n]);\n\nconst UnknownInstructionResult = union([\n pick({\n parsed: unknown(),\n program: string(),\n programId: string(),\n }),\n pick({\n accounts: array(string()),\n data: string(),\n programId: string(),\n }),\n]);\n\nconst ParsedOrRawInstruction = coerce(\n InstructionResult,\n UnknownInstructionResult,\n value => {\n if ('accounts' in value) {\n return create(value, RawInstructionResult);\n } else {\n return create(value, ParsedInstructionResult);\n }\n },\n);\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionResult = pick({\n signatures: array(string()),\n message: pick({\n accountKeys: array(AnnotatedAccountKey),\n instructions: array(ParsedOrRawInstruction),\n recentBlockhash: string(),\n addressTableLookups: optional(nullable(array(AddressTableLookupStruct))),\n }),\n});\n\nconst TokenBalanceResult = pick({\n accountIndex: number(),\n mint: string(),\n owner: optional(string()),\n uiTokenAmount: TokenAmountResult,\n});\n\nconst LoadedAddressesResult = pick({\n writable: array(PublicKeyFromString),\n readonly: array(PublicKeyFromString),\n});\n\n/**\n * @internal\n */\nconst ConfirmedTransactionMetaResult = pick({\n err: TransactionErrorResult,\n fee: number(),\n innerInstructions: optional(\n nullable(\n array(\n pick({\n index: number(),\n instructions: array(\n pick({\n accounts: array(number()),\n data: string(),\n programIdIndex: number(),\n }),\n ),\n }),\n ),\n ),\n ),\n preBalances: array(number()),\n postBalances: array(number()),\n logMessages: optional(nullable(array(string()))),\n preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n loadedAddresses: optional(LoadedAddressesResult),\n computeUnitsConsumed: optional(number()),\n});\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionMetaResult = pick({\n err: TransactionErrorResult,\n fee: number(),\n innerInstructions: optional(\n nullable(\n array(\n pick({\n index: number(),\n instructions: array(ParsedOrRawInstruction),\n }),\n ),\n ),\n ),\n preBalances: array(number()),\n postBalances: array(number()),\n logMessages: optional(nullable(array(string()))),\n preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n loadedAddresses: optional(LoadedAddressesResult),\n computeUnitsConsumed: optional(number()),\n});\n\nconst TransactionVersionStruct = union([literal(0), literal('legacy')]);\n\n/** @internal */\nconst RewardsResult = pick({\n pubkey: string(),\n lamports: number(),\n postBalance: nullable(number()),\n rewardType: nullable(string()),\n commission: optional(nullable(number())),\n});\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ConfirmedTransactionResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `none`\n */\nconst GetNoneModeBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `accounts`\n */\nconst GetAccountsModeBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ConfirmedTransactionAccountsModeResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message\n */\nconst GetParsedBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ParsedConfirmedTransactionResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message when `transactionDetails` is `accounts`\n */\nconst GetParsedAccountsModeBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ConfirmedTransactionAccountsModeResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message when `transactionDetails` is `none`\n */\nconst GetParsedNoneModeBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getConfirmedBlock\" message\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetBlockRpcResult} instead.\n */\nconst GetConfirmedBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ConfirmedTransactionResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockSignaturesRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n signatures: array(string()),\n blockTime: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getTransaction\" message\n */\nconst GetTransactionRpcResult = jsonRpcResult(\n nullable(\n pick({\n slot: number(),\n meta: ConfirmedTransactionMetaResult,\n blockTime: optional(nullable(number())),\n transaction: ConfirmedTransactionResult,\n version: optional(TransactionVersionStruct),\n }),\n ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getTransaction\" message\n */\nconst GetParsedTransactionRpcResult = jsonRpcResult(\n nullable(\n pick({\n slot: number(),\n transaction: ParsedConfirmedTransactionResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n blockTime: optional(nullable(number())),\n version: optional(TransactionVersionStruct),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getRecentBlockhash\" message\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetLatestBlockhashRpcResult} instead.\n */\nconst GetRecentBlockhashAndContextRpcResult = jsonRpcResultAndContext(\n pick({\n blockhash: string(),\n feeCalculator: pick({\n lamportsPerSignature: number(),\n }),\n }),\n);\n\n/**\n * Expected JSON RPC response for the \"getLatestBlockhash\" message\n */\nconst GetLatestBlockhashRpcResult = jsonRpcResultAndContext(\n pick({\n blockhash: string(),\n lastValidBlockHeight: number(),\n }),\n);\n\nconst PerfSampleResult = pick({\n slot: number(),\n numTransactions: number(),\n numSlots: number(),\n samplePeriodSecs: number(),\n});\n\n/*\n * Expected JSON RPC response for \"getRecentPerformanceSamples\" message\n */\nconst GetRecentPerformanceSamplesRpcResult = jsonRpcResult(\n array(PerfSampleResult),\n);\n\n/**\n * Expected JSON RPC response for the \"getFeeCalculatorForBlockhash\" message\n */\nconst GetFeeCalculatorRpcResult = jsonRpcResultAndContext(\n nullable(\n pick({\n feeCalculator: pick({\n lamportsPerSignature: number(),\n }),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"requestAirdrop\" message\n */\nconst RequestAirdropRpcResult = jsonRpcResult(string());\n\n/**\n * Expected JSON RPC response for the \"sendTransaction\" message\n */\nconst SendTransactionRpcResult = jsonRpcResult(string());\n\n/**\n * Information about the latest slot being processed by a node\n */\nexport type SlotInfo = {\n /** Currently processing slot */\n slot: number;\n /** Parent of the current slot */\n parent: number;\n /** The root block of the current slot's fork */\n root: number;\n};\n\n/**\n * Parsed account data\n */\nexport type ParsedAccountData = {\n /** Name of the program that owns this account */\n program: string;\n /** Parsed account data */\n parsed: any;\n /** Space used by account data */\n space: number;\n};\n\n/**\n * Stake Activation data\n */\nexport type StakeActivationData = {\n /** the stake account's activation state */\n state: 'active' | 'inactive' | 'activating' | 'deactivating';\n /** stake active during the epoch */\n active: number;\n /** stake inactive during the epoch */\n inactive: number;\n};\n\n/**\n * Data slice argument for getProgramAccounts\n */\nexport type DataSlice = {\n /** offset of data slice */\n offset: number;\n /** length of data slice */\n length: number;\n};\n\n/**\n * Memory comparison filter for getProgramAccounts\n */\nexport type MemcmpFilter = {\n memcmp: {\n /** offset into program account data to start comparison */\n offset: number;\n /** data to match, as base-58 encoded string and limited to less than 129 bytes */\n bytes: string;\n };\n};\n\n/**\n * Data size comparison filter for getProgramAccounts\n */\nexport type DataSizeFilter = {\n /** Size of data for program account data length comparison */\n dataSize: number;\n};\n\n/**\n * A filter object for getProgramAccounts\n */\nexport type GetProgramAccountsFilter = MemcmpFilter | DataSizeFilter;\n\n/**\n * Configuration object for getProgramAccounts requests\n */\nexport type GetProgramAccountsConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** Optional encoding for account data (default base64)\n * To use \"jsonParsed\" encoding, please refer to `getParsedProgramAccounts` in connection.ts\n * */\n encoding?: 'base64';\n /** Optional data slice to limit the returned account data */\n dataSlice?: DataSlice;\n /** Optional array of filters to apply to accounts */\n filters?: GetProgramAccountsFilter[];\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n /** wrap the result in an RpcResponse JSON object */\n withContext?: boolean;\n};\n\nexport type GetProgramAccountsResponse = readonly Readonly<{\n account: AccountInfo;\n /** the account Pubkey as base-58 encoded string */\n pubkey: PublicKey;\n}>[];\n\n/**\n * Configuration object for getParsedProgramAccounts\n */\nexport type GetParsedProgramAccountsConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** Optional array of filters to apply to accounts */\n filters?: GetProgramAccountsFilter[];\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for getMultipleAccounts\n */\nexport type GetMultipleAccountsConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n /** Optional data slice to limit the returned account data */\n dataSlice?: DataSlice;\n};\n\n/**\n * Configuration object for `getStakeActivation`\n */\nexport type GetStakeActivationConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** Epoch for which to calculate activation details. If parameter not provided, defaults to current epoch */\n epoch?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getStakeActivation`\n */\nexport type GetTokenAccountsByOwnerConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getStakeActivation`\n */\nexport type GetTransactionCountConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getNonce`\n */\nexport type GetNonceConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getNonceAndContext`\n */\nexport type GetNonceAndContextConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Information describing an account\n */\nexport type AccountInfo = {\n /** `true` if this account's data contains a loaded program */\n executable: boolean;\n /** Identifier of the program that owns the account */\n owner: PublicKey;\n /** Number of lamports assigned to the account */\n lamports: number;\n /** Optional data assigned to the account */\n data: T;\n /** Optional rent epoch info for account */\n rentEpoch?: number;\n};\n\n/**\n * Account information identified by pubkey\n */\nexport type KeyedAccountInfo = {\n accountId: PublicKey;\n accountInfo: AccountInfo;\n};\n\n/**\n * Callback function for account change notifications\n */\nexport type AccountChangeCallback = (\n accountInfo: AccountInfo,\n context: Context,\n) => void;\n\n/**\n * Callback function for program account change notifications\n */\nexport type ProgramAccountChangeCallback = (\n keyedAccountInfo: KeyedAccountInfo,\n context: Context,\n) => void;\n\n/**\n * Callback function for slot change notifications\n */\nexport type SlotChangeCallback = (slotInfo: SlotInfo) => void;\n\n/**\n * Callback function for slot update notifications\n */\nexport type SlotUpdateCallback = (slotUpdate: SlotUpdate) => void;\n\n/**\n * Callback function for signature status notifications\n */\nexport type SignatureResultCallback = (\n signatureResult: SignatureResult,\n context: Context,\n) => void;\n\n/**\n * Signature status notification with transaction result\n */\nexport type SignatureStatusNotification = {\n type: 'status';\n result: SignatureResult;\n};\n\n/**\n * Signature received notification\n */\nexport type SignatureReceivedNotification = {\n type: 'received';\n};\n\n/**\n * Callback function for signature notifications\n */\nexport type SignatureSubscriptionCallback = (\n notification: SignatureStatusNotification | SignatureReceivedNotification,\n context: Context,\n) => void;\n\n/**\n * Signature subscription options\n */\nexport type SignatureSubscriptionOptions = {\n commitment?: Commitment;\n enableReceivedNotification?: boolean;\n};\n\n/**\n * Callback function for root change notifications\n */\nexport type RootChangeCallback = (root: number) => void;\n\n/**\n * @internal\n */\nconst LogsResult = pick({\n err: TransactionErrorResult,\n logs: array(string()),\n signature: string(),\n});\n\n/**\n * Logs result.\n */\nexport type Logs = {\n err: TransactionError | null;\n logs: string[];\n signature: string;\n};\n\n/**\n * Expected JSON RPC response for the \"logsNotification\" message.\n */\nconst LogsNotificationResult = pick({\n result: notificationResultAndContext(LogsResult),\n subscription: number(),\n});\n\n/**\n * Filter for log subscriptions.\n */\nexport type LogsFilter = PublicKey | 'all' | 'allWithVotes';\n\n/**\n * Callback function for log notifications.\n */\nexport type LogsCallback = (logs: Logs, ctx: Context) => void;\n\n/**\n * Signature result\n */\nexport type SignatureResult = {\n err: TransactionError | null;\n};\n\n/**\n * Transaction error\n */\nexport type TransactionError = {} | string;\n\n/**\n * Transaction confirmation status\n *
\n *   'processed': Transaction landed in a block which has reached 1 confirmation by the connected node\n *   'confirmed': Transaction landed in a block which has reached 1 confirmation by the cluster\n *   'finalized': Transaction landed in a block which has been finalized by the cluster\n * 
\n */\nexport type TransactionConfirmationStatus =\n | 'processed'\n | 'confirmed'\n | 'finalized';\n\n/**\n * Signature status\n */\nexport type SignatureStatus = {\n /** when the transaction was processed */\n slot: number;\n /** the number of blocks that have been confirmed and voted on in the fork containing `slot` */\n confirmations: number | null;\n /** transaction error, if any */\n err: TransactionError | null;\n /** cluster confirmation status, if data available. Possible responses: `processed`, `confirmed`, `finalized` */\n confirmationStatus?: TransactionConfirmationStatus;\n};\n\n/**\n * A confirmed signature with its status\n */\nexport type ConfirmedSignatureInfo = {\n /** the transaction signature */\n signature: string;\n /** when the transaction was processed */\n slot: number;\n /** error, if any */\n err: TransactionError | null;\n /** memo associated with the transaction, if any */\n memo: string | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n /** Cluster confirmation status, if available. Possible values: `processed`, `confirmed`, `finalized` */\n confirmationStatus?: TransactionConfirmationStatus;\n};\n\n/**\n * An object defining headers to be passed to the RPC server\n */\nexport type HttpHeaders = {\n [header: string]: string;\n} & {\n // Prohibited headers; for internal use only.\n 'solana-client'?: never;\n};\n\n/**\n * The type of the JavaScript `fetch()` API\n */\nexport type FetchFn = typeof fetchImpl;\n\n/**\n * A callback used to augment the outgoing HTTP request\n */\nexport type FetchMiddleware = (\n info: Parameters[0],\n init: Parameters[1],\n fetch: (...a: Parameters) => void,\n) => void;\n\n/**\n * Configuration for instantiating a Connection\n */\nexport type ConnectionConfig = {\n /**\n * An `http.Agent` that will be used to manage socket connections (eg. to implement connection\n * persistence). Set this to `false` to create a connection that uses no agent. This applies to\n * Node environments only.\n */\n httpAgent?: NodeHttpAgent | NodeHttpsAgent | false;\n /** Optional commitment level */\n commitment?: Commitment;\n /** Optional endpoint URL to the fullnode JSON RPC PubSub WebSocket Endpoint */\n wsEndpoint?: string;\n /** Optional HTTP headers object */\n httpHeaders?: HttpHeaders;\n /** Optional custom fetch function */\n fetch?: FetchFn;\n /** Optional fetch middleware callback */\n fetchMiddleware?: FetchMiddleware;\n /** Optional Disable retrying calls when server responds with HTTP 429 (Too Many Requests) */\n disableRetryOnRateLimit?: boolean;\n /** time to allow for the server to initially process a transaction (in milliseconds) */\n confirmTransactionInitialTimeout?: number;\n};\n\n/** @internal */\nconst COMMON_HTTP_HEADERS = {\n 'solana-client': `js/${process.env.npm_package_version ?? 'UNKNOWN'}`,\n};\n\n/**\n * A connection to a fullnode JSON RPC endpoint\n */\nexport class Connection {\n /** @internal */ _commitment?: Commitment;\n /** @internal */ _confirmTransactionInitialTimeout?: number;\n /** @internal */ _rpcEndpoint: string;\n /** @internal */ _rpcWsEndpoint: string;\n /** @internal */ _rpcClient: RpcClient;\n /** @internal */ _rpcRequest: RpcRequest;\n /** @internal */ _rpcBatchRequest: RpcBatchRequest;\n /** @internal */ _rpcWebSocket: RpcWebSocketClient;\n /** @internal */ _rpcWebSocketConnected: boolean = false;\n /** @internal */ _rpcWebSocketHeartbeat: ReturnType<\n typeof setInterval\n > | null = null;\n /** @internal */ _rpcWebSocketIdleTimeout: ReturnType<\n typeof setTimeout\n > | null = null;\n /** @internal\n * A number that we increment every time an active connection closes.\n * Used to determine whether the same socket connection that was open\n * when an async operation started is the same one that's active when\n * its continuation fires.\n *\n */ private _rpcWebSocketGeneration: number = 0;\n\n /** @internal */ _disableBlockhashCaching: boolean = false;\n /** @internal */ _pollingBlockhash: boolean = false;\n /** @internal */ _blockhashInfo: {\n latestBlockhash: BlockhashWithExpiryBlockHeight | null;\n lastFetch: number;\n simulatedSignatures: Array;\n transactionSignatures: Array;\n } = {\n latestBlockhash: null,\n lastFetch: 0,\n transactionSignatures: [],\n simulatedSignatures: [],\n };\n\n /** @internal */ private _nextClientSubscriptionId: ClientSubscriptionId = 0;\n /** @internal */ private _subscriptionDisposeFunctionsByClientSubscriptionId: {\n [clientSubscriptionId: ClientSubscriptionId]:\n | SubscriptionDisposeFn\n | undefined;\n } = {};\n /** @internal */ private _subscriptionHashByClientSubscriptionId: {\n [clientSubscriptionId: ClientSubscriptionId]:\n | SubscriptionConfigHash\n | undefined;\n } = {};\n /** @internal */ private _subscriptionStateChangeCallbacksByHash: {\n [hash: SubscriptionConfigHash]:\n | Set\n | undefined;\n } = {};\n /** @internal */ private _subscriptionCallbacksByServerSubscriptionId: {\n [serverSubscriptionId: ServerSubscriptionId]:\n | Set\n | undefined;\n } = {};\n /** @internal */ private _subscriptionsByHash: {\n [hash: SubscriptionConfigHash]: Subscription | undefined;\n } = {};\n /**\n * Special case.\n * After a signature is processed, RPCs automatically dispose of the\n * subscription on the server side. We need to track which of these\n * subscriptions have been disposed in such a way, so that we know\n * whether the client is dealing with a not-yet-processed signature\n * (in which case we must tear down the server subscription) or an\n * already-processed signature (in which case the client can simply\n * clear out the subscription locally without telling the server).\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n /** @internal */ private _subscriptionsAutoDisposedByRpc: Set =\n new Set();\n\n /**\n * Establish a JSON RPC connection\n *\n * @param endpoint URL to the fullnode JSON RPC endpoint\n * @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object\n */\n constructor(\n endpoint: string,\n commitmentOrConfig?: Commitment | ConnectionConfig,\n ) {\n let wsEndpoint;\n let httpHeaders;\n let fetch;\n let fetchMiddleware;\n let disableRetryOnRateLimit;\n let httpAgent;\n if (commitmentOrConfig && typeof commitmentOrConfig === 'string') {\n this._commitment = commitmentOrConfig;\n } else if (commitmentOrConfig) {\n this._commitment = commitmentOrConfig.commitment;\n this._confirmTransactionInitialTimeout =\n commitmentOrConfig.confirmTransactionInitialTimeout;\n wsEndpoint = commitmentOrConfig.wsEndpoint;\n httpHeaders = commitmentOrConfig.httpHeaders;\n fetch = commitmentOrConfig.fetch;\n fetchMiddleware = commitmentOrConfig.fetchMiddleware;\n disableRetryOnRateLimit = commitmentOrConfig.disableRetryOnRateLimit;\n httpAgent = commitmentOrConfig.httpAgent;\n }\n\n this._rpcEndpoint = assertEndpointUrl(endpoint);\n this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint);\n\n this._rpcClient = createRpcClient(\n endpoint,\n httpHeaders,\n fetch,\n fetchMiddleware,\n disableRetryOnRateLimit,\n httpAgent,\n );\n this._rpcRequest = createRpcRequest(this._rpcClient);\n this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient);\n\n this._rpcWebSocket = new RpcWebSocketClient(this._rpcWsEndpoint, {\n autoconnect: false,\n max_reconnects: Infinity,\n });\n this._rpcWebSocket.on('open', this._wsOnOpen.bind(this));\n this._rpcWebSocket.on('error', this._wsOnError.bind(this));\n this._rpcWebSocket.on('close', this._wsOnClose.bind(this));\n this._rpcWebSocket.on(\n 'accountNotification',\n this._wsOnAccountNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'programNotification',\n this._wsOnProgramAccountNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'slotNotification',\n this._wsOnSlotNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'slotsUpdatesNotification',\n this._wsOnSlotUpdatesNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'signatureNotification',\n this._wsOnSignatureNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'rootNotification',\n this._wsOnRootNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'logsNotification',\n this._wsOnLogsNotification.bind(this),\n );\n }\n\n /**\n * The default commitment used for requests\n */\n get commitment(): Commitment | undefined {\n return this._commitment;\n }\n\n /**\n * The RPC endpoint\n */\n get rpcEndpoint(): string {\n return this._rpcEndpoint;\n }\n\n /**\n * Fetch the balance for the specified public key, return with context\n */\n async getBalanceAndContext(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetBalanceConfig,\n ): Promise> {\n /** @internal */\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getBalance', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get balance for ${publicKey.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the balance for the specified public key\n */\n async getBalance(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetBalanceConfig,\n ): Promise {\n return await this.getBalanceAndContext(publicKey, commitmentOrConfig)\n .then(x => x.value)\n .catch(e => {\n throw new Error(\n 'failed to get balance of account ' + publicKey.toBase58() + ': ' + e,\n );\n });\n }\n\n /**\n * Fetch the estimated production time of a block\n */\n async getBlockTime(slot: number): Promise {\n const unsafeRes = await this._rpcRequest('getBlockTime', [slot]);\n const res = create(unsafeRes, jsonRpcResult(nullable(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get block time for slot ${slot}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the lowest slot that the node has information about in its ledger.\n * This value may increase over time if the node is configured to purge older ledger data\n */\n async getMinimumLedgerSlot(): Promise {\n const unsafeRes = await this._rpcRequest('minimumLedgerSlot', []);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get minimum ledger slot',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the slot of the lowest confirmed block that has not been purged from the ledger\n */\n async getFirstAvailableBlock(): Promise {\n const unsafeRes = await this._rpcRequest('getFirstAvailableBlock', []);\n const res = create(unsafeRes, SlotRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get first available block',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch information about the current supply\n */\n async getSupply(\n config?: GetSupplyConfig | Commitment,\n ): Promise> {\n let configArg: GetSupplyConfig = {};\n if (typeof config === 'string') {\n configArg = {commitment: config};\n } else if (config) {\n configArg = {\n ...config,\n commitment: (config && config.commitment) || this.commitment,\n };\n } else {\n configArg = {\n commitment: this.commitment,\n };\n }\n\n const unsafeRes = await this._rpcRequest('getSupply', [configArg]);\n const res = create(unsafeRes, GetSupplyRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get supply');\n }\n return res.result;\n }\n\n /**\n * Fetch the current supply of a token mint\n */\n async getTokenSupply(\n tokenMintAddress: PublicKey,\n commitment?: Commitment,\n ): Promise> {\n const args = this._buildArgs([tokenMintAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenSupply', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get token supply');\n }\n return res.result;\n }\n\n /**\n * Fetch the current balance of a token account\n */\n async getTokenAccountBalance(\n tokenAddress: PublicKey,\n commitment?: Commitment,\n ): Promise> {\n const args = this._buildArgs([tokenAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenAccountBalance', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get token account balance',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the token accounts owned by the specified account\n *\n * @return {Promise}\n */\n async getTokenAccountsByOwner(\n ownerAddress: PublicKey,\n filter: TokenAccountsFilter,\n commitmentOrConfig?: Commitment | GetTokenAccountsByOwnerConfig,\n ): Promise> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n let _args: any[] = [ownerAddress.toBase58()];\n if ('mint' in filter) {\n _args.push({mint: filter.mint.toBase58()});\n } else {\n _args.push({programId: filter.programId.toBase58()});\n }\n\n const args = this._buildArgs(_args, commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n const res = create(unsafeRes, GetTokenAccountsByOwner);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get token accounts owned by account ${ownerAddress.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch parsed token accounts owned by the specified account\n *\n * @return {Promise}>>>}\n */\n async getParsedTokenAccountsByOwner(\n ownerAddress: PublicKey,\n filter: TokenAccountsFilter,\n commitment?: Commitment,\n ): Promise<\n RpcResponseAndContext<\n Array<{pubkey: PublicKey; account: AccountInfo}>\n >\n > {\n let _args: any[] = [ownerAddress.toBase58()];\n if ('mint' in filter) {\n _args.push({mint: filter.mint.toBase58()});\n } else {\n _args.push({programId: filter.programId.toBase58()});\n }\n\n const args = this._buildArgs(_args, commitment, 'jsonParsed');\n const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n const res = create(unsafeRes, GetParsedTokenAccountsByOwner);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get token accounts owned by account ${ownerAddress.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the 20 largest accounts with their current balances\n */\n async getLargestAccounts(\n config?: GetLargestAccountsConfig,\n ): Promise>> {\n const arg = {\n ...config,\n commitment: (config && config.commitment) || this.commitment,\n };\n const args = arg.filter || arg.commitment ? [arg] : [];\n const unsafeRes = await this._rpcRequest('getLargestAccounts', args);\n const res = create(unsafeRes, GetLargestAccountsRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get largest accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch the 20 largest token accounts with their current balances\n * for a given mint.\n */\n async getTokenLargestAccounts(\n mintAddress: PublicKey,\n commitment?: Commitment,\n ): Promise>> {\n const args = this._buildArgs([mintAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenLargestAccounts', args);\n const res = create(unsafeRes, GetTokenLargestAccountsResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get token largest accounts',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for the specified public key, return with context\n */\n async getAccountInfoAndContext(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n ): Promise | null>> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment,\n 'base64',\n config,\n );\n const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(nullable(AccountInfoResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info about account ${publicKey.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch parsed account info for the specified public key\n */\n async getParsedAccountInfo(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n ): Promise<\n RpcResponseAndContext | null>\n > {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment,\n 'jsonParsed',\n config,\n );\n const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info about account ${publicKey.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for the specified public key\n */\n async getAccountInfo(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n ): Promise | null> {\n try {\n const res = await this.getAccountInfoAndContext(\n publicKey,\n commitmentOrConfig,\n );\n return res.value;\n } catch (e) {\n throw new Error(\n 'failed to get info about account ' + publicKey.toBase58() + ': ' + e,\n );\n }\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n */\n async getMultipleParsedAccounts(\n publicKeys: PublicKey[],\n rawConfig?: GetMultipleAccountsConfig,\n ): Promise<\n RpcResponseAndContext<(AccountInfo | null)[]>\n > {\n const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n const keys = publicKeys.map(key => key.toBase58());\n const args = this._buildArgs([keys], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult))),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for accounts ${keys}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n */\n async getMultipleAccountsInfoAndContext(\n publicKeys: PublicKey[],\n commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n ): Promise | null)[]>> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const keys = publicKeys.map(key => key.toBase58());\n const args = this._buildArgs([keys], commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(array(nullable(AccountInfoResult))),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for accounts ${keys}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys\n */\n async getMultipleAccountsInfo(\n publicKeys: PublicKey[],\n commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n ): Promise<(AccountInfo | null)[]> {\n const res = await this.getMultipleAccountsInfoAndContext(\n publicKeys,\n commitmentOrConfig,\n );\n return res.value;\n }\n\n /**\n * Returns epoch activation information for a stake account that has been delegated\n */\n async getStakeActivation(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetStakeActivationConfig,\n epoch?: number,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment,\n undefined /* encoding */,\n {\n ...config,\n epoch: epoch != null ? epoch : config?.epoch,\n },\n );\n\n const unsafeRes = await this._rpcRequest('getStakeActivation', args);\n const res = create(unsafeRes, jsonRpcResult(StakeActivationResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get Stake Activation ${publicKey.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the accounts owned by the specified program id\n *\n * @return {Promise}>>}\n */\n async getProgramAccounts(\n programId: PublicKey,\n configOrCommitment: GetProgramAccountsConfig &\n Readonly<{withContext: true}>,\n ): Promise>;\n // eslint-disable-next-line no-dupe-class-members\n async getProgramAccounts(\n programId: PublicKey,\n configOrCommitment?: GetProgramAccountsConfig | Commitment,\n ): Promise;\n // eslint-disable-next-line no-dupe-class-members\n async getProgramAccounts(\n programId: PublicKey,\n configOrCommitment?: GetProgramAccountsConfig | Commitment,\n ): Promise<\n | GetProgramAccountsResponse\n | RpcResponseAndContext\n > {\n const {commitment, config} =\n extractCommitmentFromConfig(configOrCommitment);\n const {encoding, ...configWithoutEncoding} = config || {};\n const args = this._buildArgs(\n [programId.toBase58()],\n commitment,\n encoding || 'base64',\n configWithoutEncoding,\n );\n const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n const baseSchema = array(KeyedAccountInfoResult);\n const res =\n configWithoutEncoding.withContext === true\n ? create(unsafeRes, jsonRpcResultAndContext(baseSchema))\n : create(unsafeRes, jsonRpcResult(baseSchema));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get accounts owned by program ${programId.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch and parse all the accounts owned by the specified program id\n *\n * @return {Promise}>>}\n */\n async getParsedProgramAccounts(\n programId: PublicKey,\n configOrCommitment?: GetParsedProgramAccountsConfig | Commitment,\n ): Promise<\n Array<{\n pubkey: PublicKey;\n account: AccountInfo;\n }>\n > {\n const {commitment, config} =\n extractCommitmentFromConfig(configOrCommitment);\n const args = this._buildArgs(\n [programId.toBase58()],\n commitment,\n 'jsonParsed',\n config,\n );\n const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n const res = create(\n unsafeRes,\n jsonRpcResult(array(KeyedParsedAccountInfoResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get accounts owned by program ${programId.toBase58()}`,\n );\n }\n return res.result;\n }\n\n confirmTransaction(\n strategy: TransactionConfirmationStrategy,\n commitment?: Commitment,\n ): Promise>;\n\n /** @deprecated Instead, call `confirmTransaction` and pass in {@link TransactionConfirmationStrategy} */\n // eslint-disable-next-line no-dupe-class-members\n confirmTransaction(\n strategy: TransactionSignature,\n commitment?: Commitment,\n ): Promise>;\n\n // eslint-disable-next-line no-dupe-class-members\n async confirmTransaction(\n strategy: TransactionConfirmationStrategy | TransactionSignature,\n commitment?: Commitment,\n ): Promise> {\n let rawSignature: string;\n\n if (typeof strategy == 'string') {\n rawSignature = strategy;\n } else {\n const config = strategy as TransactionConfirmationStrategy;\n\n if (config.abortSignal?.aborted) {\n return Promise.reject(config.abortSignal.reason);\n }\n rawSignature = config.signature;\n }\n\n let decodedSignature;\n\n try {\n decodedSignature = bs58.decode(rawSignature);\n } catch (err) {\n throw new Error('signature must be base58 encoded: ' + rawSignature);\n }\n\n assert(decodedSignature.length === 64, 'signature has invalid length');\n\n if (typeof strategy === 'string') {\n return await this.confirmTransactionUsingLegacyTimeoutStrategy({\n commitment: commitment || this.commitment,\n signature: rawSignature,\n });\n } else if ('lastValidBlockHeight' in strategy) {\n return await this.confirmTransactionUsingBlockHeightExceedanceStrategy({\n commitment: commitment || this.commitment,\n strategy,\n });\n } else {\n return await this.confirmTransactionUsingDurableNonceStrategy({\n commitment: commitment || this.commitment,\n strategy,\n });\n }\n }\n\n private getCancellationPromise(signal?: AbortSignal): Promise {\n return new Promise((_, reject) => {\n if (signal == null) {\n return;\n }\n if (signal.aborted) {\n reject(signal.reason);\n } else {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n });\n }\n });\n }\n\n private getTransactionConfirmationPromise({\n commitment,\n signature,\n }: {\n commitment?: Commitment;\n signature: string;\n }): {\n abortConfirmation(): void;\n confirmationPromise: Promise<{\n __type: TransactionStatus.PROCESSED;\n response: RpcResponseAndContext;\n }>;\n } {\n let signatureSubscriptionId: number | undefined;\n let disposeSignatureSubscriptionStateChangeObserver:\n | SubscriptionStateChangeDisposeFn\n | undefined;\n let done = false;\n const confirmationPromise = new Promise<{\n __type: TransactionStatus.PROCESSED;\n response: RpcResponseAndContext;\n }>((resolve, reject) => {\n try {\n signatureSubscriptionId = this.onSignature(\n signature,\n (result: SignatureResult, context: Context) => {\n signatureSubscriptionId = undefined;\n const response = {\n context,\n value: result,\n };\n resolve({__type: TransactionStatus.PROCESSED, response});\n },\n commitment,\n );\n const subscriptionSetupPromise = new Promise(\n resolveSubscriptionSetup => {\n if (signatureSubscriptionId == null) {\n resolveSubscriptionSetup();\n } else {\n disposeSignatureSubscriptionStateChangeObserver =\n this._onSubscriptionStateChange(\n signatureSubscriptionId,\n nextState => {\n if (nextState === 'subscribed') {\n resolveSubscriptionSetup();\n }\n },\n );\n }\n },\n );\n (async () => {\n await subscriptionSetupPromise;\n if (done) return;\n const response = await this.getSignatureStatus(signature);\n if (done) return;\n if (response == null) {\n return;\n }\n const {context, value} = response;\n if (value == null) {\n return;\n }\n if (value?.err) {\n reject(value.err);\n } else {\n switch (commitment) {\n case 'confirmed':\n case 'single':\n case 'singleGossip': {\n if (value.confirmationStatus === 'processed') {\n return;\n }\n break;\n }\n case 'finalized':\n case 'max':\n case 'root': {\n if (\n value.confirmationStatus === 'processed' ||\n value.confirmationStatus === 'confirmed'\n ) {\n return;\n }\n break;\n }\n // exhaust enums to ensure full coverage\n case 'processed':\n case 'recent':\n }\n done = true;\n resolve({\n __type: TransactionStatus.PROCESSED,\n response: {\n context,\n value,\n },\n });\n }\n })();\n } catch (err) {\n reject(err);\n }\n });\n const abortConfirmation = () => {\n if (disposeSignatureSubscriptionStateChangeObserver) {\n disposeSignatureSubscriptionStateChangeObserver();\n disposeSignatureSubscriptionStateChangeObserver = undefined;\n }\n if (signatureSubscriptionId != null) {\n this.removeSignatureListener(signatureSubscriptionId);\n signatureSubscriptionId = undefined;\n }\n };\n return {abortConfirmation, confirmationPromise};\n }\n\n private async confirmTransactionUsingBlockHeightExceedanceStrategy({\n commitment,\n strategy: {abortSignal, lastValidBlockHeight, signature},\n }: {\n commitment?: Commitment;\n strategy: BlockheightBasedTransactionConfirmationStrategy;\n }) {\n let done: boolean = false;\n const expiryPromise = new Promise<{\n __type: TransactionStatus.BLOCKHEIGHT_EXCEEDED;\n }>(resolve => {\n const checkBlockHeight = async () => {\n try {\n const blockHeight = await this.getBlockHeight(commitment);\n return blockHeight;\n } catch (_e) {\n return -1;\n }\n };\n (async () => {\n let currentBlockHeight = await checkBlockHeight();\n if (done) return;\n while (currentBlockHeight <= lastValidBlockHeight) {\n await sleep(1000);\n if (done) return;\n currentBlockHeight = await checkBlockHeight();\n if (done) return;\n }\n resolve({__type: TransactionStatus.BLOCKHEIGHT_EXCEEDED});\n })();\n });\n const {abortConfirmation, confirmationPromise} =\n this.getTransactionConfirmationPromise({commitment, signature});\n const cancellationPromise = this.getCancellationPromise(abortSignal);\n let result: RpcResponseAndContext;\n try {\n const outcome = await Promise.race([\n cancellationPromise,\n confirmationPromise,\n expiryPromise,\n ]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n throw new TransactionExpiredBlockheightExceededError(signature);\n }\n } finally {\n done = true;\n abortConfirmation();\n }\n return result;\n }\n\n private async confirmTransactionUsingDurableNonceStrategy({\n commitment,\n strategy: {\n abortSignal,\n minContextSlot,\n nonceAccountPubkey,\n nonceValue,\n signature,\n },\n }: {\n commitment?: Commitment;\n strategy: DurableNonceTransactionConfirmationStrategy;\n }) {\n let done: boolean = false;\n const expiryPromise = new Promise<{\n __type: TransactionStatus.NONCE_INVALID;\n slotInWhichNonceDidAdvance: number | null;\n }>(resolve => {\n let currentNonceValue: string | undefined = nonceValue;\n let lastCheckedSlot: number | null = null;\n const getCurrentNonceValue = async () => {\n try {\n const {context, value: nonceAccount} = await this.getNonceAndContext(\n nonceAccountPubkey,\n {\n commitment,\n minContextSlot,\n },\n );\n lastCheckedSlot = context.slot;\n return nonceAccount?.nonce;\n } catch (e) {\n // If for whatever reason we can't reach/read the nonce\n // account, just keep using the last-known value.\n return currentNonceValue;\n }\n };\n (async () => {\n currentNonceValue = await getCurrentNonceValue();\n if (done) return;\n while (\n true // eslint-disable-line no-constant-condition\n ) {\n if (nonceValue !== currentNonceValue) {\n resolve({\n __type: TransactionStatus.NONCE_INVALID,\n slotInWhichNonceDidAdvance: lastCheckedSlot,\n });\n return;\n }\n await sleep(2000);\n if (done) return;\n currentNonceValue = await getCurrentNonceValue();\n if (done) return;\n }\n })();\n });\n const {abortConfirmation, confirmationPromise} =\n this.getTransactionConfirmationPromise({commitment, signature});\n const cancellationPromise = this.getCancellationPromise(abortSignal);\n let result: RpcResponseAndContext;\n try {\n const outcome = await Promise.race([\n cancellationPromise,\n confirmationPromise,\n expiryPromise,\n ]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n // Double check that the transaction is indeed unconfirmed.\n let signatureStatus:\n | RpcResponseAndContext\n | null\n | undefined;\n while (\n true // eslint-disable-line no-constant-condition\n ) {\n const status = await this.getSignatureStatus(signature);\n if (status == null) {\n break;\n }\n if (\n status.context.slot <\n (outcome.slotInWhichNonceDidAdvance ?? minContextSlot)\n ) {\n await sleep(400);\n continue;\n }\n signatureStatus = status;\n break;\n }\n if (signatureStatus?.value) {\n const commitmentForStatus = commitment || 'finalized';\n const {confirmationStatus} = signatureStatus.value;\n switch (commitmentForStatus) {\n case 'processed':\n case 'recent':\n if (\n confirmationStatus !== 'processed' &&\n confirmationStatus !== 'confirmed' &&\n confirmationStatus !== 'finalized'\n ) {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n case 'confirmed':\n case 'single':\n case 'singleGossip':\n if (\n confirmationStatus !== 'confirmed' &&\n confirmationStatus !== 'finalized'\n ) {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n case 'finalized':\n case 'max':\n case 'root':\n if (confirmationStatus !== 'finalized') {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n default:\n // Exhaustive switch.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n ((_: never) => {})(commitmentForStatus);\n }\n result = {\n context: signatureStatus.context,\n value: {err: signatureStatus.value.err},\n };\n } else {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n }\n } finally {\n done = true;\n abortConfirmation();\n }\n return result;\n }\n\n private async confirmTransactionUsingLegacyTimeoutStrategy({\n commitment,\n signature,\n }: {\n commitment?: Commitment;\n signature: string;\n }) {\n let timeoutId;\n const expiryPromise = new Promise<{\n __type: TransactionStatus.TIMED_OUT;\n timeoutMs: number;\n }>(resolve => {\n let timeoutMs = this._confirmTransactionInitialTimeout || 60 * 1000;\n switch (commitment) {\n case 'processed':\n case 'recent':\n case 'single':\n case 'confirmed':\n case 'singleGossip': {\n timeoutMs = this._confirmTransactionInitialTimeout || 30 * 1000;\n break;\n }\n // exhaust enums to ensure full coverage\n case 'finalized':\n case 'max':\n case 'root':\n }\n timeoutId = setTimeout(\n () => resolve({__type: TransactionStatus.TIMED_OUT, timeoutMs}),\n timeoutMs,\n );\n });\n const {abortConfirmation, confirmationPromise} =\n this.getTransactionConfirmationPromise({\n commitment,\n signature,\n });\n let result: RpcResponseAndContext;\n try {\n const outcome = await Promise.race([confirmationPromise, expiryPromise]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n throw new TransactionExpiredTimeoutError(\n signature,\n outcome.timeoutMs / 1000,\n );\n }\n } finally {\n clearTimeout(timeoutId);\n abortConfirmation();\n }\n return result;\n }\n\n /**\n * Return the list of nodes that are currently participating in the cluster\n */\n async getClusterNodes(): Promise> {\n const unsafeRes = await this._rpcRequest('getClusterNodes', []);\n const res = create(unsafeRes, jsonRpcResult(array(ContactInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get cluster nodes');\n }\n return res.result;\n }\n\n /**\n * Return the list of nodes that are currently participating in the cluster\n */\n async getVoteAccounts(commitment?: Commitment): Promise {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getVoteAccounts', args);\n const res = create(unsafeRes, GetVoteAccounts);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get vote accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch the current slot that the node is processing\n */\n async getSlot(\n commitmentOrConfig?: Commitment | GetSlotConfig,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getSlot', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot');\n }\n return res.result;\n }\n\n /**\n * Fetch the current slot leader of the cluster\n */\n async getSlotLeader(\n commitmentOrConfig?: Commitment | GetSlotLeaderConfig,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getSlotLeader', args);\n const res = create(unsafeRes, jsonRpcResult(string()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot leader');\n }\n return res.result;\n }\n\n /**\n * Fetch `limit` number of slot leaders starting from `startSlot`\n *\n * @param startSlot fetch slot leaders starting from this slot\n * @param limit number of slot leaders to return\n */\n async getSlotLeaders(\n startSlot: number,\n limit: number,\n ): Promise> {\n const args = [startSlot, limit];\n const unsafeRes = await this._rpcRequest('getSlotLeaders', args);\n const res = create(unsafeRes, jsonRpcResult(array(PublicKeyFromString)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot leaders');\n }\n return res.result;\n }\n\n /**\n * Fetch the current status of a signature\n */\n async getSignatureStatus(\n signature: TransactionSignature,\n config?: SignatureStatusConfig,\n ): Promise> {\n const {context, value: values} = await this.getSignatureStatuses(\n [signature],\n config,\n );\n assert(values.length === 1);\n const value = values[0];\n return {context, value};\n }\n\n /**\n * Fetch the current statuses of a batch of signatures\n */\n async getSignatureStatuses(\n signatures: Array,\n config?: SignatureStatusConfig,\n ): Promise>> {\n const params: any[] = [signatures];\n if (config) {\n params.push(config);\n }\n const unsafeRes = await this._rpcRequest('getSignatureStatuses', params);\n const res = create(unsafeRes, GetSignatureStatusesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get signature status');\n }\n return res.result;\n }\n\n /**\n * Fetch the current transaction count of the cluster\n */\n async getTransactionCount(\n commitmentOrConfig?: Commitment | GetTransactionCountConfig,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getTransactionCount', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get transaction count',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the current total currency supply of the cluster in lamports\n *\n * @deprecated Deprecated since v1.2.8. Please use {@link getSupply} instead.\n */\n async getTotalSupply(commitment?: Commitment): Promise {\n const result = await this.getSupply({\n commitment,\n excludeNonCirculatingAccountsList: true,\n });\n return result.value.total;\n }\n\n /**\n * Fetch the cluster InflationGovernor parameters\n */\n async getInflationGovernor(\n commitment?: Commitment,\n ): Promise {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getInflationGovernor', args);\n const res = create(unsafeRes, GetInflationGovernorRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation');\n }\n return res.result;\n }\n\n /**\n * Fetch the inflation reward for a list of addresses for an epoch\n */\n async getInflationReward(\n addresses: PublicKey[],\n epoch?: number,\n commitmentOrConfig?: Commitment | GetInflationRewardConfig,\n ): Promise<(InflationReward | null)[]> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [addresses.map(pubkey => pubkey.toBase58())],\n commitment,\n undefined /* encoding */,\n {\n ...config,\n epoch: epoch != null ? epoch : config?.epoch,\n },\n );\n const unsafeRes = await this._rpcRequest('getInflationReward', args);\n const res = create(unsafeRes, GetInflationRewardResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation reward');\n }\n return res.result;\n }\n\n /**\n * Fetch the specific inflation values for the current epoch\n */\n async getInflationRate(): Promise {\n const unsafeRes = await this._rpcRequest('getInflationRate', []);\n const res = create(unsafeRes, GetInflationRateRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation rate');\n }\n return res.result;\n }\n\n /**\n * Fetch the Epoch Info parameters\n */\n async getEpochInfo(\n commitmentOrConfig?: Commitment | GetEpochInfoConfig,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getEpochInfo', args);\n const res = create(unsafeRes, GetEpochInfoRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get epoch info');\n }\n return res.result;\n }\n\n /**\n * Fetch the Epoch Schedule parameters\n */\n async getEpochSchedule(): Promise {\n const unsafeRes = await this._rpcRequest('getEpochSchedule', []);\n const res = create(unsafeRes, GetEpochScheduleRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get epoch schedule');\n }\n const epochSchedule = res.result;\n return new EpochSchedule(\n epochSchedule.slotsPerEpoch,\n epochSchedule.leaderScheduleSlotOffset,\n epochSchedule.warmup,\n epochSchedule.firstNormalEpoch,\n epochSchedule.firstNormalSlot,\n );\n }\n\n /**\n * Fetch the leader schedule for the current epoch\n * @return {Promise>}\n */\n async getLeaderSchedule(): Promise {\n const unsafeRes = await this._rpcRequest('getLeaderSchedule', []);\n const res = create(unsafeRes, GetLeaderScheduleRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get leader schedule');\n }\n return res.result;\n }\n\n /**\n * Fetch the minimum balance needed to exempt an account of `dataLength`\n * size from rent\n */\n async getMinimumBalanceForRentExemption(\n dataLength: number,\n commitment?: Commitment,\n ): Promise {\n const args = this._buildArgs([dataLength], commitment);\n const unsafeRes = await this._rpcRequest(\n 'getMinimumBalanceForRentExemption',\n args,\n );\n const res = create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult);\n if ('error' in res) {\n console.warn('Unable to fetch minimum balance for rent exemption');\n return 0;\n }\n return res.result;\n }\n\n /**\n * Fetch a recent blockhash from the cluster, return with context\n * @return {Promise>}\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead.\n */\n async getRecentBlockhashAndContext(commitment?: Commitment): Promise<\n RpcResponseAndContext<{\n blockhash: Blockhash;\n feeCalculator: FeeCalculator;\n }>\n > {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getRecentBlockhash', args);\n const res = create(unsafeRes, GetRecentBlockhashAndContextRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get recent blockhash');\n }\n return res.result;\n }\n\n /**\n * Fetch recent performance samples\n * @return {Promise>}\n */\n async getRecentPerformanceSamples(\n limit?: number,\n ): Promise> {\n const unsafeRes = await this._rpcRequest(\n 'getRecentPerformanceSamples',\n limit ? [limit] : [],\n );\n const res = create(unsafeRes, GetRecentPerformanceSamplesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get recent performance samples',\n );\n }\n\n return res.result;\n }\n\n /**\n * Fetch the fee calculator for a recent blockhash from the cluster, return with context\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link getFeeForMessage} instead.\n */\n async getFeeCalculatorForBlockhash(\n blockhash: Blockhash,\n commitment?: Commitment,\n ): Promise> {\n const args = this._buildArgs([blockhash], commitment);\n const unsafeRes = await this._rpcRequest(\n 'getFeeCalculatorForBlockhash',\n args,\n );\n\n const res = create(unsafeRes, GetFeeCalculatorRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get fee calculator');\n }\n const {context, value} = res.result;\n return {\n context,\n value: value !== null ? value.feeCalculator : null,\n };\n }\n\n /**\n * Fetch the fee for a message from the cluster, return with context\n */\n async getFeeForMessage(\n message: VersionedMessage,\n commitment?: Commitment,\n ): Promise> {\n const wireMessage = toBuffer(message.serialize()).toString('base64');\n const args = this._buildArgs([wireMessage], commitment);\n const unsafeRes = await this._rpcRequest('getFeeForMessage', args);\n\n const res = create(unsafeRes, jsonRpcResultAndContext(nullable(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get fee for message');\n }\n if (res.result === null) {\n throw new Error('invalid blockhash');\n }\n return res.result;\n }\n\n /**\n * Fetch a list of prioritization fees from recent blocks.\n */\n async getRecentPrioritizationFees(\n config?: GetRecentPrioritizationFeesConfig,\n ): Promise {\n const accounts = config?.lockedWritableAccounts?.map(key => key.toBase58());\n const args = this._buildArgs(accounts?.length ? [accounts] : []);\n const unsafeRes = await this._rpcRequest(\n 'getRecentPrioritizationFees',\n args,\n );\n const res = create(unsafeRes, GetRecentPrioritizationFeesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get recent prioritization fees',\n );\n }\n return res.result;\n }\n /**\n * Fetch a recent blockhash from the cluster\n * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>}\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead.\n */\n async getRecentBlockhash(\n commitment?: Commitment,\n ): Promise<{blockhash: Blockhash; feeCalculator: FeeCalculator}> {\n try {\n const res = await this.getRecentBlockhashAndContext(commitment);\n return res.value;\n } catch (e) {\n throw new Error('failed to get recent blockhash: ' + e);\n }\n }\n\n /**\n * Fetch the latest blockhash from the cluster\n * @return {Promise}\n */\n async getLatestBlockhash(\n commitmentOrConfig?: Commitment | GetLatestBlockhashConfig,\n ): Promise {\n try {\n const res = await this.getLatestBlockhashAndContext(commitmentOrConfig);\n return res.value;\n } catch (e) {\n throw new Error('failed to get recent blockhash: ' + e);\n }\n }\n\n /**\n * Fetch the latest blockhash from the cluster\n * @return {Promise}\n */\n async getLatestBlockhashAndContext(\n commitmentOrConfig?: Commitment | GetLatestBlockhashConfig,\n ): Promise> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getLatestBlockhash', args);\n const res = create(unsafeRes, GetLatestBlockhashRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get latest blockhash');\n }\n return res.result;\n }\n\n /**\n * Fetch the node version\n */\n async getVersion(): Promise {\n const unsafeRes = await this._rpcRequest('getVersion', []);\n const res = create(unsafeRes, jsonRpcResult(VersionResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get version');\n }\n return res.result;\n }\n\n /**\n * Fetch the genesis hash\n */\n async getGenesisHash(): Promise {\n const unsafeRes = await this._rpcRequest('getGenesisHash', []);\n const res = create(unsafeRes, jsonRpcResult(string()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get genesis hash');\n }\n return res.result;\n }\n\n /**\n * Fetch a processed block from the cluster.\n *\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n async getBlock(\n slot: number,\n rawConfig?: GetBlockConfig,\n ): Promise;\n\n /**\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig: GetBlockConfig & {transactionDetails: 'accounts'},\n ): Promise;\n\n /**\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig: GetBlockConfig & {transactionDetails: 'none'},\n ): Promise;\n\n /**\n * Fetch a processed block from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise;\n\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & {transactionDetails: 'accounts'},\n ): Promise;\n\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & {transactionDetails: 'none'},\n ): Promise;\n\n /**\n * Fetch a processed block from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise<\n | VersionedBlockResponse\n | VersionedAccountsModeBlockResponse\n | VersionedNoneModeBlockResponse\n | null\n > {\n const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed(\n [slot],\n commitment as Finality,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getBlock', args);\n try {\n switch (config?.transactionDetails) {\n case 'accounts': {\n const res = create(unsafeRes, GetAccountsModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n case 'none': {\n const res = create(unsafeRes, GetNoneModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n default: {\n const res = create(unsafeRes, GetBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n const {result} = res;\n return result\n ? {\n ...result,\n transactions: result.transactions.map(\n ({transaction, meta, version}) => ({\n meta,\n transaction: {\n ...transaction,\n message: versionedMessageFromResponse(\n version,\n transaction.message,\n ),\n },\n version,\n }),\n ),\n }\n : null;\n }\n }\n } catch (e) {\n throw new SolanaJSONRPCError(\n e as JSONRPCError,\n 'failed to get confirmed block',\n );\n }\n }\n\n /**\n * Fetch parsed transaction details for a confirmed or finalized block\n */\n async getParsedBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise;\n\n // eslint-disable-next-line no-dupe-class-members\n async getParsedBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & {transactionDetails: 'accounts'},\n ): Promise;\n\n // eslint-disable-next-line no-dupe-class-members\n async getParsedBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & {transactionDetails: 'none'},\n ): Promise;\n // eslint-disable-next-line no-dupe-class-members\n async getParsedBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise<\n | ParsedBlockResponse\n | ParsedAccountsModeBlockResponse\n | ParsedNoneModeBlockResponse\n | null\n > {\n const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed(\n [slot],\n commitment as Finality,\n 'jsonParsed',\n config,\n );\n const unsafeRes = await this._rpcRequest('getBlock', args);\n try {\n switch (config?.transactionDetails) {\n case 'accounts': {\n const res = create(unsafeRes, GetParsedAccountsModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n case 'none': {\n const res = create(unsafeRes, GetParsedNoneModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n default: {\n const res = create(unsafeRes, GetParsedBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n }\n } catch (e) {\n throw new SolanaJSONRPCError(e as JSONRPCError, 'failed to get block');\n }\n }\n\n /*\n * Returns the current block height of the node\n */\n getBlockHeight = (() => {\n const requestPromises: {[hash: string]: Promise} = {};\n return async (\n commitmentOrConfig?: Commitment | GetBlockHeightConfig,\n ): Promise => {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const requestHash = fastStableStringify(args);\n requestPromises[requestHash] =\n requestPromises[requestHash] ??\n (async () => {\n try {\n const unsafeRes = await this._rpcRequest('getBlockHeight', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get block height information',\n );\n }\n return res.result;\n } finally {\n delete requestPromises[requestHash];\n }\n })();\n return await requestPromises[requestHash];\n };\n })();\n\n /*\n * Returns recent block production information from the current or previous epoch\n */\n async getBlockProduction(\n configOrCommitment?: GetBlockProductionConfig | Commitment,\n ): Promise> {\n let extra: Omit | undefined;\n let commitment: Commitment | undefined;\n\n if (typeof configOrCommitment === 'string') {\n commitment = configOrCommitment;\n } else if (configOrCommitment) {\n const {commitment: c, ...rest} = configOrCommitment;\n commitment = c;\n extra = rest;\n }\n\n const args = this._buildArgs([], commitment, 'base64', extra);\n const unsafeRes = await this._rpcRequest('getBlockProduction', args);\n const res = create(unsafeRes, BlockProductionResponseStruct);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get block production information',\n );\n }\n\n return res.result;\n }\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n *\n * @deprecated Instead, call `getTransaction` using a\n * `GetVersionedTransactionConfig` by setting the\n * `maxSupportedTransactionVersion` property.\n */\n async getTransaction(\n signature: string,\n rawConfig?: GetTransactionConfig,\n ): Promise;\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransaction(\n signature: string,\n rawConfig: GetVersionedTransactionConfig,\n ): Promise;\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransaction(\n signature: string,\n rawConfig?: GetVersionedTransactionConfig,\n ): Promise {\n const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment as Finality,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n\n const result = res.result;\n if (!result) return result;\n\n return {\n ...result,\n transaction: {\n ...result.transaction,\n message: versionedMessageFromResponse(\n result.version,\n result.transaction.message,\n ),\n },\n };\n }\n\n /**\n * Fetch parsed transaction details for a confirmed or finalized transaction\n */\n async getParsedTransaction(\n signature: TransactionSignature,\n commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment as Finality,\n 'jsonParsed',\n config,\n );\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n return res.result;\n }\n\n /**\n * Fetch parsed transaction details for a batch of confirmed transactions\n */\n async getParsedTransactions(\n signatures: TransactionSignature[],\n commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n ): Promise<(ParsedTransactionWithMeta | null)[]> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment as Finality,\n 'jsonParsed',\n config,\n );\n return {\n methodName: 'getTransaction',\n args,\n };\n });\n\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map((unsafeRes: any) => {\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n }\n return res.result;\n });\n\n return res;\n }\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link TransactionResponse}.\n *\n * @deprecated Instead, call `getTransactions` using a\n * `GetVersionedTransactionConfig` by setting the\n * `maxSupportedTransactionVersion` property.\n */\n async getTransactions(\n signatures: TransactionSignature[],\n commitmentOrConfig?: GetTransactionConfig | Finality,\n ): Promise<(TransactionResponse | null)[]>;\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link\n * VersionedTransactionResponse}.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransactions(\n signatures: TransactionSignature[],\n commitmentOrConfig: GetVersionedTransactionConfig | Finality,\n ): Promise<(VersionedTransactionResponse | null)[]>;\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link\n * VersionedTransactionResponse}.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransactions(\n signatures: TransactionSignature[],\n commitmentOrConfig: GetVersionedTransactionConfig | Finality,\n ): Promise<(VersionedTransactionResponse | null)[]> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment as Finality,\n undefined /* encoding */,\n config,\n );\n return {\n methodName: 'getTransaction',\n args,\n };\n });\n\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map((unsafeRes: any) => {\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n }\n const result = res.result;\n if (!result) return result;\n\n return {\n ...result,\n transaction: {\n ...result.transaction,\n message: versionedMessageFromResponse(\n result.version,\n result.transaction.message,\n ),\n },\n };\n });\n\n return res;\n }\n\n /**\n * Fetch a list of Transactions and transaction statuses from the cluster\n * for a confirmed block.\n *\n * @deprecated Deprecated since v1.13.0. Please use {@link getBlock} instead.\n */\n async getConfirmedBlock(\n slot: number,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed([slot], commitment);\n const unsafeRes = await this._rpcRequest('getConfirmedBlock', args);\n const res = create(unsafeRes, GetConfirmedBlockRpcResult);\n\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n }\n\n const result = res.result;\n if (!result) {\n throw new Error('Confirmed block ' + slot + ' not found');\n }\n\n const block = {\n ...result,\n transactions: result.transactions.map(({transaction, meta}) => {\n const message = new Message(transaction.message);\n return {\n meta,\n transaction: {\n ...transaction,\n message,\n },\n };\n }),\n };\n\n return {\n ...block,\n transactions: block.transactions.map(({transaction, meta}) => {\n return {\n meta,\n transaction: Transaction.populate(\n transaction.message,\n transaction.signatures,\n ),\n };\n }),\n };\n }\n\n /**\n * Fetch confirmed blocks between two slots\n */\n async getBlocks(\n startSlot: number,\n endSlot?: number,\n commitment?: Finality,\n ): Promise> {\n const args = this._buildArgsAtLeastConfirmed(\n endSlot !== undefined ? [startSlot, endSlot] : [startSlot],\n commitment,\n );\n const unsafeRes = await this._rpcRequest('getBlocks', args);\n const res = create(unsafeRes, jsonRpcResult(array(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get blocks');\n }\n return res.result;\n }\n\n /**\n * Fetch a list of Signatures from the cluster for a block, excluding rewards\n */\n async getBlockSignatures(\n slot: number,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed(\n [slot],\n commitment,\n undefined,\n {\n transactionDetails: 'signatures',\n rewards: false,\n },\n );\n const unsafeRes = await this._rpcRequest('getBlock', args);\n const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Block ' + slot + ' not found');\n }\n return result;\n }\n\n /**\n * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link getBlockSignatures} instead.\n */\n async getConfirmedBlockSignatures(\n slot: number,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed(\n [slot],\n commitment,\n undefined,\n {\n transactionDetails: 'signatures',\n rewards: false,\n },\n );\n const unsafeRes = await this._rpcRequest('getConfirmedBlock', args);\n const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Confirmed block ' + slot + ' not found');\n }\n return result;\n }\n\n /**\n * Fetch a transaction details for a confirmed transaction\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link getTransaction} instead.\n */\n async getConfirmedTransaction(\n signature: TransactionSignature,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment);\n const unsafeRes = await this._rpcRequest('getConfirmedTransaction', args);\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n\n const result = res.result;\n if (!result) return result;\n\n const message = new Message(result.transaction.message);\n const signatures = result.transaction.signatures;\n return {\n ...result,\n transaction: Transaction.populate(message, signatures),\n };\n }\n\n /**\n * Fetch parsed transaction details for a confirmed transaction\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransaction} instead.\n */\n async getParsedConfirmedTransaction(\n signature: TransactionSignature,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment,\n 'jsonParsed',\n );\n const unsafeRes = await this._rpcRequest('getConfirmedTransaction', args);\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get confirmed transaction',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch parsed transaction details for a batch of confirmed transactions\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransactions} instead.\n */\n async getParsedConfirmedTransactions(\n signatures: TransactionSignature[],\n commitment?: Finality,\n ): Promise<(ParsedConfirmedTransaction | null)[]> {\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment,\n 'jsonParsed',\n );\n return {\n methodName: 'getConfirmedTransaction',\n args,\n };\n });\n\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map((unsafeRes: any) => {\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get confirmed transactions',\n );\n }\n return res.result;\n });\n\n return res;\n }\n\n /**\n * Fetch a list of all the confirmed signatures for transactions involving an address\n * within a specified slot range. Max range allowed is 10,000 slots.\n *\n * @deprecated Deprecated since v1.3. Please use {@link getConfirmedSignaturesForAddress2} instead.\n *\n * @param address queried address\n * @param startSlot start slot, inclusive\n * @param endSlot end slot, inclusive\n */\n async getConfirmedSignaturesForAddress(\n address: PublicKey,\n startSlot: number,\n endSlot: number,\n ): Promise> {\n let options: any = {};\n\n let firstAvailableBlock = await this.getFirstAvailableBlock();\n while (!('until' in options)) {\n startSlot--;\n if (startSlot <= 0 || startSlot < firstAvailableBlock) {\n break;\n }\n\n try {\n const block = await this.getConfirmedBlockSignatures(\n startSlot,\n 'finalized',\n );\n if (block.signatures.length > 0) {\n options.until =\n block.signatures[block.signatures.length - 1].toString();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('skipped')) {\n continue;\n } else {\n throw err;\n }\n }\n }\n\n let highestConfirmedRoot = await this.getSlot('finalized');\n while (!('before' in options)) {\n endSlot++;\n if (endSlot > highestConfirmedRoot) {\n break;\n }\n\n try {\n const block = await this.getConfirmedBlockSignatures(endSlot);\n if (block.signatures.length > 0) {\n options.before =\n block.signatures[block.signatures.length - 1].toString();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('skipped')) {\n continue;\n } else {\n throw err;\n }\n }\n }\n\n const confirmedSignatureInfo = await this.getConfirmedSignaturesForAddress2(\n address,\n options,\n );\n return confirmedSignatureInfo.map(info => info.signature);\n }\n\n /**\n * Returns confirmed signatures for transactions involving an\n * address backwards in time from the provided signature or most recent confirmed block\n *\n *\n * @param address queried address\n * @param options\n */\n async getConfirmedSignaturesForAddress2(\n address: PublicKey,\n options?: ConfirmedSignaturesForAddress2Options,\n commitment?: Finality,\n ): Promise> {\n const args = this._buildArgsAtLeastConfirmed(\n [address.toBase58()],\n commitment,\n undefined,\n options,\n );\n const unsafeRes = await this._rpcRequest(\n 'getConfirmedSignaturesForAddress2',\n args,\n );\n const res = create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get confirmed signatures for address',\n );\n }\n return res.result;\n }\n\n /**\n * Returns confirmed signatures for transactions involving an\n * address backwards in time from the provided signature or most recent confirmed block\n *\n *\n * @param address queried address\n * @param options\n */\n async getSignaturesForAddress(\n address: PublicKey,\n options?: SignaturesForAddressOptions,\n commitment?: Finality,\n ): Promise> {\n const args = this._buildArgsAtLeastConfirmed(\n [address.toBase58()],\n commitment,\n undefined,\n options,\n );\n const unsafeRes = await this._rpcRequest('getSignaturesForAddress', args);\n const res = create(unsafeRes, GetSignaturesForAddressRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get signatures for address',\n );\n }\n return res.result;\n }\n\n async getAddressLookupTable(\n accountKey: PublicKey,\n config?: GetAccountInfoConfig,\n ): Promise> {\n const {context, value: accountInfo} = await this.getAccountInfoAndContext(\n accountKey,\n config,\n );\n\n let value = null;\n if (accountInfo !== null) {\n value = new AddressLookupTableAccount({\n key: accountKey,\n state: AddressLookupTableAccount.deserialize(accountInfo.data),\n });\n }\n\n return {\n context,\n value,\n };\n }\n\n /**\n * Fetch the contents of a Nonce account from the cluster, return with context\n */\n async getNonceAndContext(\n nonceAccount: PublicKey,\n commitmentOrConfig?: Commitment | GetNonceAndContextConfig,\n ): Promise> {\n const {context, value: accountInfo} = await this.getAccountInfoAndContext(\n nonceAccount,\n commitmentOrConfig,\n );\n\n let value = null;\n if (accountInfo !== null) {\n value = NonceAccount.fromAccountData(accountInfo.data);\n }\n\n return {\n context,\n value,\n };\n }\n\n /**\n * Fetch the contents of a Nonce account from the cluster\n */\n async getNonce(\n nonceAccount: PublicKey,\n commitmentOrConfig?: Commitment | GetNonceConfig,\n ): Promise {\n return await this.getNonceAndContext(nonceAccount, commitmentOrConfig)\n .then(x => x.value)\n .catch(e => {\n throw new Error(\n 'failed to get nonce for account ' +\n nonceAccount.toBase58() +\n ': ' +\n e,\n );\n });\n }\n\n /**\n * Request an allocation of lamports to the specified address\n *\n * ```typescript\n * import { Connection, PublicKey, LAMPORTS_PER_SOL } from \"@solana/web3.js\";\n *\n * (async () => {\n * const connection = new Connection(\"https://api.testnet.solana.com\", \"confirmed\");\n * const myAddress = new PublicKey(\"2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM\");\n * const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL);\n * await connection.confirmTransaction(signature);\n * })();\n * ```\n */\n async requestAirdrop(\n to: PublicKey,\n lamports: number,\n ): Promise {\n const unsafeRes = await this._rpcRequest('requestAirdrop', [\n to.toBase58(),\n lamports,\n ]);\n const res = create(unsafeRes, RequestAirdropRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `airdrop to ${to.toBase58()} failed`,\n );\n }\n return res.result;\n }\n\n /**\n * @internal\n */\n async _blockhashWithExpiryBlockHeight(\n disableCache: boolean,\n ): Promise {\n if (!disableCache) {\n // Wait for polling to finish\n while (this._pollingBlockhash) {\n await sleep(100);\n }\n const timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch;\n const expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS;\n if (this._blockhashInfo.latestBlockhash !== null && !expired) {\n return this._blockhashInfo.latestBlockhash;\n }\n }\n\n return await this._pollNewBlockhash();\n }\n\n /**\n * @internal\n */\n async _pollNewBlockhash(): Promise {\n this._pollingBlockhash = true;\n try {\n const startTime = Date.now();\n const cachedLatestBlockhash = this._blockhashInfo.latestBlockhash;\n const cachedBlockhash = cachedLatestBlockhash\n ? cachedLatestBlockhash.blockhash\n : null;\n for (let i = 0; i < 50; i++) {\n const latestBlockhash = await this.getLatestBlockhash('finalized');\n\n if (cachedBlockhash !== latestBlockhash.blockhash) {\n this._blockhashInfo = {\n latestBlockhash,\n lastFetch: Date.now(),\n transactionSignatures: [],\n simulatedSignatures: [],\n };\n return latestBlockhash;\n }\n\n // Sleep for approximately half a slot\n await sleep(MS_PER_SLOT / 2);\n }\n\n throw new Error(\n `Unable to obtain a new blockhash after ${Date.now() - startTime}ms`,\n );\n } finally {\n this._pollingBlockhash = false;\n }\n }\n\n /**\n * get the stake minimum delegation\n */\n async getStakeMinimumDelegation(\n config?: GetStakeMinimumDelegationConfig,\n ): Promise> {\n const {commitment, config: configArg} = extractCommitmentFromConfig(config);\n const args = this._buildArgs([], commitment, 'base64', configArg);\n const unsafeRes = await this._rpcRequest('getStakeMinimumDelegation', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get stake minimum delegation`,\n );\n }\n return res.result;\n }\n\n /**\n * Simulate a transaction\n *\n * @deprecated Instead, call {@link simulateTransaction} with {@link\n * VersionedTransaction} and {@link SimulateTransactionConfig} parameters\n */\n simulateTransaction(\n transactionOrMessage: Transaction | Message,\n signers?: Array,\n includeAccounts?: boolean | Array,\n ): Promise>;\n\n /**\n * Simulate a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n simulateTransaction(\n transaction: VersionedTransaction,\n config?: SimulateTransactionConfig,\n ): Promise>;\n\n /**\n * Simulate a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n async simulateTransaction(\n transactionOrMessage: VersionedTransaction | Transaction | Message,\n configOrSigners?: SimulateTransactionConfig | Array,\n includeAccounts?: boolean | Array,\n ): Promise> {\n if ('message' in transactionOrMessage) {\n const versionedTx = transactionOrMessage;\n const wireTransaction = versionedTx.serialize();\n const encodedTransaction =\n Buffer.from(wireTransaction).toString('base64');\n if (Array.isArray(configOrSigners) || includeAccounts !== undefined) {\n throw new Error('Invalid arguments');\n }\n\n const config: any = configOrSigners || {};\n config.encoding = 'base64';\n if (!('commitment' in config)) {\n config.commitment = this.commitment;\n }\n\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n if ('error' in res) {\n throw new Error('failed to simulate transaction: ' + res.error.message);\n }\n return res.result;\n }\n\n let transaction;\n if (transactionOrMessage instanceof Transaction) {\n let originalTx: Transaction = transactionOrMessage;\n transaction = new Transaction();\n transaction.feePayer = originalTx.feePayer;\n transaction.instructions = transactionOrMessage.instructions;\n transaction.nonceInfo = originalTx.nonceInfo;\n transaction.signatures = originalTx.signatures;\n } else {\n transaction = Transaction.populate(transactionOrMessage);\n // HACK: this function relies on mutating the populated transaction\n transaction._message = transaction._json = undefined;\n }\n\n if (configOrSigners !== undefined && !Array.isArray(configOrSigners)) {\n throw new Error('Invalid arguments');\n }\n\n const signers = configOrSigners;\n if (transaction.nonceInfo && signers) {\n transaction.sign(...signers);\n } else {\n let disableCache = this._disableBlockhashCaching;\n for (;;) {\n const latestBlockhash = await this._blockhashWithExpiryBlockHeight(\n disableCache,\n );\n transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n transaction.recentBlockhash = latestBlockhash.blockhash;\n\n if (!signers) break;\n\n transaction.sign(...signers);\n if (!transaction.signature) {\n throw new Error('!signature'); // should never happen\n }\n\n const signature = transaction.signature.toString('base64');\n if (\n !this._blockhashInfo.simulatedSignatures.includes(signature) &&\n !this._blockhashInfo.transactionSignatures.includes(signature)\n ) {\n // The signature of this transaction has not been seen before with the\n // current recentBlockhash, all done. Let's break\n this._blockhashInfo.simulatedSignatures.push(signature);\n break;\n } else {\n // This transaction would be treated as duplicate (its derived signature\n // matched to one of already recorded signatures).\n // So, we must fetch a new blockhash for a different signature by disabling\n // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n disableCache = true;\n }\n }\n }\n\n const message = transaction._compile();\n const signData = message.serialize();\n const wireTransaction = transaction._serialize(signData);\n const encodedTransaction = wireTransaction.toString('base64');\n const config: any = {\n encoding: 'base64',\n commitment: this.commitment,\n };\n\n if (includeAccounts) {\n const addresses = (\n Array.isArray(includeAccounts)\n ? includeAccounts\n : message.nonProgramIds()\n ).map(key => key.toBase58());\n\n config['accounts'] = {\n encoding: 'base64',\n addresses,\n };\n }\n\n if (signers) {\n config.sigVerify = true;\n }\n\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n if ('error' in res) {\n let logs;\n if ('data' in res.error) {\n logs = res.error.data.logs;\n if (logs && Array.isArray(logs)) {\n const traceIndent = '\\n ';\n const logTrace = traceIndent + logs.join(traceIndent);\n console.error(res.error.message, logTrace);\n }\n }\n throw new SendTransactionError(\n 'failed to simulate transaction: ' + res.error.message,\n logs,\n );\n }\n return res.result;\n }\n\n /**\n * Sign and send a transaction\n *\n * @deprecated Instead, call {@link sendTransaction} with a {@link\n * VersionedTransaction}\n */\n sendTransaction(\n transaction: Transaction,\n signers: Array,\n options?: SendOptions,\n ): Promise;\n\n /**\n * Send a signed transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n sendTransaction(\n transaction: VersionedTransaction,\n options?: SendOptions,\n ): Promise;\n\n /**\n * Sign and send a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n async sendTransaction(\n transaction: VersionedTransaction | Transaction,\n signersOrOptions?: Array | SendOptions,\n options?: SendOptions,\n ): Promise {\n if ('version' in transaction) {\n if (signersOrOptions && Array.isArray(signersOrOptions)) {\n throw new Error('Invalid arguments');\n }\n\n const wireTransaction = transaction.serialize();\n return await this.sendRawTransaction(wireTransaction, signersOrOptions);\n }\n\n if (signersOrOptions === undefined || !Array.isArray(signersOrOptions)) {\n throw new Error('Invalid arguments');\n }\n\n const signers = signersOrOptions;\n if (transaction.nonceInfo) {\n transaction.sign(...signers);\n } else {\n let disableCache = this._disableBlockhashCaching;\n for (;;) {\n const latestBlockhash = await this._blockhashWithExpiryBlockHeight(\n disableCache,\n );\n transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n transaction.recentBlockhash = latestBlockhash.blockhash;\n transaction.sign(...signers);\n if (!transaction.signature) {\n throw new Error('!signature'); // should never happen\n }\n\n const signature = transaction.signature.toString('base64');\n if (!this._blockhashInfo.transactionSignatures.includes(signature)) {\n // The signature of this transaction has not been seen before with the\n // current recentBlockhash, all done. Let's break\n this._blockhashInfo.transactionSignatures.push(signature);\n break;\n } else {\n // This transaction would be treated as duplicate (its derived signature\n // matched to one of already recorded signatures).\n // So, we must fetch a new blockhash for a different signature by disabling\n // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n disableCache = true;\n }\n }\n }\n\n const wireTransaction = transaction.serialize();\n return await this.sendRawTransaction(wireTransaction, options);\n }\n\n /**\n * Send a transaction that has already been signed and serialized into the\n * wire format\n */\n async sendRawTransaction(\n rawTransaction: Buffer | Uint8Array | Array,\n options?: SendOptions,\n ): Promise {\n const encodedTransaction = toBuffer(rawTransaction).toString('base64');\n const result = await this.sendEncodedTransaction(\n encodedTransaction,\n options,\n );\n return result;\n }\n\n /**\n * Send a transaction that has already been signed, serialized into the\n * wire format, and encoded as a base64 string\n */\n async sendEncodedTransaction(\n encodedTransaction: string,\n options?: SendOptions,\n ): Promise {\n const config: any = {encoding: 'base64'};\n const skipPreflight = options && options.skipPreflight;\n const preflightCommitment =\n (options && options.preflightCommitment) || this.commitment;\n\n if (options && options.maxRetries != null) {\n config.maxRetries = options.maxRetries;\n }\n if (options && options.minContextSlot != null) {\n config.minContextSlot = options.minContextSlot;\n }\n if (skipPreflight) {\n config.skipPreflight = skipPreflight;\n }\n if (preflightCommitment) {\n config.preflightCommitment = preflightCommitment;\n }\n\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('sendTransaction', args);\n const res = create(unsafeRes, SendTransactionRpcResult);\n if ('error' in res) {\n let logs;\n if ('data' in res.error) {\n logs = res.error.data.logs;\n }\n throw new SendTransactionError(\n 'failed to send transaction: ' + res.error.message,\n logs,\n );\n }\n return res.result;\n }\n\n /**\n * @internal\n */\n _wsOnOpen() {\n this._rpcWebSocketConnected = true;\n this._rpcWebSocketHeartbeat = setInterval(() => {\n // Ping server every 5s to prevent idle timeouts\n (async () => {\n try {\n await this._rpcWebSocket.notify('ping');\n // eslint-disable-next-line no-empty\n } catch {}\n })();\n }, 5000);\n this._updateSubscriptions();\n }\n\n /**\n * @internal\n */\n _wsOnError(err: Error) {\n this._rpcWebSocketConnected = false;\n console.error('ws error:', err.message);\n }\n\n /**\n * @internal\n */\n _wsOnClose(code: number) {\n this._rpcWebSocketConnected = false;\n this._rpcWebSocketGeneration =\n (this._rpcWebSocketGeneration + 1) % Number.MAX_SAFE_INTEGER;\n if (this._rpcWebSocketIdleTimeout) {\n clearTimeout(this._rpcWebSocketIdleTimeout);\n this._rpcWebSocketIdleTimeout = null;\n }\n if (this._rpcWebSocketHeartbeat) {\n clearInterval(this._rpcWebSocketHeartbeat);\n this._rpcWebSocketHeartbeat = null;\n }\n\n if (code === 1000) {\n // explicit close, check if any subscriptions have been made since close\n this._updateSubscriptions();\n return;\n }\n\n // implicit close, prepare subscriptions for auto-reconnect\n this._subscriptionCallbacksByServerSubscriptionId = {};\n Object.entries(\n this._subscriptionsByHash as Record,\n ).forEach(([hash, subscription]) => {\n this._setSubscription(hash, {\n ...subscription,\n state: 'pending',\n });\n });\n }\n\n /**\n * @internal\n */\n private _setSubscription(\n hash: SubscriptionConfigHash,\n nextSubscription: Subscription,\n ) {\n const prevState = this._subscriptionsByHash[hash]?.state;\n this._subscriptionsByHash[hash] = nextSubscription;\n if (prevState !== nextSubscription.state) {\n const stateChangeCallbacks =\n this._subscriptionStateChangeCallbacksByHash[hash];\n if (stateChangeCallbacks) {\n stateChangeCallbacks.forEach(cb => {\n try {\n cb(nextSubscription.state);\n // eslint-disable-next-line no-empty\n } catch {}\n });\n }\n }\n }\n\n /**\n * @internal\n */\n private _onSubscriptionStateChange(\n clientSubscriptionId: ClientSubscriptionId,\n callback: SubscriptionStateChangeCallback,\n ): SubscriptionStateChangeDisposeFn {\n const hash =\n this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n if (hash == null) {\n return () => {};\n }\n const stateChangeCallbacks = (this._subscriptionStateChangeCallbacksByHash[\n hash\n ] ||= new Set());\n stateChangeCallbacks.add(callback);\n return () => {\n stateChangeCallbacks.delete(callback);\n if (stateChangeCallbacks.size === 0) {\n delete this._subscriptionStateChangeCallbacksByHash[hash];\n }\n };\n }\n\n /**\n * @internal\n */\n async _updateSubscriptions() {\n if (Object.keys(this._subscriptionsByHash).length === 0) {\n if (this._rpcWebSocketConnected) {\n this._rpcWebSocketConnected = false;\n this._rpcWebSocketIdleTimeout = setTimeout(() => {\n this._rpcWebSocketIdleTimeout = null;\n try {\n this._rpcWebSocket.close();\n } catch (err) {\n // swallow error if socket has already been closed.\n if (err instanceof Error) {\n console.log(\n `Error when closing socket connection: ${err.message}`,\n );\n }\n }\n }, 500);\n }\n return;\n }\n\n if (this._rpcWebSocketIdleTimeout !== null) {\n clearTimeout(this._rpcWebSocketIdleTimeout);\n this._rpcWebSocketIdleTimeout = null;\n this._rpcWebSocketConnected = true;\n }\n\n if (!this._rpcWebSocketConnected) {\n this._rpcWebSocket.connect();\n return;\n }\n\n const activeWebSocketGeneration = this._rpcWebSocketGeneration;\n const isCurrentConnectionStillActive = () => {\n return activeWebSocketGeneration === this._rpcWebSocketGeneration;\n };\n\n await Promise.all(\n // Don't be tempted to change this to `Object.entries`. We call\n // `_updateSubscriptions` recursively when processing the state,\n // so it's important that we look up the *current* version of\n // each subscription, every time we process a hash.\n Object.keys(this._subscriptionsByHash).map(async hash => {\n const subscription = this._subscriptionsByHash[hash];\n if (subscription === undefined) {\n // This entry has since been deleted. Skip.\n return;\n }\n switch (subscription.state) {\n case 'pending':\n case 'unsubscribed':\n if (subscription.callbacks.size === 0) {\n /**\n * You can end up here when:\n *\n * - a subscription has recently unsubscribed\n * without having new callbacks added to it\n * while the unsubscribe was in flight, or\n * - when a pending subscription has its\n * listeners removed before a request was\n * sent to the server.\n *\n * Being that nobody is interested in this\n * subscription any longer, delete it.\n */\n delete this._subscriptionsByHash[hash];\n if (subscription.state === 'unsubscribed') {\n delete this._subscriptionCallbacksByServerSubscriptionId[\n subscription.serverSubscriptionId\n ];\n }\n await this._updateSubscriptions();\n return;\n }\n await (async () => {\n const {args, method} = subscription;\n try {\n this._setSubscription(hash, {\n ...subscription,\n state: 'subscribing',\n });\n const serverSubscriptionId: ServerSubscriptionId =\n (await this._rpcWebSocket.call(method, args)) as number;\n this._setSubscription(hash, {\n ...subscription,\n serverSubscriptionId,\n state: 'subscribed',\n });\n this._subscriptionCallbacksByServerSubscriptionId[\n serverSubscriptionId\n ] = subscription.callbacks;\n await this._updateSubscriptions();\n } catch (e) {\n if (e instanceof Error) {\n console.error(\n `${method} error for argument`,\n args,\n e.message,\n );\n }\n if (!isCurrentConnectionStillActive()) {\n return;\n }\n // TODO: Maybe add an 'errored' state or a retry limit?\n this._setSubscription(hash, {\n ...subscription,\n state: 'pending',\n });\n await this._updateSubscriptions();\n }\n })();\n break;\n case 'subscribed':\n if (subscription.callbacks.size === 0) {\n // By the time we successfully set up a subscription\n // with the server, the client stopped caring about it.\n // Tear it down now.\n await (async () => {\n const {serverSubscriptionId, unsubscribeMethod} = subscription;\n if (\n this._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)\n ) {\n /**\n * Special case.\n * If we're dealing with a subscription that has been auto-\n * disposed by the RPC, then we can skip the RPC call to\n * tear down the subscription here.\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n this._subscriptionsAutoDisposedByRpc.delete(\n serverSubscriptionId,\n );\n } else {\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribing',\n });\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribing',\n });\n try {\n await this._rpcWebSocket.call(unsubscribeMethod, [\n serverSubscriptionId,\n ]);\n } catch (e) {\n if (e instanceof Error) {\n console.error(`${unsubscribeMethod} error:`, e.message);\n }\n if (!isCurrentConnectionStillActive()) {\n return;\n }\n // TODO: Maybe add an 'errored' state or a retry limit?\n this._setSubscription(hash, {\n ...subscription,\n state: 'subscribed',\n });\n await this._updateSubscriptions();\n return;\n }\n }\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribed',\n });\n await this._updateSubscriptions();\n })();\n }\n break;\n case 'subscribing':\n case 'unsubscribing':\n break;\n }\n }),\n );\n }\n\n /**\n * @internal\n */\n private _handleServerNotification<\n TCallback extends SubscriptionConfig['callback'],\n >(\n serverSubscriptionId: ServerSubscriptionId,\n callbackArgs: Parameters,\n ): void {\n const callbacks =\n this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId];\n if (callbacks === undefined) {\n return;\n }\n callbacks.forEach(cb => {\n try {\n cb(\n // I failed to find a way to convince TypeScript that `cb` is of type\n // `TCallback` which is certainly compatible with `Parameters`.\n // See https://github.com/microsoft/TypeScript/issues/47615\n // @ts-ignore\n ...callbackArgs,\n );\n } catch (e) {\n console.error(e);\n }\n });\n }\n\n /**\n * @internal\n */\n _wsOnAccountNotification(notification: object) {\n const {result, subscription} = create(\n notification,\n AccountNotificationResult,\n );\n this._handleServerNotification(subscription, [\n result.value,\n result.context,\n ]);\n }\n\n /**\n * @internal\n */\n private _makeSubscription(\n subscriptionConfig: SubscriptionConfig,\n /**\n * When preparing `args` for a call to `_makeSubscription`, be sure\n * to carefully apply a default `commitment` property, if necessary.\n *\n * - If the user supplied a `commitment` use that.\n * - Otherwise, if the `Connection::commitment` is set, use that.\n * - Otherwise, set it to the RPC server default: `finalized`.\n *\n * This is extremely important to ensure that these two fundamentally\n * identical subscriptions produce the same identifying hash:\n *\n * - A subscription made without specifying a commitment.\n * - A subscription made where the commitment specified is the same\n * as the default applied to the subscription above.\n *\n * Example; these two subscriptions must produce the same hash:\n *\n * - An `accountSubscribe` subscription for `'PUBKEY'`\n * - An `accountSubscribe` subscription for `'PUBKEY'` with commitment\n * `'finalized'`.\n *\n * See the 'making a subscription with defaulted params omitted' test\n * in `connection-subscriptions.ts` for more.\n */\n args: IWSRequestParams,\n ): ClientSubscriptionId {\n const clientSubscriptionId = this._nextClientSubscriptionId++;\n const hash = fastStableStringify(\n [subscriptionConfig.method, args],\n true /* isArrayProp */,\n );\n const existingSubscription = this._subscriptionsByHash[hash];\n if (existingSubscription === undefined) {\n this._subscriptionsByHash[hash] = {\n ...subscriptionConfig,\n args,\n callbacks: new Set([subscriptionConfig.callback]),\n state: 'pending',\n };\n } else {\n existingSubscription.callbacks.add(subscriptionConfig.callback);\n }\n this._subscriptionHashByClientSubscriptionId[clientSubscriptionId] = hash;\n this._subscriptionDisposeFunctionsByClientSubscriptionId[\n clientSubscriptionId\n ] = async () => {\n delete this._subscriptionDisposeFunctionsByClientSubscriptionId[\n clientSubscriptionId\n ];\n delete this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n const subscription = this._subscriptionsByHash[hash];\n assert(\n subscription !== undefined,\n `Could not find a \\`Subscription\\` when tearing down client subscription #${clientSubscriptionId}`,\n );\n subscription.callbacks.delete(subscriptionConfig.callback);\n await this._updateSubscriptions();\n };\n this._updateSubscriptions();\n return clientSubscriptionId;\n }\n\n /**\n * Register a callback to be invoked whenever the specified account changes\n *\n * @param publicKey Public key of the account to monitor\n * @param callback Function to invoke whenever the account is changed\n * @param commitment Specify the commitment level account changes must reach before notification\n * @return subscription id\n */\n onAccountChange(\n publicKey: PublicKey,\n callback: AccountChangeCallback,\n commitment?: Commitment,\n ): ClientSubscriptionId {\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment || this._commitment || 'finalized', // Apply connection/server default.\n 'base64',\n );\n return this._makeSubscription(\n {\n callback,\n method: 'accountSubscribe',\n unsubscribeMethod: 'accountUnsubscribe',\n },\n args,\n );\n }\n\n /**\n * Deregister an account notification callback\n *\n * @param id client subscription id to deregister\n */\n async removeAccountChangeListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'account change',\n );\n }\n\n /**\n * @internal\n */\n _wsOnProgramAccountNotification(notification: Object) {\n const {result, subscription} = create(\n notification,\n ProgramAccountNotificationResult,\n );\n this._handleServerNotification(subscription, [\n {\n accountId: result.value.pubkey,\n accountInfo: result.value.account,\n },\n result.context,\n ]);\n }\n\n /**\n * Register a callback to be invoked whenever accounts owned by the\n * specified program change\n *\n * @param programId Public key of the program to monitor\n * @param callback Function to invoke whenever the account is changed\n * @param commitment Specify the commitment level account changes must reach before notification\n * @param filters The program account filters to pass into the RPC method\n * @return subscription id\n */\n onProgramAccountChange(\n programId: PublicKey,\n callback: ProgramAccountChangeCallback,\n commitment?: Commitment,\n filters?: GetProgramAccountsFilter[],\n ): ClientSubscriptionId {\n const args = this._buildArgs(\n [programId.toBase58()],\n commitment || this._commitment || 'finalized', // Apply connection/server default.\n 'base64' /* encoding */,\n filters ? {filters: filters} : undefined /* extra */,\n );\n return this._makeSubscription(\n {\n callback,\n method: 'programSubscribe',\n unsubscribeMethod: 'programUnsubscribe',\n },\n args,\n );\n }\n\n /**\n * Deregister an account notification callback\n *\n * @param id client subscription id to deregister\n */\n async removeProgramAccountChangeListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'program account change',\n );\n }\n\n /**\n * Registers a callback to be invoked whenever logs are emitted.\n */\n onLogs(\n filter: LogsFilter,\n callback: LogsCallback,\n commitment?: Commitment,\n ): ClientSubscriptionId {\n const args = this._buildArgs(\n [typeof filter === 'object' ? {mentions: [filter.toString()]} : filter],\n commitment || this._commitment || 'finalized', // Apply connection/server default.\n );\n return this._makeSubscription(\n {\n callback,\n method: 'logsSubscribe',\n unsubscribeMethod: 'logsUnsubscribe',\n },\n args,\n );\n }\n\n /**\n * Deregister a logs callback.\n *\n * @param id client subscription id to deregister.\n */\n async removeOnLogsListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'logs');\n }\n\n /**\n * @internal\n */\n _wsOnLogsNotification(notification: Object) {\n const {result, subscription} = create(notification, LogsNotificationResult);\n this._handleServerNotification(subscription, [\n result.value,\n result.context,\n ]);\n }\n\n /**\n * @internal\n */\n _wsOnSlotNotification(notification: Object) {\n const {result, subscription} = create(notification, SlotNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon slot changes\n *\n * @param callback Function to invoke whenever the slot changes\n * @return subscription id\n */\n onSlotChange(callback: SlotChangeCallback): ClientSubscriptionId {\n return this._makeSubscription(\n {\n callback,\n method: 'slotSubscribe',\n unsubscribeMethod: 'slotUnsubscribe',\n },\n [] /* args */,\n );\n }\n\n /**\n * Deregister a slot notification callback\n *\n * @param id client subscription id to deregister\n */\n async removeSlotChangeListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'slot change',\n );\n }\n\n /**\n * @internal\n */\n _wsOnSlotUpdatesNotification(notification: Object) {\n const {result, subscription} = create(\n notification,\n SlotUpdateNotificationResult,\n );\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s\n * may be useful to track live progress of a cluster.\n *\n * @param callback Function to invoke whenever the slot updates\n * @return subscription id\n */\n onSlotUpdate(callback: SlotUpdateCallback): ClientSubscriptionId {\n return this._makeSubscription(\n {\n callback,\n method: 'slotsUpdatesSubscribe',\n unsubscribeMethod: 'slotsUpdatesUnsubscribe',\n },\n [] /* args */,\n );\n }\n\n /**\n * Deregister a slot update notification callback\n *\n * @param id client subscription id to deregister\n */\n async removeSlotUpdateListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'slot update',\n );\n }\n\n /**\n * @internal\n */\n\n private async _unsubscribeClientSubscription(\n clientSubscriptionId: ClientSubscriptionId,\n subscriptionName: string,\n ) {\n const dispose =\n this._subscriptionDisposeFunctionsByClientSubscriptionId[\n clientSubscriptionId\n ];\n if (dispose) {\n await dispose();\n } else {\n console.warn(\n 'Ignored unsubscribe request because an active subscription with id ' +\n `\\`${clientSubscriptionId}\\` for '${subscriptionName}' events ` +\n 'could not be found.',\n );\n }\n }\n\n _buildArgs(\n args: Array,\n override?: Commitment,\n encoding?: 'jsonParsed' | 'base64',\n extra?: any,\n ): Array {\n const commitment = override || this._commitment;\n if (commitment || encoding || extra) {\n let options: any = {};\n if (encoding) {\n options.encoding = encoding;\n }\n if (commitment) {\n options.commitment = commitment;\n }\n if (extra) {\n options = Object.assign(options, extra);\n }\n args.push(options);\n }\n return args;\n }\n\n /**\n * @internal\n */\n _buildArgsAtLeastConfirmed(\n args: Array,\n override?: Finality,\n encoding?: 'jsonParsed' | 'base64',\n extra?: any,\n ): Array {\n const commitment = override || this._commitment;\n if (commitment && !['confirmed', 'finalized'].includes(commitment)) {\n throw new Error(\n 'Using Connection with default commitment: `' +\n this._commitment +\n '`, but method requires at least `confirmed`',\n );\n }\n return this._buildArgs(args, override, encoding, extra);\n }\n\n /**\n * @internal\n */\n _wsOnSignatureNotification(notification: Object) {\n const {result, subscription} = create(\n notification,\n SignatureNotificationResult,\n );\n if (result.value !== 'receivedSignature') {\n /**\n * Special case.\n * After a signature is processed, RPCs automatically dispose of the\n * subscription on the server side. We need to track which of these\n * subscriptions have been disposed in such a way, so that we know\n * whether the client is dealing with a not-yet-processed signature\n * (in which case we must tear down the server subscription) or an\n * already-processed signature (in which case the client can simply\n * clear out the subscription locally without telling the server).\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n this._subscriptionsAutoDisposedByRpc.add(subscription);\n }\n this._handleServerNotification(\n subscription,\n result.value === 'receivedSignature'\n ? [{type: 'received'}, result.context]\n : [{type: 'status', result: result.value}, result.context],\n );\n }\n\n /**\n * Register a callback to be invoked upon signature updates\n *\n * @param signature Transaction signature string in base 58\n * @param callback Function to invoke on signature notifications\n * @param commitment Specify the commitment level signature must reach before notification\n * @return subscription id\n */\n onSignature(\n signature: TransactionSignature,\n callback: SignatureResultCallback,\n commitment?: Commitment,\n ): ClientSubscriptionId {\n const args = this._buildArgs(\n [signature],\n commitment || this._commitment || 'finalized', // Apply connection/server default.\n );\n const clientSubscriptionId = this._makeSubscription(\n {\n callback: (notification, context) => {\n if (notification.type === 'status') {\n callback(notification.result, context);\n // Signatures subscriptions are auto-removed by the RPC service\n // so no need to explicitly send an unsubscribe message.\n try {\n this.removeSignatureListener(clientSubscriptionId);\n // eslint-disable-next-line no-empty\n } catch (_err) {\n // Already removed.\n }\n }\n },\n method: 'signatureSubscribe',\n unsubscribeMethod: 'signatureUnsubscribe',\n },\n args,\n );\n return clientSubscriptionId;\n }\n\n /**\n * Register a callback to be invoked when a transaction is\n * received and/or processed.\n *\n * @param signature Transaction signature string in base 58\n * @param callback Function to invoke on signature notifications\n * @param options Enable received notifications and set the commitment\n * level that signature must reach before notification\n * @return subscription id\n */\n onSignatureWithOptions(\n signature: TransactionSignature,\n callback: SignatureSubscriptionCallback,\n options?: SignatureSubscriptionOptions,\n ): ClientSubscriptionId {\n const {commitment, ...extra} = {\n ...options,\n commitment:\n (options && options.commitment) || this._commitment || 'finalized', // Apply connection/server default.\n };\n const args = this._buildArgs(\n [signature],\n commitment,\n undefined /* encoding */,\n extra,\n );\n const clientSubscriptionId = this._makeSubscription(\n {\n callback: (notification, context) => {\n callback(notification, context);\n // Signatures subscriptions are auto-removed by the RPC service\n // so no need to explicitly send an unsubscribe message.\n try {\n this.removeSignatureListener(clientSubscriptionId);\n // eslint-disable-next-line no-empty\n } catch (_err) {\n // Already removed.\n }\n },\n method: 'signatureSubscribe',\n unsubscribeMethod: 'signatureUnsubscribe',\n },\n args,\n );\n return clientSubscriptionId;\n }\n\n /**\n * Deregister a signature notification callback\n *\n * @param id client subscription id to deregister\n */\n async removeSignatureListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'signature result',\n );\n }\n\n /**\n * @internal\n */\n _wsOnRootNotification(notification: Object) {\n const {result, subscription} = create(notification, RootNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon root changes\n *\n * @param callback Function to invoke whenever the root changes\n * @return subscription id\n */\n onRootChange(callback: RootChangeCallback): ClientSubscriptionId {\n return this._makeSubscription(\n {\n callback,\n method: 'rootSubscribe',\n unsubscribeMethod: 'rootUnsubscribe',\n },\n [] /* args */,\n );\n }\n\n /**\n * Deregister a root notification callback\n *\n * @param id client subscription id to deregister\n */\n async removeRootChangeListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'root change',\n );\n }\n}\n","import {generateKeypair, getPublicKey, Ed25519Keypair} from './utils/ed25519';\nimport {PublicKey} from './publickey';\n\n/**\n * Keypair signer interface\n */\nexport interface Signer {\n publicKey: PublicKey;\n secretKey: Uint8Array;\n}\n\n/**\n * An account keypair used for signing transactions.\n */\nexport class Keypair {\n private _keypair: Ed25519Keypair;\n\n /**\n * Create a new keypair instance.\n * Generate random keypair if no {@link Ed25519Keypair} is provided.\n *\n * @param keypair ed25519 keypair\n */\n constructor(keypair?: Ed25519Keypair) {\n this._keypair = keypair ?? generateKeypair();\n }\n\n /**\n * Generate a new random keypair\n */\n static generate(): Keypair {\n return new Keypair(generateKeypair());\n }\n\n /**\n * Create a keypair from a raw secret key byte array.\n *\n * This method should only be used to recreate a keypair from a previously\n * generated secret key. Generating keypairs from a random seed should be done\n * with the {@link Keypair.fromSeed} method.\n *\n * @throws error if the provided secret key is invalid and validation is not skipped.\n *\n * @param secretKey secret key byte array\n * @param options: skip secret key validation\n */\n static fromSecretKey(\n secretKey: Uint8Array,\n options?: {skipValidation?: boolean},\n ): Keypair {\n if (secretKey.byteLength !== 64) {\n throw new Error('bad secret key size');\n }\n const publicKey = secretKey.slice(32, 64);\n if (!options || !options.skipValidation) {\n const privateScalar = secretKey.slice(0, 32);\n const computedPublicKey = getPublicKey(privateScalar);\n for (let ii = 0; ii < 32; ii++) {\n if (publicKey[ii] !== computedPublicKey[ii]) {\n throw new Error('provided secretKey is invalid');\n }\n }\n }\n return new Keypair({publicKey, secretKey});\n }\n\n /**\n * Generate a keypair from a 32 byte seed.\n *\n * @param seed seed byte array\n */\n static fromSeed(seed: Uint8Array): Keypair {\n const publicKey = getPublicKey(seed);\n const secretKey = new Uint8Array(64);\n secretKey.set(seed);\n secretKey.set(publicKey, 32);\n return new Keypair({publicKey, secretKey});\n }\n\n /**\n * The public key for this keypair\n */\n get publicKey(): PublicKey {\n return new PublicKey(this._keypair.publicKey);\n }\n\n /**\n * The raw secret key for this keypair\n */\n get secretKey(): Uint8Array {\n return new Uint8Array(this._keypair.secretKey);\n }\n}\n","import {toBufferLE} from 'bigint-buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport * as Layout from '../../layout';\nimport {PublicKey} from '../../publickey';\nimport * as bigintLayout from '../../utils/bigint';\nimport {SystemProgram} from '../system';\nimport {TransactionInstruction} from '../../transaction';\nimport {decodeData, encodeData, IInstructionInputData} from '../../instruction';\n\nexport * from './state';\n\nexport type CreateLookupTableParams = {\n /** Account used to derive and control the new address lookup table. */\n authority: PublicKey;\n /** Account that will fund the new address lookup table. */\n payer: PublicKey;\n /** A recent slot must be used in the derivation path for each initialized table. */\n recentSlot: bigint | number;\n};\n\nexport type FreezeLookupTableParams = {\n /** Address lookup table account to freeze. */\n lookupTable: PublicKey;\n /** Account which is the current authority. */\n authority: PublicKey;\n};\n\nexport type ExtendLookupTableParams = {\n /** Address lookup table account to extend. */\n lookupTable: PublicKey;\n /** Account which is the current authority. */\n authority: PublicKey;\n /** Account that will fund the table reallocation.\n * Not required if the reallocation has already been funded. */\n payer?: PublicKey;\n /** List of Public Keys to be added to the lookup table. */\n addresses: Array;\n};\n\nexport type DeactivateLookupTableParams = {\n /** Address lookup table account to deactivate. */\n lookupTable: PublicKey;\n /** Account which is the current authority. */\n authority: PublicKey;\n};\n\nexport type CloseLookupTableParams = {\n /** Address lookup table account to close. */\n lookupTable: PublicKey;\n /** Account which is the current authority. */\n authority: PublicKey;\n /** Recipient of closed account lamports. */\n recipient: PublicKey;\n};\n\n/**\n * An enumeration of valid LookupTableInstructionType's\n */\nexport type LookupTableInstructionType =\n | 'CreateLookupTable'\n | 'ExtendLookupTable'\n | 'CloseLookupTable'\n | 'FreezeLookupTable'\n | 'DeactivateLookupTable';\n\ntype LookupTableInstructionInputData = {\n CreateLookupTable: IInstructionInputData &\n Readonly<{\n recentSlot: bigint;\n bumpSeed: number;\n }>;\n FreezeLookupTable: IInstructionInputData;\n ExtendLookupTable: IInstructionInputData &\n Readonly<{\n numberOfAddresses: bigint;\n addresses: Array;\n }>;\n DeactivateLookupTable: IInstructionInputData;\n CloseLookupTable: IInstructionInputData;\n};\n\n/**\n * An enumeration of valid address lookup table InstructionType's\n * @internal\n */\nexport const LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({\n CreateLookupTable: {\n index: 0,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['CreateLookupTable']\n >([\n BufferLayout.u32('instruction'),\n bigintLayout.u64('recentSlot'),\n BufferLayout.u8('bumpSeed'),\n ]),\n },\n FreezeLookupTable: {\n index: 1,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['FreezeLookupTable']\n >([BufferLayout.u32('instruction')]),\n },\n ExtendLookupTable: {\n index: 2,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['ExtendLookupTable']\n >([\n BufferLayout.u32('instruction'),\n bigintLayout.u64(),\n BufferLayout.seq(\n Layout.publicKey(),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'addresses',\n ),\n ]),\n },\n DeactivateLookupTable: {\n index: 3,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['DeactivateLookupTable']\n >([BufferLayout.u32('instruction')]),\n },\n CloseLookupTable: {\n index: 4,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['CloseLookupTable']\n >([BufferLayout.u32('instruction')]),\n },\n});\n\nexport class AddressLookupTableInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): LookupTableInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const index = instructionTypeLayout.decode(instruction.data);\n\n let type: LookupTableInstructionType | undefined;\n for (const [layoutType, layout] of Object.entries(\n LOOKUP_TABLE_INSTRUCTION_LAYOUTS,\n )) {\n if ((layout as any).index == index) {\n type = layoutType as LookupTableInstructionType;\n break;\n }\n }\n if (!type) {\n throw new Error(\n 'Invalid Instruction. Should be a LookupTable Instruction',\n );\n }\n return type;\n }\n\n static decodeCreateLookupTable(\n instruction: TransactionInstruction,\n ): CreateLookupTableParams {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 4);\n\n const {recentSlot} = decodeData(\n LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable,\n instruction.data,\n );\n\n return {\n authority: instruction.keys[1].pubkey,\n payer: instruction.keys[2].pubkey,\n recentSlot: Number(recentSlot),\n };\n }\n\n static decodeExtendLookupTable(\n instruction: TransactionInstruction,\n ): ExtendLookupTableParams {\n this.checkProgramId(instruction.programId);\n if (instruction.keys.length < 2) {\n throw new Error(\n `invalid instruction; found ${instruction.keys.length} keys, expected at least 2`,\n );\n }\n\n const {addresses} = decodeData(\n LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable,\n instruction.data,\n );\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n payer:\n instruction.keys.length > 2 ? instruction.keys[2].pubkey : undefined,\n addresses: addresses.map(buffer => new PublicKey(buffer)),\n };\n }\n\n static decodeCloseLookupTable(\n instruction: TransactionInstruction,\n ): CloseLookupTableParams {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 3);\n\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n recipient: instruction.keys[2].pubkey,\n };\n }\n\n static decodeFreezeLookupTable(\n instruction: TransactionInstruction,\n ): FreezeLookupTableParams {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 2);\n\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n };\n }\n\n static decodeDeactivateLookupTable(\n instruction: TransactionInstruction,\n ): DeactivateLookupTableParams {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 2);\n\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(AddressLookupTableProgram.programId)) {\n throw new Error(\n 'invalid instruction; programId is not AddressLookupTable Program',\n );\n }\n }\n /**\n * @internal\n */\n static checkKeysLength(keys: Array, expectedLength: number) {\n if (keys.length < expectedLength) {\n throw new Error(\n `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n );\n }\n }\n}\n\nexport class AddressLookupTableProgram {\n /**\n * @internal\n */\n constructor() {}\n\n static programId: PublicKey = new PublicKey(\n 'AddressLookupTab1e1111111111111111111111111',\n );\n\n static createLookupTable(params: CreateLookupTableParams) {\n const [lookupTableAddress, bumpSeed] = PublicKey.findProgramAddressSync(\n [params.authority.toBuffer(), toBufferLE(BigInt(params.recentSlot), 8)],\n this.programId,\n );\n\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;\n const data = encodeData(type, {\n recentSlot: BigInt(params.recentSlot),\n bumpSeed: bumpSeed,\n });\n\n const keys = [\n {\n pubkey: lookupTableAddress,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n {\n pubkey: params.payer,\n isSigner: true,\n isWritable: true,\n },\n {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n ];\n\n return [\n new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n }),\n lookupTableAddress,\n ] as [TransactionInstruction, PublicKey];\n }\n\n static freezeLookupTable(params: FreezeLookupTableParams) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;\n const data = encodeData(type);\n\n const keys = [\n {\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n ];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n });\n }\n\n static extendLookupTable(params: ExtendLookupTableParams) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;\n const data = encodeData(type, {\n addresses: params.addresses.map(addr => addr.toBytes()),\n });\n\n const keys = [\n {\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n ];\n\n if (params.payer) {\n keys.push(\n {\n pubkey: params.payer,\n isSigner: true,\n isWritable: true,\n },\n {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n );\n }\n\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n });\n }\n\n static deactivateLookupTable(params: DeactivateLookupTableParams) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;\n const data = encodeData(type);\n\n const keys = [\n {\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n ];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n });\n }\n\n static closeLookupTable(params: CloseLookupTableParams) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;\n const data = encodeData(type);\n\n const keys = [\n {\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n {\n pubkey: params.recipient,\n isSigner: false,\n isWritable: true,\n },\n ];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n });\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n encodeData,\n decodeData,\n InstructionType,\n IInstructionInputData,\n} from '../instruction';\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport {u64} from '../utils/bigint';\n\n/**\n * Compute Budget Instruction class\n */\nexport class ComputeBudgetInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a compute budget instruction and retrieve the instruction type.\n */\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): ComputeBudgetInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u8('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n let type: ComputeBudgetInstructionType | undefined;\n for (const [ixType, layout] of Object.entries(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS,\n )) {\n if (layout.index == typeIndex) {\n type = ixType as ComputeBudgetInstructionType;\n break;\n }\n }\n\n if (!type) {\n throw new Error(\n 'Instruction type incorrect; not a ComputeBudgetInstruction',\n );\n }\n\n return type;\n }\n\n /**\n * Decode request units compute budget instruction and retrieve the instruction params.\n */\n static decodeRequestUnits(\n instruction: TransactionInstruction,\n ): RequestUnitsParams {\n this.checkProgramId(instruction.programId);\n const {units, additionalFee} = decodeData(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits,\n instruction.data,\n );\n return {units, additionalFee};\n }\n\n /**\n * Decode request heap frame compute budget instruction and retrieve the instruction params.\n */\n static decodeRequestHeapFrame(\n instruction: TransactionInstruction,\n ): RequestHeapFrameParams {\n this.checkProgramId(instruction.programId);\n const {bytes} = decodeData(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame,\n instruction.data,\n );\n return {bytes};\n }\n\n /**\n * Decode set compute unit limit compute budget instruction and retrieve the instruction params.\n */\n static decodeSetComputeUnitLimit(\n instruction: TransactionInstruction,\n ): SetComputeUnitLimitParams {\n this.checkProgramId(instruction.programId);\n const {units} = decodeData(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit,\n instruction.data,\n );\n return {units};\n }\n\n /**\n * Decode set compute unit price compute budget instruction and retrieve the instruction params.\n */\n static decodeSetComputeUnitPrice(\n instruction: TransactionInstruction,\n ): SetComputeUnitPriceParams {\n this.checkProgramId(instruction.programId);\n const {microLamports} = decodeData(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice,\n instruction.data,\n );\n return {microLamports};\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(ComputeBudgetProgram.programId)) {\n throw new Error(\n 'invalid instruction; programId is not ComputeBudgetProgram',\n );\n }\n }\n}\n\n/**\n * An enumeration of valid ComputeBudgetInstructionType's\n */\nexport type ComputeBudgetInstructionType =\n // FIXME\n // It would be preferable for this type to be `keyof ComputeBudgetInstructionInputData`\n // but Typedoc does not transpile `keyof` expressions.\n // See https://github.com/TypeStrong/typedoc/issues/1894\n | 'RequestUnits'\n | 'RequestHeapFrame'\n | 'SetComputeUnitLimit'\n | 'SetComputeUnitPrice';\n\ntype ComputeBudgetInstructionInputData = {\n RequestUnits: IInstructionInputData & Readonly;\n RequestHeapFrame: IInstructionInputData & Readonly;\n SetComputeUnitLimit: IInstructionInputData &\n Readonly;\n SetComputeUnitPrice: IInstructionInputData &\n Readonly;\n};\n\n/**\n * Request units instruction params\n */\nexport interface RequestUnitsParams {\n /** Units to request for transaction-wide compute */\n units: number;\n /** Prioritization fee lamports */\n additionalFee: number;\n}\n\n/**\n * Request heap frame instruction params\n */\nexport type RequestHeapFrameParams = {\n /** Requested transaction-wide program heap size in bytes. Must be multiple of 1024. Applies to each program, including CPIs. */\n bytes: number;\n};\n\n/**\n * Set compute unit limit instruction params\n */\nexport interface SetComputeUnitLimitParams {\n /** Transaction-wide compute unit limit */\n units: number;\n}\n\n/**\n * Set compute unit price instruction params\n */\nexport interface SetComputeUnitPriceParams {\n /** Transaction compute unit price used for prioritization fees */\n microLamports: number | bigint;\n}\n\n/**\n * An enumeration of valid ComputeBudget InstructionType's\n * @internal\n */\nexport const COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze<{\n [Instruction in ComputeBudgetInstructionType]: InstructionType<\n ComputeBudgetInstructionInputData[Instruction]\n >;\n}>({\n RequestUnits: {\n index: 0,\n layout: BufferLayout.struct<\n ComputeBudgetInstructionInputData['RequestUnits']\n >([\n BufferLayout.u8('instruction'),\n BufferLayout.u32('units'),\n BufferLayout.u32('additionalFee'),\n ]),\n },\n RequestHeapFrame: {\n index: 1,\n layout: BufferLayout.struct<\n ComputeBudgetInstructionInputData['RequestHeapFrame']\n >([BufferLayout.u8('instruction'), BufferLayout.u32('bytes')]),\n },\n SetComputeUnitLimit: {\n index: 2,\n layout: BufferLayout.struct<\n ComputeBudgetInstructionInputData['SetComputeUnitLimit']\n >([BufferLayout.u8('instruction'), BufferLayout.u32('units')]),\n },\n SetComputeUnitPrice: {\n index: 3,\n layout: BufferLayout.struct<\n ComputeBudgetInstructionInputData['SetComputeUnitPrice']\n >([BufferLayout.u8('instruction'), u64('microLamports')]),\n },\n});\n\n/**\n * Factory class for transaction instructions to interact with the Compute Budget program\n */\nexport class ComputeBudgetProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Compute Budget program\n */\n static programId: PublicKey = new PublicKey(\n 'ComputeBudget111111111111111111111111111111',\n );\n\n /**\n * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}\n */\n static requestUnits(params: RequestUnitsParams): TransactionInstruction {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data,\n });\n }\n\n static requestHeapFrame(\n params: RequestHeapFrameParams,\n ): TransactionInstruction {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data,\n });\n }\n\n static setComputeUnitLimit(\n params: SetComputeUnitLimitParams,\n ): TransactionInstruction {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data,\n });\n }\n\n static setComputeUnitPrice(\n params: SetComputeUnitPriceParams,\n ): TransactionInstruction {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;\n const data = encodeData(type, {\n microLamports: BigInt(params.microLamports),\n });\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data,\n });\n }\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {Keypair} from '../keypair';\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport assert from '../utils/assert';\nimport {sign} from '../utils/ed25519';\n\nconst PRIVATE_KEY_BYTES = 64;\nconst PUBLIC_KEY_BYTES = 32;\nconst SIGNATURE_BYTES = 64;\n\n/**\n * Params for creating an ed25519 instruction using a public key\n */\nexport type CreateEd25519InstructionWithPublicKeyParams = {\n publicKey: Uint8Array;\n message: Uint8Array;\n signature: Uint8Array;\n instructionIndex?: number;\n};\n\n/**\n * Params for creating an ed25519 instruction using a private key\n */\nexport type CreateEd25519InstructionWithPrivateKeyParams = {\n privateKey: Uint8Array;\n message: Uint8Array;\n instructionIndex?: number;\n};\n\nconst ED25519_INSTRUCTION_LAYOUT = BufferLayout.struct<\n Readonly<{\n messageDataOffset: number;\n messageDataSize: number;\n messageInstructionIndex: number;\n numSignatures: number;\n padding: number;\n publicKeyInstructionIndex: number;\n publicKeyOffset: number;\n signatureInstructionIndex: number;\n signatureOffset: number;\n }>\n>([\n BufferLayout.u8('numSignatures'),\n BufferLayout.u8('padding'),\n BufferLayout.u16('signatureOffset'),\n BufferLayout.u16('signatureInstructionIndex'),\n BufferLayout.u16('publicKeyOffset'),\n BufferLayout.u16('publicKeyInstructionIndex'),\n BufferLayout.u16('messageDataOffset'),\n BufferLayout.u16('messageDataSize'),\n BufferLayout.u16('messageInstructionIndex'),\n]);\n\nexport class Ed25519Program {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the ed25519 program\n */\n static programId: PublicKey = new PublicKey(\n 'Ed25519SigVerify111111111111111111111111111',\n );\n\n /**\n * Create an ed25519 instruction with a public key and signature. The\n * public key must be a buffer that is 32 bytes long, and the signature\n * must be a buffer of 64 bytes.\n */\n static createInstructionWithPublicKey(\n params: CreateEd25519InstructionWithPublicKeyParams,\n ): TransactionInstruction {\n const {publicKey, message, signature, instructionIndex} = params;\n\n assert(\n publicKey.length === PUBLIC_KEY_BYTES,\n `Public Key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`,\n );\n\n assert(\n signature.length === SIGNATURE_BYTES,\n `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`,\n );\n\n const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;\n const signatureOffset = publicKeyOffset + publicKey.length;\n const messageDataOffset = signatureOffset + signature.length;\n const numSignatures = 1;\n\n const instructionData = Buffer.alloc(messageDataOffset + message.length);\n\n const index =\n instructionIndex == null\n ? 0xffff // An index of `u16::MAX` makes it default to the current instruction.\n : instructionIndex;\n\n ED25519_INSTRUCTION_LAYOUT.encode(\n {\n numSignatures,\n padding: 0,\n signatureOffset,\n signatureInstructionIndex: index,\n publicKeyOffset,\n publicKeyInstructionIndex: index,\n messageDataOffset,\n messageDataSize: message.length,\n messageInstructionIndex: index,\n },\n instructionData,\n );\n\n instructionData.fill(publicKey, publicKeyOffset);\n instructionData.fill(signature, signatureOffset);\n instructionData.fill(message, messageDataOffset);\n\n return new TransactionInstruction({\n keys: [],\n programId: Ed25519Program.programId,\n data: instructionData,\n });\n }\n\n /**\n * Create an ed25519 instruction with a private key. The private key\n * must be a buffer that is 64 bytes long.\n */\n static createInstructionWithPrivateKey(\n params: CreateEd25519InstructionWithPrivateKeyParams,\n ): TransactionInstruction {\n const {privateKey, message, instructionIndex} = params;\n\n assert(\n privateKey.length === PRIVATE_KEY_BYTES,\n `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${privateKey.length} bytes`,\n );\n\n try {\n const keypair = Keypair.fromSecretKey(privateKey);\n const publicKey = keypair.publicKey.toBytes();\n const signature = sign(message, keypair.secretKey);\n\n return this.createInstructionWithPublicKey({\n publicKey,\n message,\n signature,\n instructionIndex,\n });\n } catch (error) {\n throw new Error(`Error creating instruction; ${error}`);\n }\n }\n}\n","import {secp256k1} from '@noble/curves/secp256k1';\n\nexport const ecdsaSign = (\n msgHash: Parameters[0],\n privKey: Parameters[1],\n) => {\n const signature = secp256k1.sign(msgHash, privKey);\n return [signature.toCompactRawBytes(), signature.recovery!] as const;\n};\nexport const isValidPrivateKey = secp256k1.utils.isValidPrivateKey;\nexport const publicKeyCreate = secp256k1.getPublicKey;\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\nimport {keccak_256} from '@noble/hashes/sha3';\n\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport assert from '../utils/assert';\nimport {publicKeyCreate, ecdsaSign} from '../utils/secp256k1';\nimport {toBuffer} from '../utils/to-buffer';\n\nconst PRIVATE_KEY_BYTES = 32;\nconst ETHEREUM_ADDRESS_BYTES = 20;\nconst PUBLIC_KEY_BYTES = 64;\nconst SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;\n\n/**\n * Params for creating an secp256k1 instruction using a public key\n */\nexport type CreateSecp256k1InstructionWithPublicKeyParams = {\n publicKey: Buffer | Uint8Array | Array;\n message: Buffer | Uint8Array | Array;\n signature: Buffer | Uint8Array | Array;\n recoveryId: number;\n instructionIndex?: number;\n};\n\n/**\n * Params for creating an secp256k1 instruction using an Ethereum address\n */\nexport type CreateSecp256k1InstructionWithEthAddressParams = {\n ethAddress: Buffer | Uint8Array | Array | string;\n message: Buffer | Uint8Array | Array;\n signature: Buffer | Uint8Array | Array;\n recoveryId: number;\n instructionIndex?: number;\n};\n\n/**\n * Params for creating an secp256k1 instruction using a private key\n */\nexport type CreateSecp256k1InstructionWithPrivateKeyParams = {\n privateKey: Buffer | Uint8Array | Array;\n message: Buffer | Uint8Array | Array;\n instructionIndex?: number;\n};\n\nconst SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct<\n Readonly<{\n ethAddress: Uint8Array;\n ethAddressInstructionIndex: number;\n ethAddressOffset: number;\n messageDataOffset: number;\n messageDataSize: number;\n messageInstructionIndex: number;\n numSignatures: number;\n recoveryId: number;\n signature: Uint8Array;\n signatureInstructionIndex: number;\n signatureOffset: number;\n }>\n>([\n BufferLayout.u8('numSignatures'),\n BufferLayout.u16('signatureOffset'),\n BufferLayout.u8('signatureInstructionIndex'),\n BufferLayout.u16('ethAddressOffset'),\n BufferLayout.u8('ethAddressInstructionIndex'),\n BufferLayout.u16('messageDataOffset'),\n BufferLayout.u16('messageDataSize'),\n BufferLayout.u8('messageInstructionIndex'),\n BufferLayout.blob(20, 'ethAddress'),\n BufferLayout.blob(64, 'signature'),\n BufferLayout.u8('recoveryId'),\n]);\n\nexport class Secp256k1Program {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the secp256k1 program\n */\n static programId: PublicKey = new PublicKey(\n 'KeccakSecp256k11111111111111111111111111111',\n );\n\n /**\n * Construct an Ethereum address from a secp256k1 public key buffer.\n * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer\n */\n static publicKeyToEthAddress(\n publicKey: Buffer | Uint8Array | Array,\n ): Buffer {\n assert(\n publicKey.length === PUBLIC_KEY_BYTES,\n `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`,\n );\n\n try {\n return Buffer.from(keccak_256(toBuffer(publicKey))).slice(\n -ETHEREUM_ADDRESS_BYTES,\n );\n } catch (error) {\n throw new Error(`Error constructing Ethereum address: ${error}`);\n }\n }\n\n /**\n * Create an secp256k1 instruction with a public key. The public key\n * must be a buffer that is 64 bytes long.\n */\n static createInstructionWithPublicKey(\n params: CreateSecp256k1InstructionWithPublicKeyParams,\n ): TransactionInstruction {\n const {publicKey, message, signature, recoveryId, instructionIndex} =\n params;\n return Secp256k1Program.createInstructionWithEthAddress({\n ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey),\n message,\n signature,\n recoveryId,\n instructionIndex,\n });\n }\n\n /**\n * Create an secp256k1 instruction with an Ethereum address. The address\n * must be a hex string or a buffer that is 20 bytes long.\n */\n static createInstructionWithEthAddress(\n params: CreateSecp256k1InstructionWithEthAddressParams,\n ): TransactionInstruction {\n const {\n ethAddress: rawAddress,\n message,\n signature,\n recoveryId,\n instructionIndex = 0,\n } = params;\n\n let ethAddress;\n if (typeof rawAddress === 'string') {\n if (rawAddress.startsWith('0x')) {\n ethAddress = Buffer.from(rawAddress.substr(2), 'hex');\n } else {\n ethAddress = Buffer.from(rawAddress, 'hex');\n }\n } else {\n ethAddress = rawAddress;\n }\n\n assert(\n ethAddress.length === ETHEREUM_ADDRESS_BYTES,\n `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`,\n );\n\n const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;\n const ethAddressOffset = dataStart;\n const signatureOffset = dataStart + ethAddress.length;\n const messageDataOffset = signatureOffset + signature.length + 1;\n const numSignatures = 1;\n\n const instructionData = Buffer.alloc(\n SECP256K1_INSTRUCTION_LAYOUT.span + message.length,\n );\n\n SECP256K1_INSTRUCTION_LAYOUT.encode(\n {\n numSignatures,\n signatureOffset,\n signatureInstructionIndex: instructionIndex,\n ethAddressOffset,\n ethAddressInstructionIndex: instructionIndex,\n messageDataOffset,\n messageDataSize: message.length,\n messageInstructionIndex: instructionIndex,\n signature: toBuffer(signature),\n ethAddress: toBuffer(ethAddress),\n recoveryId,\n },\n instructionData,\n );\n\n instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);\n\n return new TransactionInstruction({\n keys: [],\n programId: Secp256k1Program.programId,\n data: instructionData,\n });\n }\n\n /**\n * Create an secp256k1 instruction with a private key. The private key\n * must be a buffer that is 32 bytes long.\n */\n static createInstructionWithPrivateKey(\n params: CreateSecp256k1InstructionWithPrivateKeyParams,\n ): TransactionInstruction {\n const {privateKey: pkey, message, instructionIndex} = params;\n\n assert(\n pkey.length === PRIVATE_KEY_BYTES,\n `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`,\n );\n\n try {\n const privateKey = toBuffer(pkey);\n const publicKey = publicKeyCreate(\n privateKey,\n false /* isCompressed */,\n ).slice(1); // throw away leading byte\n const messageHash = Buffer.from(keccak_256(toBuffer(message)));\n const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);\n\n return this.createInstructionWithPublicKey({\n publicKey,\n message,\n signature,\n recoveryId,\n instructionIndex,\n });\n } catch (error) {\n throw new Error(`Error creating instruction; ${error}`);\n }\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n encodeData,\n decodeData,\n InstructionType,\n IInstructionInputData,\n} from '../instruction';\nimport * as Layout from '../layout';\nimport {PublicKey} from '../publickey';\nimport {SystemProgram} from './system';\nimport {\n SYSVAR_CLOCK_PUBKEY,\n SYSVAR_RENT_PUBKEY,\n SYSVAR_STAKE_HISTORY_PUBKEY,\n} from '../sysvar';\nimport {Transaction, TransactionInstruction} from '../transaction';\nimport {toBuffer} from '../utils/to-buffer';\n\n/**\n * Address of the stake config account which configures the rate\n * of stake warmup and cooldown as well as the slashing penalty.\n */\nexport const STAKE_CONFIG_ID = new PublicKey(\n 'StakeConfig11111111111111111111111111111111',\n);\n\n/**\n * Stake account authority info\n */\nexport class Authorized {\n /** stake authority */\n staker: PublicKey;\n /** withdraw authority */\n withdrawer: PublicKey;\n\n /**\n * Create a new Authorized object\n * @param staker the stake authority\n * @param withdrawer the withdraw authority\n */\n constructor(staker: PublicKey, withdrawer: PublicKey) {\n this.staker = staker;\n this.withdrawer = withdrawer;\n }\n}\n\ntype AuthorizedRaw = Readonly<{\n staker: Uint8Array;\n withdrawer: Uint8Array;\n}>;\n\n/**\n * Stake account lockup info\n */\nexport class Lockup {\n /** Unix timestamp of lockup expiration */\n unixTimestamp: number;\n /** Epoch of lockup expiration */\n epoch: number;\n /** Lockup custodian authority */\n custodian: PublicKey;\n\n /**\n * Create a new Lockup object\n */\n constructor(unixTimestamp: number, epoch: number, custodian: PublicKey) {\n this.unixTimestamp = unixTimestamp;\n this.epoch = epoch;\n this.custodian = custodian;\n }\n\n /**\n * Default, inactive Lockup value\n */\n static default: Lockup = new Lockup(0, 0, PublicKey.default);\n}\n\ntype LockupRaw = Readonly<{\n custodian: Uint8Array;\n epoch: number;\n unixTimestamp: number;\n}>;\n\n/**\n * Create stake account transaction params\n */\nexport type CreateStakeAccountParams = {\n /** Address of the account which will fund creation */\n fromPubkey: PublicKey;\n /** Address of the new stake account */\n stakePubkey: PublicKey;\n /** Authorities of the new stake account */\n authorized: Authorized;\n /** Lockup of the new stake account */\n lockup?: Lockup;\n /** Funding amount */\n lamports: number;\n};\n\n/**\n * Create stake account with seed transaction params\n */\nexport type CreateStakeAccountWithSeedParams = {\n fromPubkey: PublicKey;\n stakePubkey: PublicKey;\n basePubkey: PublicKey;\n seed: string;\n authorized: Authorized;\n lockup?: Lockup;\n lamports: number;\n};\n\n/**\n * Initialize stake instruction params\n */\nexport type InitializeStakeParams = {\n stakePubkey: PublicKey;\n authorized: Authorized;\n lockup?: Lockup;\n};\n\n/**\n * Delegate stake instruction params\n */\nexport type DelegateStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n votePubkey: PublicKey;\n};\n\n/**\n * Authorize stake instruction params\n */\nexport type AuthorizeStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n newAuthorizedPubkey: PublicKey;\n stakeAuthorizationType: StakeAuthorizationType;\n custodianPubkey?: PublicKey;\n};\n\n/**\n * Authorize stake instruction params using a derived key\n */\nexport type AuthorizeWithSeedStakeParams = {\n stakePubkey: PublicKey;\n authorityBase: PublicKey;\n authoritySeed: string;\n authorityOwner: PublicKey;\n newAuthorizedPubkey: PublicKey;\n stakeAuthorizationType: StakeAuthorizationType;\n custodianPubkey?: PublicKey;\n};\n\n/**\n * Split stake instruction params\n */\nexport type SplitStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n splitStakePubkey: PublicKey;\n lamports: number;\n};\n\n/**\n * Split with seed transaction params\n */\nexport type SplitStakeWithSeedParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n splitStakePubkey: PublicKey;\n basePubkey: PublicKey;\n seed: string;\n lamports: number;\n};\n\n/**\n * Withdraw stake instruction params\n */\nexport type WithdrawStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n toPubkey: PublicKey;\n lamports: number;\n custodianPubkey?: PublicKey;\n};\n\n/**\n * Deactivate stake instruction params\n */\nexport type DeactivateStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n};\n\n/**\n * Merge stake instruction params\n */\nexport type MergeStakeParams = {\n stakePubkey: PublicKey;\n sourceStakePubKey: PublicKey;\n authorizedPubkey: PublicKey;\n};\n\n/**\n * Stake Instruction class\n */\nexport class StakeInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a stake instruction and retrieve the instruction type.\n */\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): StakeInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n let type: StakeInstructionType | undefined;\n for (const [ixType, layout] of Object.entries(STAKE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType as StakeInstructionType;\n break;\n }\n }\n\n if (!type) {\n throw new Error('Instruction type incorrect; not a StakeInstruction');\n }\n\n return type;\n }\n\n /**\n * Decode a initialize stake instruction and retrieve the instruction params.\n */\n static decodeInitialize(\n instruction: TransactionInstruction,\n ): InitializeStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {authorized, lockup} = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.Initialize,\n instruction.data,\n );\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n authorized: new Authorized(\n new PublicKey(authorized.staker),\n new PublicKey(authorized.withdrawer),\n ),\n lockup: new Lockup(\n lockup.unixTimestamp,\n lockup.epoch,\n new PublicKey(lockup.custodian),\n ),\n };\n }\n\n /**\n * Decode a delegate stake instruction and retrieve the instruction params.\n */\n static decodeDelegate(\n instruction: TransactionInstruction,\n ): DelegateStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 6);\n decodeData(STAKE_INSTRUCTION_LAYOUTS.Delegate, instruction.data);\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n votePubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[5].pubkey,\n };\n }\n\n /**\n * Decode an authorize stake instruction and retrieve the instruction params.\n */\n static decodeAuthorize(\n instruction: TransactionInstruction,\n ): AuthorizeStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {newAuthorized, stakeAuthorizationType} = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.Authorize,\n instruction.data,\n );\n\n const o: AuthorizeStakeParams = {\n stakePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n stakeAuthorizationType: {\n index: stakeAuthorizationType,\n },\n };\n if (instruction.keys.length > 3) {\n o.custodianPubkey = instruction.keys[3].pubkey;\n }\n return o;\n }\n\n /**\n * Decode an authorize-with-seed stake instruction and retrieve the instruction params.\n */\n static decodeAuthorizeWithSeed(\n instruction: TransactionInstruction,\n ): AuthorizeWithSeedStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {\n newAuthorized,\n stakeAuthorizationType,\n authoritySeed,\n authorityOwner,\n } = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,\n instruction.data,\n );\n\n const o: AuthorizeWithSeedStakeParams = {\n stakePubkey: instruction.keys[0].pubkey,\n authorityBase: instruction.keys[1].pubkey,\n authoritySeed: authoritySeed,\n authorityOwner: new PublicKey(authorityOwner),\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n stakeAuthorizationType: {\n index: stakeAuthorizationType,\n },\n };\n if (instruction.keys.length > 3) {\n o.custodianPubkey = instruction.keys[3].pubkey;\n }\n return o;\n }\n\n /**\n * Decode a split stake instruction and retrieve the instruction params.\n */\n static decodeSplit(instruction: TransactionInstruction): SplitStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {lamports} = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.Split,\n instruction.data,\n );\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n splitStakePubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n lamports,\n };\n }\n\n /**\n * Decode a merge stake instruction and retrieve the instruction params.\n */\n static decodeMerge(instruction: TransactionInstruction): MergeStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData(STAKE_INSTRUCTION_LAYOUTS.Merge, instruction.data);\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n sourceStakePubKey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n };\n }\n\n /**\n * Decode a withdraw stake instruction and retrieve the instruction params.\n */\n static decodeWithdraw(\n instruction: TransactionInstruction,\n ): WithdrawStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 5);\n const {lamports} = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.Withdraw,\n instruction.data,\n );\n\n const o: WithdrawStakeParams = {\n stakePubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n lamports,\n };\n if (instruction.keys.length > 5) {\n o.custodianPubkey = instruction.keys[5].pubkey;\n }\n return o;\n }\n\n /**\n * Decode a deactivate stake instruction and retrieve the instruction params.\n */\n static decodeDeactivate(\n instruction: TransactionInstruction,\n ): DeactivateStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData(STAKE_INSTRUCTION_LAYOUTS.Deactivate, instruction.data);\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(StakeProgram.programId)) {\n throw new Error('invalid instruction; programId is not StakeProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys: Array, expectedLength: number) {\n if (keys.length < expectedLength) {\n throw new Error(\n `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n );\n }\n }\n}\n\n/**\n * An enumeration of valid StakeInstructionType's\n */\nexport type StakeInstructionType =\n // FIXME\n // It would be preferable for this type to be `keyof StakeInstructionInputData`\n // but Typedoc does not transpile `keyof` expressions.\n // See https://github.com/TypeStrong/typedoc/issues/1894\n | 'Authorize'\n | 'AuthorizeWithSeed'\n | 'Deactivate'\n | 'Delegate'\n | 'Initialize'\n | 'Merge'\n | 'Split'\n | 'Withdraw';\n\ntype StakeInstructionInputData = {\n Authorize: IInstructionInputData &\n Readonly<{\n newAuthorized: Uint8Array;\n stakeAuthorizationType: number;\n }>;\n AuthorizeWithSeed: IInstructionInputData &\n Readonly<{\n authorityOwner: Uint8Array;\n authoritySeed: string;\n instruction: number;\n newAuthorized: Uint8Array;\n stakeAuthorizationType: number;\n }>;\n Deactivate: IInstructionInputData;\n Delegate: IInstructionInputData;\n Initialize: IInstructionInputData &\n Readonly<{\n authorized: AuthorizedRaw;\n lockup: LockupRaw;\n }>;\n Merge: IInstructionInputData;\n Split: IInstructionInputData &\n Readonly<{\n lamports: number;\n }>;\n Withdraw: IInstructionInputData &\n Readonly<{\n lamports: number;\n }>;\n};\n\n/**\n * An enumeration of valid stake InstructionType's\n * @internal\n */\nexport const STAKE_INSTRUCTION_LAYOUTS = Object.freeze<{\n [Instruction in StakeInstructionType]: InstructionType<\n StakeInstructionInputData[Instruction]\n >;\n}>({\n Initialize: {\n index: 0,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.authorized(),\n Layout.lockup(),\n ]),\n },\n Authorize: {\n index: 1,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('newAuthorized'),\n BufferLayout.u32('stakeAuthorizationType'),\n ]),\n },\n Delegate: {\n index: 2,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n ]),\n },\n Split: {\n index: 3,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('lamports'),\n ]),\n },\n Withdraw: {\n index: 4,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('lamports'),\n ]),\n },\n Deactivate: {\n index: 5,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n ]),\n },\n Merge: {\n index: 7,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n ]),\n },\n AuthorizeWithSeed: {\n index: 8,\n layout: BufferLayout.struct(\n [\n BufferLayout.u32('instruction'),\n Layout.publicKey('newAuthorized'),\n BufferLayout.u32('stakeAuthorizationType'),\n Layout.rustString('authoritySeed'),\n Layout.publicKey('authorityOwner'),\n ],\n ),\n },\n});\n\n/**\n * Stake authorization type\n */\nexport type StakeAuthorizationType = {\n /** The Stake Authorization index (from solana-stake-program) */\n index: number;\n};\n\n/**\n * An enumeration of valid StakeAuthorizationLayout's\n */\nexport const StakeAuthorizationLayout = Object.freeze({\n Staker: {\n index: 0,\n },\n Withdrawer: {\n index: 1,\n },\n});\n\n/**\n * Factory class for transactions to interact with the Stake program\n */\nexport class StakeProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Stake program\n */\n static programId: PublicKey = new PublicKey(\n 'Stake11111111111111111111111111111111111111',\n );\n\n /**\n * Max space of a Stake account\n *\n * This is generated from the solana-stake-program StakeState struct as\n * `StakeState::size_of()`:\n * https://docs.rs/solana-stake-program/latest/solana_stake_program/stake_state/enum.StakeState.html\n */\n static space: number = 200;\n\n /**\n * Generate an Initialize instruction to add to a Stake Create transaction\n */\n static initialize(params: InitializeStakeParams): TransactionInstruction {\n const {stakePubkey, authorized, lockup: maybeLockup} = params;\n const lockup: Lockup = maybeLockup || Lockup.default;\n const type = STAKE_INSTRUCTION_LAYOUTS.Initialize;\n const data = encodeData(type, {\n authorized: {\n staker: toBuffer(authorized.staker.toBuffer()),\n withdrawer: toBuffer(authorized.withdrawer.toBuffer()),\n },\n lockup: {\n unixTimestamp: lockup.unixTimestamp,\n epoch: lockup.epoch,\n custodian: toBuffer(lockup.custodian.toBuffer()),\n },\n });\n const instructionData = {\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n ],\n programId: this.programId,\n data,\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a Transaction that creates a new Stake account at\n * an address generated with `from`, a seed, and the Stake programId\n */\n static createAccountWithSeed(\n params: CreateStakeAccountWithSeedParams,\n ): Transaction {\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.createAccountWithSeed({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.stakePubkey,\n basePubkey: params.basePubkey,\n seed: params.seed,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId,\n }),\n );\n\n const {stakePubkey, authorized, lockup} = params;\n return transaction.add(this.initialize({stakePubkey, authorized, lockup}));\n }\n\n /**\n * Generate a Transaction that creates a new Stake account\n */\n static createAccount(params: CreateStakeAccountParams): Transaction {\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.stakePubkey,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId,\n }),\n );\n\n const {stakePubkey, authorized, lockup} = params;\n return transaction.add(this.initialize({stakePubkey, authorized, lockup}));\n }\n\n /**\n * Generate a Transaction that delegates Stake tokens to a validator\n * Vote PublicKey. This transaction can also be used to redelegate Stake\n * to a new validator Vote PublicKey.\n */\n static delegate(params: DelegateStakeParams): Transaction {\n const {stakePubkey, authorizedPubkey, votePubkey} = params;\n\n const type = STAKE_INSTRUCTION_LAYOUTS.Delegate;\n const data = encodeData(type);\n\n return new Transaction().add({\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: votePubkey, isSigner: false, isWritable: false},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: STAKE_CONFIG_ID, isSigner: false, isWritable: false},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that authorizes a new PublicKey as Staker\n * or Withdrawer on the Stake account.\n */\n static authorize(params: AuthorizeStakeParams): Transaction {\n const {\n stakePubkey,\n authorizedPubkey,\n newAuthorizedPubkey,\n stakeAuthorizationType,\n custodianPubkey,\n } = params;\n\n const type = STAKE_INSTRUCTION_LAYOUTS.Authorize;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n stakeAuthorizationType: stakeAuthorizationType.index,\n });\n\n const keys = [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: true},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: false,\n isWritable: false,\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that authorizes a new PublicKey as Staker\n * or Withdrawer on the Stake account.\n */\n static authorizeWithSeed(params: AuthorizeWithSeedStakeParams): Transaction {\n const {\n stakePubkey,\n authorityBase,\n authoritySeed,\n authorityOwner,\n newAuthorizedPubkey,\n stakeAuthorizationType,\n custodianPubkey,\n } = params;\n\n const type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n stakeAuthorizationType: stakeAuthorizationType.index,\n authoritySeed: authoritySeed,\n authorityOwner: toBuffer(authorityOwner.toBuffer()),\n });\n\n const keys = [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: authorityBase, isSigner: true, isWritable: false},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n ];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: false,\n isWritable: false,\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * @internal\n */\n static splitInstruction(params: SplitStakeParams): TransactionInstruction {\n const {stakePubkey, authorizedPubkey, splitStakePubkey, lamports} = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Split;\n const data = encodeData(type, {lamports});\n return new TransactionInstruction({\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: splitStakePubkey, isSigner: false, isWritable: true},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that splits Stake tokens into another stake account\n */\n static split(params: SplitStakeParams): Transaction {\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.createAccount({\n fromPubkey: params.authorizedPubkey,\n newAccountPubkey: params.splitStakePubkey,\n lamports: 0,\n space: this.space,\n programId: this.programId,\n }),\n );\n return transaction.add(this.splitInstruction(params));\n }\n\n /**\n * Generate a Transaction that splits Stake tokens into another account\n * derived from a base public key and seed\n */\n static splitWithSeed(params: SplitStakeWithSeedParams): Transaction {\n const {\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n basePubkey,\n seed,\n lamports,\n } = params;\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.allocate({\n accountPubkey: splitStakePubkey,\n basePubkey,\n seed,\n space: this.space,\n programId: this.programId,\n }),\n );\n return transaction.add(\n this.splitInstruction({\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n lamports,\n }),\n );\n }\n\n /**\n * Generate a Transaction that merges Stake accounts.\n */\n static merge(params: MergeStakeParams): Transaction {\n const {stakePubkey, sourceStakePubKey, authorizedPubkey} = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Merge;\n const data = encodeData(type);\n\n return new Transaction().add({\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: sourceStakePubKey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that withdraws deactivated Stake tokens.\n */\n static withdraw(params: WithdrawStakeParams): Transaction {\n const {stakePubkey, authorizedPubkey, toPubkey, lamports, custodianPubkey} =\n params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Withdraw;\n const data = encodeData(type, {lamports});\n\n const keys = [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: toPubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: false,\n isWritable: false,\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that deactivates Stake tokens.\n */\n static deactivate(params: DeactivateStakeParams): Transaction {\n const {stakePubkey, authorizedPubkey} = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Deactivate;\n const data = encodeData(type);\n\n return new Transaction().add({\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n encodeData,\n decodeData,\n InstructionType,\n IInstructionInputData,\n} from '../instruction';\nimport * as Layout from '../layout';\nimport {PublicKey} from '../publickey';\nimport {SystemProgram} from './system';\nimport {SYSVAR_CLOCK_PUBKEY, SYSVAR_RENT_PUBKEY} from '../sysvar';\nimport {Transaction, TransactionInstruction} from '../transaction';\nimport {toBuffer} from '../utils/to-buffer';\n\n/**\n * Vote account info\n */\nexport class VoteInit {\n nodePubkey: PublicKey;\n authorizedVoter: PublicKey;\n authorizedWithdrawer: PublicKey;\n commission: number; /** [0, 100] */\n\n constructor(\n nodePubkey: PublicKey,\n authorizedVoter: PublicKey,\n authorizedWithdrawer: PublicKey,\n commission: number,\n ) {\n this.nodePubkey = nodePubkey;\n this.authorizedVoter = authorizedVoter;\n this.authorizedWithdrawer = authorizedWithdrawer;\n this.commission = commission;\n }\n}\n\n/**\n * Create vote account transaction params\n */\nexport type CreateVoteAccountParams = {\n fromPubkey: PublicKey;\n votePubkey: PublicKey;\n voteInit: VoteInit;\n lamports: number;\n};\n\n/**\n * InitializeAccount instruction params\n */\nexport type InitializeAccountParams = {\n votePubkey: PublicKey;\n nodePubkey: PublicKey;\n voteInit: VoteInit;\n};\n\n/**\n * Authorize instruction params\n */\nexport type AuthorizeVoteParams = {\n votePubkey: PublicKey;\n /** Current vote or withdraw authority, depending on `voteAuthorizationType` */\n authorizedPubkey: PublicKey;\n newAuthorizedPubkey: PublicKey;\n voteAuthorizationType: VoteAuthorizationType;\n};\n\n/**\n * AuthorizeWithSeed instruction params\n */\nexport type AuthorizeVoteWithSeedParams = {\n currentAuthorityDerivedKeyBasePubkey: PublicKey;\n currentAuthorityDerivedKeyOwnerPubkey: PublicKey;\n currentAuthorityDerivedKeySeed: string;\n newAuthorizedPubkey: PublicKey;\n voteAuthorizationType: VoteAuthorizationType;\n votePubkey: PublicKey;\n};\n\n/**\n * Withdraw from vote account transaction params\n */\nexport type WithdrawFromVoteAccountParams = {\n votePubkey: PublicKey;\n authorizedWithdrawerPubkey: PublicKey;\n lamports: number;\n toPubkey: PublicKey;\n};\n\n/**\n * Vote Instruction class\n */\nexport class VoteInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a vote instruction and retrieve the instruction type.\n */\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): VoteInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n let type: VoteInstructionType | undefined;\n for (const [ixType, layout] of Object.entries(VOTE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType as VoteInstructionType;\n break;\n }\n }\n\n if (!type) {\n throw new Error('Instruction type incorrect; not a VoteInstruction');\n }\n\n return type;\n }\n\n /**\n * Decode an initialize vote instruction and retrieve the instruction params.\n */\n static decodeInitializeAccount(\n instruction: TransactionInstruction,\n ): InitializeAccountParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 4);\n\n const {voteInit} = decodeData(\n VOTE_INSTRUCTION_LAYOUTS.InitializeAccount,\n instruction.data,\n );\n\n return {\n votePubkey: instruction.keys[0].pubkey,\n nodePubkey: instruction.keys[3].pubkey,\n voteInit: new VoteInit(\n new PublicKey(voteInit.nodePubkey),\n new PublicKey(voteInit.authorizedVoter),\n new PublicKey(voteInit.authorizedWithdrawer),\n voteInit.commission,\n ),\n };\n }\n\n /**\n * Decode an authorize instruction and retrieve the instruction params.\n */\n static decodeAuthorize(\n instruction: TransactionInstruction,\n ): AuthorizeVoteParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {newAuthorized, voteAuthorizationType} = decodeData(\n VOTE_INSTRUCTION_LAYOUTS.Authorize,\n instruction.data,\n );\n\n return {\n votePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n voteAuthorizationType: {\n index: voteAuthorizationType,\n },\n };\n }\n\n /**\n * Decode an authorize instruction and retrieve the instruction params.\n */\n static decodeAuthorizeWithSeed(\n instruction: TransactionInstruction,\n ): AuthorizeVoteWithSeedParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {\n voteAuthorizeWithSeedArgs: {\n currentAuthorityDerivedKeyOwnerPubkey,\n currentAuthorityDerivedKeySeed,\n newAuthorized,\n voteAuthorizationType,\n },\n } = decodeData(\n VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,\n instruction.data,\n );\n\n return {\n currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey,\n currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(\n currentAuthorityDerivedKeyOwnerPubkey,\n ),\n currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n voteAuthorizationType: {\n index: voteAuthorizationType,\n },\n votePubkey: instruction.keys[0].pubkey,\n };\n }\n\n /**\n * Decode a withdraw instruction and retrieve the instruction params.\n */\n static decodeWithdraw(\n instruction: TransactionInstruction,\n ): WithdrawFromVoteAccountParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {lamports} = decodeData(\n VOTE_INSTRUCTION_LAYOUTS.Withdraw,\n instruction.data,\n );\n\n return {\n votePubkey: instruction.keys[0].pubkey,\n authorizedWithdrawerPubkey: instruction.keys[2].pubkey,\n lamports,\n toPubkey: instruction.keys[1].pubkey,\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(VoteProgram.programId)) {\n throw new Error('invalid instruction; programId is not VoteProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys: Array, expectedLength: number) {\n if (keys.length < expectedLength) {\n throw new Error(\n `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n );\n }\n }\n}\n\n/**\n * An enumeration of valid VoteInstructionType's\n */\nexport type VoteInstructionType =\n // FIXME\n // It would be preferable for this type to be `keyof VoteInstructionInputData`\n // but Typedoc does not transpile `keyof` expressions.\n // See https://github.com/TypeStrong/typedoc/issues/1894\n 'Authorize' | 'AuthorizeWithSeed' | 'InitializeAccount' | 'Withdraw';\n\n/** @internal */\nexport type VoteAuthorizeWithSeedArgs = Readonly<{\n currentAuthorityDerivedKeyOwnerPubkey: Uint8Array;\n currentAuthorityDerivedKeySeed: string;\n newAuthorized: Uint8Array;\n voteAuthorizationType: number;\n}>;\ntype VoteInstructionInputData = {\n Authorize: IInstructionInputData & {\n newAuthorized: Uint8Array;\n voteAuthorizationType: number;\n };\n AuthorizeWithSeed: IInstructionInputData & {\n voteAuthorizeWithSeedArgs: VoteAuthorizeWithSeedArgs;\n };\n InitializeAccount: IInstructionInputData & {\n voteInit: Readonly<{\n authorizedVoter: Uint8Array;\n authorizedWithdrawer: Uint8Array;\n commission: number;\n nodePubkey: Uint8Array;\n }>;\n };\n Withdraw: IInstructionInputData & {\n lamports: number;\n };\n};\n\nconst VOTE_INSTRUCTION_LAYOUTS = Object.freeze<{\n [Instruction in VoteInstructionType]: InstructionType<\n VoteInstructionInputData[Instruction]\n >;\n}>({\n InitializeAccount: {\n index: 0,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.voteInit(),\n ]),\n },\n Authorize: {\n index: 1,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('newAuthorized'),\n BufferLayout.u32('voteAuthorizationType'),\n ]),\n },\n Withdraw: {\n index: 3,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('lamports'),\n ]),\n },\n AuthorizeWithSeed: {\n index: 10,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.voteAuthorizeWithSeedArgs(),\n ]),\n },\n});\n\n/**\n * VoteAuthorize type\n */\nexport type VoteAuthorizationType = {\n /** The VoteAuthorize index (from solana-vote-program) */\n index: number;\n};\n\n/**\n * An enumeration of valid VoteAuthorization layouts.\n */\nexport const VoteAuthorizationLayout = Object.freeze({\n Voter: {\n index: 0,\n },\n Withdrawer: {\n index: 1,\n },\n});\n\n/**\n * Factory class for transactions to interact with the Vote program\n */\nexport class VoteProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Vote program\n */\n static programId: PublicKey = new PublicKey(\n 'Vote111111111111111111111111111111111111111',\n );\n\n /**\n * Max space of a Vote account\n *\n * This is generated from the solana-vote-program VoteState struct as\n * `VoteState::size_of()`:\n * https://docs.rs/solana-vote-program/1.9.5/solana_vote_program/vote_state/struct.VoteState.html#method.size_of\n *\n * KEEP IN SYNC WITH `VoteState::size_of()` in https://github.com/solana-labs/solana/blob/a474cb24b9238f5edcc982f65c0b37d4a1046f7e/sdk/program/src/vote/state/mod.rs#L340-L342\n */\n static space: number = process.env.TEST_LIVE ? 3762 : 3731;\n\n /**\n * Generate an Initialize instruction.\n */\n static initializeAccount(\n params: InitializeAccountParams,\n ): TransactionInstruction {\n const {votePubkey, nodePubkey, voteInit} = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;\n const data = encodeData(type, {\n voteInit: {\n nodePubkey: toBuffer(voteInit.nodePubkey.toBuffer()),\n authorizedVoter: toBuffer(voteInit.authorizedVoter.toBuffer()),\n authorizedWithdrawer: toBuffer(\n voteInit.authorizedWithdrawer.toBuffer(),\n ),\n commission: voteInit.commission,\n },\n });\n const instructionData = {\n keys: [\n {pubkey: votePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {pubkey: nodePubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a transaction that creates a new Vote account.\n */\n static createAccount(params: CreateVoteAccountParams): Transaction {\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.votePubkey,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId,\n }),\n );\n\n return transaction.add(\n this.initializeAccount({\n votePubkey: params.votePubkey,\n nodePubkey: params.voteInit.nodePubkey,\n voteInit: params.voteInit,\n }),\n );\n }\n\n /**\n * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.\n */\n static authorize(params: AuthorizeVoteParams): Transaction {\n const {\n votePubkey,\n authorizedPubkey,\n newAuthorizedPubkey,\n voteAuthorizationType,\n } = params;\n\n const type = VOTE_INSTRUCTION_LAYOUTS.Authorize;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n voteAuthorizationType: voteAuthorizationType.index,\n });\n\n const keys = [\n {pubkey: votePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ];\n\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account\n * where the current Voter or Withdrawer authority is a derived key.\n */\n static authorizeWithSeed(params: AuthorizeVoteWithSeedParams): Transaction {\n const {\n currentAuthorityDerivedKeyBasePubkey,\n currentAuthorityDerivedKeyOwnerPubkey,\n currentAuthorityDerivedKeySeed,\n newAuthorizedPubkey,\n voteAuthorizationType,\n votePubkey,\n } = params;\n\n const type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n const data = encodeData(type, {\n voteAuthorizeWithSeedArgs: {\n currentAuthorityDerivedKeyOwnerPubkey: toBuffer(\n currentAuthorityDerivedKeyOwnerPubkey.toBuffer(),\n ),\n currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n voteAuthorizationType: voteAuthorizationType.index,\n },\n });\n\n const keys = [\n {pubkey: votePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {\n pubkey: currentAuthorityDerivedKeyBasePubkey,\n isSigner: true,\n isWritable: false,\n },\n ];\n\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction to withdraw from a Vote account.\n */\n static withdraw(params: WithdrawFromVoteAccountParams): Transaction {\n const {votePubkey, authorizedWithdrawerPubkey, lamports, toPubkey} = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.Withdraw;\n const data = encodeData(type, {lamports});\n\n const keys = [\n {pubkey: votePubkey, isSigner: false, isWritable: true},\n {pubkey: toPubkey, isSigner: false, isWritable: true},\n {pubkey: authorizedWithdrawerPubkey, isSigner: true, isWritable: false},\n ];\n\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction to withdraw safely from a Vote account.\n *\n * This function was created as a safeguard for vote accounts running validators, `safeWithdraw`\n * checks that the withdraw amount will not exceed the specified balance while leaving enough left\n * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the\n * `withdraw` method directly.\n */\n static safeWithdraw(\n params: WithdrawFromVoteAccountParams,\n currentVoteAccountBalance: number,\n rentExemptMinimum: number,\n ): Transaction {\n if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {\n throw new Error(\n 'Withdraw will leave vote account with insuffcient funds.',\n );\n }\n return VoteProgram.withdraw(params);\n }\n}\n","import {Buffer} from 'buffer';\nimport {\n assert as assertType,\n optional,\n string,\n type as pick,\n} from 'superstruct';\n\nimport * as Layout from './layout';\nimport * as shortvec from './utils/shortvec-encoding';\nimport {PublicKey, PUBLIC_KEY_LENGTH} from './publickey';\n\nexport const VALIDATOR_INFO_KEY = new PublicKey(\n 'Va1idator1nfo111111111111111111111111111111',\n);\n\n/**\n * @internal\n */\ntype ConfigKey = {\n publicKey: PublicKey;\n isSigner: boolean;\n};\n\n/**\n * Info used to identity validators.\n */\nexport type Info = {\n /** validator name */\n name: string;\n /** optional, validator website */\n website?: string;\n /** optional, extra information the validator chose to share */\n details?: string;\n /** optional, used to identify validators on keybase.io */\n keybaseUsername?: string;\n};\n\nconst InfoString = pick({\n name: string(),\n website: optional(string()),\n details: optional(string()),\n keybaseUsername: optional(string()),\n});\n\n/**\n * ValidatorInfo class\n */\nexport class ValidatorInfo {\n /**\n * validator public key\n */\n key: PublicKey;\n /**\n * validator information\n */\n info: Info;\n\n /**\n * Construct a valid ValidatorInfo\n *\n * @param key validator public key\n * @param info validator information\n */\n constructor(key: PublicKey, info: Info) {\n this.key = key;\n this.info = info;\n }\n\n /**\n * Deserialize ValidatorInfo from the config account data. Exactly two config\n * keys are required in the data.\n *\n * @param buffer config account data\n * @return null if info was not found\n */\n static fromConfigData(\n buffer: Buffer | Uint8Array | Array,\n ): ValidatorInfo | null {\n let byteArray = [...buffer];\n const configKeyCount = shortvec.decodeLength(byteArray);\n if (configKeyCount !== 2) return null;\n\n const configKeys: Array = [];\n for (let i = 0; i < 2; i++) {\n const publicKey = new PublicKey(byteArray.slice(0, PUBLIC_KEY_LENGTH));\n byteArray = byteArray.slice(PUBLIC_KEY_LENGTH);\n const isSigner = byteArray.slice(0, 1)[0] === 1;\n byteArray = byteArray.slice(1);\n configKeys.push({publicKey, isSigner});\n }\n\n if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) {\n if (configKeys[1].isSigner) {\n const rawInfo: any = Layout.rustString().decode(Buffer.from(byteArray));\n const info = JSON.parse(rawInfo as string);\n assertType(info, InfoString);\n return new ValidatorInfo(configKeys[1].publicKey, info);\n }\n }\n\n return null;\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\nimport type {Buffer} from 'buffer';\n\nimport * as Layout from './layout';\nimport {PublicKey} from './publickey';\nimport {toBuffer} from './utils/to-buffer';\n\nexport const VOTE_PROGRAM_ID = new PublicKey(\n 'Vote111111111111111111111111111111111111111',\n);\n\nexport type Lockout = {\n slot: number;\n confirmationCount: number;\n};\n\n/**\n * History of how many credits earned by the end of each epoch\n */\nexport type EpochCredits = Readonly<{\n epoch: number;\n credits: number;\n prevCredits: number;\n}>;\n\nexport type AuthorizedVoter = Readonly<{\n epoch: number;\n authorizedVoter: PublicKey;\n}>;\n\ntype AuthorizedVoterRaw = Readonly<{\n authorizedVoter: Uint8Array;\n epoch: number;\n}>;\n\ntype PriorVoters = Readonly<{\n buf: PriorVoterRaw[];\n idx: number;\n isEmpty: number;\n}>;\n\nexport type PriorVoter = Readonly<{\n authorizedPubkey: PublicKey;\n epochOfLastAuthorizedSwitch: number;\n targetEpoch: number;\n}>;\n\ntype PriorVoterRaw = Readonly<{\n authorizedPubkey: Uint8Array;\n epochOfLastAuthorizedSwitch: number;\n targetEpoch: number;\n}>;\n\nexport type BlockTimestamp = Readonly<{\n slot: number;\n timestamp: number;\n}>;\n\ntype VoteAccountData = Readonly<{\n authorizedVoters: AuthorizedVoterRaw[];\n authorizedWithdrawer: Uint8Array;\n commission: number;\n epochCredits: EpochCredits[];\n lastTimestamp: BlockTimestamp;\n nodePubkey: Uint8Array;\n priorVoters: PriorVoters;\n rootSlot: number;\n rootSlotValid: number;\n votes: Lockout[];\n}>;\n\n/**\n * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88\n *\n * @internal\n */\nconst VoteAccountLayout = BufferLayout.struct([\n Layout.publicKey('nodePubkey'),\n Layout.publicKey('authorizedWithdrawer'),\n BufferLayout.u8('commission'),\n BufferLayout.nu64(), // votes.length\n BufferLayout.seq(\n BufferLayout.struct([\n BufferLayout.nu64('slot'),\n BufferLayout.u32('confirmationCount'),\n ]),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'votes',\n ),\n BufferLayout.u8('rootSlotValid'),\n BufferLayout.nu64('rootSlot'),\n BufferLayout.nu64(), // authorizedVoters.length\n BufferLayout.seq(\n BufferLayout.struct([\n BufferLayout.nu64('epoch'),\n Layout.publicKey('authorizedVoter'),\n ]),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'authorizedVoters',\n ),\n BufferLayout.struct(\n [\n BufferLayout.seq(\n BufferLayout.struct([\n Layout.publicKey('authorizedPubkey'),\n BufferLayout.nu64('epochOfLastAuthorizedSwitch'),\n BufferLayout.nu64('targetEpoch'),\n ]),\n 32,\n 'buf',\n ),\n BufferLayout.nu64('idx'),\n BufferLayout.u8('isEmpty'),\n ],\n 'priorVoters',\n ),\n BufferLayout.nu64(), // epochCredits.length\n BufferLayout.seq(\n BufferLayout.struct([\n BufferLayout.nu64('epoch'),\n BufferLayout.nu64('credits'),\n BufferLayout.nu64('prevCredits'),\n ]),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'epochCredits',\n ),\n BufferLayout.struct(\n [BufferLayout.nu64('slot'), BufferLayout.nu64('timestamp')],\n 'lastTimestamp',\n ),\n]);\n\ntype VoteAccountArgs = {\n nodePubkey: PublicKey;\n authorizedWithdrawer: PublicKey;\n commission: number;\n rootSlot: number | null;\n votes: Lockout[];\n authorizedVoters: AuthorizedVoter[];\n priorVoters: PriorVoter[];\n epochCredits: EpochCredits[];\n lastTimestamp: BlockTimestamp;\n};\n\n/**\n * VoteAccount class\n */\nexport class VoteAccount {\n nodePubkey: PublicKey;\n authorizedWithdrawer: PublicKey;\n commission: number;\n rootSlot: number | null;\n votes: Lockout[];\n authorizedVoters: AuthorizedVoter[];\n priorVoters: PriorVoter[];\n epochCredits: EpochCredits[];\n lastTimestamp: BlockTimestamp;\n\n /**\n * @internal\n */\n constructor(args: VoteAccountArgs) {\n this.nodePubkey = args.nodePubkey;\n this.authorizedWithdrawer = args.authorizedWithdrawer;\n this.commission = args.commission;\n this.rootSlot = args.rootSlot;\n this.votes = args.votes;\n this.authorizedVoters = args.authorizedVoters;\n this.priorVoters = args.priorVoters;\n this.epochCredits = args.epochCredits;\n this.lastTimestamp = args.lastTimestamp;\n }\n\n /**\n * Deserialize VoteAccount from the account data.\n *\n * @param buffer account data\n * @return VoteAccount\n */\n static fromAccountData(\n buffer: Buffer | Uint8Array | Array,\n ): VoteAccount {\n const versionOffset = 4;\n const va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset);\n\n let rootSlot: number | null = va.rootSlot;\n if (!va.rootSlotValid) {\n rootSlot = null;\n }\n\n return new VoteAccount({\n nodePubkey: new PublicKey(va.nodePubkey),\n authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer),\n commission: va.commission,\n votes: va.votes,\n rootSlot,\n authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter),\n priorVoters: getPriorVoters(va.priorVoters),\n epochCredits: va.epochCredits,\n lastTimestamp: va.lastTimestamp,\n });\n }\n}\n\nfunction parseAuthorizedVoter({\n authorizedVoter,\n epoch,\n}: AuthorizedVoterRaw): AuthorizedVoter {\n return {\n epoch,\n authorizedVoter: new PublicKey(authorizedVoter),\n };\n}\n\nfunction parsePriorVoters({\n authorizedPubkey,\n epochOfLastAuthorizedSwitch,\n targetEpoch,\n}: PriorVoterRaw): PriorVoter {\n return {\n authorizedPubkey: new PublicKey(authorizedPubkey),\n epochOfLastAuthorizedSwitch,\n targetEpoch,\n };\n}\n\nfunction getPriorVoters({buf, idx, isEmpty}: PriorVoters): PriorVoter[] {\n if (isEmpty) {\n return [];\n }\n\n return [\n ...buf.slice(idx + 1).map(parsePriorVoters),\n ...buf.slice(0, idx).map(parsePriorVoters),\n ];\n}\n"],"names":["require","_Buffer","base","ALPHABET","length","TypeError","BASE_MAP","Uint8Array","j","i","x","charAt","xc","charCodeAt","BASE","LEADER","FACTOR","Math","log","iFACTOR","encode","source","Array","isArray","from","isBuffer","zeroes","pbegin","pend","size","b58","carry","it1","Error","it2","str","repeat","decodeUnsafe","alloc","psz","b256","it3","it4","vch","allocUnsafe","fill","decode","string","buffer","module","exports","basex","defaultURI","async","getApi","uri","resp","fetch","fullUri","json","path","baseURI","getCollections","page","limit","search","onChainOnly","getCollectionPricing","getNftStats","id","BigInt","_1n","_2n","u8a","a","hexes","v","toString","padStart","bytesToHex","bytes","hex","hexToNumber","hexToBytes","array","hexByte","slice","byte","Number","parseInt","isNaN","bytesToNumberBE","bytesToNumberLE","reverse","numberToBytesBE","n","len","numberToBytesLE","ensureBytes","title","expectedLength","res","e","concatBytes","arrs","r","reduce","sum","pad","forEach","set","equalBytes","b1","b2","utf8ToBytes","TextEncoder","bitMask","u8n","data","u8fr","arr","createHmacDrbg","hashLen","qByteLen","hmacFn","k","reset","h","b","reseed","seed","gen","out","sl","push","genUntil","pred","validatorFns","bigint","val","function","boolean","isSafeInteger","field","object","Fp","isValid","hash","outputLen","validateObject","validators","optValidators","checkField","fieldName","type","isOptional","checkVal","undefined","String","Object","entries","_0n","_3n","_4n","_5n","_8n","mod","result","pow","num","power","modulo","pow2","invert","number","y","u","q","m","gcd","tonelliShanks","P","legendreC","Q","S","Z","p1div4","root","eql","sqr","Q1div2","neg","ONE","g","mul","ZERO","t2","ge","FpSqrt","c1","n2","nv","sub","isNegativeLE","FIELD_FIELDS","validateField","initial","ORDER","MASK","BYTES","BITS","opts","map","FpPow","f","p","d","FpInvertBatch","nums","tmp","lastMultiplied","acc","is0","inverted","inv","reduceRight","nLength","nBitLength","_nBitLength","nByteLength","ceil","Field","bitLen","isLE","redef","sqrtP","freeze","create","isOdd","lhs","rhs","add","div","sqrN","addN","subN","mulN","sqrt","invertBatch","lst","cmov","c","toBytes","fromBytes","FpSqrtEven","elm","hashToPrivateScalar","groupOrder","minLen","wNAF","bits","constTimeNegate","condition","item","negate","W","windows","windowSize","unsafeLadder","double","precomputeWindow","points","window","precomputes","mask","maxNumber","shiftBy","offset","wbits","offset1","offset2","abs","cond1","cond2","wNAFCached","precomputesMap","transform","_WINDOW_SIZE","comp","get","validateBasic","curve","Gx","Gy","VERIFY_DEFAULT","zip215","validateOpts","ut","randomBytes","adjustScalarBytes","domain","uvRatio","mapToCurve","twistedEdwards","curveDef","CURVE","CURVE_ORDER","prehash","cHash","cofactor","modP","value","ctx","phflag","inBig","inRange","max","in0MaskRange","assertInRange","assertGE0","pointPrecomputes","Map","isPoint","other","Point","constructor","ex","ey","ez","et","toAffine","toInv","fromAffine","_setWindowSize","delete","assertValidity","X","Y","T","X2","Y2","Z2","Z4","aX2","left","right","XY","ZT","equals","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","A","B","C","D","x1y1","E","G","F","H","X3","Y3","T3","Z3","T1","T2","subtract","wnaf","normalizeZ","multiply","scalar","multiplyUnsafe","I","isSmallOrder","isTorsionFree","iz","z","ax","ay","zz","clearCofactor","normed","lastByte","y2","isXOdd","isLastByteOdd","privKey","getExtendedPublicKey","point","toRawBytes","toHex","modN","modN_LE","key","hashed","head","prefix","pointBytes","getPublicKey","hashDomainToScalar","context","msgs","msg","sign","options","R","s","verifyOpts","verify","sig","publicKey","SB","fromHex","error","RkA","utils","randomPrivateKey","precompute","ExtendedPoint","montgomeryBits","powPminus2","Gu","montgomery","montgomeryBytes","fieldLen","cswap","swap","x_2","x_3","dummy","assertFieldElement","a24","montgomeryLadder","pointU","x_1","sw","z_2","z_3","t","k_t","AA","BB","DA","CB","dacb","da_cb","z2","encodeUCoordinate","decodeUCoordinate","uEnc","decodeScalar","scalarMult","_scalar","pu","GuBytes","scalarMultBase","getSharedSecret","privateKey","validateDST","dst","os2ip","i2osp","strxor","isBytes","isNum","expand_message_xmd","DST","lenInBytes","b_in_bytes","blockLen","r_in_bytes","ell","DST_prime","Z_pad","l_i_b_str","b_0","args","pseudo_random_bytes","expand_message_xof","dkLen","update","digest","hash_to_field","count","expand","_DST","log2p","L","len_in_bytes","prb","elm_offset","tv","subarray","isogenyMap","COEFF","xNum","xDen","yNum","yDen","createHasher","def","hashToCurve","u0","u1","encodeToCurve","encodeDST","ED25519_P","ED25519_SQRT_M1","_10n","_20n","_40n","_80n","ed25519_pow_2_252_3","x2","b4","b5","b10","b20","b40","b80","b160","b240","b250","pow_p_5_8","v3","v7","vx2","root1","root2","useRoot1","useRoot2","noRoot","ed25519Defaults","sha512","ed25519","ed25519_domain","ELL2_C1","ELL2_C2","ELL2_C3","ELL2_C4","ELL2_J","map_to_curve_elligator2_curve25519","tv1","xd","x1n","tv2","gxd","gx1","tv3","y11","y12","e1","y1","x2n","y21","y22","gx2","e2","e3","xn","e4","xMn","xMd","yMn","yMd","ELL2_C1_EDWARDS","map_to_curve_elligator2_edwards25519","yn","yd","htf","scalars","assertRstPoint","RistrettoPoint","SQRT_M1","SQRT_AD_MINUS_ONE","INVSQRT_A_MINUS_D","ONE_MINUS_D_SQ","D_MINUS_ONE_SQ","invertSqrt","MAX_255B","bytes255ToNumberLE","calcElligatorRistrettoMap","r0","Ns","Ns_D_is_sq","s_","Nt","s2","W0","W1","W2","W3","ep","ap","r1","R1","r2","R2","emsg","u2","u1_2","u2_2","Dx","Dy","u2sq","invsqrt","D1","D2","zInv","_x","_y","one","two","validatePointOpts","allowedPrivateKeyLengths","wrapPrivateKey","allowInfinityPoint","endo","beta","splitScalar","b2n","h2b","DER","Err","_parseInt","l","toSig","sBytes","rBytesLeft","hexFromSig","shl","rhl","rl","weierstrassPoints","isCompressed","tail","weierstrassEquation","x3","isWithinCurveOrder","assertGE","normPrivateKeyToScalar","lengths","includes","assertPrjPoint","px","py","pz","hasEvenY","U1","U2","b3","t0","t1","t3","t4","t5","k1neg","k1","k2neg","k2","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","_bits","ProjectivePoint","hmac","bits2int","bits2int_modN","lowS","weierstrass","compressedLen","uncompressedLen","isValidFieldElement","invN","cat","isYOdd","isHeadOdd","numToNByteStr","isBiggerThanHalfOrder","HALF","normalizeS","slcNum","to","Signature","recovery","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","ir","hasHighS","toDERRawBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","rand","fromPrivateKey","isProbPub","privateA","publicB","delta","ORDER_MASK","int2octets","prepSig","defaultSigOpts","some","extraEntropy","ent","h1int","seedArgs","k2sig","kBytes","ik","normS","defaultVerOpts","drbg","signature","sg","_sig","fromDER","derError","fromCompact","message","is","SWUFpSqrtRatio","o","c2","c3","c4","c5","c6","c7","sqrtRatio","tv5","tv4","isQR","tvv5","mapToCurveSimpleSWU","tv6","getHash","createCurve","defHash","secp256k1P","secp256k1N","divNearest","sqrtMod","_6n","_11n","_22n","_23n","_44n","_88n","b6","b9","b11","b22","b44","b88","b176","b220","b223","secp256k1","a1","a2","POW_2_128","sha256","fe","TAGGED_HASH_PREFIXES","taggedHash","tag","messages","tagP","tagH","pointToBytes","numTo32b","GmulAdd","schnorrGetExtPubKey","priv","d_","lift_x","xx","challenge","schnorrGetPublicKey","schnorrSign","auxRand","k_","rx","schnorrVerify","pub","isoMap","mapSWU","generateKeypair","privateScalar","secretKey","isOnCurve","toBuffer","Buffer","byteOffset","byteLength","Struct","properties","assign","this","serialize","SOLANA_SCHEMA","static","deserialize","deserializeUnchecked","MAX_SEED_LENGTH","PUBLIC_KEY_LENGTH","isPublicKeyData","_bn","uniquePublicKeyCounter","_Symbol$toStringTag","Symbol","toStringTag","PublicKey","super","decoded","bs58","BN","eq","toBase58","toJSON","buf","toArrayLike","zeroPad","copy","fromPublicKey","programId","publicKeyBytes","seeds","createProgramAddressSync","address","nonce","seedsWithNonce","concat","err","findProgramAddressSync","pubkeyData","pubkey","default","kind","fields","PACKET_DATA_SIZE","VERSION_PREFIX_MASK","SIGNATURE_LENGTH_IN_BYTES","TransactionExpiredBlockheightExceededError","defineProperty","prototype","TransactionExpiredTimeoutError","timeoutSeconds","toFixed","TransactionExpiredNonceInvalidError","MessageAccountKeys","staticAccountKeys","accountKeysFromLookups","keySegments","writable","readonly","index","keySegment","flat","compileInstructions","instructions","U8_MAX","keyIndexMap","findKeyIndex","keyIndex","instruction","programIdIndex","accountKeyIndexes","keys","meta","property","BufferLayout","rustString","rsl","_decode","bind","_encode","rslShim","chars","span","authorized","lockup","voteInit","voteAuthorizeWithSeedArgs","getAlloc","getItemAlloc","elementLayout","layout","decodeLength","elem","shift","encodeLength","rem_len","assert","CompiledKeys","payer","keyMetaMap","getOrInsertDefault","keyMeta","isSigner","isWritable","isInvoked","payerKeyMeta","ix","accountMeta","getMessageComponents","mapEntries","writableSigners","filter","readonlySigners","writableNonSigners","readonlyNonSigners","header","numRequiredSignatures","numReadonlySignedAccounts","numReadonlyUnsignedAccounts","payerAddress","extractTableLookup","lookupTable","writableIndexes","drainedWritableKeys","drainKeysFoundInLookupTable","state","addresses","readonlyIndexes","drainedReadonlyKeys","accountKey","lookupTableEntries","keyMetaFilter","lookupTableIndexes","drainedKeys","lookupTableIndex","findIndex","entry","Message","accountKeys","recentBlockhash","indexToProgramIds","account","version","compiledInstructions","accounts","addressTableLookups","getAccountKeys","compiledKeys","compile","payerKey","isAccountSigner","isAccountWritable","numSignedAccounts","unsignedAccountIndex","numUnsignedAccounts","numWritableUnsignedAccounts","numWritableSignedAccounts","isProgramId","has","programIds","values","nonProgramIds","_","numKeys","keyCount","keyIndicesCount","dataCount","keyIndices","dataLength","instructionCount","instructionBuffer","instructionBufferLength","instructionLayout","signDataLayout","transaction","signData","byteArray","accountCount","dataSlice","messageArgs","TransactionStatus","DEFAULT_SIGNATURE","TransactionInstruction","Transaction","signatures","feePayer","lastValidBlockHeight","nonceInfo","minNonceContextSlot","_message","_json","hasOwnProperty","call","minContextSlot","blockhash","nonceInstruction","signers","items","compileMessage","JSON","stringify","console","warn","accountMetas","uniqueMetas","pubkeyString","uniqueIndex","sort","localeMatcher","usage","sensitivity","ignorePunctuation","numeric","caseFirst","localeCompare","feePayerIndex","payerMeta","splice","unshift","signedKeys","unsignedKeys","indexOf","_compile","valid","every","pair","serializeMessage","connection","getFeeForMessage","setSigners","seen","Set","uniqueSigners","signer","_partialSign","partialSign","_addSignature","addSignature","sigpair","verifySignatures","requireAllSignatures","_verifySignatures","config","_serialize","signatureCount","transactionLength","wireTransaction","keyObj","populate","sigPubkeyPair","NUM_TICKS_PER_SECOND","DEFAULT_TICKS_PER_SLOT","NUM_SLOTS_PER_SECOND","MS_PER_SLOT","SYSVAR_CLOCK_PUBKEY","SYSVAR_RECENT_BLOCKHASHES_PUBKEY","SYSVAR_RENT_PUBKEY","SYSVAR_STAKE_HISTORY_PUBKEY","sendAndConfirmTransaction","sendOptions","skipPreflight","preflightCommitment","commitment","maxRetries","sendTransaction","status","confirmTransaction","abortSignal","nonceAccountPubkey","nonceValue","sleep","ms","Promise","resolve","setTimeout","encodeData","allocLength","layoutFields","FeeCalculatorLayout","NonceAccountLayout","NONCE_ACCOUNT_LENGTH","encodeDecode","bigInt","blob","bigIntLayout","src","toBigIntLE","toBufferLE","u64","SYSTEM_INSTRUCTION_LAYOUTS","Create","Assign","Transfer","CreateWithSeed","AdvanceNonceAccount","WithdrawNonceAccount","InitializeNonceAccount","AuthorizeNonceAccount","Allocate","AllocateWithSeed","AssignWithSeed","TransferWithSeed","UpgradeNonceAccount","SystemProgram","params","lamports","space","fromPubkey","newAccountPubkey","basePubkey","toPubkey","accountPubkey","createAccountWithSeed","noncePubkey","createAccount","initParams","authorizedPubkey","nonceInitialize","instructionData","newAuthorizedPubkey","CHUNK_SIZE","Loader","chunkSize","program","balanceNeeded","getMinimumBalanceForRentExemption","programInfo","getAccountInfo","executable","allocate","owner","transfer","dataLayout","transactions","bytesLength","bytesLengthPadding","_rpcEndpoint","REQUESTS_PER_SECOND","all","deployCommitment","finalizeSignature","currentSlot","getSlot","slot","round","SendTransactionError","logs","SolanaJSONRPCError","code","customMessage","name","globalThis","PublicKeyFromString","coerce","instance","RawAccountDataResult","tuple","literal","BufferFromRawAccountData","createRpcResult","union","jsonrpc","unknown","optional","any","UnknownRpcResult","jsonRpcResult","schema","jsonRpcResultAndContext","notificationResultAndContext","GetInflationGovernorResult","foundation","foundationTerm","taper","terminal","GetRecentPrioritizationFeesResult","nullable","epoch","effectiveSlot","amount","postBalance","commission","prioritizationFee","GetInflationRateResult","total","validator","GetEpochInfoResult","slotIndex","slotsInEpoch","absoluteSlot","blockHeight","transactionCount","GetEpochScheduleResult","slotsPerEpoch","leaderScheduleSlotOffset","warmup","firstNormalEpoch","firstNormalSlot","GetLeaderScheduleResult","record","TransactionErrorResult","SignatureStatusResult","SignatureReceivedResult","rentEpoch","unitsConsumed","returnData","byIdentity","range","firstSlot","lastSlot","circulating","nonCirculating","nonCirculatingAccounts","TokenAmountResult","uiAmount","decimals","uiAmountString","ParsedAccountDataResult","parsed","AccountInfoResult","ParsedOrRawAccountData","ParsedAccountInfoResult","ProgramAccountInfoResult","active","inactive","memo","blockTime","subscription","SlotInfoResult","parent","SlotUpdateResult","timestamp","stats","numTransactionEntries","numSuccessfulTransactions","numFailedTransactions","maxTransactionsPerEntry","VoteAccountInfoResult","gossip","tpu","rpc","votePubkey","nodePubkey","activatedStake","epochVoteAccount","epochCredits","lastVote","rootSlot","ConfirmationStatus","current","delinquent","SignatureStatusResponse","confirmations","confirmationStatus","AddressTableLookupStruct","ConfirmedTransactionResult","AnnotatedAccountKey","ConfirmedTransactionAccountsModeResult","ParsedInstructionResult","RawInstructionResult","InstructionResult","UnknownInstructionResult","ParsedOrRawInstruction","ParsedConfirmedTransactionResult","TokenBalanceResult","accountIndex","mint","uiTokenAmount","LoadedAddressesResult","ConfirmedTransactionMetaResult","fee","innerInstructions","preBalances","postBalances","logMessages","preTokenBalances","postTokenBalances","loadedAddresses","computeUnitsConsumed","ParsedConfirmedTransactionMetaResult","TransactionVersionStruct","RewardsResult","rewardType","PerfSampleResult","previousBlockhash","parentSlot","rewards","feeCalculator","lamportsPerSignature","numTransactions","numSlots","samplePeriodSecs","LogsResult","Keypair","keypair","_keypair","skipValidation","computedPublicKey","ii","LOOKUP_TABLE_INSTRUCTION_LAYOUTS","CreateLookupTable","FreezeLookupTable","ExtendLookupTable","DeactivateLookupTable","CloseLookupTable","AddressLookupTableProgram","lookupTableAddress","bumpSeed","authority","recentSlot","addr","recipient","COMPUTE_BUDGET_INSTRUCTION_LAYOUTS","RequestUnits","RequestHeapFrame","SetComputeUnitLimit","SetComputeUnitPrice","ComputeBudgetProgram","microLamports","PRIVATE_KEY_BYTES$1","PUBLIC_KEY_BYTES$1","SIGNATURE_BYTES","ED25519_INSTRUCTION_LAYOUT","Ed25519Program","instructionIndex","publicKeyOffset","signatureOffset","messageDataOffset","numSignatures","padding","signatureInstructionIndex","publicKeyInstructionIndex","messageDataSize","messageInstructionIndex","fromSecretKey","createInstructionWithPublicKey","ecdsaSign","publicKeyCreate","PRIVATE_KEY_BYTES","ETHEREUM_ADDRESS_BYTES","PUBLIC_KEY_BYTES","SIGNATURE_OFFSETS_SERIALIZED_SIZE","SECP256K1_INSTRUCTION_LAYOUT","Secp256k1Program","keccak_256","recoveryId","createInstructionWithEthAddress","ethAddress","publicKeyToEthAddress","rawAddress","startsWith","substr","dataStart","ethAddressOffset","ethAddressInstructionIndex","pkey","messageHash","STAKE_CONFIG_ID","Lockup","unixTimestamp","custodian","STAKE_INSTRUCTION_LAYOUTS","Initialize","Authorize","Delegate","Split","Withdraw","Deactivate","Merge","AuthorizeWithSeed","Staker","Withdrawer","StakeProgram","stakePubkey","maybeLockup","staker","withdrawer","initialize","stakeAuthorizationType","custodianPubkey","newAuthorized","authorityBase","authoritySeed","authorityOwner","splitStakePubkey","splitInstruction","sourceStakePubKey","VOTE_INSTRUCTION_LAYOUTS","InitializeAccount","Voter","VoteProgram","authorizedVoter","authorizedWithdrawer","initializeAccount","voteAuthorizationType","currentAuthorityDerivedKeyBasePubkey","currentAuthorityDerivedKeyOwnerPubkey","currentAuthorityDerivedKeySeed","authorizedWithdrawerPubkey","currentVoteAccountBalance","rentExemptMinimum","withdraw","website","details","keybaseUsername"],"sourceRoot":""}