@solana/web3.js 2.0.0-experimental.20e2b21 → 2.0.0-experimental.22a4e54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.browser.cjs +84 -1
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.js +66 -3
- package/dist/index.browser.js.map +1 -1
- package/dist/index.development.js +2250 -199
- package/dist/index.development.js.map +1 -1
- package/dist/index.native.js +66 -3
- package/dist/index.native.js.map +1 -1
- package/dist/index.node.cjs +84 -1
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.js +66 -3
- package/dist/index.node.js.map +1 -1
- package/dist/index.production.min.js +36 -4
- package/dist/types/index.d.ts +4 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/rpc-default-config.d.ts.map +1 -0
- package/dist/types/rpc-integer-overflow-error.d.ts.map +1 -0
- package/dist/types/rpc-request-coalescer.d.ts.map +1 -0
- package/dist/types/rpc-request-deduplication.d.ts.map +1 -0
- package/dist/types/rpc-transport.d.ts.map +1 -0
- package/dist/types/rpc-websocket-autopinger.d.ts +8 -0
- package/dist/types/rpc-websocket-autopinger.d.ts.map +1 -0
- package/dist/types/rpc-websocket-transport.d.ts +7 -0
- package/dist/types/rpc-websocket-transport.d.ts.map +1 -0
- package/dist/types/rpc.d.ts +4 -3
- package/dist/types/rpc.d.ts.map +1 -0
- package/package.json +21 -21
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../build-scripts/env-shim.ts","../../../node_modules/.pnpm/base-x@4.0.0/node_modules/base-x/src/index.js","../../../node_modules/.pnpm/bs58@5.0.0/node_modules/bs58/index.js","../../../node_modules/.pnpm/fast-stable-stringify@1.0.0/node_modules/fast-stable-stringify/index.js","../src/index.ts","../../keys/src/base58.ts","../src/rpc.ts","../../rpc-core/src/params-patcher.ts","../../rpc-core/src/response-patcher-allowed-numeric-values.ts","../../rpc-core/src/response-patcher.ts","../../rpc-core/src/rpc-methods/index.ts","../../rpc-transport/src/json-rpc-errors.ts","../../rpc-transport/src/json-rpc-message-id.ts","../../rpc-transport/src/json-rpc-message.ts","../../rpc-transport/src/json-rpc.ts","../../fetch-impl/src/index.browser.ts","../../rpc-transport/src/transports/http/http-transport-errors.ts","../../rpc-transport/src/transports/http/http-transport-headers.ts","../../rpc-transport/src/transports/http/http-transport.ts","../src/rpc-default-config.ts","../src/rpc-integer-overflow-error.ts","../src/rpc-transport.ts","../src/rpc-request-coalescer.ts","../src/rpc-request-deduplication.ts"],"names":["i","j","bs58","e","__DEV__","index_browser_default","fastStableStringify","normalizeHeaders"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAMA,aAAS,KAAM,UAAU;AACvB,UAAI,SAAS,UAAU,KAAK;AAAE,cAAM,IAAI,UAAU,mBAAmB;AAAA,MAAE;AACvE,UAAI,WAAW,IAAI,WAAW,GAAG;AACjC,eAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,iBAAS,CAAC,IAAI;AAAA,MAChB;AACA,eAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,YAAI,IAAI,SAAS,OAAO,CAAC;AACzB,YAAI,KAAK,EAAE,WAAW,CAAC;AACvB,YAAI,SAAS,EAAE,MAAM,KAAK;AAAE,gBAAM,IAAI,UAAU,IAAI,eAAe;AAAA,QAAE;AACrE,iBAAS,EAAE,IAAI;AAAA,MACjB;AACA,UAAI,OAAO,SAAS;AACpB,UAAI,SAAS,SAAS,OAAO,CAAC;AAC9B,UAAI,SAAS,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI,GAAG;AAC1C,UAAI,UAAU,KAAK,IAAI,GAAG,IAAI,KAAK,IAAI,IAAI;AAC3C,eAAS,OAAQ,QAAQ;AACvB,YAAI,kBAAkB,YAAY;AAAA,QAClC,WAAW,YAAY,OAAO,MAAM,GAAG;AACrC,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1E;AAAA,EACJ;AACA,MAAI,aAAa,WAAW,QAAQ,YAAY,SAAS,YAAY,WAAW,YAAY,SAAS;AACjG,eAAO,6BAAAG,SAAoB,CAAC,QAAQ,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAC/D;AACJ;;;AFFA,SAASC,kBACL,SACiD;AACjD,QAAM,MAA8B,CAAC;AACrC,aAAW,cAAc,SAAS;AAC9B,QAAI,WAAW,YAAY,CAAC,IAAI,QAAQ,UAAU;AAAA,EACtD;AACA,SAAO;AACX;AAEO,SAAS,0BAA0B,QAAkE;AACxG,SAAO;AAAA,IACH,oBAAoB;AAAA,MAChB,GAAG;AAAA,MACH,SAAS;AAAA,QACL,GAAI,OAAO,UAAUA,kBAAiB,OAAO,OAAO,IAAI;AAAA,QACxD,GAAI;AAAA;AAAA,UAEA,iBAAiB,MAAM,yBAAiB;AAAA,QAC5C;AAAA,MACJ;AAAA,IACJ,CAAC;AAAA,IACD;AAAA,EACJ;AACJ","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","'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.\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 (source instanceof Uint8Array) {\n } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\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 new Uint8Array() }\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 = new Uint8Array(zeroes + (size - it4))\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","const basex = require('base-x')\nconst ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\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 * from '@solana/keys';\nexport * from './rpc';\nexport * from './rpc-transport';\n","import bs58 from 'bs58';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = bs58.decode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n","import { createSolanaRpcApi, SolanaRpcMethods } from '@solana/rpc-core';\nimport { createJsonRpc } from '@solana/rpc-transport';\nimport type { Rpc } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\n\nexport function createSolanaRpc(config: Omit<Parameters<typeof createJsonRpc>[0], 'api'>): Rpc<SolanaRpcMethods> {\n return createJsonRpc<SolanaRpcMethods>({\n ...config,\n api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n });\n}\n","type IntegerOverflowHandler = (keyPath: (number | string)[], value: bigint) => void;\ntype Patched<T> = T extends object ? { [Property in keyof T]: Patched<T[Property]> } : T extends bigint ? number : T;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction visitNode<T>(value: T, keyPath: (number | string)[], onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n if (Array.isArray(value)) {\n return value.map((element, ii) =>\n visitNode(element, [...keyPath, ii], onIntegerOverflow)\n ) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const propName in value) {\n if (Object.prototype.hasOwnProperty.call(value, propName)) {\n out[propName] = visitNode(value[propName], [...keyPath, propName], onIntegerOverflow);\n }\n }\n return out as TypescriptBug33014;\n } else if (typeof value === 'bigint') {\n // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // downcasting `bigints` to `numbers`.\n if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {\n onIntegerOverflow(keyPath, value);\n }\n return Number(value) as TypescriptBug33014;\n } else {\n return value as TypescriptBug33014;\n }\n}\n\nexport function patchParamsForSolanaLabsRpc<T>(params: T, onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n return visitNode(params, [], onIntegerOverflow);\n}\n","import { KeyPath } from './response-patcher';\nimport { KEYPATH_WILDCARD } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nexport const ALLOWED_NUMERIC_KEYPATHS: Partial<\n Record<keyof ReturnType<typeof createSolanaRpcApi>, readonly KeyPath[]>\n> = {\n getBlockTime: [[]],\n getInflationReward: [[KEYPATH_WILDCARD, 'commission']],\n getRecentPerformanceSamples: [[KEYPATH_WILDCARD, 'samplePeriodSecs']],\n getVoteAccounts: [\n ['current', KEYPATH_WILDCARD, 'commission'],\n ['delinquent', KEYPATH_WILDCARD, 'commission'],\n ],\n};\n","import { ALLOWED_NUMERIC_KEYPATHS } from './response-patcher-allowed-numeric-values';\nimport { KEYPATH_WILDCARD, KeyPathWildcard } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\n\nexport type KeyPath = ReadonlyArray<KeyPathWildcard | number | string | KeyPath>;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction getNextAllowedKeypaths(keyPaths: readonly KeyPath[], property: number | string) {\n return keyPaths\n .filter(keyPath => (keyPath[0] === KEYPATH_WILDCARD && typeof property === 'number') || keyPath[0] === property)\n .map(keyPath => keyPath.slice(1));\n}\n\nfunction visitNode<T>(value: unknown, allowedKeypaths: readonly KeyPath[]): T {\n if (Array.isArray(value)) {\n return value.map((element, ii) => {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, ii);\n return visitNode(element, nextAllowedKeypaths);\n }) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const [propName, innerValue] of Object.entries(value)) {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, propName);\n out[propName] = visitNode(innerValue, nextAllowedKeypaths);\n }\n return out as TypescriptBug33014;\n } else if (\n typeof value === 'number' &&\n // The presence of an allowed keypath on the route to this value implies it's allowlisted;\n // Upcast the value to `bigint` unless an allowed keypath is present.\n allowedKeypaths.length === 0\n ) {\n // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // upcasting `numbers` to `bigints`.\n return BigInt(value) as TypescriptBug33014;\n } else {\n return value as TypescriptBug33014;\n }\n}\n\nexport function patchResponseForSolanaLabsRpc<T>(\n rawResponse: unknown,\n methodName?: keyof ReturnType<typeof createSolanaRpcApi>\n): T {\n const allowedKeypaths = methodName ? ALLOWED_NUMERIC_KEYPATHS[methodName] : undefined;\n return visitNode(rawResponse, allowedKeypaths ?? []);\n}\n","import { IRpcApi, RpcRequest } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { patchParamsForSolanaLabsRpc } from '../params-patcher';\nimport { patchResponseForSolanaLabsRpc } from '../response-patcher';\nimport { GetAccountInfoApi } from './getAccountInfo';\nimport { GetBalanceApi } from './getBalance';\nimport { GetBlockHeightApi } from './getBlockHeight';\nimport { GetBlockProductionApi } from './getBlockProduction';\nimport { GetBlocksApi } from './getBlocks';\nimport { GetBlockTimeApi } from './getBlockTime';\nimport { GetEpochInfoApi } from './getEpochInfo';\nimport { GetFirstAvailableBlockApi } from './getFirstAvailableBlock';\nimport { GetInflationRewardApi } from './getInflationReward';\nimport { GetLatestBlockhashApi } from './getLatestBlockhash';\nimport { GetMaxRetransmitSlotApi } from './getMaxRetransmitSlot';\nimport { GetMaxShredInsertSlotApi } from './getMaxShredInsertSlot';\nimport { GetRecentPerformanceSamplesApi } from './getRecentPerformanceSamples';\nimport { GetSignaturesForAddressApi } from './getSignaturesForAddress';\nimport { GetSlotApi } from './getSlot';\nimport { GetStakeMinimumDelegationApi } from './getStakeMinimumDelegation';\nimport { GetSupplyApi } from './getSupply';\nimport { GetTransactionCountApi } from './getTransactionCount';\nimport { GetVoteAccountsApi } from './getVoteAccounts';\nimport { MinimumLedgerSlotApi } from './minimumLedgerSlot';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcMethods = GetAccountInfoApi &\n GetBalanceApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlockTimeApi &\n GetEpochInfoApi &\n GetFirstAvailableBlockApi &\n GetInflationRewardApi &\n GetLatestBlockhashApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetRecentPerformanceSamplesApi &\n GetSignaturesForAddressApi &\n GetSlotApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTransactionCountApi &\n GetVoteAccountsApi &\n MinimumLedgerSlotApi;\n\nexport function createSolanaRpcApi(config?: Config): IRpcApi<SolanaRpcMethods> {\n return new Proxy({} as IRpcApi<SolanaRpcMethods>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<TMethodName extends keyof IRpcApi<SolanaRpcMethods>>(\n ...args: Parameters<NonNullable<ProxyHandler<IRpcApi<SolanaRpcMethods>>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof SolanaRpcMethods;\n return function (\n ...rawParams: Parameters<\n SolanaRpcMethods[TMethodName] extends CallableFunction ? SolanaRpcMethods[TMethodName] : never\n >\n ): RpcRequest<ReturnType<SolanaRpcMethods[TMethodName]>> {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n const params = patchParamsForSolanaLabsRpc(\n rawParams,\n handleIntegerOverflow\n ? (keyPath, value) => handleIntegerOverflow(methodName, keyPath, value)\n : undefined\n );\n return {\n methodName,\n params,\n responseProcessor: rawResponse => patchResponseForSolanaLabsRpc(rawResponse, methodName),\n };\n };\n },\n });\n}\n","// Keep in sync with https://github.com/solana-labs/solana/blob/master/rpc-client-api/src/custom_error.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nexport const SolanaJsonRpcErrorCode = {\n JSON_RPC_INVALID_PARAMS: -32602,\n JSON_RPC_SCAN_ERROR: -32012,\n JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016,\n JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n} as const;\ntype SolanaJsonRpcErrorCodeEnum = (typeof SolanaJsonRpcErrorCode)[keyof typeof SolanaJsonRpcErrorCode];\n\ntype SolanaJsonRpcErrorDetails = Readonly<{\n code: number;\n data?: unknown;\n message: string;\n}>;\n\nexport class SolanaJsonRpcError extends Error {\n readonly code: SolanaJsonRpcErrorCodeEnum;\n readonly data: unknown;\n constructor(details: SolanaJsonRpcErrorDetails) {\n super(`JSON-RPC 2.0 error (${details.code}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.code = details.code as SolanaJsonRpcErrorCodeEnum;\n this.data = details.data;\n }\n get name() {\n return 'SolanaJsonRpcError';\n }\n}\n","let _nextMessageId = 0;\nexport function getNextMessageId() {\n const id = _nextMessageId;\n _nextMessageId = (_nextMessageId + 1) % Number.MAX_SAFE_INTEGER;\n return id;\n}\n","import { getNextMessageId } from './json-rpc-message-id';\n\nexport function createJsonRpcMessage<TParams>(method: string, params: TParams) {\n return {\n id: getNextMessageId(),\n jsonrpc: '2.0',\n method,\n params,\n };\n}\n","import { SolanaJsonRpcError } from './json-rpc-errors';\nimport { createJsonRpcMessage } from './json-rpc-message';\nimport { PendingRpcRequest, Rpc, RpcConfig, RpcRequest, SendOptions } from './json-rpc-types';\n\ninterface IHasIdentifier {\n readonly id: number;\n}\ntype JsonRpcResponse<TResponse> = IHasIdentifier &\n Readonly<{ result: TResponse } | { error: { code: number; message: string; data?: unknown } }>;\n\nfunction createPendingRpcRequest<TRpcMethods, TResponse>(\n rpcConfig: RpcConfig<TRpcMethods>,\n pendingRequest: RpcRequest<TResponse>\n): PendingRpcRequest<TResponse> {\n return {\n async send(options?: SendOptions): Promise<TResponse> {\n const { methodName, params, responseProcessor } = pendingRequest;\n const payload = createJsonRpcMessage(methodName, params);\n const response = await rpcConfig.transport<JsonRpcResponse<unknown>>({\n payload,\n signal: options?.abortSignal,\n });\n if ('error' in response) {\n throw new SolanaJsonRpcError(response.error);\n } else {\n return (responseProcessor ? responseProcessor(response.result) : response.result) as TResponse;\n }\n },\n };\n}\n\nfunction makeProxy<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const createRpcRequest = Reflect.get(target, methodName, receiver);\n const newRequest = createRpcRequest\n ? createRpcRequest(...rawParams)\n : { methodName, params: rawParams };\n return createPendingRpcRequest(rpcConfig, newRequest);\n };\n },\n }) as Rpc<TRpcMethods>;\n}\n\nexport function createJsonRpc<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return makeProxy(rpcConfig);\n}\n","export default globalThis.fetch;\n","type SolanaHttpErrorDetails = Readonly<{\n statusCode: number;\n message: string;\n}>;\n\nexport class SolanaHttpError extends Error {\n readonly statusCode: number;\n constructor(details: SolanaHttpErrorDetails) {\n super(`HTTP error (${details.statusCode}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.statusCode = details.statusCode;\n }\n get name() {\n return 'SolanaHttpError';\n }\n}\n","export type AllowedHttpRequestHeaders = Readonly<\n { [headerName: string]: string } & {\n // Someone can still sneak a forbidden header past Typescript if they do something like\n // fOo-BaR, but at that point they deserve the runtime failure.\n [K in DisallowedHeaders | ForbiddenHeaders as\n | K // `Foo-Bar`\n | Capitalize<Lowercase<K>> // `Foo-bar`\n | Lowercase<K> // `foo-bar`\n | Uncapitalize<K> // `foo-Bar`\n // `FOO-BAR`\n | Uppercase<K>]?: never;\n }\n>;\n// These are headers that we simply don't allow the developer to override because they're\n// fundamental to the operation of the JSON-RPC transport.\ntype DisallowedHeaders = 'Accept' | 'Content-Length' | 'Content-Type' | 'Solana-Client';\ntype ForbiddenHeaders =\n | 'Accept-Charset'\n | 'Accept-Encoding'\n | 'Access-Control-Request-Headers'\n | 'Access-Control-Request-Method'\n | 'Connection'\n | 'Content-Length'\n | 'Cookie'\n | 'Date'\n | 'DNT'\n | 'Expect'\n | 'Host'\n | 'Keep-Alive'\n | 'Origin'\n | 'Permissions-Policy'\n // No currently available Typescript technique allows you to match on a prefix.\n // | 'Proxy-'\n // | 'Sec-'\n | 'Referer'\n | 'TE'\n | 'Trailer'\n | 'Transfer-Encoding'\n | 'Upgrade'\n | 'Via';\n\n// These are headers which are fundamental to the JSON-RPC transport, and must not be modified.\nconst DISALLOWED_HEADERS: Record<string, boolean> = {\n accept: true,\n 'content-length': true,\n 'content-type': true,\n};\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS: Record<string, boolean> = {\n 'accept-charset': true,\n 'accept-encoding': true,\n 'access-control-request-headers': true,\n 'access-control-request-method': true,\n connection: true,\n 'content-length': true,\n cookie: true,\n date: true,\n dnt: true,\n expect: true,\n host: true,\n 'keep-alive': true,\n origin: true,\n 'permissions-policy': true,\n // No currently available Typescript technique allows you to match on a prefix.\n // 'proxy-':true,\n // 'sec-':true,\n referer: true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n via: true,\n};\n\nexport function assertIsAllowedHttpRequestHeaders(\n headers: Record<string, string>\n): asserts headers is AllowedHttpRequestHeaders {\n const badHeaders = Object.keys(headers).filter(headerName => {\n const lowercaseHeaderName = headerName.toLowerCase();\n return (\n DISALLOWED_HEADERS[headerName.toLowerCase()] === true ||\n FORBIDDEN_HEADERS[headerName.toLowerCase()] === true ||\n lowercaseHeaderName.startsWith('proxy-') ||\n lowercaseHeaderName.startsWith('sec-')\n );\n });\n if (badHeaders.length > 0) {\n throw new Error(\n `${badHeaders.length > 1 ? 'These headers are' : 'This header is'} forbidden: ` +\n `\\`${badHeaders.join('`, `')}\\`. Learn more at ` +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.'\n );\n }\n}\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers, such as those defined\n * in the `DisallowedHeaders` type.\n */\nexport function normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n","import type { Agent as NodeHttpAgent } from 'node:http';\nimport type { Agent as NodeHttpsAgent } from 'node:https';\n\nimport fetchImpl from 'fetch-impl';\n\nimport { IRpcTransport } from '../transport-types';\nimport { SolanaHttpError } from './http-transport-errors';\nimport {\n AllowedHttpRequestHeaders,\n assertIsAllowedHttpRequestHeaders,\n normalizeHeaders,\n} from './http-transport-headers';\n\ntype Config = Readonly<{\n headers?: AllowedHttpRequestHeaders;\n httpAgentNodeOnly?: NodeHttpAgent | NodeHttpsAgent | ((parsedUrl: URL) => NodeHttpAgent | NodeHttpsAgent);\n url: string;\n}>;\n\nexport function createHttpTransport({ httpAgentNodeOnly, headers, url }: Config): IRpcTransport {\n if (__DEV__ && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\n }\n const agent = __NODEJS__ ? httpAgentNodeOnly : undefined;\n if (__DEV__ && httpAgentNodeOnly != null) {\n console.warn(\n 'createHttpTransport(): The `httpAgentNodeOnly` config you supplied has been ' +\n 'ignored; HTTP agents are only usable in Node environments.'\n );\n }\n const customHeaders = headers && normalizeHeaders(headers);\n return async function makeHttpRequest<TResponse>({\n payload,\n signal,\n }: Parameters<IRpcTransport>[0]): Promise<TResponse> {\n const body = JSON.stringify(payload);\n const requestInfo = {\n agent,\n body,\n headers: {\n ...customHeaders,\n // Keep these headers lowercase so they will override any user-supplied headers above.\n accept: 'application/json',\n 'content-length': body.length.toString(),\n 'content-type': 'application/json; charset=utf-8',\n },\n method: 'POST',\n signal,\n };\n const response = await fetchImpl(url, requestInfo);\n if (!response.ok) {\n throw new SolanaHttpError({\n message: response.statusText,\n statusCode: response.status,\n });\n }\n return (await response.json()) as TResponse;\n };\n}\n","import { createSolanaRpcApi } from '@solana/rpc-core';\n\nimport { SolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\nexport const DEFAULT_RPC_CONFIG: Partial<Parameters<typeof createSolanaRpcApi>[0]> = {\n onIntegerOverflow(methodName, keyPath, value) {\n throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);\n },\n};\n","export class SolanaJsonRpcIntegerOverflowError extends Error {\n readonly methodName: string;\n readonly keyPath: (number | string)[];\n readonly value: bigint;\n constructor(methodName: string, keyPath: (number | string)[], value: bigint) {\n const argPosition = (typeof keyPath[0] === 'number' ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;\n let ordinal = '';\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n ordinal = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n ordinal = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n ordinal = argPosition + 'rd';\n } else {\n ordinal = argPosition + 'th';\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : null;\n super(\n `The ${ordinal} argument to the \\`${methodName}\\` RPC method` +\n `${path ? ` at path \\`${path}\\`` : ''} was \\`${value}\\`. This number is ` +\n 'unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.'\n );\n this.keyPath = keyPath;\n this.methodName = methodName;\n this.value = value;\n }\n get name() {\n return 'SolanaJsonRpcIntegerOverflowError';\n }\n}\n","import { createHttpTransport } from '@solana/rpc-transport';\nimport { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getRpcTransportWithRequestCoalescing } from './rpc-request-coalescer';\nimport { getSolanaRpcPayloadDeduplicationKey } from './rpc-request-deduplication';\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers.\n */\nfunction normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n\nexport function createDefaultRpcTransport(config: Parameters<typeof createHttpTransport>[0]): IRpcTransport {\n return getRpcTransportWithRequestCoalescing(\n createHttpTransport({\n ...config,\n headers: {\n ...(config.headers ? normalizeHeaders(config.headers) : undefined),\n ...({\n // Keep these headers lowercase so they will override any user-supplied headers above.\n 'solana-client': `js/${__VERSION__}` ?? 'UNKNOWN',\n } as { [overrideHeader: string]: string }),\n },\n }),\n getSolanaRpcPayloadDeduplicationKey\n );\n}\n","import { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\ntype CoalescedRequest = {\n readonly abortController: AbortController;\n numConsumers: number;\n readonly responsePromise: Promise<unknown>;\n};\n\ntype GetDeduplicationKeyFn = (payload: unknown) => string | undefined;\n\nexport function getRpcTransportWithRequestCoalescing(\n transport: IRpcTransport,\n getDeduplicationKey: GetDeduplicationKeyFn\n): IRpcTransport {\n let coalescedRequestsByDeduplicationKey: Record<string, CoalescedRequest> | undefined;\n return async function makeCoalescedHttpRequest<TResponse>(\n config: Parameters<IRpcTransport>[0]\n ): Promise<TResponse> {\n const { payload, signal } = config;\n const deduplicationKey = getDeduplicationKey(payload);\n if (deduplicationKey === undefined) {\n return await transport(config);\n }\n if (!coalescedRequestsByDeduplicationKey) {\n Promise.resolve().then(() => {\n coalescedRequestsByDeduplicationKey = undefined;\n });\n coalescedRequestsByDeduplicationKey = {};\n }\n if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {\n const abortController = new AbortController();\n coalescedRequestsByDeduplicationKey[deduplicationKey] = {\n abortController,\n numConsumers: 0,\n responsePromise: transport<TResponse>({\n ...config,\n signal: abortController.signal,\n }),\n };\n }\n const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];\n coalescedRequest.numConsumers++;\n if (signal) {\n const responsePromise = coalescedRequest.responsePromise as Promise<TResponse>;\n return await new Promise<TResponse>((resolve, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n signal.removeEventListener('abort', handleAbort);\n coalescedRequest.numConsumers -= 1;\n if (coalescedRequest.numConsumers === 0) {\n const abortController = coalescedRequest.abortController;\n abortController.abort();\n }\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n signal.addEventListener('abort', handleAbort);\n responsePromise.then(resolve).finally(() => {\n signal.removeEventListener('abort', handleAbort);\n });\n });\n } else {\n return (await coalescedRequest.responsePromise) as TResponse;\n }\n };\n}\n","// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return;\n }\n if ('jsonrpc' in payload && payload.jsonrpc === '2.0' && 'method' in payload && 'params' in payload) {\n return fastStableStringify([payload.method, payload.params]);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../build-scripts/env-shim.ts","../../../node_modules/.pnpm/fast-stable-stringify@1.0.0/node_modules/fast-stable-stringify/index.js","../src/index.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/fixSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/mapSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/baseX.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/base58.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/nullCharacters.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/utf8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/common.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u32.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/shortU16.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/sumSerializerSizes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/array.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/string.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/struct.ts","../../assertions/src/subtle-crypto.ts","../../addresses/src/base58.ts","../../addresses/src/computed-address.ts","../../addresses/src/vendor/noble/ed25519.ts","../../addresses/src/curve.ts","../../addresses/src/public-key.ts","../../instructions/src/roles.ts","../../keys/src/key-pair.ts","../../keys/src/signatures.ts","../../transactions/src/unsigned-transaction.ts","../../transactions/src/blockhash.ts","../../transactions/src/create-transaction.ts","../../transactions/src/durable-nonce.ts","../../transactions/src/fee-payer.ts","../../transactions/src/instructions.ts","../../transactions/src/signatures.ts","../../transactions/src/accounts.ts","../../transactions/src/compile-address-table-lookups.ts","../../transactions/src/compile-header.ts","../../transactions/src/compile-instructions.ts","../../transactions/src/compile-lifetime-token.ts","../../transactions/src/compile-static-accounts.ts","../../transactions/src/message.ts","../../transactions/src/serializers/message.ts","../../transactions/src/serializers/address-table-lookup.ts","../../transactions/src/serializers/header.ts","../../transactions/src/serializers/instruction.ts","../../transactions/src/serializers/unimplemented.ts","../../transactions/src/serializers/transaction-version.ts","../../transactions/src/serializers/transaction.ts","../../transactions/src/compile-transaction.ts","../src/rpc.ts","../../rpc-core/src/params-patcher.ts","../../rpc-core/src/response-patcher-allowed-numeric-values.ts","../../rpc-core/src/response-patcher.ts","../../rpc-core/src/rpc-methods/index.ts","../../rpc-core/src/rpc-subscriptions/index.ts","../../rpc-transport/src/json-rpc-errors.ts","../../rpc-transport/src/json-rpc-message-id.ts","../../rpc-transport/src/json-rpc-message.ts","../../rpc-transport/src/json-rpc.ts","../../rpc-transport/src/json-rpc-subscription.ts","../../fetch-impl/src/index.browser.ts","../../rpc-transport/src/transports/http/http-transport-errors.ts","../../rpc-transport/src/transports/http/http-transport-headers.ts","../../rpc-transport/src/transports/http/http-transport.ts","../../ws-impl/src/index.browser.ts","../../rpc-transport/src/transports/websocket/websocket-connection.ts","../../rpc-transport/src/transports/websocket/websocket-transport.ts","../src/rpc-default-config.ts","../src/rpc-integer-overflow-error.ts","../src/rpc-transport.ts","../src/rpc-request-coalescer.ts","../src/rpc-request-deduplication.ts","../src/rpc-websocket-transport.ts","../src/rpc-websocket-autopinger.ts"],"names":["mergeBytes","bytesArr","totalLength","reduce","total","arr","length","result","Uint8Array","offset","forEach","set","padBytes","bytes","paddedBytes","fill","fixBytes","slice","DeserializingEmptyBufferError","Error","constructor","serializer","name","NotEnoughBytesError","expected","actual","ExpectedFixedSizeSerializerError","message","fixSerializer","fixedBytes","description","fixedSize","maxSize","serialize","value","deserialize","buffer","mapSerializer","unmap","map","InvalidBaseStringError","base","cause","baseX","alphabet","baseBigInt","BigInt","match","RegExp","chars","trailIndex","findIndex","c","leadingZeroes","Array","from","tailChars","base10Number","baseXPower","i","indexOf","tailBytes","unshift","Number","concat","n","repeat","sum","byte","join","base58","removeNullCharacters","replace","utf8","TextEncoder","encode","TextDecoder","decode","Endian","NumberOutOfRangeError","RangeError","min","max","numberFactory","input","littleEndian","defaultDescription","size","options","endian","Little","range","assertRange","ArrayBuffer","DataView","assertEnoughBytes","view","toDataView","get","toArrayBuffer","array","byteOffset","byteLength","u8","setUint8","getUint8","u32","le","setUint32","getUint32","shortU16","ii","alignedValue","nextSevenBits","byteCount","byteIndex","currentByte","InvalidNumberOfItemsError","InvalidArrayLikeRemainderSizeError","remainderSize","itemSize","UnrecognizedArrayLikeSerializerSizeError","JSON","stringify","sumSerializerSizes","sizes","all","getResolvedSize","childrenSizes","childrenSize","remainder","getSizeDescription","getSizeFromChildren","getSizePrefix","realSize","item","v","resolvedSize","newOffset","values","push","byteSerializer","contentBytes","lengthBytes","lengthBigInt","lengthOffset","contentBuffer","contentOffset","string","encoding","struct","fields","fieldDescriptions","String","field","fieldBytes","key","__DEV__","e","AccountRole","AccountRole2","IS_WRITABLE_BITMASK","isSignerRole","isWritableRole","mergeRoles","getBase58EncodedAddressComparator","BASE_CONFIG","visitNode","makeProxy","index_browser_default","resolve","reject","fastStableStringify","normalizeHeaders","args"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA,QAAI,cAAc,OAAO,UAAU;AACnC,QAAI,UAAU,OAAO,QAAQ,SAAS,KAAK;AACzC,UAAI,OAAO,CAAC;AACZ,eAAS,QAAQ,KAAK;AACrB,aAAK,KAAK,IAAI;AAAA,MACf;AACA,aAAO;AAAA,IACR;AAED,aAAS,UAAU,KAAK,aAAa;AACpC,UAAI,GAAG,KAAK,KAAK,MAAM,KAAK,SAAS;AACrC,UAAI,QAAQ,MAAM;AACjB,eAAO;AAAA,MACR;AACA,UAAI,QAAQ,OAAO;AAClB,eAAO;AAAA,MACR;AACA,cAAQ,OAAO,KAAK;AAAA,QACnB,KAAK;AACJ,cAAI,QAAQ,MAAM;AACjB,mBAAO;AAAA,UACR,WAAW,IAAI,UAAU,OAAO,IAAI,WAAW,YAAY;AAC1D,mBAAO,UAAU,IAAI,OAAO,GAAG,WAAW;AAAA,UAC3C,OAAO;AACN,oBAAQ,YAAY,KAAK,GAAG;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AAC;AACD,OAAC,YAAY;AACT,YAAI;AAEA,2BAAiB,KAAK,YAAY;AAC9B,6BAAiB;AAAA,UACrB;AAAA,QACJ,QAAQ;AAAA,QAER,UAAE;AACE,8BAAoB,OAAO,UAAU;AACrC,wBAAc,UAAU;AAAA,QAC5B;AAAA,MACJ,GAAG;AACH,uBAAiB;AAAA,IACrB;AACA,WAAO,oBAAoB,IAAI,UAAU;AAAA,EAC7C;AACJ;;;ADhDO,SAAS,uCACZ,QAIsB;AACtB,QAAM,EAAE,YAAY,GAAG,KAAK,IAAI;AAChC,SAAO,kCAAkC;AAAA,IACrC,YAAY,cAAc;AAAA,IAC1B,WAAW,yBAAyB;AAAA,MAChC,GAAG;AAAA,MACH,yBACI,OAAO;AAAA,MAEP;AAAA,IACR,CAAC;AAAA,EACL,CAAC;AACL","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\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 * from '@solana/addresses';\nexport * from '@solana/instructions';\nexport * from '@solana/keys';\nexport * from '@solana/transactions';\nexport * from './rpc';\nexport * from './rpc-transport';\nexport * from './rpc-websocket-transport';\n","export * from '@metaplex-foundation/umi-serializers-core';\nexport * from '@metaplex-foundation/umi-serializers-encodings';\nexport * from '@metaplex-foundation/umi-serializers-numbers';\nexport { array } from './array.mjs';\nexport { bitArray } from './bitArray.mjs';\nexport { bool } from './bool.mjs';\nexport { bytes } from './bytes.mjs';\nexport { dataEnum } from './dataEnum.mjs';\nexport { EnumDiscriminatorOutOfRangeError, InvalidArrayLikeRemainderSizeError, InvalidDataEnumVariantError, InvalidNumberOfItemsError, InvalidScalarEnumVariantError, UnrecognizedArrayLikeSerializerSizeError } from './errors.mjs';\nexport { map } from './map.mjs';\nexport { nullable } from './nullable.mjs';\nexport { option } from './option.mjs';\nexport { publicKey } from './publicKey.mjs';\nexport { scalarEnum } from './scalarEnum.mjs';\nexport { set } from './set.mjs';\nexport { string } from './string.mjs';\nexport { struct } from './struct.mjs';\nexport { tuple } from './tuple.mjs';\nexport { unit } from './unit.mjs';\nexport { maxSerializerSizes } from './maxSerializerSizes.mjs';\nexport { sumSerializerSizes } from './sumSerializerSizes.mjs';\n//# sourceMappingURL=index.mjs.map\n","export { fixBytes, mergeBytes, padBytes } from './bytes.mjs';\nexport { DeserializingEmptyBufferError, ExpectedFixedSizeSerializerError, NotEnoughBytesError } from './errors.mjs';\nexport { fixSerializer } from './fixSerializer.mjs';\nexport { mapSerializer } from './mapSerializer.mjs';\nexport { reverseSerializer } from './reverseSerializer.mjs';\n//# sourceMappingURL=index.mjs.map\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * @category Utils\n */\nexport const mergeBytes = (bytesArr: Uint8Array[]): Uint8Array => {\n const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n bytesArr.forEach((arr) => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n * @category Utils\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n * @category Utils\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.slice(0, length), length);\n","/** @category Errors */\nexport class DeserializingEmptyBufferError extends Error {\n readonly name: string = 'DeserializingEmptyBufferError';\n\n constructor(serializer: string) {\n super(`Serializer [${serializer}] cannot deserialize empty buffers.`);\n }\n}\n\n/** @category Errors */\nexport class NotEnoughBytesError extends Error {\n readonly name: string = 'NotEnoughBytesError';\n\n constructor(\n serializer: string,\n expected: bigint | number,\n actual: bigint | number\n ) {\n super(\n `Serializer [${serializer}] expected ${expected} bytes, got ${actual}.`\n );\n }\n}\n\n/** @category Errors */\nexport class ExpectedFixedSizeSerializerError extends Error {\n readonly name: string = 'ExpectedFixedSizeSerializerError';\n\n constructor(message?: string) {\n message ??= 'Expected a fixed-size serializer, got a variable-size one.';\n super(message);\n }\n}\n","import { fixBytes } from './bytes';\nimport { Serializer } from './common';\nimport { NotEnoughBytesError } from './errors';\n\n/**\n * Creates a fixed-size serializer from a given serializer.\n *\n * @param serializer - The serializer to wrap into a fixed-size serializer.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the serializer.\n *\n * @category Serializers\n */\nexport function fixSerializer<T, U extends T = T>(\n serializer: Serializer<T, U>,\n fixedBytes: number,\n description?: string\n): Serializer<T, U> {\n return {\n description:\n description ?? `fixed(${fixedBytes}, ${serializer.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n serialize: (value: T) => fixBytes(serializer.serialize(value), fixedBytes),\n deserialize: (buffer: Uint8Array, offset = 0) => {\n // Slice the buffer to the fixed size.\n buffer = buffer.slice(offset, offset + fixedBytes);\n // Ensure we have enough bytes.\n if (buffer.length < fixedBytes) {\n throw new NotEnoughBytesError(\n 'fixSerializer',\n fixedBytes,\n buffer.length\n );\n }\n // If the nested serializer is fixed-size, pad and truncate the buffer accordingly.\n if (serializer.fixedSize !== null) {\n buffer = fixBytes(buffer, serializer.fixedSize);\n }\n // Deserialize the value using the nested serializer.\n const [value] = serializer.deserialize(buffer, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n","import { Serializer } from './common';\n\n/**\n * Converts a serializer A to a serializer B by mapping their values.\n * @category Serializers\n */\nexport function mapSerializer<NewFrom, OldFrom, To extends NewFrom & OldFrom>(\n serializer: Serializer<OldFrom, To>,\n unmap: (value: NewFrom) => OldFrom\n): Serializer<NewFrom, To>;\nexport function mapSerializer<\n NewFrom,\n OldFrom,\n NewTo extends NewFrom = NewFrom,\n OldTo extends OldFrom = OldFrom\n>(\n serializer: Serializer<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map: (value: OldTo, buffer: Uint8Array, offset: number) => NewTo\n): Serializer<NewFrom, NewTo>;\nexport function mapSerializer<\n NewFrom,\n OldFrom,\n NewTo extends NewFrom = NewFrom,\n OldTo extends OldFrom = OldFrom\n>(\n serializer: Serializer<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map?: (value: OldTo, buffer: Uint8Array, offset: number) => NewTo\n): Serializer<NewFrom, NewTo> {\n return {\n description: serializer.description,\n fixedSize: serializer.fixedSize,\n maxSize: serializer.maxSize,\n serialize: (value: NewFrom) => serializer.serialize(unmap(value)),\n deserialize: (buffer: Uint8Array, offset = 0) => {\n const [value, length] = serializer.deserialize(buffer, offset);\n return map\n ? [map(value, buffer, offset), length]\n : [value as any, length];\n },\n };\n}\n","export { base10 } from './base10.mjs';\nexport { base16 } from './base16.mjs';\nexport { base58 } from './base58.mjs';\nexport { base64 } from './base64.mjs';\nexport { baseX } from './baseX.mjs';\nexport { baseXReslice } from './baseXReslice.mjs';\nexport { InvalidBaseStringError } from './errors.mjs';\nexport { padNullCharacters, removeNullCharacters } from './nullCharacters.mjs';\nexport { utf8 } from './utf8.mjs';\n//# sourceMappingURL=index.mjs.map\n","/** @category Errors */\nexport class InvalidBaseStringError extends Error {\n readonly name: string = 'InvalidBaseStringError';\n\n readonly cause?: Error;\n\n constructor(value: string, base: number, cause?: Error) {\n const message = `Expected a string of base ${base}, got [${value}].`;\n super(message);\n this.cause = cause;\n }\n}\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { InvalidBaseStringError } from './errors';\n\n/**\n * A string serializer that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create serializers such as base10 or base58.\n *\n * @category Serializers\n */\nexport const baseX = (alphabet: string): Serializer<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n serialize(value: string): Uint8Array {\n // Check if the value is valid.\n if (!value.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new InvalidBaseStringError(value, base);\n }\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex((c) => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n deserialize(buffer, offset = 0): [string, number] {\n if (buffer.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n const bytes = buffer.slice(offset);\n let trailIndex = bytes.findIndex((n) => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, buffer.length];\n\n // From bytes to base10.\n let base10Number = bytes\n .slice(trailIndex)\n .reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), buffer.length];\n },\n };\n};\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { baseX } from './baseX';\n\n/**\n * A string serializer that uses base58 encoding.\n * @category Serializers\n */\nexport const base58: Serializer<string> = baseX(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n","/**\n * Removes null characters from a string.\n * @category Utils\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters at the end.\n * @category Utils\n */\nexport const padNullCharacters = (value: string, chars: number) =>\n value.padEnd(chars, '\\u0000');\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { removeNullCharacters } from './nullCharacters';\n\n/**\n * A string serializer that uses UTF-8 encoding\n * using the native `TextEncoder` API.\n * @category Serializers\n */\nexport const utf8: Serializer<string> = {\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n serialize(value: string) {\n return new TextEncoder().encode(value);\n },\n deserialize(buffer, offset = 0) {\n const value = new TextDecoder().decode(buffer.slice(offset));\n return [removeNullCharacters(value), buffer.length];\n },\n};\n","export { Endian } from './common.mjs';\nexport { NumberOutOfRangeError } from './errors.mjs';\nexport { f32 } from './f32.mjs';\nexport { f64 } from './f64.mjs';\nexport { i8 } from './i8.mjs';\nexport { i16 } from './i16.mjs';\nexport { i32 } from './i32.mjs';\nexport { i64 } from './i64.mjs';\nexport { i128 } from './i128.mjs';\nexport { u8 } from './u8.mjs';\nexport { u16 } from './u16.mjs';\nexport { u32 } from './u32.mjs';\nexport { u64 } from './u64.mjs';\nexport { u128 } from './u128.mjs';\nexport { shortU16 } from './shortU16.mjs';\n//# sourceMappingURL=index.mjs.map\n","import {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\n\n/**\n * Defines a serializer for numbers and bigints.\n * @category Serializers\n */\nexport type NumberSerializer =\n | Serializer<number>\n | Serializer<number | bigint, bigint>;\n\n/**\n * Defines the options for u8 and i8 serializers.\n * @category Serializers\n */\nexport type SingleByteNumberSerializerOptions = BaseSerializerOptions;\n\n/**\n * Defines the options for number serializers that use more than one byte.\n * @category Serializers\n */\nexport type NumberSerializerOptions = BaseSerializerOptions & {\n /**\n * Whether the serializer should use little-endian or big-endian encoding.\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the endianness of a number serializer.\n * @category Serializers\n */\nexport enum Endian {\n Little = 'le',\n Big = 'be',\n}\n","/** @category Errors */\nexport class NumberOutOfRangeError extends RangeError {\n readonly name: string = 'NumberOutOfRangeError';\n\n constructor(\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n actual: number | bigint\n ) {\n super(\n `Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`\n );\n }\n}\n","import {\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport {\n Endian,\n NumberSerializer,\n NumberSerializerOptions,\n SingleByteNumberSerializerOptions,\n} from './common';\nimport { NumberOutOfRangeError } from './errors';\n\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number | bigint, bigint>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number | bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): NumberSerializer {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian =\n !('endian' in input.options) || input.options.endian === Endian.Little;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n maxSize: input.size,\n serialize(value: number | bigint): Uint8Array {\n if (input.range) {\n assertRange(input.name, input.range[0], input.range[1], value);\n }\n const buffer = new ArrayBuffer(input.size);\n input.set(new DataView(buffer), value, littleEndian);\n return new Uint8Array(buffer);\n },\n deserialize(bytes, offset = 0): [number | bigint, number] {\n const slice = bytes.slice(offset, offset + input.size);\n assertEnoughBytes('i8', slice, input.size);\n const view = toDataView(slice);\n return [input.get(view, littleEndian), offset + input.size];\n },\n } as NumberSerializer;\n}\n\n/**\n * Helper function to ensure that the array buffer is converted properly from a uint8array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n * @param {Uint8Array} array Uint8array that's being converted into an array buffer\n * @returns {ArrayBuffer} An array buffer that's necessary to construct a data view\n */\nexport const toArrayBuffer = (array: Uint8Array): ArrayBuffer =>\n array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);\n\nexport const toDataView = (array: Uint8Array): DataView =>\n new DataView(toArrayBuffer(array));\n\nexport const assertRange = (\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) => {\n if (value < min || value > max) {\n throw new NumberOutOfRangeError(serializer, min, max, value);\n }\n};\n\nexport const assertEnoughBytes = (\n serializer: string,\n bytes: Uint8Array,\n expected: number\n) => {\n if (bytes.length === 0) {\n throw new DeserializingEmptyBufferError(serializer);\n }\n if (bytes.length < expected) {\n throw new NotEnoughBytesError(serializer, expected, bytes.length);\n }\n};\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { SingleByteNumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u8 = (\n options: SingleByteNumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u8',\n size: 1,\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n get: (view) => view.getUint8(0),\n options,\n });\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u32 = (\n options: NumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u32',\n size: 4,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n get: (view, le) => view.getUint32(0, le),\n options,\n });\n","/* eslint-disable no-bitwise */\nimport {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { assertRange } from './utils';\n\n/**\n * Defines the options for the shortU16 serializer.\n * @category Serializers\n */\nexport type ShortU16SerializerOptions = BaseSerializerOptions;\n\n/**\n * Same as u16, but serialized with 1 to 3 bytes.\n *\n * If the value is above 0x7f, the top bit is set and the remaining\n * value is stored in the next bytes. Each byte follows the same\n * pattern until the 3rd byte. The 3rd byte, if needed, uses\n * all 8 bits to store the last byte of the original value.\n *\n * @category Serializers\n */\nexport const shortU16 = (\n options: ShortU16SerializerOptions = {}\n): Serializer<number> => ({\n description: options.description ?? 'shortU16',\n fixedSize: null,\n maxSize: 3,\n serialize: (value: number): Uint8Array => {\n assertRange('shortU16', 0, 65535, value);\n const bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = value >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n bytes[ii - 1] |= 0b10000000;\n }\n }\n return new Uint8Array(bytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0): [number, number] => {\n let value = 0;\n let byteCount = 0;\n while (\n ++byteCount // eslint-disable-line no-plusplus\n ) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n});\n","/** @category Errors */\nexport class InvalidNumberOfItemsError extends Error {\n readonly name = 'InvalidNumberOfItemsError';\n\n constructor(\n serializer: string,\n expected: number | bigint,\n actual: number | bigint\n ) {\n super(`Expected [${serializer}] to have ${expected} items, got ${actual}.`);\n }\n}\n\n/** @category Errors */\nexport class InvalidArrayLikeRemainderSizeError extends Error {\n readonly name = 'InvalidArrayLikeRemainderSizeError';\n\n constructor(remainderSize: number | bigint, itemSize: number | bigint) {\n super(\n `The remainder of the buffer (${remainderSize} bytes) cannot be split into chunks of ${itemSize} bytes. ` +\n `Serializers of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainderSize} modulo ${itemSize} should be equal to zero.`\n );\n }\n}\n\n/** @category Errors */\nexport class UnrecognizedArrayLikeSerializerSizeError extends Error {\n readonly name = 'UnrecognizedArrayLikeSerializerSizeError';\n\n constructor(size: never) {\n super(`Unrecognized array-like serializer size: ${JSON.stringify(size)}`);\n }\n}\n\n/** @category Errors */\nexport class InvalidDataEnumVariantError extends Error {\n readonly name = 'InvalidDataEnumVariantError';\n\n constructor(invalidVariant: string, validVariants: string[]) {\n super(\n `Invalid data enum variant. ` +\n `Expected one of [${validVariants.join(', ')}], ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class InvalidScalarEnumVariantError extends Error {\n readonly name = 'InvalidScalarEnumVariantError';\n\n constructor(\n invalidVariant: string | number | bigint,\n validVariants: string[],\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Invalid scalar enum variant. ` +\n `Expected one of [${validVariants.join(', ')}] ` +\n `or a number between ${min} and ${max}, ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class EnumDiscriminatorOutOfRangeError extends RangeError {\n readonly name = 'EnumDiscriminatorOutOfRangeError';\n\n constructor(\n discriminator: number | bigint,\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Enum discriminator out of range. ` +\n `Expected a number between ${min} and ${max}, got ${discriminator}.`\n );\n }\n}\n","export function sumSerializerSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : all + size),\n 0 as number | null\n );\n}\n","import { ExpectedFixedSizeSerializerError } from '@metaplex-foundation/umi-serializers-core';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport {\n InvalidArrayLikeRemainderSizeError,\n UnrecognizedArrayLikeSerializerSizeError,\n} from './errors';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\nexport function getResolvedSize(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: number\n): [number | bigint, number] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.deserialize(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumSerializerSizes(childrenSizes);\n if (childrenSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n throw new InvalidArrayLikeRemainderSizeError(remainder, childrenSize);\n }\n return [remainder / childrenSize, offset];\n }\n\n throw new UnrecognizedArrayLikeSerializerSizeError(size);\n}\n\nexport function getSizeDescription(\n size: ArrayLikeSerializerSize | string\n): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getSizeFromChildren(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumSerializerSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getSizePrefix(\n size: ArrayLikeSerializerSize,\n realSize: number\n): Uint8Array {\n return typeof size === 'object' ? size.serialize(realSize) : new Uint8Array();\n}\n","import {\n BaseSerializerOptions,\n ExpectedFixedSizeSerializerError,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { u32 } from '@metaplex-foundation/umi-serializers-numbers';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport { InvalidNumberOfItemsError } from './errors';\nimport {\n getResolvedSize,\n getSizeDescription,\n getSizeFromChildren,\n getSizePrefix,\n} from './utils';\n\n/**\n * Defines the options for array serializers.\n * @category Serializers\n */\nexport type ArraySerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the array.\n * @defaultValue `u32()`\n */\n size?: ArrayLikeSerializerSize;\n};\n\n/**\n * Creates a serializer for an array of items.\n *\n * @param item - The serializer to use for the array's items.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function array<T, U extends T = T>(\n item: Serializer<T, U>,\n options: ArraySerializerOptions = {}\n): Serializer<T[], U[]> {\n const size = options.size ?? u32();\n if (size === 'remainder' && item.fixedSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n return {\n description:\n options.description ??\n `array(${item.description}; ${getSizeDescription(size)})`,\n fixedSize: getSizeFromChildren(size, [item.fixedSize]),\n maxSize: getSizeFromChildren(size, [item.maxSize]),\n serialize: (value: T[]) => {\n if (typeof size === 'number' && value.length !== size) {\n throw new InvalidNumberOfItemsError('array', size, value.length);\n }\n return mergeBytes([\n getSizePrefix(size, value.length),\n ...value.map((v) => item.serialize(v)),\n ]);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = getResolvedSize(\n size,\n [item.fixedSize],\n bytes,\n offset\n );\n offset = newOffset;\n const values: U[] = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.deserialize(bytes, offset);\n values.push(value);\n offset = newOffset;\n }\n return [values, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializer } from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for bytes serializers.\n * @category Serializers\n */\nexport type BytesSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the buffer. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the buffer with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `'variable'`\n */\n size?: NumberSerializer | number | 'variable';\n};\n\n/**\n * Creates a serializer that passes the buffer as-is.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function bytes(\n options: BytesSerializerOptions = {}\n): Serializer<Uint8Array> {\n const size = options.size ?? 'variable';\n const description =\n options.description ?? `bytes(${getSizeDescription(size)})`;\n\n const byteSerializer: Serializer<Uint8Array> = {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => new Uint8Array(value),\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n };\n\n if (size === 'variable') {\n return byteSerializer;\n }\n\n if (typeof size === 'number') {\n return fixSerializer(byteSerializer, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => {\n const contentBytes = byteSerializer.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('bytes');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('bytes', length, contentBuffer.length);\n }\n const [value, contentOffset] = byteSerializer.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { utf8 } from '@metaplex-foundation/umi-serializers-encodings';\nimport {\n NumberSerializer,\n u32,\n} from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for string serializers.\n * @category Serializers\n */\nexport type StringSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `u32()`\n */\n size?: NumberSerializer | number | 'variable';\n /**\n * The string serializer to use for encoding and decoding the content.\n * @defaultValue `utf8`\n */\n encoding?: Serializer<string>;\n};\n\n/**\n * Creates a string serializer.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function string(\n options: StringSerializerOptions = {}\n): Serializer<string> {\n const size = options.size ?? u32();\n const encoding = options.encoding ?? utf8;\n const description =\n options.description ??\n `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixSerializer(encoding, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: string) => {\n const contentBytes = encoding.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('string');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('string', length, contentBuffer.length);\n }\n const [value, contentOffset] = encoding.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\n/**\n * Get the name and serializer of each field in a struct.\n * @category Serializers\n */\nexport type StructToSerializerTuple<T extends object, U extends T> = Array<\n {\n [K in keyof T]: [K, Serializer<T[K], U[K]>];\n }[keyof T]\n>;\n\n/**\n * Defines the options for struct serializers.\n * @category Serializers\n */\nexport type StructSerializerOptions = BaseSerializerOptions;\n\n/**\n * Creates a serializer for a custom object.\n *\n * @param fields - The name and serializer of each field.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function struct<T extends object, U extends T = T>(\n fields: StructToSerializerTuple<T, U>,\n options: StructSerializerOptions = {}\n): Serializer<T, U> {\n const fieldDescriptions = fields\n .map(([name, serializer]) => `${String(name)}: ${serializer.description}`)\n .join(', ');\n return {\n description: options.description ?? `struct(${fieldDescriptions})`,\n fixedSize: sumSerializerSizes(fields.map(([, field]) => field.fixedSize)),\n maxSize: sumSerializerSizes(fields.map(([, field]) => field.maxSize)),\n serialize: (struct: T) => {\n const fieldBytes = fields.map(([key, serializer]) =>\n serializer.serialize(struct[key])\n );\n return mergeBytes(fieldBytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const struct: Partial<U> = {};\n fields.forEach(([key, serializer]) => {\n const [value, newOffset] = serializer.deserialize(bytes, offset);\n offset = newOffset;\n struct[key] = value;\n });\n return [struct as U, offset];\n },\n };\n}\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\nimport { Base58EncodedAddress, getBase58EncodedAddressCodec } from './base58';\nimport { compressedPointBytesAreOnCurve } from './curve';\n\ntype PDAInput = Readonly<{\n programAddress: Base58EncodedAddress;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Base58EncodedAddress;\n programAddress: Base58EncodedAddress;\n seed: Seed;\n}>;\n\ntype Seed = string | Uint8Array;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\n// TODO: Coded error.\nclass PointOnCurveError extends Error {}\n\nasync function createProgramDerivedAddress({ programAddress, seeds }: PDAInput): Promise<Base58EncodedAddress> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n // TODO: Coded error.\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getBase58EncodedAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.serialize(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n // TODO: Coded error.\n throw new PointOnCurveError('Invalid seeds; point must fall off the Ed25519 curve');\n }\n return base58EncodedAddressCodec.deserialize(addressBytes)[0];\n}\n\nexport async function getProgramDerivedAddress({ programAddress, seeds }: PDAInput): Promise<\n Readonly<{\n bumpSeed: number;\n pda: Base58EncodedAddress;\n }>\n> {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n return {\n bumpSeed,\n pda: await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n }),\n };\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n // TODO: Coded error.\n throw new Error('Unable to find a viable program address bump seed');\n}\n\nexport async function createAddressWithSeed({\n baseAddress,\n programAddress,\n seed,\n}: SeedInput): Promise<Base58EncodedAddress> {\n const { serialize, deserialize } = getBase58EncodedAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n\n const programAddressBytes = serialize(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])\n ) {\n // TODO: Coded error.\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...serialize(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return deserialize(addressBytes)[0];\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: Uint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport async function compressedPointBytesAreOnCurve(bytes: Uint8Array): Promise<boolean> {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Base58EncodedAddress, getBase58EncodedAddressCodec } from './base58';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n","/**\n * Quick primer on bitwise operations: https://stackoverflow.com/a/1436448/802047\n */\n\nexport enum AccountRole {\n // Bitflag guide: is signer ⌄⌄ is writable\n WRITABLE_SIGNER = /* 3 */ 0b11, // prettier-ignore\n READONLY_SIGNER = /* 2 */ 0b10, // prettier-ignore\n WRITABLE = /* 1 */ 0b01, // prettier-ignore\n READONLY = /* 0 */ 0b00, // prettier-ignore\n}\n\nconst IS_SIGNER_BITMASK = 0b10;\nconst IS_WRITABLE_BITMASK = 0b01;\n\nexport function downgradeRoleToNonSigner(role: AccountRole.READONLY_SIGNER): AccountRole.READONLY;\nexport function downgradeRoleToNonSigner(role: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole {\n return role & ~IS_SIGNER_BITMASK;\n}\n\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE): AccountRole.READONLY;\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE_SIGNER): AccountRole.READONLY_SIGNER;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole {\n return role & ~IS_WRITABLE_BITMASK;\n}\n\nexport function isSignerRole(role: AccountRole): role is AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER {\n return role >= AccountRole.READONLY_SIGNER;\n}\n\nexport function isWritableRole(role: AccountRole): role is AccountRole.WRITABLE | AccountRole.WRITABLE_SIGNER {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\n\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE_SIGNER, roleB: AccountRole): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.READONLY_SIGNER): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY, roleB: AccountRole.READONLY): AccountRole.READONLY; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole {\n return roleA | roleB;\n}\n\nexport function upgradeRoleToSigner(role: AccountRole.READONLY): AccountRole.READONLY_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole {\n return role | IS_SIGNER_BITMASK;\n}\n\nexport function upgradeRoleToWritable(role: AccountRole.READONLY): AccountRole.WRITABLE;\nexport function upgradeRoleToWritable(role: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole {\n return role | IS_WRITABLE_BITMASK;\n}\n","import { assertKeyGenerationIsAvailable } from '@solana/assertions';\n\nexport async function generateKeyPair(): Promise<CryptoKeyPair> {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ 'Ed25519', // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify']\n );\n return keyPair as CryptoKeyPair;\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n","import { ITransactionWithSignatures } from '.';\nimport { BaseTransaction } from './types';\n\nexport function getUnsignedTransaction<TTransaction extends BaseTransaction>(\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction & ITransactionWithSignatures, keyof ITransactionWithSignatures> {\n if ('signatures' in transaction) {\n // The implication of the lifetime constraint changing is that any existing signatures are invalid.\n const {\n signatures: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n","import { base58 } from '@metaplex-foundation/umi-serializers';\n\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport type Blockhash = string & { readonly __brand: unique symbol };\n\ntype BlockhashLifetimeConstraint = Readonly<{\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n}>;\n\nexport interface ITransactionWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 ||\n // Highest value (32 bytes of 255)\n putativeBlockhash.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeBlockhash);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBlockhash}\\` is not a blockhash`, {\n cause: e,\n });\n }\n}\n\nexport function setTransactionLifetimeUsingBlockhash<TTransaction extends BaseTransaction & IDurableNonceTransaction>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures | 'lifetimeConstraint'> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash<\n TTransaction extends BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n) {\n if (\n 'lifetimeConstraint' in transaction &&\n transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n lifetimeConstraint: blockhashLifetimeConstraint,\n };\n Object.freeze(out);\n return out;\n}\n","import { Transaction, TransactionVersion } from './types';\n\ntype TransactionConfig<TVersion extends TransactionVersion> = Readonly<{\n version: TVersion;\n}>;\n\nexport function createTransaction<TVersion extends TransactionVersion>(\n config: TransactionConfig<TVersion>\n): Extract<Transaction, { version: TVersion }>;\nexport function createTransaction<TVersion extends TransactionVersion>({\n version,\n}: TransactionConfig<TVersion>): Transaction {\n const out: Transaction = {\n instructions: [],\n version,\n };\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport { AccountRole, IInstruction, IInstructionWithAccounts, IInstructionWithData } from '@solana/instructions';\nimport { ReadonlyAccount, ReadonlySignerAccount, WritableAccount } from '@solana/instructions/dist/types/accounts';\n\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\ntype AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n> = IInstruction<'11111111111111111111111111111111'> &\n IInstructionWithAccounts<\n readonly [\n WritableAccount<TNonceAccountAddress>,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount<TNonceAuthorityAddress>\n ]\n > &\n IInstructionWithData<AdvanceNonceAccountInstructionData>;\ntype AdvanceNonceAccountInstructionData = Uint8Array & {\n readonly __brand: unique symbol;\n};\ntype DurableNonceConfig<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> = Readonly<{\n readonly nonce: Nonce<TNonceValue>;\n readonly nonceAccountAddress: Base58EncodedAddress<TNonceAccountAddress>;\n readonly nonceAuthorityAddress: Base58EncodedAddress<TNonceAuthorityAddress>;\n}>;\nexport type Nonce<TNonceValue extends string = string> = TNonceValue & { readonly __brand: unique symbol };\ntype NonceLifetimeConstraint<TNonceValue extends string = string> = Readonly<{\n nonce: Nonce<TNonceValue>;\n}>;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Base58EncodedAddress<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS =\n '11111111111111111111111111111111' as Base58EncodedAddress<'11111111111111111111111111111111'>;\n\nexport interface IDurableNonceTransaction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint<TNonceValue>;\n}\n\nexport function assertIsDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): asserts transaction is BaseTransaction & IDurableNonceTransaction {\n if (!isDurableNonceTransaction(transaction)) {\n // TODO: Coded error.\n throw new Error('Transaction is not a durable nonce transaction');\n }\n}\n\nfunction createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n>(\n nonceAccountAddress: Base58EncodedAddress<TNonceAccountAddress>,\n nonceAuthorityAddress: Base58EncodedAddress<TNonceAuthorityAddress>\n): AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\nfunction isAdvanceNonceAccountInstruction(instruction: IInstruction): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.programAddress === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accounts?.length === 3 &&\n // First account is nonce account address\n instruction.accounts[0].address != null &&\n instruction.accounts[0].role === AccountRole.WRITABLE &&\n // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS &&\n instruction.accounts[1].role === AccountRole.READONLY &&\n // Third account is nonce authority account\n instruction.accounts[2].address != null &&\n instruction.accounts[2].role === AccountRole.READONLY_SIGNER\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: Uint8Array): data is AdvanceNonceAccountInstructionData {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n\nfunction isDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): transaction is BaseTransaction & IDurableNonceTransaction {\n return (\n 'lifetimeConstraint' in transaction &&\n typeof transaction.lifetimeConstraint.nonce === 'string' &&\n transaction.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transaction.instructions[0])\n );\n}\n\nexport function setTransactionLifetimeUsingDurableNonce<\n TTransaction extends BaseTransaction,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n>(\n {\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n }: DurableNonceConfig<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>,\n transaction: TTransaction | (TTransaction & IDurableNonceTransaction)\n): TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue> {\n const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction);\n if (\n isAlreadyDurableNonceTransaction &&\n transaction.lifetimeConstraint.nonce === nonce &&\n transaction.instructions[0].accounts[0].address === nonceAccountAddress &&\n transaction.instructions[0].accounts[2].address === nonceAuthorityAddress\n ) {\n return transaction as TTransaction &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...(isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions),\n ],\n lifetimeConstraint: {\n nonce,\n },\n } as TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport interface ITransactionWithFeePayer<TAddress extends string = string> {\n readonly feePayer: Base58EncodedAddress<TAddress>;\n}\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<TFeePayerAddress> & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction: TTransaction | (TTransaction & ITransactionWithFeePayer<TFeePayerAddress>)\n): TTransaction & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | TTransaction\n | (TTransaction & ITransactionWithFeePayer<TFeePayerAddress>)\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<TFeePayerAddress> & ITransactionWithSignatures)\n) {\n if ('feePayer' in transaction && feePayer === transaction.feePayer) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n feePayer,\n };\n Object.freeze(out);\n return out;\n}\n","import { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport function appendTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [...transaction.instructions, instruction],\n };\n Object.freeze(out);\n return out;\n}\n\nexport function prependTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [instruction, ...transaction.instructions],\n };\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress, getAddressFromPublicKey } from '@solana/addresses';\nimport { Ed25519Signature, signBytes } from '@solana/keys';\n\nimport { CompiledMessage, compileMessage } from './message';\nimport { getCompiledMessageEncoder } from './serializers/message';\n\nexport interface IFullySignedTransaction extends ITransactionWithSignatures {\n readonly __brand: unique symbol;\n}\nexport interface ITransactionWithSignatures {\n readonly signatures: Readonly<Record<Base58EncodedAddress, Ed25519Signature>>;\n}\n\nasync function getCompiledMessageSignature(message: CompiledMessage, secretKey: CryptoKey) {\n const wireMessageBytes = getCompiledMessageEncoder().serialize(message);\n const signature = await signBytes(secretKey, wireMessageBytes);\n return signature;\n}\n\nexport async function signTransaction<TTransaction extends Parameters<typeof compileMessage>[0]>(\n keyPair: CryptoKeyPair,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Promise<TTransaction & ITransactionWithSignatures> {\n const compiledMessage = compileMessage(transaction);\n const [signerPublicKey, signature] = await Promise.all([\n getAddressFromPublicKey(keyPair.publicKey),\n getCompiledMessageSignature(compiledMessage, keyPair.privateKey),\n ]);\n const nextSignatures = {\n ...('signatures' in transaction ? transaction.signatures : null),\n ...({ [signerPublicKey]: signature } as ITransactionWithSignatures['signatures']),\n };\n const out = {\n ...transaction,\n signatures: nextSignatures,\n };\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress, getBase58EncodedAddressComparator } from '@solana/addresses';\nimport {\n AccountRole,\n IAccountLookupMeta,\n IAccountMeta,\n IInstruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit<WritableSignerAccount, 'address'> & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit<ReadonlyAccountLookup | WritableAccountLookup, 'address'> & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = (IAccountMeta | IAccountLookupMeta)[] & { readonly __brand: unique symbol };\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Base58EncodedAddress,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry | Record<never, never>\n ) => AddressMap[Base58EncodedAddress]\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(\n feePayer: Base58EncodedAddress,\n instructions: readonly IInstruction[]\n): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set<Base58EncodedAddress>();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and set as the fee payer. Program addresses may not pay fees.'\n );\n default:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and marked writable. Program addresses may not be writable.'\n );\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType<typeof getBase58EncodedAddressComparator>;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry as FeePayerAccountEntry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getBase58EncodedAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry as LookupTableAccountEntry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${account.address}\\`) which is both invoked and ` +\n 'marked writable. Program addresses may not be ' +\n 'writable.'\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType<typeof getBase58EncodedAddressComparator>;\n const orderedAccounts: (IAccountMeta | IAccountLookupMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getBase58EncodedAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Base58EncodedAddress<typeof address>,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Base58EncodedAddress, getBase58EncodedAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype AddressTableLookup = Readonly<{\n lookupTableAddress: Base58EncodedAddress;\n readableIndices: readonly number[];\n writableIndices: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Base58EncodedAddress,\n { readonly readableIndices: number[]; readonly writableIndices: number[] }\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readableIndices: [],\n writableIndices: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndices.push(account.addressIndex);\n } else {\n entry.readableIndices.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getBase58EncodedAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Base58EncodedAddress,\n ...index[lookupTableAddress as unknown as Base58EncodedAddress],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype MessageHeader = Readonly<{\n numReadonlyNonSignerAccounts: number;\n numReadonlySignerAccounts: number;\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport { IInstruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n accountIndices?: number[];\n data?: Uint8Array;\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record<Base58EncodedAddress, number> = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly IInstruction[],\n orderedAccounts: OrderedAccounts\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { IDurableNonceTransaction, ITransactionWithBlockhashLifetime } from './index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (ITransactionWithBlockhashLifetime | IDurableNonceTransaction)['lifetimeConstraint']\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Base58EncodedAddress[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { ITransactionWithBlockhashLifetime } from './blockhash';\nimport { getCompiledAddressTableLookups } from './compile-address-table-lookups';\nimport { getCompiledMessageHeader } from './compile-header';\nimport { getCompiledInstructions } from './compile-instructions';\nimport { getCompiledLifetimeToken } from './compile-lifetime-token';\nimport { getCompiledStaticAccounts } from './compile-static-accounts';\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithFeePayer } from './fee-payer';\nimport { BaseTransaction } from './types';\n\ntype BaseCompiledMessage = Readonly<{\n header: ReturnType<typeof getCompiledMessageHeader>;\n instructions: ReturnType<typeof getCompiledInstructions>;\n lifetimeToken: ReturnType<typeof getCompiledLifetimeToken>;\n staticAccounts: ReturnType<typeof getCompiledStaticAccounts>;\n}>;\n\ntype CompilableTransaction = BaseTransaction &\n ITransactionWithFeePayer &\n (ITransactionWithBlockhashLifetime | IDurableNonceTransaction);\n\nexport type CompiledMessage = LegacyCompiledMessage | VersionedCompiledMessage;\n\ntype LegacyCompiledMessage = BaseCompiledMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledMessage = BaseCompiledMessage &\n Readonly<{\n addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups>;\n version: number;\n }>;\n\nexport function compileMessage(\n transaction: CompilableTransaction & Readonly<{ version: 'legacy' }>\n): LegacyCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): VersionedCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): CompiledMessage {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...(transaction.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),\n lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transaction.version,\n };\n}\n","import {\n array,\n base58,\n mapSerializer,\n Serializer,\n shortU16,\n string,\n struct,\n StructToSerializerTuple,\n} from '@metaplex-foundation/umi-serializers';\nimport { getBase58EncodedAddressCodec } from '@solana/addresses';\n\nimport { CompiledMessage } from '../message';\nimport { SerializedMessageBytes } from '../types';\nimport { getAddressTableLookupCodec } from './address-table-lookup';\nimport { getMessageHeaderCodec } from './header';\nimport { getInstructionCodec } from './instruction';\nimport { getTransactionVersionCodec } from './transaction-version';\nimport { getUnimplementedDecoder, getUnimplementedEncoder } from './unimplemented';\n\nconst BASE_CONFIG = {\n description: __DEV__ ? 'The wire format of a Solana transaction message' : '',\n fixedSize: null,\n maxSize: null,\n} as const;\n\nfunction deserialize(bytes: Uint8Array, offset = 0): [CompiledMessage, number] {\n const preludeAndOffset = struct(getPreludeStructSerializerTuple()).deserialize(bytes, offset);\n const [prelude, endOfPreludeOffset] = preludeAndOffset;\n if (prelude.version === 'legacy') {\n return preludeAndOffset;\n }\n const [addressTableLookups, finalOffset] = getAddressTableLookupsSerializer().deserialize(\n bytes,\n endOfPreludeOffset\n );\n return [\n {\n ...prelude,\n ...(addressTableLookups.length ? { addressTableLookups } : null),\n },\n finalOffset,\n ];\n}\n\nfunction serialize(compiledMessage: CompiledMessage): SerializedMessageBytes {\n if (compiledMessage.version === 'legacy') {\n return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage) as SerializedMessageBytes;\n } else {\n return mapSerializer(\n struct([\n ...getPreludeStructSerializerTuple(),\n ['addressTableLookups', getAddressTableLookupsSerializer()],\n ] as StructToSerializerTuple<CompiledMessage, CompiledMessage>),\n (value: CompiledMessage) => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n } as Exclude<CompiledMessage, { readonly version: 'legacy' }>;\n }\n ).serialize(compiledMessage) as SerializedMessageBytes;\n }\n}\n\nfunction getPreludeStructSerializerTuple(): StructToSerializerTuple<CompiledMessage, CompiledMessage> {\n return [\n ['version', getTransactionVersionCodec()],\n ['header', getMessageHeaderCodec()],\n [\n 'staticAccounts',\n array(getBase58EncodedAddressCodec(), {\n description: __DEV__ ? 'A compact-array of static account addresses belonging to this transaction' : '',\n size: shortU16(),\n }),\n ],\n [\n 'lifetimeToken',\n string({\n description: __DEV__\n ? 'A 32-byte token that specifies the lifetime of this transaction (eg. a ' +\n 'recent blockhash, or a durable nonce)'\n : '',\n encoding: base58,\n size: 32,\n }),\n ],\n [\n 'instructions',\n array(getInstructionCodec(), {\n description: __DEV__ ? 'A compact-array of instructions belonging to this transaction' : '',\n size: shortU16(),\n }),\n ],\n ];\n}\n\nfunction getAddressTableLookupsSerializer() {\n return array(getAddressTableLookupCodec(), {\n ...(__DEV__ ? { description: 'A compact array of address table lookups belonging to this transaction' } : null),\n size: shortU16(),\n });\n}\n\nexport function getCompiledMessageEncoder(): Serializer<CompiledMessage> {\n return {\n ...BASE_CONFIG,\n deserialize: getUnimplementedDecoder('CompiledMessage'),\n serialize,\n };\n}\n\nexport function getCompiledMessageDecoder(): Serializer<CompiledMessage> {\n return {\n ...BASE_CONFIG,\n deserialize,\n serialize: getUnimplementedEncoder('CompiledMessage'),\n };\n}\n\nexport function getCompiledMessageCodec(): Serializer<CompiledMessage> {\n return {\n ...BASE_CONFIG,\n deserialize,\n serialize,\n };\n}\n","import { array, Serializer, shortU16, struct, StructToSerializerTuple, u8 } from '@metaplex-foundation/umi-serializers';\nimport { getBase58EncodedAddressCodec } from '@solana/addresses';\n\nimport { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\n\ntype AddressTableLookup = ReturnType<typeof getCompiledAddressTableLookups>[number];\n\nexport function getAddressTableLookupCodec(): Serializer<AddressTableLookup> {\n return struct(\n [\n [\n 'lookupTableAddress',\n getBase58EncodedAddressCodec(\n __DEV__\n ? {\n description:\n 'The address of the address lookup table account from which ' +\n 'instruction addresses should be looked up',\n }\n : undefined\n ),\n ],\n [\n 'writableIndices',\n array(u8(), {\n ...(__DEV__\n ? {\n description:\n 'The indices of the accounts in the lookup table that should ' +\n 'be loaded as writeable',\n }\n : null),\n size: shortU16(),\n }),\n ],\n [\n 'readableIndices',\n array(u8(), {\n ...(__DEV__\n ? {\n description:\n 'The indices of the accounts in the lookup table that should ' +\n 'be loaded as read-only',\n }\n : undefined),\n size: shortU16(),\n }),\n ],\n ] as StructToSerializerTuple<AddressTableLookup, AddressTableLookup>,\n __DEV__\n ? {\n description:\n 'A pointer to the address of an address lookup table, along with the ' +\n 'readonly/writeable indices of the addresses that should be loaded from it',\n }\n : undefined\n );\n}\n","import { Serializer, struct, u8 } from '@metaplex-foundation/umi-serializers';\n\nimport { getCompiledMessageHeader } from '../compile-header';\n\ntype MessageHeader = ReturnType<typeof getCompiledMessageHeader>;\n\nexport function getMessageHeaderCodec(): Serializer<MessageHeader> {\n return struct(\n [\n [\n 'numSignerAccounts',\n u8(\n __DEV__\n ? {\n description:\n 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction',\n }\n : undefined\n ),\n ],\n [\n 'numReadonlySignerAccounts',\n u8(\n __DEV__\n ? {\n description:\n 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable',\n }\n : undefined\n ),\n ],\n [\n 'numReadonlyNonSignerAccounts',\n u8(\n __DEV__\n ? {\n description:\n 'The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable',\n }\n : undefined\n ),\n ],\n ],\n __DEV__\n ? {\n description:\n 'The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses',\n }\n : undefined\n );\n}\n","import { array, bytes, mapSerializer, Serializer, shortU16, struct, u8 } from '@metaplex-foundation/umi-serializers';\n\nimport { getCompiledInstructions } from '../compile-instructions';\n\ntype Instruction = ReturnType<typeof getCompiledInstructions>[number];\n\nexport function getInstructionCodec(): Serializer<Instruction> {\n return mapSerializer<Instruction, Required<Instruction>>(\n struct([\n [\n 'programAddressIndex',\n u8(\n __DEV__\n ? {\n description:\n 'The index of the program being called, according to the ' +\n 'well-ordered accounts list for this transaction',\n }\n : undefined\n ),\n ],\n [\n 'accountIndices',\n array(\n u8({\n description: __DEV__\n ? 'The index of an account, according to the well-ordered accounts ' +\n 'list for this transaction'\n : '',\n }),\n {\n description: __DEV__\n ? 'An optional list of account indices, according to the ' +\n 'well-ordered accounts list for this transaction, in the order in ' +\n 'which the program being called expects them'\n : '',\n size: shortU16(),\n }\n ),\n ],\n [\n 'data',\n bytes({\n description: __DEV__ ? 'An optional buffer of data passed to the instruction' : '',\n size: shortU16(),\n }),\n ],\n ]),\n (value: Instruction) => {\n if (value.accountIndices !== undefined && value.data !== undefined) {\n return value as Required<Instruction>;\n }\n return {\n ...value,\n accountIndices: value.accountIndices ?? [],\n data: value.data ?? new Uint8Array(0),\n } as Required<Instruction>;\n },\n (value: Required<Instruction>) => {\n if (value.accountIndices.length && value.data.byteLength) {\n return value;\n }\n const { accountIndices, data, ...rest } = value;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n }\n );\n}\n","function getError(type: 'decoder' | 'encoder', name: string) {\n const functionSuffix = name + type[0].toUpperCase() + type.slice(1);\n return new Error(\n `No ${type} exists for ${name}. Use \\`get${functionSuffix}()\\` if you need a ${type}, and \\`get${name}Codec()\\` if you need to both encode and decode ${name}`\n );\n}\n\nexport function getUnimplementedDecoder(name: string): () => never {\n return () => {\n throw getError('decoder', name);\n };\n}\n\nexport function getUnimplementedEncoder(name: string): () => never {\n return () => {\n throw getError('encoder', name);\n };\n}\n","import { Serializer } from '@metaplex-foundation/umi-serializers';\n\nimport { TransactionVersion } from '../types';\nimport { getUnimplementedDecoder, getUnimplementedEncoder } from './unimplemented';\n\nconst VERSION_FLAG_MASK = 0x80;\n\nconst BASE_CONFIG = {\n description: __DEV__ ? 'A single byte that encodes the version of the transaction' : '',\n fixedSize: null,\n maxSize: 1,\n} as const;\n\nfunction deserialize(bytes: Uint8Array, offset = 0): [TransactionVersion, number] {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n // No version flag set; it's a legacy (unversioned) transaction.\n return ['legacy', offset];\n } else {\n const version = (firstByte ^ VERSION_FLAG_MASK) as TransactionVersion;\n return [version, offset + 1];\n }\n}\n\nfunction serialize(value: TransactionVersion): Uint8Array {\n if (value === 'legacy') {\n return new Uint8Array();\n }\n if (value < 0 || value > 127) {\n // TODO: Coded error.\n throw new Error(`Transaction version must be in the range [0, 127]. \\`${value}\\` given.`);\n }\n return new Uint8Array([value | VERSION_FLAG_MASK]);\n}\n\nexport function getTransactionVersionDecoder(): Serializer<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n deserialize,\n serialize: getUnimplementedEncoder('TransactionVersion'),\n };\n}\n\nexport function getTransactionVersionEncoder(): Serializer<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n deserialize: getUnimplementedDecoder('TransactionVersion'),\n serialize,\n };\n}\n\nexport function getTransactionVersionCodec(): Serializer<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n deserialize,\n serialize,\n };\n}\n","import { array, bytes, Serializer, shortU16, struct } from '@metaplex-foundation/umi-serializers';\n\nimport { getCompiledTransaction } from '../compile-transaction';\nimport { getCompiledMessageEncoder } from './message';\nimport { getUnimplementedDecoder } from './unimplemented';\n\nconst BASE_CONFIG = {\n description: __DEV__ ? 'The wire format of a Solana transaction' : '',\n fixedSize: null,\n maxSize: null,\n} as const;\n\ntype SerializableTransaction = Parameters<typeof getCompiledTransaction>[0];\n\nfunction serialize(transaction: SerializableTransaction) {\n const compiledTransaction = getCompiledTransaction(transaction);\n return struct([\n [\n 'signatures',\n array(bytes({ size: 64 }), {\n ...(__DEV__ ? { description: 'A compact array of 64-byte, base-64 encoded Ed25519 signatures' } : null),\n size: shortU16(),\n }),\n ],\n ['compiledMessage', getCompiledMessageEncoder()],\n ]).serialize(compiledTransaction);\n}\n\nexport function getTransactionEncoder(): Serializer<SerializableTransaction> {\n return {\n ...BASE_CONFIG,\n deserialize: getUnimplementedDecoder('CompiledMessage'),\n serialize,\n };\n}\n","import { Ed25519Signature } from '@solana/keys';\n\nimport { CompiledMessage, compileMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\n\ntype CompiledTransaction = Readonly<{\n compiledMessage: CompiledMessage;\n signatures: Ed25519Signature[];\n}>;\n\ntype CompilableTransaction = Parameters<typeof compileMessage>[0];\n\nexport function getCompiledTransaction(\n transaction: CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n): CompiledTransaction {\n const compiledMessage = compileMessage(transaction);\n let signatures;\n if ('signatures' in transaction) {\n signatures = [];\n for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {\n signatures[ii] =\n transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));\n }\n } else {\n signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));\n }\n return {\n compiledMessage,\n signatures,\n };\n}\n","import {\n createSolanaRpcApi,\n createSolanaRpcSubscriptionsApi,\n SolanaRpcMethods,\n SolanaRpcSubscriptions,\n} from '@solana/rpc-core';\nimport { createJsonRpc, createJsonSubscriptionRpc } from '@solana/rpc-transport';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\n\nexport function createSolanaRpc(config: Omit<Parameters<typeof createJsonRpc>[0], 'api'>): Rpc<SolanaRpcMethods> {\n return createJsonRpc({\n ...config,\n api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n });\n}\n\nexport function createSolanaRpcSubscriptions(\n config: Omit<Parameters<typeof createJsonSubscriptionRpc>[0], 'api'>\n): RpcSubscriptions<SolanaRpcSubscriptions> {\n return createJsonSubscriptionRpc({\n ...config,\n api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG),\n });\n}\n","type IntegerOverflowHandler = (keyPath: (number | string)[], value: bigint) => void;\ntype Patched<T> = T extends object ? { [Property in keyof T]: Patched<T[Property]> } : T extends bigint ? number : T;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction visitNode<T>(value: T, keyPath: (number | string)[], onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n if (Array.isArray(value)) {\n return value.map((element, ii) =>\n visitNode(element, [...keyPath, ii], onIntegerOverflow)\n ) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const propName in value) {\n if (Object.prototype.hasOwnProperty.call(value, propName)) {\n out[propName] = visitNode(value[propName], [...keyPath, propName], onIntegerOverflow);\n }\n }\n return out as TypescriptBug33014;\n } else if (typeof value === 'bigint') {\n // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // downcasting `bigints` to `numbers`.\n if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {\n onIntegerOverflow(keyPath, value);\n }\n return Number(value) as TypescriptBug33014;\n } else {\n return value as TypescriptBug33014;\n }\n}\n\nexport function patchParamsForSolanaLabsRpc<T>(params: T, onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n return visitNode(params, [], onIntegerOverflow);\n}\n","import { KeyPath } from './response-patcher';\nimport { KEYPATH_WILDCARD } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\nimport { createSolanaRpcSubscriptionsApi } from './rpc-subscriptions';\n\ntype AllowedNumericKeypaths<TApi> = Partial<Record<keyof TApi, readonly KeyPath[]>>;\n\nlet memoizedNotificationKeypaths: AllowedNumericKeypaths<ReturnType<typeof createSolanaRpcSubscriptionsApi>>;\nlet memoizedResponseKeypaths: AllowedNumericKeypaths<ReturnType<typeof createSolanaRpcApi>>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nexport function getAllowedNumericKeypathsForNotification(): AllowedNumericKeypaths<\n ReturnType<typeof createSolanaRpcSubscriptionsApi>\n> {\n if (!memoizedNotificationKeypaths) {\n memoizedNotificationKeypaths = {};\n }\n return memoizedNotificationKeypaths;\n}\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nexport function getAllowedNumericKeypathsForResponse(): AllowedNumericKeypaths<ReturnType<typeof createSolanaRpcApi>> {\n if (!memoizedResponseKeypaths) {\n // Numeric values nested in `jsonParsed` accounts\n const jsonParsedTokenAccountsConfigs = [\n // parsed Token/Token22 token account\n ['data', 'parsed', 'info', 'tokenAmount', 'decimals'],\n ['data', 'parsed', 'info', 'tokenAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'decimals'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'uiAmount'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'decimals'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'uiAmount'],\n [\n 'data',\n 'parsed',\n 'info',\n 'extensions',\n KEYPATH_WILDCARD,\n 'state',\n 'olderTransferFee',\n 'transferFeeBasisPoints',\n ],\n [\n 'data',\n 'parsed',\n 'info',\n 'extensions',\n KEYPATH_WILDCARD,\n 'state',\n 'newerTransferFee',\n 'transferFeeBasisPoints',\n ],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n ];\n const jsonParsedAccountsConfigs = [\n ...jsonParsedTokenAccountsConfigs,\n // parsed AddressTableLookup account\n ['data', 'parsed', 'info', 'lastExtendedSlotStartIndex'],\n // parsed Config account\n ['data', 'parsed', 'info', 'slashPenalty'],\n ['data', 'parsed', 'info', 'warmupCooldownRate'],\n // parsed Token/Token22 mint account\n ['data', 'parsed', 'info', 'decimals'],\n // parsed Token/Token22 multisig account\n ['data', 'parsed', 'info', 'numRequiredSigners'],\n ['data', 'parsed', 'info', 'numValidSigners'],\n // parsed Stake account\n ['data', 'parsed', 'info', 'stake', 'delegation', 'warmupCooldownRate'],\n // parsed Sysvar rent account\n ['data', 'parsed', 'info', 'exemptionThreshold'],\n ['data', 'parsed', 'info', 'burnPercent'],\n // parsed Vote account\n ['data', 'parsed', 'info', 'commission'],\n ['data', 'parsed', 'info', 'votes', KEYPATH_WILDCARD, 'confirmationCount'],\n ];\n memoizedResponseKeypaths = {\n getAccountInfo: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n getBlock: [\n ['blockTime'],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'innerInstructions', KEYPATH_WILDCARD, 'index'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', 'header', 'numReadonlySignedAccounts'],\n ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', 'header', 'numReadonlyUnsignedAccounts'],\n ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', 'header', 'numRequiredSignatures'],\n ['rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n getBlockTime: [[]],\n getClusterNodes: [\n [KEYPATH_WILDCARD, 'featureSet'],\n [KEYPATH_WILDCARD, 'shredVersion'],\n ],\n getInflationGovernor: [['initial'], ['foundation'], ['foundationTerm'], ['taper'], ['terminal']],\n getInflationRate: [['foundation'], ['total'], ['validator']],\n getInflationReward: [[KEYPATH_WILDCARD, 'commission']],\n getMultipleAccounts: jsonParsedAccountsConfigs.map(c => ['value', KEYPATH_WILDCARD, ...c]),\n getProgramAccounts: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n getRecentPerformanceSamples: [[KEYPATH_WILDCARD, 'samplePeriodSecs']],\n getTokenAccountBalance: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenLargestAccounts: [\n ['value', KEYPATH_WILDCARD, 'decimals'],\n ['value', KEYPATH_WILDCARD, 'uiAmount'],\n ],\n getTokenSupply: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTransaction: [\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ['meta', 'innerInstructions', KEYPATH_WILDCARD, 'index'],\n ['meta', 'innerInstructions', KEYPATH_WILDCARD, 'instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n [\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n ['transaction', 'message', 'instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['transaction', 'message', 'instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['transaction', 'message', 'header', 'numReadonlySignedAccounts'],\n ['transaction', 'message', 'header', 'numReadonlyUnsignedAccounts'],\n ['transaction', 'message', 'header', 'numRequiredSignatures'],\n ],\n getVersion: [['feature-set']],\n getVoteAccounts: [\n ['current', KEYPATH_WILDCARD, 'commission'],\n ['delinquent', KEYPATH_WILDCARD, 'commission'],\n ],\n simulateTransaction: jsonParsedAccountsConfigs.map(c => ['value', 'accounts', KEYPATH_WILDCARD, ...c]),\n };\n }\n return memoizedResponseKeypaths;\n}\n","import {\n getAllowedNumericKeypathsForNotification,\n getAllowedNumericKeypathsForResponse,\n} from './response-patcher-allowed-numeric-values';\nimport { KEYPATH_WILDCARD, KeyPathWildcard } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\nimport { createSolanaRpcSubscriptionsApi } from './rpc-subscriptions';\n\nexport type KeyPath = ReadonlyArray<KeyPathWildcard | number | string | KeyPath>;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction getNextAllowedKeypaths(keyPaths: readonly KeyPath[], property: number | string) {\n return keyPaths\n .filter(keyPath => (keyPath[0] === KEYPATH_WILDCARD && typeof property === 'number') || keyPath[0] === property)\n .map(keyPath => keyPath.slice(1));\n}\n\nfunction visitNode<T>(value: unknown, allowedKeypaths: readonly KeyPath[]): T {\n if (Array.isArray(value)) {\n return value.map((element, ii) => {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, ii);\n return visitNode(element, nextAllowedKeypaths);\n }) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const [propName, innerValue] of Object.entries(value)) {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, propName);\n out[propName] = visitNode(innerValue, nextAllowedKeypaths);\n }\n return out as TypescriptBug33014;\n } else if (\n typeof value === 'number' &&\n // The presence of an allowed keypath on the route to this value implies it's allowlisted;\n // Upcast the value to `bigint` unless an allowed keypath is present.\n allowedKeypaths.length === 0 &&\n // Only try to upcast an Integer to `bigint`\n Number.isInteger(value)\n ) {\n // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // upcasting `numbers` to `bigints`.\n return BigInt(value) as TypescriptBug33014;\n } else {\n return value as TypescriptBug33014;\n }\n}\n\nexport function patchResponseForSolanaLabsRpc<T>(\n rawResponse: unknown,\n methodName?: keyof ReturnType<typeof createSolanaRpcApi>\n): T {\n const allowedKeypaths = methodName ? getAllowedNumericKeypathsForResponse()[methodName] : undefined;\n return visitNode(rawResponse, allowedKeypaths ?? []);\n}\n\nexport function patchResponseForSolanaLabsRpcSubscriptions<T>(\n rawResponse: unknown,\n methodName?: keyof ReturnType<typeof createSolanaRpcSubscriptionsApi>\n): T {\n const allowedKeypaths = methodName ? getAllowedNumericKeypathsForNotification()[methodName] : undefined;\n return visitNode(rawResponse, allowedKeypaths ?? []);\n}\n","import { IRpcApi, RpcRequest } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { patchParamsForSolanaLabsRpc } from '../params-patcher';\nimport { patchResponseForSolanaLabsRpc } from '../response-patcher';\nimport { GetAccountInfoApi } from './getAccountInfo';\nimport { GetBalanceApi } from './getBalance';\nimport { GetBlockApi } from './getBlock';\nimport { GetBlockCommitmentApi } from './getBlockCommitment';\nimport { GetBlockHeightApi } from './getBlockHeight';\nimport { GetBlockProductionApi } from './getBlockProduction';\nimport { GetBlocksApi } from './getBlocks';\nimport { GetBlocksWithLimitApi } from './getBlocksWithLimit';\nimport { GetBlockTimeApi } from './getBlockTime';\nimport { GetClusterNodesApi } from './getClusterNodes';\nimport { GetEpochInfoApi } from './getEpochInfo';\nimport { GetEpochScheduleApi } from './getEpochSchedule';\nimport { GetFeeForMessageApi } from './getFeeForMessage';\nimport { GetFirstAvailableBlockApi } from './getFirstAvailableBlock';\nimport { GetGenesisHashApi } from './getGenesisHash';\nimport { GetHealthApi } from './getHealth';\nimport { GetHighestSnapshotSlotApi } from './getHighestSnapshotSlot';\nimport { GetIdentityApi } from './getIdentity';\nimport { GetInflationGovernorApi } from './getInflationGovernor';\nimport { GetInflationRateApi } from './getInflationRate';\nimport { GetInflationRewardApi } from './getInflationReward';\nimport { GetLargestAccountsApi } from './getLargestAccounts';\nimport { GetLatestBlockhashApi } from './getLatestBlockhash';\nimport { GetLeaderScheduleApi } from './getLeaderSchedule';\nimport { GetMaxRetransmitSlotApi } from './getMaxRetransmitSlot';\nimport { GetMaxShredInsertSlotApi } from './getMaxShredInsertSlot';\nimport { GetMinimumBalanceForRentExemptionApi } from './getMinimumBalanceForRentExemption';\nimport { GetMultipleAccountsApi } from './getMultipleAccounts';\nimport { GetProgramAccountsApi } from './getProgramAccounts';\nimport { GetRecentPerformanceSamplesApi } from './getRecentPerformanceSamples';\nimport { GetRecentPrioritizationFeesApi } from './getRecentPrioritizationFees';\nimport { GetSignaturesForAddressApi } from './getSignaturesForAddress';\nimport { GetSignatureStatusesApi } from './getSignatureStatuses';\nimport { GetSlotApi } from './getSlot';\nimport { GetSlotLeaderApi } from './getSlotLeader';\nimport { GetSlotLeadersApi } from './getSlotLeaders';\nimport { GetStakeActivationApi } from './getStakeActivation';\nimport { GetStakeMinimumDelegationApi } from './getStakeMinimumDelegation';\nimport { GetSupplyApi } from './getSupply';\nimport { GetTokenAccountBalanceApi } from './getTokenAccountBalance';\nimport { GetTokenAccountsByDelegateApi } from './getTokenAccountsByDelegate';\nimport { GetTokenAccountsByOwnerApi } from './getTokenAccountsByOwner';\nimport { GetTokenLargestAccountsApi } from './getTokenLargestAccounts';\nimport { GetTokenSupplyApi } from './getTokenSupply';\nimport { GetTransactionApi } from './getTransaction';\nimport { GetTransactionCountApi } from './getTransactionCount';\nimport { GetVersionApi } from './getVersion';\nimport { GetVoteAccountsApi } from './getVoteAccounts';\nimport { IsBlockhashValidApi } from './isBlockhashValid';\nimport { MinimumLedgerSlotApi } from './minimumLedgerSlot';\nimport { RequestAirdropApi } from './requestAirdrop';\nimport { SendTransactionApi } from './sendTransaction';\nimport { SimulateTransactionApi } from './simulateTransaction';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcMethods = GetAccountInfoApi &\n GetBalanceApi &\n GetBlockApi &\n GetBlockCommitmentApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlocksWithLimitApi &\n GetBlockTimeApi &\n GetClusterNodesApi &\n GetEpochInfoApi &\n GetEpochScheduleApi &\n GetFeeForMessageApi &\n GetFirstAvailableBlockApi &\n GetGenesisHashApi &\n GetHealthApi &\n GetHighestSnapshotSlotApi &\n GetIdentityApi &\n GetInflationGovernorApi &\n GetInflationRateApi &\n GetInflationRewardApi &\n GetLargestAccountsApi &\n GetLatestBlockhashApi &\n GetLeaderScheduleApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetMinimumBalanceForRentExemptionApi &\n GetMultipleAccountsApi &\n GetProgramAccountsApi &\n GetRecentPerformanceSamplesApi &\n GetRecentPrioritizationFeesApi &\n GetSignaturesForAddressApi &\n GetSignatureStatusesApi &\n GetSlotApi &\n GetSlotLeaderApi &\n GetSlotLeadersApi &\n GetStakeActivationApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTokenAccountBalanceApi &\n GetTokenAccountsByDelegateApi &\n GetTokenAccountsByOwnerApi &\n GetTokenLargestAccountsApi &\n GetTokenSupplyApi &\n GetTransactionApi &\n GetTransactionCountApi &\n GetVersionApi &\n GetVoteAccountsApi &\n IsBlockhashValidApi &\n MinimumLedgerSlotApi &\n RequestAirdropApi &\n SendTransactionApi &\n SimulateTransactionApi;\n\nexport type { Commitment } from './common';\n\nexport function createSolanaRpcApi(config?: Config): IRpcApi<SolanaRpcMethods> {\n return new Proxy({} as IRpcApi<SolanaRpcMethods>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<TMethodName extends keyof IRpcApi<SolanaRpcMethods>>(\n ...args: Parameters<NonNullable<ProxyHandler<IRpcApi<SolanaRpcMethods>>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof SolanaRpcMethods;\n return function (\n ...rawParams: Parameters<\n SolanaRpcMethods[TMethodName] extends CallableFunction ? SolanaRpcMethods[TMethodName] : never\n >\n ): RpcRequest<ReturnType<SolanaRpcMethods[TMethodName]>> {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n const params = patchParamsForSolanaLabsRpc(\n rawParams,\n handleIntegerOverflow\n ? (keyPath, value) => handleIntegerOverflow(methodName, keyPath, value)\n : undefined\n );\n return {\n methodName,\n params,\n responseProcessor: rawResponse => patchResponseForSolanaLabsRpc(rawResponse, methodName),\n };\n };\n },\n });\n}\n","import { IRpcSubscriptionsApi, RpcSubscription } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { patchParamsForSolanaLabsRpc } from '../params-patcher';\nimport { patchResponseForSolanaLabsRpcSubscriptions } from '../response-patcher';\nimport { SlotNotificationsApi } from './slot-notifications';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcSubscriptions = SlotNotificationsApi;\n\nexport function createSolanaRpcSubscriptionsApi(config?: Config): IRpcSubscriptionsApi<SolanaRpcSubscriptions> {\n return new Proxy({} as IRpcSubscriptionsApi<SolanaRpcSubscriptions>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<TNotificationName extends keyof IRpcSubscriptionsApi<SolanaRpcSubscriptions>>(\n ...args: Parameters<NonNullable<ProxyHandler<IRpcSubscriptionsApi<SolanaRpcSubscriptions>>['get']>>\n ) {\n const [_, p] = args;\n const notificationName = p.toString() as keyof SolanaRpcSubscriptions;\n return function (\n ...rawParams: Parameters<\n SolanaRpcSubscriptions[TNotificationName] extends CallableFunction\n ? SolanaRpcSubscriptions[TNotificationName]\n : never\n >\n ): RpcSubscription<ReturnType<SolanaRpcSubscriptions[TNotificationName]>> {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n const params = patchParamsForSolanaLabsRpc(\n rawParams,\n handleIntegerOverflow\n ? (keyPath, value) => handleIntegerOverflow(notificationName, keyPath, value)\n : undefined\n );\n return {\n params,\n responseProcessor: rawResponse =>\n patchResponseForSolanaLabsRpcSubscriptions(rawResponse, notificationName),\n subscribeMethodName: notificationName.replace(/Notifications$/, 'Subscribe'),\n unsubscribeMethodName: notificationName.replace(/Notifications$/, 'Unsubscribe'),\n };\n };\n },\n });\n}\n","// Keep in sync with https://github.com/solana-labs/solana/blob/master/rpc-client-api/src/custom_error.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nexport const SolanaJsonRpcErrorCode = {\n JSON_RPC_INVALID_PARAMS: -32602,\n JSON_RPC_SCAN_ERROR: -32012,\n JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016,\n JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n} as const;\ntype SolanaJsonRpcErrorCodeEnum = (typeof SolanaJsonRpcErrorCode)[keyof typeof SolanaJsonRpcErrorCode];\n\ntype SolanaJsonRpcErrorDetails = Readonly<{\n code: number;\n data?: unknown;\n message: string;\n}>;\n\nexport class SolanaJsonRpcError extends Error {\n readonly code: SolanaJsonRpcErrorCodeEnum;\n readonly data: unknown;\n constructor(details: SolanaJsonRpcErrorDetails) {\n super(`JSON-RPC 2.0 error (${details.code}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.code = details.code as SolanaJsonRpcErrorCodeEnum;\n this.data = details.data;\n }\n get name() {\n return 'SolanaJsonRpcError';\n }\n}\n","let _nextMessageId = 0;\nexport function getNextMessageId() {\n const id = _nextMessageId;\n _nextMessageId = (_nextMessageId + 1) % Number.MAX_SAFE_INTEGER;\n return id;\n}\n","import { getNextMessageId } from './json-rpc-message-id';\n\nexport function createJsonRpcMessage<TParams>(method: string, params: TParams) {\n return {\n id: getNextMessageId(),\n jsonrpc: '2.0',\n method,\n params,\n };\n}\n","import { SolanaJsonRpcError } from './json-rpc-errors';\nimport { createJsonRpcMessage } from './json-rpc-message';\nimport { PendingRpcRequest, Rpc, RpcConfig, RpcRequest, SendOptions } from './json-rpc-types';\n\ninterface IHasIdentifier {\n readonly id: number;\n}\nexport type JsonRpcResponse<TResponse> = IHasIdentifier &\n Readonly<{ result: TResponse } | { error: { code: number; message: string; data?: unknown } }>;\n\nfunction createPendingRpcRequest<TRpcMethods, TResponse>(\n rpcConfig: RpcConfig<TRpcMethods>,\n pendingRequest: RpcRequest<TResponse>\n): PendingRpcRequest<TResponse> {\n return {\n async send(options?: SendOptions): Promise<TResponse> {\n const { methodName, params, responseProcessor } = pendingRequest;\n const payload = createJsonRpcMessage(methodName, params);\n const response = await rpcConfig.transport<JsonRpcResponse<unknown>>({\n payload,\n signal: options?.abortSignal,\n });\n if ('error' in response) {\n throw new SolanaJsonRpcError(response.error);\n } else {\n return (responseProcessor ? responseProcessor(response.result) : response.result) as TResponse;\n }\n },\n };\n}\n\nfunction makeProxy<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const createRpcRequest = Reflect.get(target, methodName, receiver);\n const newRequest = createRpcRequest\n ? createRpcRequest(...rawParams)\n : { methodName, params: rawParams };\n return createPendingRpcRequest(rpcConfig, newRequest);\n };\n },\n }) as Rpc<TRpcMethods>;\n}\n\nexport function createJsonRpc<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return makeProxy(rpcConfig);\n}\n","import { JsonRpcResponse } from './json-rpc';\nimport { SolanaJsonRpcError } from './json-rpc-errors';\nimport { createJsonRpcMessage } from './json-rpc-message';\nimport {\n PendingRpcSubscription,\n RpcSubscription,\n RpcSubscriptionConfig,\n RpcSubscriptions,\n SubscribeOptions,\n} from './json-rpc-types';\n\ntype JsonRpcNotification<TNotification> = Readonly<{\n params: Readonly<{\n result: TNotification;\n subscription: number;\n }>;\n}>;\ntype SubscriptionId = number;\n\nfunction registerIterableFatal(iterable: AsyncIterable<unknown>, catchFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch (e) {\n // Run the catch function if the iterator throws.\n catchFn(e);\n }\n })();\n}\n\nfunction createPendingRpcSubscription<TRpcSubscriptionMethods, TNotification>(\n rpcConfig: RpcSubscriptionConfig<TRpcSubscriptionMethods>,\n { params, subscribeMethodName, unsubscribeMethodName, responseProcessor }: RpcSubscription<TNotification>\n): PendingRpcSubscription<TNotification> {\n return {\n async subscribe(options?: SubscribeOptions): Promise<AsyncIterable<TNotification>> {\n options?.abortSignal?.throwIfAborted();\n let subscriptionId: number | undefined;\n function handleCleanup() {\n if (subscriptionId !== undefined) {\n const payload = createJsonRpcMessage(unsubscribeMethodName, [subscriptionId]);\n connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload).finally(() => {\n connectionAbortController.abort();\n });\n } else {\n connectionAbortController.abort();\n }\n }\n options?.abortSignal?.addEventListener('abort', handleCleanup);\n /**\n * STEP 1: Send the subscribe message.\n */\n const connectionAbortController = new AbortController();\n const subscribeMessage = createJsonRpcMessage(subscribeMethodName, params);\n const connection = await rpcConfig.transport({\n payload: subscribeMessage,\n signal: connectionAbortController.signal,\n });\n function handleConnectionFatal() {\n options?.abortSignal?.removeEventListener('abort', handleCleanup);\n }\n registerIterableFatal(connection, handleConnectionFatal);\n /**\n * STEP 2: Wait for the acknowledgement from the server with the subscription id.\n */\n for await (const message of connection as AsyncIterable<\n JsonRpcNotification<unknown> | JsonRpcResponse<SubscriptionId>\n >) {\n if ('id' in message && message.id === subscribeMessage.id) {\n if ('error' in message) {\n throw new SolanaJsonRpcError(message.error);\n } else {\n subscriptionId = message.result as SubscriptionId;\n break;\n }\n }\n }\n if (subscriptionId == null) {\n // TODO: Coded error.\n throw new Error('Failed to obtain a subscription id from the server');\n }\n /**\n * STEP 3: Return an iterable that yields notifications for this subscription id.\n */\n return {\n async *[Symbol.asyncIterator]() {\n for await (const message of connection as AsyncIterable<\n JsonRpcNotification<unknown> | JsonRpcResponse<SubscriptionId>\n >) {\n if (!('params' in message) || message.params.subscription !== subscriptionId) {\n continue;\n }\n const notification = message.params.result as TNotification;\n yield responseProcessor ? responseProcessor(notification) : notification;\n }\n },\n };\n },\n };\n}\n\nfunction makeProxy<TRpcSubscriptionMethods>(\n rpcConfig: RpcSubscriptionConfig<TRpcSubscriptionMethods>\n): RpcSubscriptions<TRpcSubscriptionMethods> {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const createRpcSubscription = Reflect.get(target, methodName, receiver);\n if (p.toString().endsWith('Notifications') === false && !createRpcSubscription) {\n // TODO: Coded error.\n throw new Error(\n \"Either the notification name must end in 'Notifications' or the API \" +\n 'must supply a subscription creator function to map between the ' +\n 'notification name and the subscribe/unsubscribe method names.'\n );\n }\n const newRequest = createRpcSubscription\n ? createRpcSubscription(...rawParams)\n : {\n params: rawParams,\n subscribeMethodName: methodName.replace(/Notifications$/, 'Subscribe'),\n unsubscribeMethodName: methodName.replace(/Notifications$/, 'Unsubscribe'),\n };\n return createPendingRpcSubscription(rpcConfig, newRequest);\n };\n },\n }) as RpcSubscriptions<TRpcSubscriptionMethods>;\n}\n\nexport function createJsonSubscriptionRpc<TRpcSubscriptionMethods>(\n rpcConfig: RpcSubscriptionConfig<TRpcSubscriptionMethods>\n): RpcSubscriptions<TRpcSubscriptionMethods> {\n return makeProxy(rpcConfig);\n}\n","export default globalThis.fetch;\n","type SolanaHttpErrorDetails = Readonly<{\n statusCode: number;\n message: string;\n}>;\n\nexport class SolanaHttpError extends Error {\n readonly statusCode: number;\n constructor(details: SolanaHttpErrorDetails) {\n super(`HTTP error (${details.statusCode}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.statusCode = details.statusCode;\n }\n get name() {\n return 'SolanaHttpError';\n }\n}\n","export type AllowedHttpRequestHeaders = Readonly<\n { [headerName: string]: string } & {\n // Someone can still sneak a forbidden header past Typescript if they do something like\n // fOo-BaR, but at that point they deserve the runtime failure.\n [K in DisallowedHeaders | ForbiddenHeaders as\n | K // `Foo-Bar`\n | Capitalize<Lowercase<K>> // `Foo-bar`\n | Lowercase<K> // `foo-bar`\n | Uncapitalize<K> // `foo-Bar`\n // `FOO-BAR`\n | Uppercase<K>]?: never;\n }\n>;\n// These are headers that we simply don't allow the developer to override because they're\n// fundamental to the operation of the JSON-RPC transport.\ntype DisallowedHeaders = 'Accept' | 'Content-Length' | 'Content-Type' | 'Solana-Client';\ntype ForbiddenHeaders =\n | 'Accept-Charset'\n | 'Accept-Encoding'\n | 'Access-Control-Request-Headers'\n | 'Access-Control-Request-Method'\n | 'Connection'\n | 'Content-Length'\n | 'Cookie'\n | 'Date'\n | 'DNT'\n | 'Expect'\n | 'Host'\n | 'Keep-Alive'\n | 'Origin'\n | 'Permissions-Policy'\n // No currently available Typescript technique allows you to match on a prefix.\n // | 'Proxy-'\n // | 'Sec-'\n | 'Referer'\n | 'TE'\n | 'Trailer'\n | 'Transfer-Encoding'\n | 'Upgrade'\n | 'Via';\n\n// These are headers which are fundamental to the JSON-RPC transport, and must not be modified.\nconst DISALLOWED_HEADERS: Record<string, boolean> = {\n accept: true,\n 'content-length': true,\n 'content-type': true,\n};\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS: Record<string, boolean> = {\n 'accept-charset': true,\n 'accept-encoding': true,\n 'access-control-request-headers': true,\n 'access-control-request-method': true,\n connection: true,\n 'content-length': true,\n cookie: true,\n date: true,\n dnt: true,\n expect: true,\n host: true,\n 'keep-alive': true,\n origin: true,\n 'permissions-policy': true,\n // No currently available Typescript technique allows you to match on a prefix.\n // 'proxy-':true,\n // 'sec-':true,\n referer: true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n via: true,\n};\n\nexport function assertIsAllowedHttpRequestHeaders(\n headers: Record<string, string>\n): asserts headers is AllowedHttpRequestHeaders {\n const badHeaders = Object.keys(headers).filter(headerName => {\n const lowercaseHeaderName = headerName.toLowerCase();\n return (\n DISALLOWED_HEADERS[headerName.toLowerCase()] === true ||\n FORBIDDEN_HEADERS[headerName.toLowerCase()] === true ||\n lowercaseHeaderName.startsWith('proxy-') ||\n lowercaseHeaderName.startsWith('sec-')\n );\n });\n if (badHeaders.length > 0) {\n throw new Error(\n `${badHeaders.length > 1 ? 'These headers are' : 'This header is'} forbidden: ` +\n `\\`${badHeaders.join('`, `')}\\`. Learn more at ` +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.'\n );\n }\n}\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers, such as those defined\n * in the `DisallowedHeaders` type.\n */\nexport function normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n","import type { Agent as NodeHttpAgent } from 'node:http';\nimport type { Agent as NodeHttpsAgent } from 'node:https';\n\nimport fetchImpl from 'fetch-impl';\n\nimport { IRpcTransport } from '../transport-types';\nimport { SolanaHttpError } from './http-transport-errors';\nimport {\n AllowedHttpRequestHeaders,\n assertIsAllowedHttpRequestHeaders,\n normalizeHeaders,\n} from './http-transport-headers';\n\ntype Config = Readonly<{\n headers?: AllowedHttpRequestHeaders;\n httpAgentNodeOnly?: NodeHttpAgent | NodeHttpsAgent | ((parsedUrl: URL) => NodeHttpAgent | NodeHttpsAgent);\n url: string;\n}>;\n\nexport function createHttpTransport({ httpAgentNodeOnly, headers, url }: Config): IRpcTransport {\n if (__DEV__ && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\n }\n const agent = __NODEJS__ ? httpAgentNodeOnly : undefined;\n if (__DEV__ && httpAgentNodeOnly != null) {\n console.warn(\n 'createHttpTransport(): The `httpAgentNodeOnly` config you supplied has been ' +\n 'ignored; HTTP agents are only usable in Node environments.'\n );\n }\n const customHeaders = headers && normalizeHeaders(headers);\n return async function makeHttpRequest<TResponse>({\n payload,\n signal,\n }: Parameters<IRpcTransport>[0]): Promise<TResponse> {\n const body = JSON.stringify(payload);\n const requestInfo = {\n agent,\n body,\n headers: {\n ...customHeaders,\n // Keep these headers lowercase so they will override any user-supplied headers above.\n accept: 'application/json',\n 'content-length': body.length.toString(),\n 'content-type': 'application/json; charset=utf-8',\n },\n method: 'POST',\n signal,\n };\n const response = await fetchImpl(url, requestInfo);\n if (!response.ok) {\n throw new SolanaHttpError({\n message: response.statusText,\n statusCode: response.status,\n });\n }\n return (await response.json()) as TResponse;\n };\n}\n","export default globalThis.WebSocket;\n","import WebSocket from 'ws-impl';\n\ntype Config = Readonly<{\n sendBufferHighWatermark: number;\n signal: AbortSignal;\n url: string;\n}>;\ntype IteratorKey = symbol;\ntype IteratorState =\n | {\n __hasPolled: true;\n onMessage: Parameters<ConstructorParameters<typeof Promise>[0]>[0];\n onError: Parameters<ConstructorParameters<typeof Promise>[0]>[1];\n }\n | {\n __hasPolled: false;\n queuedMessages: unknown[];\n };\nexport type RpcWebSocketConnection = Readonly<{\n send(payload: unknown): Promise<void>;\n [Symbol.asyncIterator](): AsyncGenerator<unknown>;\n}>;\n\nexport async function createWebSocketConnection({\n sendBufferHighWatermark,\n signal,\n url,\n}: Config): Promise<RpcWebSocketConnection> {\n return new Promise((resolve, reject) => {\n signal.addEventListener('abort', handleAbort, { once: true });\n const iteratorState: Map<IteratorKey, IteratorState> = new Map();\n function handleAbort() {\n if (webSocket.readyState !== WebSocket.CLOSED && webSocket.readyState !== WebSocket.CLOSING) {\n webSocket.close(1000);\n }\n }\n function handleClose(ev: CloseEvent) {\n bufferDrainWatcher?.onCancel();\n signal.removeEventListener('abort', handleAbort);\n webSocket.removeEventListener('close', handleClose);\n webSocket.removeEventListener('error', handleError);\n webSocket.removeEventListener('open', handleOpen);\n webSocket.removeEventListener('message', handleMessage);\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onError } = state;\n iteratorState.delete(iteratorKey);\n onError(ev);\n } else {\n iteratorState.delete(iteratorKey);\n }\n });\n }\n function handleError(ev: Event) {\n if (!hasConnected) {\n reject(\n // TODO: Coded error\n new Error('WebSocket failed to connect', { cause: ev })\n );\n }\n }\n let hasConnected = false;\n let bufferDrainWatcher: Readonly<{ onCancel(): void; promise: Promise<void> }> | undefined;\n function handleOpen() {\n hasConnected = true;\n resolve({\n async send(payload: unknown) {\n const message = JSON.stringify(payload);\n if (\n !bufferDrainWatcher &&\n webSocket.readyState === WebSocket.OPEN &&\n webSocket.bufferedAmount > sendBufferHighWatermark\n ) {\n let onCancel: () => void;\n const promise = new Promise<void>((resolve, reject) => {\n const intervalId = setInterval(() => {\n if (\n webSocket.readyState !== WebSocket.OPEN ||\n !(webSocket.bufferedAmount > sendBufferHighWatermark)\n ) {\n clearInterval(intervalId);\n bufferDrainWatcher = undefined;\n resolve();\n }\n }, 16);\n onCancel = () => {\n bufferDrainWatcher = undefined;\n clearInterval(intervalId);\n reject(\n // TODO: Coded error\n new Error('WebSocket was closed before payload could be sent')\n );\n };\n });\n bufferDrainWatcher = {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n onCancel,\n promise,\n };\n }\n if (bufferDrainWatcher) {\n await bufferDrainWatcher.promise;\n }\n webSocket.send(message);\n },\n async *[Symbol.asyncIterator]() {\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new Error('Invariant: WebSocket message iterator is missing state storage');\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new Error(\n 'Invariant: WebSocket message iterator state is corrupt; ' +\n 'iterated without first resolving existing message promise'\n );\n }\n const queuedMessages = state.queuedMessages;\n if (queuedMessages.length) {\n state.queuedMessages = [];\n yield* queuedMessages;\n } else {\n try {\n yield await new Promise((onMessage, onError) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onError,\n onMessage,\n });\n });\n } catch (e) {\n if (\n e !== null &&\n typeof e === 'object' &&\n 'type' in e &&\n e.type === 'close' &&\n 'wasClean' in e &&\n e.wasClean\n ) {\n return;\n } else {\n // TODO: Coded error.\n throw new Error('WebSocket connection closed', { cause: e });\n }\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n });\n }\n function handleMessage({ data }: MessageEvent) {\n const message = JSON.parse(data);\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onMessage } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });\n onMessage(message);\n } else {\n state.queuedMessages.push(message);\n }\n });\n }\n const webSocket = new WebSocket(url);\n webSocket.addEventListener('close', handleClose);\n webSocket.addEventListener('error', handleError);\n webSocket.addEventListener('open', handleOpen);\n webSocket.addEventListener('message', handleMessage);\n });\n}\n","import { IRpcWebSocketTransport } from '../transport-types';\nimport { createWebSocketConnection } from './websocket-connection';\n\ntype Config = Readonly<{\n sendBufferHighWatermark: number;\n url: string;\n}>;\n\nexport function createWebSocketTransport({ sendBufferHighWatermark, url }: Config): IRpcWebSocketTransport {\n if (/^wss?:/i.test(url) === false) {\n const protocolMatch = url.match(/^([^:]+):/);\n throw new DOMException(\n protocolMatch\n ? `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${protocolMatch[1]}:' is not allowed.`\n : `Failed to construct 'WebSocket': The URL '${url}' is invalid.`\n );\n }\n return async function sendWebSocketMessage({ payload, signal }: Parameters<IRpcWebSocketTransport>[0]) {\n signal?.throwIfAborted();\n const connection = await createWebSocketConnection({\n sendBufferHighWatermark,\n signal,\n url,\n });\n signal?.throwIfAborted();\n await connection.send(payload);\n return {\n [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),\n send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: connection.send.bind(connection),\n };\n };\n}\n","import { createSolanaRpcApi } from '@solana/rpc-core';\n\nimport { SolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\nexport const DEFAULT_RPC_CONFIG: Partial<Parameters<typeof createSolanaRpcApi>[0]> = {\n onIntegerOverflow(methodName, keyPath, value) {\n throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);\n },\n};\n","export class SolanaJsonRpcIntegerOverflowError extends Error {\n readonly methodName: string;\n readonly keyPath: (number | string)[];\n readonly value: bigint;\n constructor(methodName: string, keyPath: (number | string)[], value: bigint) {\n const argPosition = (typeof keyPath[0] === 'number' ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;\n let ordinal = '';\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n ordinal = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n ordinal = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n ordinal = argPosition + 'rd';\n } else {\n ordinal = argPosition + 'th';\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : null;\n super(\n `The ${ordinal} argument to the \\`${methodName}\\` RPC method` +\n `${path ? ` at path \\`${path}\\`` : ''} was \\`${value}\\`. This number is ` +\n 'unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.'\n );\n this.keyPath = keyPath;\n this.methodName = methodName;\n this.value = value;\n }\n get name() {\n return 'SolanaJsonRpcIntegerOverflowError';\n }\n}\n","import { createHttpTransport } from '@solana/rpc-transport';\nimport { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getRpcTransportWithRequestCoalescing } from './rpc-request-coalescer';\nimport { getSolanaRpcPayloadDeduplicationKey } from './rpc-request-deduplication';\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers.\n */\nfunction normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n\nexport function createDefaultRpcTransport(config: Parameters<typeof createHttpTransport>[0]): IRpcTransport {\n return getRpcTransportWithRequestCoalescing(\n createHttpTransport({\n ...config,\n headers: {\n ...(config.headers ? normalizeHeaders(config.headers) : undefined),\n ...({\n // Keep these headers lowercase so they will override any user-supplied headers above.\n 'solana-client': `js/${__VERSION__}` ?? 'UNKNOWN',\n } as { [overrideHeader: string]: string }),\n },\n }),\n getSolanaRpcPayloadDeduplicationKey\n );\n}\n","import { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\ntype CoalescedRequest = {\n readonly abortController: AbortController;\n numConsumers: number;\n readonly responsePromise: Promise<unknown>;\n};\n\ntype GetDeduplicationKeyFn = (payload: unknown) => string | undefined;\n\nexport function getRpcTransportWithRequestCoalescing(\n transport: IRpcTransport,\n getDeduplicationKey: GetDeduplicationKeyFn\n): IRpcTransport {\n let coalescedRequestsByDeduplicationKey: Record<string, CoalescedRequest> | undefined;\n return async function makeCoalescedHttpRequest<TResponse>(\n config: Parameters<IRpcTransport>[0]\n ): Promise<TResponse> {\n const { payload, signal } = config;\n const deduplicationKey = getDeduplicationKey(payload);\n if (deduplicationKey === undefined) {\n return await transport(config);\n }\n if (!coalescedRequestsByDeduplicationKey) {\n Promise.resolve().then(() => {\n coalescedRequestsByDeduplicationKey = undefined;\n });\n coalescedRequestsByDeduplicationKey = {};\n }\n if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {\n const abortController = new AbortController();\n coalescedRequestsByDeduplicationKey[deduplicationKey] = {\n abortController,\n numConsumers: 0,\n responsePromise: transport<TResponse>({\n ...config,\n signal: abortController.signal,\n }),\n };\n }\n const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];\n coalescedRequest.numConsumers++;\n if (signal) {\n const responsePromise = coalescedRequest.responsePromise as Promise<TResponse>;\n return await new Promise<TResponse>((resolve, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n signal.removeEventListener('abort', handleAbort);\n coalescedRequest.numConsumers -= 1;\n if (coalescedRequest.numConsumers === 0) {\n const abortController = coalescedRequest.abortController;\n abortController.abort();\n }\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n signal.addEventListener('abort', handleAbort);\n responsePromise.then(resolve).finally(() => {\n signal.removeEventListener('abort', handleAbort);\n });\n });\n } else {\n return (await coalescedRequest.responsePromise) as TResponse;\n }\n };\n}\n","// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return;\n }\n if ('jsonrpc' in payload && payload.jsonrpc === '2.0' && 'method' in payload && 'params' in payload) {\n return fastStableStringify([payload.method, payload.params]);\n }\n}\n","import { createWebSocketTransport } from '@solana/rpc-transport';\nimport { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getWebSocketTransportWithAutoping } from './rpc-websocket-autopinger';\n\nexport function createDefaultRpcSubscriptionsTransport(\n config: Omit<Parameters<typeof createWebSocketTransport>[0], 'sendBufferHighWatermark'> & {\n intervalMs?: number;\n sendBufferHighWatermark?: number;\n }\n): IRpcWebSocketTransport {\n const { intervalMs, ...rest } = config;\n return getWebSocketTransportWithAutoping({\n intervalMs: intervalMs ?? 5_000,\n transport: createWebSocketTransport({\n ...rest,\n sendBufferHighWatermark:\n config.sendBufferHighWatermark ??\n // Let 128KB of data into the WebSocket buffer before buffering it in the app.\n 131_072,\n }),\n });\n}\n","import { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\ntype Config = Readonly<{\n intervalMs: number;\n transport: IRpcWebSocketTransport;\n}>;\n\nconst PING_PAYLOAD = {\n jsonrpc: '2.0',\n method: 'ping',\n} as const;\n\nexport function getWebSocketTransportWithAutoping({ intervalMs, transport }: Config): IRpcWebSocketTransport {\n const pingableConnections = new Map<\n Awaited<ReturnType<IRpcWebSocketTransport>>,\n Awaited<ReturnType<IRpcWebSocketTransport>>\n >();\n return async (...args) => {\n const connection = await transport(...args);\n let intervalId: string | number | NodeJS.Timeout | undefined;\n function restartPingTimer() {\n clearInterval(intervalId);\n intervalId = setInterval(() => {\n connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);\n }, intervalMs);\n }\n if (pingableConnections.has(connection) === false) {\n pingableConnections.set(connection, {\n [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),\n send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: (\n ...args: Parameters<typeof connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED>\n ) => {\n restartPingTimer();\n return connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(...args);\n },\n });\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of connection) {\n restartPingTimer();\n }\n } catch {\n /* empty */\n } finally {\n pingableConnections.delete(connection);\n clearInterval(intervalId);\n }\n })();\n restartPingTimer();\n }\n return pingableConnections.get(connection)!;\n };\n}\n"]}
|