@solana/web3.js 2.0.0-experimental.bd21cc5 → 2.0.0-experimental.be3a154

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.
Files changed (52) hide show
  1. package/README.md +4 -4
  2. package/dist/index.browser.cjs +1 -1
  3. package/dist/index.browser.cjs.map +1 -1
  4. package/dist/index.browser.js +3 -1
  5. package/dist/index.browser.js.map +1 -1
  6. package/dist/index.development.js +538 -632
  7. package/dist/index.development.js.map +1 -1
  8. package/dist/index.native.js +1 -1
  9. package/dist/index.native.js.map +1 -1
  10. package/dist/index.node.cjs +1 -1
  11. package/dist/index.node.cjs.map +1 -1
  12. package/dist/index.node.js +1 -1
  13. package/dist/index.node.js.map +1 -1
  14. package/dist/index.production.min.js +82 -80
  15. package/dist/types/airdrop-confirmer.d.ts +4 -5
  16. package/dist/types/airdrop-confirmer.d.ts.map +1 -0
  17. package/dist/types/airdrop.d.ts +3 -5
  18. package/dist/types/airdrop.d.ts.map +1 -0
  19. package/dist/types/cached-abortable-iterable.d.ts.map +1 -0
  20. package/dist/types/index.d.ts +9 -9
  21. package/dist/types/index.d.ts.map +1 -0
  22. package/dist/types/rpc-default-config.d.ts.map +1 -0
  23. package/dist/types/rpc-integer-overflow-error.d.ts.map +1 -0
  24. package/dist/types/rpc-request-coalescer.d.ts +1 -1
  25. package/dist/types/rpc-request-coalescer.d.ts.map +1 -0
  26. package/dist/types/rpc-request-deduplication.d.ts.map +1 -0
  27. package/dist/types/rpc-subscription-coalescer.d.ts +1 -1
  28. package/dist/types/rpc-subscription-coalescer.d.ts.map +1 -0
  29. package/dist/types/rpc-transport.d.ts +1 -2
  30. package/dist/types/rpc-transport.d.ts.map +1 -0
  31. package/dist/types/rpc-websocket-autopinger.d.ts +1 -1
  32. package/dist/types/rpc-websocket-autopinger.d.ts.map +1 -0
  33. package/dist/types/rpc-websocket-connection-sharding.d.ts +1 -1
  34. package/dist/types/rpc-websocket-connection-sharding.d.ts.map +1 -0
  35. package/dist/types/rpc-websocket-transport.d.ts +1 -2
  36. package/dist/types/rpc-websocket-transport.d.ts.map +1 -0
  37. package/dist/types/rpc.d.ts +1 -2
  38. package/dist/types/rpc.d.ts.map +1 -0
  39. package/dist/types/send-transaction.d.ts +3 -3
  40. package/dist/types/send-transaction.d.ts.map +1 -0
  41. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts +2 -3
  42. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts.map +1 -0
  43. package/dist/types/transaction-confirmation-strategy-nonce.d.ts +2 -3
  44. package/dist/types/transaction-confirmation-strategy-nonce.d.ts.map +1 -0
  45. package/dist/types/transaction-confirmation-strategy-racer.d.ts +1 -1
  46. package/dist/types/transaction-confirmation-strategy-racer.d.ts.map +1 -0
  47. package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts +2 -3
  48. package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts.map +1 -0
  49. package/dist/types/transaction-confirmation-strategy-timeout.d.ts.map +1 -0
  50. package/dist/types/transaction-confirmation.d.ts +5 -10
  51. package/dist/types/transaction-confirmation.d.ts.map +1 -0
  52. package/package.json +13 -13
@@ -1 +1 @@
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","../../codecs-core/src/assertions.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/combine-codec.ts","../../codecs-core/src/fix-codec.ts","../../codecs-core/src/map-codec.ts","../../codecs-numbers/src/assertions.ts","../../codecs-numbers/src/f32.ts","../../codecs-numbers/src/utils.ts","../../codecs-numbers/src/i64.ts","../../codecs-numbers/src/i8.ts","../../codecs-numbers/src/short-u16.ts","../../codecs-numbers/src/u128.ts","../../codecs-numbers/src/u16.ts","../../codecs-numbers/src/u32.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/baseX-reslice.ts","../../codecs-strings/src/base64.ts","../../codecs-strings/src/null-characters.ts","../../codecs-strings/src/string.ts","../../codecs-strings/src/utf8.ts","../../text-encoding-impl/src/index.browser.ts","../../assertions/src/subtle-crypto.ts","../../addresses/src/address.ts","../../addresses/src/vendor/noble/ed25519.ts","../../addresses/src/curve.ts","../../addresses/src/program-derived-address.ts","../../addresses/src/public-key.ts","../../instructions/src/roles.ts","../../keys/src/key-pair.ts","../../keys/src/signatures.ts","../../rpc-types/src/commitment.ts","../../rpc-types/src/lamports.ts","../../rpc-types/src/stringified-bigint.ts","../../rpc-types/src/stringified-number.ts","../../rpc-types/src/unix-timestamp.ts","../../codecs-data-structures/src/utils.ts","../../codecs-data-structures/src/array-like-codec-size.ts","../../codecs-data-structures/src/assertions.ts","../../codecs-data-structures/src/array.ts","../../codecs-data-structures/src/boolean.ts","../../codecs-data-structures/src/bytes.ts","../../codecs-data-structures/src/scalar-enum.ts","../../codecs-data-structures/src/set.ts","../../functional/src/pipe.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/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/transaction-version.ts","../../transactions/src/serializers/transaction.ts","../../transactions/src/compile-transaction.ts","../../transactions/src/decompile-transaction.ts","../src/airdrop.ts","../src/airdrop-confirmer.ts","../src/transaction-confirmation-strategy-racer.ts","../src/transaction-confirmation-strategy-recent-signature.ts","../src/transaction-confirmation-strategy-timeout.ts","../src/rpc.ts","../../rpc-core/src/params-patcher.ts","../../rpc-core/src/response-patcher-types.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-subscription-coalescer.ts","../src/cached-abortable-iterable.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","../src/rpc-websocket-connection-sharding.ts","../src/send-transaction.ts","../src/transaction-confirmation.ts","../src/transaction-confirmation-strategy-blockheight.ts","../src/transaction-confirmation-strategy-nonce.ts"],"names":["combineCodec","alphabet","e2","e","base58Encoder","address","encode","decode","AccountRole","signature","newOffset","mergeBytes","getU32Decoder","getU32Encoder","__DEV__","AccountRole2","IS_WRITABLE_BITMASK","isSignerRole","isWritableRole","mergeRoles","getAddressComparator","getAddressDecoder","getArrayDecoder","getArrayEncoder","getStructEncoder","getU8Encoder","getStructDecoder","getU8Decoder","mapEncoder","getShortU16Decoder","getShortU16Encoder","mapDecoder","getBytesEncoder","getBytesDecoder","getTimeoutPromise","lamports","visitNode","makeProxy","index_browser_default","resolve","reject","registerIterableCleanup","EXPLICIT_ABORT_TOKEN","deduplicationKey","pendingSubscription","fastStableStringify","import_fast_stable_stringify","normalizeHeaders","args","base58Decoder"],"mappings":";;;;;;;;;;;;;;;;;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UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA,CAAC,SAAS,SAAS,gBAAgB,kBAAkB,QAAQ,WAAW,kBAAkB,YAAY;QACtG;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA,CAAC,SAAS,SAAS,WAAW,kBAAkB,YAAY;MAChE;MACA,sBAAsB,0BAA0B,QAAQ,CAAA,MAAK;QACzD,CAAC,SAAS,kBAAkB,WAAW,GAAG,CAAC;QAC3C,CAAC,kBAAkB,WAAW,GAAG,CAAC;MACtC,CAAC;IACL;EACJ;AACA,SAAO;AACX;AAMO,SAAS,uCAAsG;AAClH,MAAI,CAAC,0BAA0B;AAC3B,+BAA2B;MACvB,gBAAgB,0BAA0B,IAAI,CAAA,MAAK,CAAC,SAAS,GAAG,CAAC,CAAC;MAClE,UAAU;QACN,CAAC,WAAW;QACZ,CAAC,gBAAgB,kBAAkB,QAAQ,oBAAoB,kBAAkB,cAAc;QAC/F;UACI;UACA;UACA;UACA;UACA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,EACJ,CAAC;AACD,SAAO;AACX","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/rpc-types';\nexport * from '@solana/transactions';\nexport * from './airdrop';\nexport * from './rpc';\nexport * from './rpc-transport';\nexport * from './rpc-websocket-transport';\nexport * from './send-transaction';\nexport * from './transaction-confirmation';\nexport * from './transaction-confirmation-strategy-blockheight';\nexport * from './transaction-confirmation-strategy-nonce';\nexport * from './transaction-confirmation-strategy-recent-signature';\n","import { CodecData } from './codec';\n\n/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n\n/**\n * Asserts that a given codec is fixed-size codec.\n */\nexport function assertFixedSizeCodec(\n data: Pick<CodecData, 'fixedSize'>,\n message?: string\n): asserts data is { fixedSize: number } {\n if (data.fixedSize === null) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.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 */\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 */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<From, To extends From = From>(\n encoder: Encoder<From>,\n decoder: Decoder<To>,\n description?: string\n): Codec<From, To> {\n if (encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`\n );\n }\n\n if (encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`\n );\n }\n\n if (description === undefined && encoder.description !== decoder.description) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. ` +\n `Pass a custom description as a third argument if you want to override the description and bypass this error.`\n );\n }\n\n return {\n decode: decoder.decode,\n description: description ?? encoder.description,\n encode: encoder.encode,\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport { Codec, CodecData, Decoder, Encoder } from './codec';\nimport { combineCodec } from './combine-codec';\n\nfunction fixCodecHelper(data: CodecData, fixedBytes: number, description?: string): CodecData {\n return {\n description: description ?? `fixed(${fixedBytes}, ${data.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n };\n}\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @param description - A custom description for the encoder.\n */\nexport function fixEncoder<T>(encoder: Encoder<T>, fixedBytes: number, description?: string): Encoder<T> {\n return {\n ...fixCodecHelper(encoder, fixedBytes, description),\n encode: (value: T) => fixBytes(encoder.encode(value), fixedBytes),\n };\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the decoder.\n */\nexport function fixDecoder<T>(decoder: Decoder<T>, fixedBytes: number, description?: string): Decoder<T> {\n return {\n ...fixCodecHelper(decoder, fixedBytes, description),\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (decoder.fixedSize !== null) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.decode(bytes, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @param description - A custom description for the codec.\n */\nexport function fixCodec<T, U extends T = T>(\n codec: Codec<T, U>,\n fixedBytes: number,\n description?: string\n): Codec<T, U> {\n return combineCodec(fixEncoder(codec, fixedBytes, description), fixDecoder(codec, fixedBytes, description));\n}\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<T, U>(encoder: Encoder<T>, unmap: (value: U) => T): Encoder<U> {\n return {\n description: encoder.description,\n encode: (value: U) => encoder.encode(unmap(value)),\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<T, U>(\n decoder: Decoder<T>,\n map: (value: T, bytes: Uint8Array, offset: number) => U\n): Decoder<U> {\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n const [value, length] = decoder.decode(bytes, offset);\n return [map(value, bytes, offset), length];\n },\n description: decoder.description,\n fixedSize: decoder.fixedSize,\n maxSize: decoder.maxSize,\n };\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<NewFrom, OldFrom, To extends NewFrom & OldFrom>(\n codec: Codec<OldFrom, To>,\n unmap: (value: NewFrom) => OldFrom\n): Codec<NewFrom, To>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map?: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo> {\n return {\n decode: map ? mapDecoder(codec, map).decode : (codec.decode as unknown as Decoder<NewTo>['decode']),\n description: codec.description,\n encode: mapEncoder(codec, unmap).encode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n };\n}\n","/**\n * Asserts that a given number is between a given range.\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) {\n if (value < min || value > max) {\n // TODO: Coded error.\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`\n );\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (config: NumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'f32',\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (config: NumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n size: 4,\n });\n\nexport const getF32Codec = (config: NumberCodecConfig = {}): Codec<number> =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n CodecData,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig, SingleByteNumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput = {\n name: string;\n size: number;\n config: SingleByteNumberCodecConfig | NumberCodecConfig;\n};\n\ntype NumberFactoryEncoderInput<T> = NumberFactorySharedInput & {\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: T, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput<T> = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => T;\n};\n\nfunction sharedNumberFactory(input: NumberFactorySharedInput): CodecData & { littleEndian: boolean | undefined } {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian = !('endian' in input.config) || input.config.endian === Endian.LITTLE;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.config.description ?? defaultDescription,\n fixedSize: input.size,\n littleEndian,\n maxSize: input.size,\n };\n}\n\nexport function numberEncoderFactory<T extends number | bigint>(input: NumberFactoryEncoderInput<T>): Encoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n description: codecData.description,\n encode(value: T): Uint8Array {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, codecData.littleEndian);\n return new Uint8Array(arrayBuffer);\n },\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\nexport function numberDecoderFactory<T extends number | bigint>(input: NumberFactoryDecoderInput<T>): Decoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n decode(bytes, offset = 0): [T, number] {\n assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, codecData.littleEndian), offset + input.size];\n },\n description: codecData.description,\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\n/**\n * Helper function to ensure that the ArrayBuffer is converted properly from a Uint8Array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nfunction toArrayBuffer(bytes: Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI64Encoder = (config: NumberCodecConfig = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n config,\n name: 'i64',\n range: [-BigInt('0x7fffffffffffffff') - 1n, BigInt('0x7fffffffffffffff')],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8,\n });\n\nexport const getI64Decoder = (config: NumberCodecConfig = {}): Decoder<bigint> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n size: 8,\n });\n\nexport const getI64Codec = (config: NumberCodecConfig = {}): Codec<number | bigint, bigint> =>\n combineCodec(getI64Encoder(config), getI64Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { SingleByteNumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI8Encoder = (config: SingleByteNumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'i8',\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, value),\n size: 1,\n });\n\nexport const getI8Decoder = (config: SingleByteNumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: view => view.getInt8(0),\n name: 'i8',\n size: 1,\n });\n\nexport const getI8Codec = (config: SingleByteNumberCodecConfig = {}): Codec<number> =>\n combineCodec(getI8Encoder(config), getI8Decoder(config));\n","import { BaseCodecConfig, Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\n\n/**\n * Defines the config for the shortU16 serializer.\n */\nexport type ShortU16CodecConfig = BaseCodecConfig;\n\n/**\n * Encodes short u16 numbers.\n * @see {@link getShortU16Codec} for a more detailed description.\n */\nexport const getShortU16Encoder = (config: ShortU16CodecConfig = {}): Encoder<number> => ({\n description: config.description ?? 'shortU16',\n encode: (value: number): Uint8Array => {\n assertNumberIsBetweenForCodec('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 fixedSize: null,\n maxSize: 3,\n});\n\n/**\n * Decodes short u16 numbers.\n * @see {@link getShortU16Codec} for a more detailed description.\n */\nexport const getShortU16Decoder = (config: ShortU16CodecConfig = {}): Decoder<number> => ({\n decode: (bytes: Uint8Array, offset = 0): [number, number] => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\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 description: config.description ?? 'shortU16',\n fixedSize: null,\n maxSize: 3,\n});\n\n/**\n * Encodes and decodes short u16 numbers.\n *\n * Short u16 numbers are the same as u16, but serialized with 1 to 3 bytes.\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 */\nexport const getShortU16Codec = (config: ShortU16CodecConfig = {}): Codec<number> =>\n combineCodec(getShortU16Encoder(config), getShortU16Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (config: NumberCodecConfig = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n config,\n name: 'u128',\n range: [0, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\nexport const getU128Decoder = (config: NumberCodecConfig = {}): Decoder<bigint> =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n size: 16,\n });\n\nexport const getU128Codec = (config: NumberCodecConfig = {}): Codec<number | bigint, bigint> =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (config: NumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'u16',\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, value, le),\n size: 2,\n });\n\nexport const getU16Decoder = (config: NumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n size: 2,\n });\n\nexport const getU16Codec = (config: NumberCodecConfig = {}): Codec<number> =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU32Encoder = (config: NumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'u32',\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, value, le),\n size: 4,\n });\n\nexport const getU32Decoder = (config: NumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n size: 4,\n });\n\nexport const getU32Codec = (config: NumberCodecConfig = {}): Codec<number> =>\n combineCodec(getU32Encoder(config), getU32Decoder(config));\n","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXEncoder = (alphabet: string): Encoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n encode(value: string): Uint8Array {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\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 fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * Decodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXDecoder = (alphabet: string): Decoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n decode(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\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, rawBytes.length];\n\n // From bytes to base10.\n let base10Number = bytes.slice(trailIndex).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(''), rawBytes.length];\n },\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * A string codec 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 codecs such as base10 or base58.\n */\nexport const getBaseXCodec = (alphabet: string): Codec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): Encoder<string> => ({\n description: 'base16',\n encode(value: string) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString('0123456789abcdef', lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n return Uint8Array.from(matches ? matches.map((byte: string) => parseInt(byte, 16)) : []);\n },\n fixedSize: null,\n maxSize: null,\n});\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): Decoder<string> => ({\n decode(bytes, offset = 0) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n description: 'base16',\n fixedSize: null,\n maxSize: null,\n});\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): Codec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by reslicing the bits of the byte array.\n * @see {@link getBaseXResliceCodec} for a more detailed description.\n */\nexport const getBaseXResliceEncoder = (alphabet: string, bits: number): Encoder<string> => ({\n description: `base${alphabet.length}`,\n encode(value: string): Uint8Array {\n assertValidBaseString(alphabet, value);\n if (value === '') return new Uint8Array();\n const charIndices = [...value].map(c => alphabet.indexOf(c));\n return new Uint8Array(reslice(charIndices, bits, 8, false));\n },\n fixedSize: null,\n maxSize: null,\n});\n\n/**\n * Decodes a string using a custom alphabet by reslicing the bits of the byte array.\n * @see {@link getBaseXResliceCodec} for a more detailed description.\n */\nexport const getBaseXResliceDecoder = (alphabet: string, bits: number): Decoder<string> => ({\n decode(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map(i => alphabet[i]).join(''), rawBytes.length];\n },\n description: `base${alphabet.length}`,\n fixedSize: null,\n maxSize: null,\n});\n\n/**\n * A string serializer that reslices bytes into custom chunks\n * of bits that are then mapped to a custom alphabet.\n *\n * This can be used to create serializers whose alphabet\n * is a power of 2 such as base16 or base64.\n */\nexport const getBaseXResliceCodec = (alphabet: string, bits: number): Codec<string> =>\n combineCodec(getBaseXResliceEncoder(alphabet, bits), getBaseXResliceDecoder(alphabet, bits));\n\n/** Helper function to reslice the bits inside bytes. */\nfunction reslice(input: number[], inputBits: number, outputBits: number, useRemainder: boolean): number[] {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = (accumulator << inputBits) | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push((accumulator >> bitsInAccumulator) & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push((accumulator << (outputBits - bitsInAccumulator)) & mask);\n }\n return output;\n}\n","import { combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Encodes strings in base64. */\nexport const getBase64Encoder = (): Encoder<string> => {\n if (__BROWSER__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n try {\n const bytes = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n return new Uint8Array(bytes);\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n return new Uint8Array(Buffer.from(value, 'base64'));\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/** Decodes strings in base64. */\nexport const getBase64Decoder = (): Decoder<string> => {\n if (__BROWSER__) {\n return {\n decode(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n decode: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString('base64'), bytes.length],\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '=')\n );\n};\n\n/** Encodes and decodes strings in base64. */\nexport const getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());\n","/**Removes null characters from a string. */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/** Pads a string with null characters at the end. */\nexport const padNullCharacters = (value: string, chars: number) => value.padEnd(chars, '\\u0000');\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecConfig,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixDecoder,\n fixEncoder,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { getUtf8Decoder, getUtf8Encoder } from './utf8';\n\n/** Defines the config for string codecs. */\nexport type StringCodecConfig<\n TPrefix extends NumberCodec | NumberEncoder | NumberDecoder,\n TEncoding extends Codec<string> | Encoder<string> | Decoder<string>\n> = BaseCodecConfig & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberCodec} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the byte array.\n * @defaultValue u32 prefix.\n */\n size?: TPrefix | number | 'variable';\n\n /**\n * The codec to use for encoding and decoding the content.\n * @defaultValue UTF-8 encoding.\n */\n encoding?: TEncoding;\n};\n\n/** Encodes strings from a given encoding and size strategy. */\nexport const getStringEncoder = (config: StringCodecConfig<NumberEncoder, Encoder<string>> = {}): Encoder<string> => {\n const size = config.size ?? getU32Encoder();\n const encoding = config.encoding ?? getUtf8Encoder();\n const description = config.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixEncoder(encoding, size, description);\n }\n\n return {\n description,\n encode: (value: string) => {\n const contentBytes = encoding.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes strings from a given encoding and size strategy. */\nexport const getStringDecoder = (config: StringCodecConfig<NumberDecoder, Decoder<string>> = {}): Decoder<string> => {\n const size = config.size ?? getU32Decoder();\n const encoding = config.encoding ?? getUtf8Decoder();\n const description = config.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixDecoder(encoding, size, description);\n }\n\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('string', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec('string', length, contentBytes);\n const [value, contentOffset] = encoding.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n },\n description,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes strings from a given encoding and size strategy. */\nexport const getStringCodec = (config: StringCodecConfig<NumberCodec, Codec<string>> = {}): Codec<string> =>\n combineCodec(getStringEncoder(config), getStringDecoder(config));\n\nfunction getSizeDescription(size: CodecData | number | 'variable'): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from 'text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/** Encodes UTF-8 strings using the native `TextEncoder` API. */\nexport const getUtf8Encoder = (): Encoder<string> => {\n let textEncoder: TextEncoder;\n return {\n description: 'utf8',\n encode: (value: string) => new Uint8Array((textEncoder ||= new TextEncoder()).encode(value)),\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes UTF-8 strings using the native `TextDecoder` API. */\nexport const getUtf8Decoder = (): Decoder<string> => {\n let textDecoder: TextDecoder;\n return {\n decode(bytes, offset = 0) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes UTF-8 strings using the native `TextEncoder` and `TextDecoder` API. */\nexport const getUtf8Codec = (): Codec<string> => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\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 { Codec, combineCodec, Decoder, Encoder, mapEncoder } from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nexport type Address<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\nexport function isAddress(putativeAddress: string): putativeAddress is Address<typeof putativeAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address<typeof putativeAddress> {\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 putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.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 base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\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(`\\`${putativeAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function address<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address<TAddress>;\n}\n\nexport function getAddressEncoder(config?: Readonly<{ description: string }>): Encoder<Address> {\n return mapEncoder(\n getStringEncoder({\n description: config?.description ?? 'Address',\n encoding: getMemoizedBase58Encoder(),\n size: 32,\n }),\n putativeAddress => address(putativeAddress)\n );\n}\n\nexport function getAddressDecoder(config?: Readonly<{ description: string }>): Decoder<Address> {\n return getStringDecoder({\n description: config?.description ?? 'Address',\n encoding: getMemoizedBase58Decoder(),\n size: 32,\n }) as Decoder<Address>;\n}\n\nexport function getAddressCodec(config?: Readonly<{ description: string }>): Codec<Address> {\n return combineCodec(getAddressEncoder(config), getAddressDecoder(config));\n}\n\nexport function getAddressComparator(): (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","/**!\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 { assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\nimport { Address, assertIsAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve';\n\n/**\n * An address derived from a program address and a set of seeds.\n * It includes the bump seed used to derive the address and\n * ensure the address is not on the Ed25519 curve.\n */\nexport type ProgramDerivedAddress<TAddress extends string = string> = Readonly<\n [Address<TAddress>, ProgramDerivedAddressBump]\n>;\n\n/**\n * A number between 0 and 255, inclusive.\n */\nexport type ProgramDerivedAddressBump = number & {\n readonly __brand: unique symbol;\n};\n\n/**\n * Returns true if the input value is a program derived address.\n */\nexport function isProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): value is ProgramDerivedAddress<TAddress> {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * Fails if the input value is not a program derived address.\n */\nexport function assertIsProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): asserts value is ProgramDerivedAddress<TAddress> {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n // TODO: Coded error.\n throw new Error(\n `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n // TODO: Coded error.\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Address;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Address;\n programAddress: Address;\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 }: ProgramDerivedAddressInput): Promise<Address> {\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 = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(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.decode(addressBytes)[0];\n}\n\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<ProgramDerivedAddress> {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\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({ baseAddress, programAddress, seed }: SeedInput): Promise<Address> {\n const { encode, decode } = getAddressCodec();\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 = encode(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([...encode(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes)[0];\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Address, getAddressDecoder } from './address';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Address> {\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] = getAddressDecoder().decode(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';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n","export type Commitment = 'confirmed' | 'finalized' | 'processed';\n\nfunction getCommitmentScore(commitment: Commitment): number {\n switch (commitment) {\n case 'finalized':\n return 2;\n case 'confirmed':\n return 1;\n case 'processed':\n return 0;\n default:\n return ((_: never) => {\n throw new Error(`Unrecognized commitment \\`${commitment}\\`.`);\n })(commitment);\n }\n}\n\nexport function commitmentComparator(a: Commitment, b: Commitment): -1 | 0 | 1 {\n if (a === b) {\n return 0;\n }\n return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;\n}\n","// FIXME(solana-labs/solana/issues/30341) Beware that any value above 9007199254740991 may be\n// truncated or rounded because of a downcast to JavaScript `number` between your calling code and\n// the JSON-RPC transport.\nexport type LamportsUnsafeBeyond2Pow53Minus1 = bigint & { readonly __brand: unique symbol };\n\n// Largest possible value to be represented by a u64\nconst maxU64Value = 18446744073709551615n; // 2n ** 64n - 1n\n\nexport function isLamports(putativeLamports: bigint): putativeLamports is LamportsUnsafeBeyond2Pow53Minus1 {\n return putativeLamports >= 0 && putativeLamports <= maxU64Value;\n}\n\nexport function assertIsLamports(\n putativeLamports: bigint\n): asserts putativeLamports is LamportsUnsafeBeyond2Pow53Minus1 {\n if (putativeLamports < 0) {\n // TODO: Coded error.\n throw new Error('Input for 64-bit unsigned integer cannot be negative');\n }\n\n if (putativeLamports > maxU64Value) {\n // TODO: Coded error.\n throw new Error('Input number is too large to be represented as a 64-bit unsigned integer');\n }\n}\n\nexport function lamports(putativeLamports: bigint): LamportsUnsafeBeyond2Pow53Minus1 {\n assertIsLamports(putativeLamports);\n return putativeLamports;\n}\n","export type StringifiedBigInt = string & { readonly __brand: unique symbol };\n\nexport function isStringifiedBigInt(putativeBigInt: string): putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n return true;\n } catch (_) {\n return false;\n }\n}\n\nexport function assertIsStringifiedBigInt(putativeBigInt: string): asserts putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n } catch (e) {\n throw new Error(`\\`${putativeBigInt}\\` cannot be parsed as a BigInt`, {\n cause: e,\n });\n }\n}\n\nexport function stringifiedBigInt(putativeBigInt: string): StringifiedBigInt {\n assertIsStringifiedBigInt(putativeBigInt);\n return putativeBigInt;\n}\n","export type StringifiedNumber = string & { readonly __brand: unique symbol };\n\nexport function isStringifiedNumber(putativeNumber: string): putativeNumber is StringifiedNumber {\n return !Number.isNaN(Number(putativeNumber));\n}\n\nexport function assertIsStringifiedNumber(putativeNumber: string): asserts putativeNumber is StringifiedNumber {\n if (Number.isNaN(Number(putativeNumber))) {\n throw new Error(`\\`${putativeNumber}\\` cannot be parsed as a Number`);\n }\n}\n\nexport function stringifiedNumber(putativeNumber: string): StringifiedNumber {\n assertIsStringifiedNumber(putativeNumber);\n return putativeNumber;\n}\n","export type UnixTimestamp = number & { readonly __brand: unique symbol };\n\nexport function isUnixTimestamp(putativeTimestamp: number): putativeTimestamp is UnixTimestamp {\n // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date\n if (putativeTimestamp > 8.64e15 || putativeTimestamp < -8.64e15) {\n return false;\n }\n return true;\n}\n\nexport function assertIsUnixTimestamp(putativeTimestamp: number): asserts putativeTimestamp is UnixTimestamp {\n // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date\n try {\n if (putativeTimestamp > 8.64e15 || putativeTimestamp < -8.64e15) {\n throw new Error('Expected input number to be in the range [-8.64e15, 8.64e15]');\n }\n } catch (e) {\n throw new Error(`\\`${putativeTimestamp}\\` is not a timestamp`, {\n cause: e,\n });\n }\n}\n\nexport function unixTimestamp(putativeTimestamp: number): UnixTimestamp {\n assertIsUnixTimestamp(putativeTimestamp);\n return putativeTimestamp;\n}\n","/** Returns the max size or null if at least one size is null. */\nexport function maxCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : Math.max(all, size)),\n 0 as number | null\n );\n}\n\n/** Returns the sum of all sizes or null if at least one size is null. */\nexport function sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n","import { CodecData, Offset } from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { sumCodecSizes } from './utils';\n\n/**\n * Represents all the size options for array-like codecs\n * — i.e. `array`, `map` and `set`.\n *\n * It can be one of the following:\n * - a {@link NumberCodec} that prefixes its content with its size.\n * - a fixed number of items.\n * - or `'remainder'` to infer the number of items by dividing\n * the rest of the byte array by the fixed size of its item.\n * Note that this option is only available for fixed-size items.\n */\nexport type ArrayLikeCodecSize<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder | CodecData> =\n | TPrefix\n | number\n | 'remainder';\n\n/** Resolves the size of an array-like codec. */\nexport function decodeArrayLikeCodecSize(\n size: ArrayLikeCodecSize<NumberDecoder>,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: Offset\n): [number | bigint, Offset] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.decode(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumCodecSizes(childrenSizes);\n if (childrenSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n // TODO: Coded error.\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${childrenSize} bytes. ` +\n `Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainder} modulo ${childrenSize} should be equal to zero.`\n );\n }\n return [remainder / childrenSize, offset];\n }\n\n // TODO: Coded error.\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\n\nexport function getArrayLikeCodecSizeDescription(size: ArrayLikeCodecSize<CodecData>): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getArrayLikeCodecSizeFromChildren(\n size: ArrayLikeCodecSize<CodecData>,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumCodecSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getArrayLikeCodecSizePrefix(size: ArrayLikeCodecSize<NumberEncoder>, realSize: number): Uint8Array {\n return typeof size === 'object' ? size.encode(realSize) : new Uint8Array();\n}\n","/** Checks the number of items in an array-like structure is expected. */\nexport function assertValidNumberOfItemsForCodec(\n codecDescription: string,\n expected: number | bigint,\n actual: number | bigint\n) {\n if (expected !== actual) {\n // TODO: Coded error.\n throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);\n }\n}\n","import { BaseCodecConfig, Codec, CodecData, combineCodec, Decoder, Encoder, mergeBytes } from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport {\n ArrayLikeCodecSize,\n decodeArrayLikeCodecSize,\n getArrayLikeCodecSizeDescription,\n getArrayLikeCodecSizeFromChildren,\n getArrayLikeCodecSizePrefix,\n} from './array-like-codec-size';\nimport { assertValidNumberOfItemsForCodec } from './assertions';\n\n/** Defines the configs for array codecs. */\nexport type ArrayCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The size of the array.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\n};\n\nfunction arrayCodecHelper(item: CodecData, size: ArrayLikeCodecSize<CodecData>, description?: string): CodecData {\n if (size === 'remainder' && item.fixedSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n return {\n description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize]),\n };\n}\n\n/**\n * Encodes an array of items.\n *\n * @param item - The encoder to use for the array's items.\n * @param config - A set of config for the encoder.\n */\nexport function getArrayEncoder<T>(item: Encoder<T>, config: ArrayCodecConfig<NumberEncoder> = {}): Encoder<T[]> {\n const size = config.size ?? getU32Encoder();\n return {\n ...arrayCodecHelper(item, size, config.description),\n encode: (value: T[]) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, value.length);\n }\n return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map(v => item.encode(v))]);\n },\n };\n}\n\n/**\n * Decodes an array of items.\n *\n * @param item - The encoder to use for the array's items.\n * @param config - A set of config for the encoder.\n */\nexport function getArrayDecoder<T>(item: Decoder<T>, config: ArrayCodecConfig<NumberDecoder> = {}): Decoder<T[]> {\n const size = config.size ?? getU32Decoder();\n return {\n ...arrayCodecHelper(item, size, config.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n const values: T[] = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.decode(bytes, offset);\n values.push(value);\n offset = newOffset;\n }\n return [values, offset];\n },\n };\n}\n\n/**\n * Creates a codec for an array of items.\n *\n * @param item - The codec to use for the array's items.\n * @param config - A set of config for the codec.\n */\nexport function getArrayCodec<T, U extends T = T>(\n item: Codec<T, U>,\n config: ArrayCodecConfig<NumberCodec> = {}\n): Codec<T[], U[]> {\n return combineCodec(getArrayEncoder(item, config), getArrayDecoder(item, config));\n}\n","import {\n assertByteArrayIsNotEmptyForCodec,\n assertFixedSizeCodec,\n BaseCodecConfig,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/** Defines the config for boolean codecs. */\nexport type BooleanCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The number codec to delegate to.\n * @defaultValue u8 size.\n */\n size?: TSize;\n};\n\n/**\n * Encodes booleans.\n *\n * @param config - A set of config for the encoder.\n */\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder> = {}): Encoder<boolean> {\n const size = config.size ?? getU8Encoder();\n assertFixedSizeCodec(size, 'Codec [bool] requires a fixed size.');\n\n return {\n description: config.description ?? `bool(${size.description})`,\n encode: (value: boolean) => size.encode(value ? 1 : 0),\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize,\n };\n}\n\n/**\n * Decodes booleans.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder> = {}): Decoder<boolean> {\n const size = config.size ?? getU8Decoder();\n assertFixedSizeCodec(size, 'Codec [bool] requires a fixed size.');\n\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('bool', bytes, offset);\n const [value, vOffset] = size.decode(bytes, offset);\n return [value === 1, vOffset];\n },\n description: config.description ?? `bool(${size.description})`,\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize,\n };\n}\n\n/**\n * Creates a boolean codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec> = {}): Codec<boolean> {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecConfig,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n fixDecoder,\n fixEncoder,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/** Defines the config for bytes codecs. */\nexport type BytesCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The size of the byte array. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the byte array with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the byte array.\n * @defaultValue `'variable'`\n */\n size?: TSize | number | 'variable';\n};\n\n/**\n * Encodes sized bytes.\n *\n * @param config - A set of config for the encoder.\n */\nexport function getBytesEncoder(config: BytesCodecConfig<NumberEncoder> = {}): Encoder<Uint8Array> {\n const size = config.size ?? 'variable';\n const sizeDescription = typeof size === 'object' ? size.description : `${size}`;\n const description = config.description ?? `bytes(${sizeDescription})`;\n\n const byteEncoder: Encoder<Uint8Array> = {\n description,\n encode: (value: Uint8Array) => value,\n fixedSize: null,\n maxSize: null,\n };\n\n if (size === 'variable') {\n return byteEncoder;\n }\n\n if (typeof size === 'number') {\n return fixEncoder(byteEncoder, size, description);\n }\n\n return {\n ...byteEncoder,\n encode: (value: Uint8Array) => {\n const contentBytes = byteEncoder.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n };\n}\n\n/**\n * Decodes sized bytes.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBytesDecoder(config: BytesCodecConfig<NumberDecoder> = {}): Decoder<Uint8Array> {\n const size = config.size ?? 'variable';\n const sizeDescription = typeof size === 'object' ? size.description : `${size}`;\n const description = config.description ?? `bytes(${sizeDescription})`;\n\n const byteDecoder: Decoder<Uint8Array> = {\n decode: (bytes: Uint8Array, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n description,\n fixedSize: null,\n maxSize: null,\n };\n\n if (size === 'variable') {\n return byteDecoder;\n }\n\n if (typeof size === 'number') {\n return fixDecoder(byteDecoder, size, description);\n }\n\n return {\n ...byteDecoder,\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('bytes', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec('bytes', length, contentBytes);\n const [value, contentOffset] = byteDecoder.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n\n/**\n * Creates a sized bytes codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBytesCodec(config: BytesCodecConfig<NumberCodec> = {}): Codec<Uint8Array> {\n return combineCodec(getBytesEncoder(config), getBytesDecoder(config));\n}\n","import {\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecConfig,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/**\n * Defines a scalar enum as a type from its constructor.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionType = ScalarEnum<Direction>;\n * ```\n */\nexport type ScalarEnum<T> = ({ [key: number | string]: string | number | T } | number | T) & NonNullable<unknown>;\n\n/** Defines the config for scalar enum codecs. */\nexport type ScalarEnumCodecConfig<TDiscriminator extends NumberCodec | NumberEncoder | NumberDecoder> =\n BaseCodecConfig & {\n /**\n * The codec to use for the enum discriminator.\n * @defaultValue u8 discriminator.\n */\n size?: TDiscriminator;\n };\n\nfunction scalarEnumCoderHelper<T>(\n constructor: ScalarEnum<T>,\n prefix: CodecData,\n description?: string\n): CodecData & {\n enumKeys: string[];\n enumValues: T[];\n isNumericEnum: boolean;\n minRange: number;\n maxRange: number;\n stringValues: string[];\n} {\n const enumKeys = Object.keys(constructor);\n const enumValues = Object.values(constructor);\n const isNumericEnum = enumValues.some(v => typeof v === 'number');\n const valueDescriptions = enumValues.filter(v => typeof v === 'string').join(', ');\n const minRange = 0;\n const maxRange = isNumericEnum ? enumValues.length / 2 - 1 : enumValues.length - 1;\n const stringValues: string[] = isNumericEnum ? [...enumKeys] : [...new Set([...enumKeys, ...enumValues])];\n\n return {\n description: description ?? `enum(${valueDescriptions}; ${prefix.description})`,\n enumKeys,\n enumValues,\n fixedSize: prefix.fixedSize,\n isNumericEnum,\n maxRange,\n maxSize: prefix.maxSize,\n minRange,\n stringValues,\n };\n}\n\n/**\n * Creates a scalar enum encoder.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param config - A set of config for the encoder.\n */\nexport function getScalarEnumEncoder<T>(\n constructor: ScalarEnum<T>,\n config: ScalarEnumCodecConfig<NumberEncoder> = {}\n): Encoder<T> {\n const prefix = config.size ?? getU8Encoder();\n const { description, fixedSize, maxSize, minRange, maxRange, stringValues, enumKeys, enumValues } =\n scalarEnumCoderHelper(constructor, prefix, config.description);\n return {\n description,\n encode: (value: T) => {\n const isInvalidNumber = typeof value === 'number' && (value < minRange || value > maxRange);\n const isInvalidString = typeof value === 'string' && !stringValues.includes(value);\n if (isInvalidNumber || isInvalidString) {\n // TODO: Coded error.\n throw new Error(\n `Invalid scalar enum variant. ` +\n `Expected one of [${stringValues.join(', ')}] ` +\n `or a number between ${minRange} and ${maxRange}, ` +\n `got \"${value}\".`\n );\n }\n if (typeof value === 'number') return prefix.encode(value);\n const valueIndex = enumValues.indexOf(value);\n if (valueIndex >= 0) return prefix.encode(valueIndex);\n return prefix.encode(enumKeys.indexOf(value as string));\n },\n fixedSize,\n maxSize,\n };\n}\n\n/**\n * Creates a scalar enum decoder.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param config - A set of config for the decoder.\n */\nexport function getScalarEnumDecoder<T>(\n constructor: ScalarEnum<T>,\n config: ScalarEnumCodecConfig<NumberDecoder> = {}\n): Decoder<T> {\n const prefix = config.size ?? getU8Decoder();\n const { description, fixedSize, maxSize, minRange, maxRange, isNumericEnum, enumValues } = scalarEnumCoderHelper(\n constructor,\n prefix,\n config.description\n );\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('enum', bytes, offset);\n const [value, newOffset] = prefix.decode(bytes, offset);\n const valueAsNumber = Number(value);\n offset = newOffset;\n if (valueAsNumber < minRange || valueAsNumber > maxRange) {\n // TODO: Coded error.\n throw new Error(\n `Enum discriminator out of range. ` +\n `Expected a number between ${minRange} and ${maxRange}, got ${valueAsNumber}.`\n );\n }\n return [(isNumericEnum ? valueAsNumber : enumValues[valueAsNumber]) as T, offset];\n },\n description,\n fixedSize,\n maxSize,\n };\n}\n\n/**\n * Creates a scalar enum codec.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param config - A set of config for the codec.\n */\nexport function getScalarEnumCodec<T>(\n constructor: ScalarEnum<T>,\n config: ScalarEnumCodecConfig<NumberCodec> = {}\n): Codec<T> {\n return combineCodec(getScalarEnumEncoder(constructor, config), getScalarEnumDecoder(constructor, config));\n}\n","import { BaseCodecConfig, Codec, CodecData, combineCodec, Decoder, Encoder, mergeBytes } from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport {\n ArrayLikeCodecSize,\n decodeArrayLikeCodecSize,\n getArrayLikeCodecSizeDescription,\n getArrayLikeCodecSizeFromChildren,\n getArrayLikeCodecSizePrefix,\n} from './array-like-codec-size';\nimport { assertValidNumberOfItemsForCodec } from './assertions';\n\n/** Defines the config for set codecs. */\nexport type SetCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The size of the set.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\n};\n\nfunction setCodecHelper(item: CodecData, size: ArrayLikeCodecSize<CodecData>, description?: string): CodecData {\n if (size === 'remainder' && item.fixedSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n return {\n description: description ?? `set(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize]),\n };\n}\n\n/**\n * Encodes an set of items.\n *\n * @param item - The encoder to use for the set's items.\n * @param config - A set of config for the encoder.\n */\nexport function getSetEncoder<T>(item: Encoder<T>, config: SetCodecConfig<NumberEncoder> = {}): Encoder<Set<T>> {\n const size = config.size ?? getU32Encoder();\n return {\n ...setCodecHelper(item, size, config.description),\n encode: (set: Set<T>) => {\n if (typeof size === 'number' && set.size !== size) {\n assertValidNumberOfItemsForCodec('set', size, set.size);\n }\n const itemBytes = Array.from(set, value => item.encode(value));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, set.size), ...itemBytes]);\n },\n };\n}\n\n/**\n * Decodes an set of items.\n *\n * @param item - The encoder to use for the set's items.\n * @param config - A set of config for the encoder.\n */\nexport function getSetDecoder<T>(item: Decoder<T>, config: SetCodecConfig<NumberDecoder> = {}): Decoder<Set<T>> {\n const size = config.size ?? getU32Decoder();\n return {\n ...setCodecHelper(item, size, config.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n const set: Set<T> = new Set();\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [set, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n set.add(value);\n }\n return [set, offset];\n },\n };\n}\n\n/**\n * Creates a codec for an set of items.\n *\n * @param item - The codec to use for the set's items.\n * @param config - A set of config for the codec.\n */\nexport function getSetCodec<T, U extends T = T>(\n item: Codec<T, U>,\n config: SetCodecConfig<NumberCodec> = {}\n): Codec<Set<T>, Set<U>> {\n return combineCodec(getSetEncoder(item, config), getSetDecoder(item, config));\n}\n","/**\n * General pipe function.\n * Provide an initial value and a list of functions to pipe it through.\n *\n * Following common implementations of pipe functions that use TypeScript,\n * this function supports a maximum arity of 10 for type safety.\n * @see https://github.com/ramda/ramda/blob/master/source/pipe.js\n * @see https://github.com/darky/rocket-pipes/blob/master/index.ts\n *\n * Note you can use nested pipes to extend this limitation, like so:\n * ```typescript\n * const myValue = pipe(\n * pipe(\n * 1,\n * (x) => x + 1,\n * (x) => x * 2,\n * (x) => x - 1,\n * ),\n * (y) => y / 3,\n * (y) => y + 1,\n * );\n * ```\n * @param init The initial value\n * @param fns Any number of functions to pipe the value through\n * @returns The final value with all functions applied\n */\nexport function pipe<TInitial>(init: TInitial): TInitial;\nexport function pipe<TInitial, R1>(init: TInitial, init_r1: (init: TInitial) => R1): R1;\nexport function pipe<TInitial, R1, R2>(init: TInitial, init_r1: (init: TInitial) => R1, r1_r2: (r1: R1) => R2): R2;\nexport function pipe<TInitial, R1, R2, R3>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3\n): R3;\nexport function pipe<TInitial, R1, R2, R3, R4>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4\n): R4;\nexport function pipe<TInitial, R1, R2, R3, R4, R5>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5\n): R5;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6\n): R6;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7\n): R7;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8\n): R8;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8,\n r8_r9: (r8: R8) => R9\n): R9;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8,\n r8_r9: (r8: R8) => R9,\n r9_r10: (r9: R9) => R10\n): R10;\nexport function pipe<TInitial>(init: TInitial, ...fns: CallableFunction[]) {\n return fns.reduce((acc, fn) => fn(acc), init);\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 { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\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\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\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 = base58Encoder.encode(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 { Address } from '@solana/addresses';\nimport {\n AccountRole,\n IInstruction,\n IInstructionWithAccounts,\n IInstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nimport { ITransactionWithSignatures } from './signatures';\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> | WritableSignerAccount<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: Address<TNonceAccountAddress>;\n readonly nonceAuthorityAddress: Address<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 Address<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address<'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: Address<TNonceAccountAddress>,\n nonceAuthorityAddress: Address<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\nexport function isAdvanceNonceAccountInstruction(\n instruction: IInstruction\n): 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 isSignerRole(instruction.accounts[2].role)\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\nfunction isAdvanceNonceAccountInstructionForNonce<\n TNonceAccountAddress extends Address = Address,\n TNonceAuthorityAddress extends Address = Address\n>(\n instruction: AdvanceNonceAccountInstruction,\n nonceAccountAddress: TNonceAccountAddress,\n nonceAuthorityAddress: TNonceAuthorityAddress\n): instruction is AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return (\n instruction.accounts[0].address === nonceAccountAddress &&\n instruction.accounts[2].address === nonceAuthorityAddress\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): Omit<TTransaction, keyof ITransactionWithSignatures> &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue> {\n let newInstructions: [\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n\n const firstInstruction = transaction.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {\n return transaction as TTransaction &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions.slice(1),\n ];\n }\n } else {\n // we don't have an existing advance nonce instruction as the first instruction, prepend one\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions,\n ];\n }\n\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: newInstructions,\n lifetimeConstraint: {\n nonce,\n },\n } as TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n Object.freeze(out);\n return out;\n}\n","import { Address } 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: Address<TAddress>;\n}\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Address<TFeePayerAddress>,\n transaction:\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Address<TFeePayerAddress>,\n transaction: TTransaction | (TTransaction & ITransactionWithFeePayer<string>)\n): TTransaction & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Address<TFeePayerAddress>,\n transaction:\n | TTransaction\n | (TTransaction & ITransactionWithFeePayer<string>)\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & 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 { Address, getAddressComparator } 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: Address,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry | Record<never, never>\n ) => AddressMap[Address]\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(feePayer: Address, instructions: readonly IInstruction[]): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set<Address>();\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 getAddressComparator>;\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 ||= getAddressComparator())(\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 getAddressComparator>;\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 ||= getAddressComparator();\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 Address<typeof address>,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype AddressTableLookup = Readonly<{\n lookupTableAddress: Address;\n readableIndices: readonly number[];\n writableIndices: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<Address, { readonly readableIndices: number[]; readonly writableIndices: number[] }> = {};\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(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Address,\n ...index[lookupTableAddress as unknown as Address],\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 { Address } 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<Address, 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 { Address } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Address[] {\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 { CompilableTransaction } from './compilable-transaction';\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';\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\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 { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n StructToDecoderTuple,\n StructToEncoderTuple,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\nimport { CompiledMessage } from '../message';\nimport { SerializedMessageBytes } from '../types';\nimport { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nconst staticAccountsDescription = __DEV__\n ? 'A compact-array of static account addresses belonging to this transaction'\n : 'staticAccounts';\nconst lifetimeTokenDescription = __DEV__\n ? 'A 32-byte token that specifies the lifetime of this transaction (eg. a ' +\n 'recent blockhash, or a durable nonce)'\n : 'lifetimeToken';\nconst instructionsDescription = __DEV__\n ? 'A compact-array of instructions belonging to this transaction'\n : 'instructions';\nconst addressTableLookupsDescription = __DEV__\n ? 'A compact array of address table lookups belonging to this transaction'\n : 'addressTableLookups';\n\nfunction getCompiledMessageLegacyEncoder(): Encoder<CompiledMessage> {\n return getStructEncoder(getPreludeStructEncoderTuple());\n}\n\nfunction getCompiledMessageVersionedEncoder(): Encoder<CompiledMessage> {\n return mapEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ] as StructToEncoderTuple<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 );\n}\n\nfunction getPreludeStructEncoderTuple(): StructToEncoderTuple<CompiledMessage> {\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n [\n 'staticAccounts',\n getArrayEncoder(getAddressEncoder(), {\n description: staticAccountsDescription,\n size: getShortU16Encoder(),\n }),\n ],\n [\n 'lifetimeToken',\n getStringEncoder({\n description: lifetimeTokenDescription,\n encoding: getBase58Encoder(),\n size: 32,\n }),\n ],\n [\n 'instructions',\n getArrayEncoder(getInstructionEncoder(), {\n description: instructionsDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ];\n}\n\nfunction getPreludeStructDecoderTuple(): StructToDecoderTuple<\n CompiledMessage & { addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups> }\n> {\n return [\n ['version', getTransactionVersionDecoder() as Decoder<number>],\n ['header', getMessageHeaderDecoder()],\n [\n 'staticAccounts',\n getArrayDecoder(getAddressDecoder(), {\n description: staticAccountsDescription,\n size: getShortU16Decoder(),\n }),\n ],\n [\n 'lifetimeToken',\n getStringDecoder({\n description: lifetimeTokenDescription,\n encoding: getBase58Decoder(),\n size: 32,\n }),\n ],\n [\n 'instructions',\n getArrayDecoder(getInstructionDecoder(), {\n description: instructionsDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ];\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Encoder(),\n });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Decoder(),\n });\n}\n\nconst messageDescription = __DEV__ ? 'The wire format of a Solana transaction message' : 'message';\n\nexport function getCompiledMessageEncoder(): Encoder<CompiledMessage> {\n return {\n description: messageDescription,\n encode: compiledMessage => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().encode(compiledMessage) as SerializedMessageBytes;\n } else {\n return getCompiledMessageVersionedEncoder().encode(compiledMessage) as SerializedMessageBytes;\n }\n },\n fixedSize: null,\n maxSize: null,\n };\n}\n\nexport function getCompiledMessageDecoder(): Decoder<CompiledMessage> {\n return mapDecoder(\n getStructDecoder(getPreludeStructDecoderTuple(), {\n description: messageDescription,\n }),\n ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups } as Exclude<\n CompiledMessage,\n { readonly version: 'legacy' }\n >;\n }\n );\n}\n\nexport function getCompiledMessageCodec(): Codec<CompiledMessage> {\n return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport { type Codec, combineCodec, type Decoder, type Encoder } from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport type { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\n\ntype AddressTableLookup = ReturnType<typeof getCompiledAddressTableLookups>[number];\n\nconst lookupTableAddressDescription = __DEV__\n ? 'The address of the address lookup table account from which instruction addresses should be looked up'\n : 'lookupTableAddress';\n\nconst writableIndicesDescription = __DEV__\n ? 'The indices of the accounts in the lookup table that should be loaded as writeable'\n : 'writableIndices';\n\nconst readableIndicesDescription = __DEV__\n ? 'The indices of the accounts in the lookup table that should be loaded as read-only'\n : 'readableIndices';\n\nconst addressTableLookupDescription = __DEV__\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 : 'addressTableLookup';\n\nlet memoizedAddressTableLookupEncoder: Encoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupEncoder(): Encoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupEncoder) {\n memoizedAddressTableLookupEncoder = getStructEncoder(\n [\n ['lookupTableAddress', getAddressEncoder({ description: lookupTableAddressDescription })],\n [\n 'writableIndices',\n getArrayEncoder(getU8Encoder(), {\n description: writableIndicesDescription,\n size: getShortU16Encoder(),\n }) as Encoder<readonly number[]>,\n ],\n [\n 'readableIndices',\n getArrayEncoder(getU8Encoder(), {\n description: readableIndicesDescription,\n size: getShortU16Encoder(),\n }) as Encoder<readonly number[]>,\n ],\n ],\n { description: addressTableLookupDescription }\n );\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: Decoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupDecoder(): Decoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupDecoder) {\n memoizedAddressTableLookupDecoder = getStructDecoder(\n [\n ['lookupTableAddress', getAddressDecoder({ description: lookupTableAddressDescription })],\n [\n 'writableIndices',\n getArrayDecoder(getU8Decoder(), {\n description: writableIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n [\n 'readableIndices',\n getArrayDecoder(getU8Decoder(), {\n description: readableIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ],\n { description: addressTableLookupDescription }\n );\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): Codec<AddressTableLookup> {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { Codec, Decoder, Encoder } from '@solana/codecs-core';\nimport { getStructCodec, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getU8Codec, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledMessageHeader } from '../compile-header';\n\ntype MessageHeader = ReturnType<typeof getCompiledMessageHeader>;\n\nlet memoizedU8Encoder: Encoder<number> | undefined;\nfunction getMemoizedU8Encoder(): Encoder<number> {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nfunction getMemoizedU8EncoderDescription(description?: string): Encoder<number> {\n const encoder = getMemoizedU8Encoder();\n return {\n ...encoder,\n description: description ?? encoder.description,\n };\n}\n\nlet memoizedU8Decoder: Decoder<number> | undefined;\nfunction getMemoizedU8Decoder(): Decoder<number> {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nfunction getMemoizedU8DecoderDescription(description?: string): Decoder<number> {\n const decoder = getMemoizedU8Decoder();\n return {\n ...decoder,\n description: description ?? decoder.description,\n };\n}\n\nlet memoizedU8Codec: Codec<number> | undefined;\nfunction getMemoizedU8Codec(): Codec<number> {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nfunction getMemoizedU8CodecDescription(description?: string): Codec<number> {\n const codec = getMemoizedU8Codec();\n return {\n ...codec,\n description: description ?? codec.description,\n };\n}\n\nconst numSignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction'\n : undefined;\n\nconst numReadonlySignerAccountsDescription = __DEV__\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 : undefined;\n\nconst numReadonlyNonSignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable'\n : undefined;\n\nconst messageHeaderDescription = __DEV__\n ? 'The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses'\n : undefined;\n\nexport function getMessageHeaderEncoder(): Encoder<MessageHeader> {\n return getStructEncoder(\n [\n ['numSignerAccounts', getMemoizedU8EncoderDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n\nexport function getMessageHeaderDecoder(): Decoder<MessageHeader> {\n return getStructDecoder(\n [\n ['numSignerAccounts', getMemoizedU8DecoderDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n\nexport function getMessageHeaderCodec(): Codec<MessageHeader> {\n return getStructCodec(\n [\n ['numSignerAccounts', getMemoizedU8CodecDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8CodecDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8CodecDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledInstructions } from '../compile-instructions';\n\ntype Instruction = ReturnType<typeof getCompiledInstructions>[number];\n\nconst programAddressIndexDescription = __DEV__\n ? 'The index of the program being called, according to the well-ordered accounts list for this transaction'\n : 'programAddressIndex';\n\nconst accountIndexDescription = __DEV__\n ? 'The index of an account, according to the well-ordered accounts list for this transaction'\n : undefined;\n\nconst accountIndicesDescription = __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 : 'accountIndices';\n\nconst dataDescription = __DEV__ ? 'An optional buffer of data passed to the instruction' : 'data';\n\nlet memoizedGetInstructionEncoder: Encoder<Instruction> | undefined;\nexport function getInstructionEncoder(): Encoder<Instruction> {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = mapEncoder<Required<Instruction>, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder({ description: programAddressIndexDescription })],\n [\n 'accountIndices',\n getArrayEncoder(getU8Encoder({ description: accountIndexDescription }), {\n description: accountIndicesDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ['data', getBytesEncoder({ description: dataDescription, size: getShortU16Encoder() })],\n ]),\n // Convert an instruction to have all fields defined\n (instruction: Instruction): Required<Instruction> => {\n if (instruction.accountIndices !== undefined && instruction.data !== undefined) {\n return instruction as Required<Instruction>;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0),\n } as Required<Instruction>;\n }\n );\n }\n\n return memoizedGetInstructionEncoder;\n}\n\nlet memoizedGetInstructionDecoder: Decoder<Instruction> | undefined;\nexport function getInstructionDecoder(): Decoder<Instruction> {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = mapDecoder<Required<Instruction>, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder({ description: programAddressIndexDescription })],\n [\n 'accountIndices',\n getArrayDecoder(getU8Decoder({ description: accountIndexDescription }), {\n description: accountIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['data', getBytesDecoder({ description: dataDescription, size: getShortU16Decoder() })],\n ]),\n // Convert an instruction to exclude optional fields if they are empty\n (instruction: Required<Instruction>): Instruction => {\n if (instruction.accountIndices.length && instruction.data.byteLength) {\n return instruction;\n }\n const { accountIndices, data, ...rest } = instruction;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n }\n );\n }\n return memoizedGetInstructionDecoder;\n}\n\nexport function getInstructionCodec(): Codec<Instruction> {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { TransactionVersion } from '../types';\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 decode(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 encode(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(): Decoder<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n decode,\n };\n}\n\nexport function getTransactionVersionEncoder(): Encoder<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n encode,\n };\n}\n\nexport function getTransactionVersionCodec(): Codec<TransactionVersion> {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { CompilableTransaction } from '../compilable-transaction';\nimport { CompiledTransaction, getCompiledTransaction } from '../compile-transaction';\nimport { decompileTransaction } from '../decompile-transaction';\nimport { ITransactionWithSignatures } from '../signatures';\nimport { getCompiledMessageDecoder, getCompiledMessageEncoder } from './message';\n\nconst signaturesDescription = __DEV__ ? 'A compact array of 64-byte, base-64 encoded Ed25519 signatures' : 'signatures';\nconst transactionDescription = __DEV__ ? 'The wire format of a Solana transaction' : 'transaction';\n\nfunction getCompiledTransactionEncoder(): Encoder<CompiledTransaction> {\n return getStructEncoder(\n [\n [\n 'signatures',\n getArrayEncoder(getBytesEncoder({ size: 64 }), {\n description: signaturesDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageEncoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nfunction getSignatureDecoder(): Decoder<SignatureBytes> {\n return mapDecoder(getBytesDecoder({ size: 64 }), bytes => bytes as SignatureBytes);\n}\n\nfunction getCompiledTransactionDecoder(): Decoder<CompiledTransaction> {\n return getStructDecoder(\n [\n [\n 'signatures',\n getArrayDecoder(getSignatureDecoder(), {\n description: signaturesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageDecoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nexport function getTransactionEncoder(): Encoder<\n CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n> {\n return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);\n}\n\nexport function getTransactionDecoder(\n lastValidBlockHeight?: bigint\n): Decoder<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return mapDecoder(getCompiledTransactionDecoder(), compiledTransaction =>\n decompileTransaction(compiledTransaction, lastValidBlockHeight)\n );\n}\n\nexport function getTransactionCodec(\n lastValidBlockHeight?: bigint\n): Codec<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));\n}\n","import { SignatureBytes } from '@solana/keys';\n\nimport { CompilableTransaction } from './compilable-transaction';\nimport { CompiledMessage, compileMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\n\nexport type CompiledTransaction = Readonly<{\n compiledMessage: CompiledMessage;\n signatures: SignatureBytes[];\n}>;\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 { Address, assertIsAddress } from '@solana/addresses';\nimport { pipe } from '@solana/functional';\nimport { AccountRole, IAccountMeta, IInstruction } from '@solana/instructions';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { Blockhash, setTransactionLifetimeUsingBlockhash } from './blockhash';\nimport { CompilableTransaction } from './compilable-transaction';\nimport { CompiledTransaction } from './compile-transaction';\nimport { createTransaction } from './create-transaction';\nimport { isAdvanceNonceAccountInstruction, Nonce, setTransactionLifetimeUsingDurableNonce } from './durable-nonce';\nimport { setTransactionFeePayer } from './fee-payer';\nimport { appendTransactionInstruction } from './instructions';\nimport { CompiledMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\nimport { TransactionVersion } from './types';\n\nfunction getAccountMetas(message: CompiledMessage): IAccountMeta[] {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts =\n message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n\n const accountMetas: IAccountMeta[] = [];\n\n let accountIndex = 0;\n for (let i = 0; i < numWritableSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlySignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY,\n });\n accountIndex++;\n }\n\n return accountMetas;\n}\n\nfunction convertInstruction(\n instruction: CompiledMessage['instructions'][0],\n accountMetas: IAccountMeta[]\n): IInstruction {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n // TODO coded error\n throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);\n }\n\n const accounts = instruction.accountIndices?.map(accountIndex => accountMetas[accountIndex]);\n const { data } = instruction;\n\n return {\n programAddress,\n ...(accounts && accounts.length ? { accounts } : {}),\n ...(data && data.length ? { data } : {}),\n };\n}\n\ntype LifetimeConstraint =\n | {\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n }\n | {\n nonce: Nonce;\n nonceAccountAddress: Address;\n nonceAuthorityAddress: Address;\n };\n\nfunction getLifetimeConstraint(\n messageLifetimeToken: string,\n firstInstruction?: IInstruction,\n lastValidBlockHeight?: bigint\n): LifetimeConstraint {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n // first instruction is not advance durable nonce, so use blockhash lifetime constraint\n return {\n blockhash: messageLifetimeToken as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n } else {\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = firstInstruction.accounts![0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = firstInstruction.accounts![2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n return {\n nonce: messageLifetimeToken as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n }\n}\n\nfunction convertSignatures(compiledTransaction: CompiledTransaction): ITransactionWithSignatures['signatures'] {\n const {\n compiledMessage: { staticAccounts },\n signatures,\n } = compiledTransaction;\n return signatures.reduce((acc, sig, index) => {\n // compiled transaction includes a fake all 0 signature if it hasn't been signed\n // we don't store those for the new tx model. So just skip if it's all 0s\n const allZeros = sig.every(byte => byte === 0);\n if (allZeros) return acc;\n\n const address = staticAccounts[index];\n return { ...acc, [address]: sig as SignatureBytes };\n }, {});\n}\n\nexport function decompileTransaction(\n compiledTransaction: CompiledTransaction,\n lastValidBlockHeight?: bigint\n): CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures) {\n const { compiledMessage } = compiledTransaction;\n\n // TODO: add support for address lookup tables\n if ('addressTableLookups' in compiledMessage && compiledMessage.addressTableLookups!.length > 0) {\n // TODO: coded error\n throw new Error('Cannot convert transaction with addressTableLookups');\n }\n\n const feePayer = compiledMessage.staticAccounts[0];\n // TODO: coded error\n if (!feePayer) throw new Error('No fee payer set in CompiledTransaction');\n\n const accountMetas = getAccountMetas(compiledMessage);\n\n const instructions: IInstruction[] = compiledMessage.instructions.map(compiledInstruction =>\n convertInstruction(compiledInstruction, accountMetas)\n );\n\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledMessage.lifetimeToken,\n firstInstruction,\n lastValidBlockHeight\n );\n\n const signatures = convertSignatures(compiledTransaction);\n\n return pipe(\n createTransaction({ version: compiledMessage.version as TransactionVersion }),\n tx => setTransactionFeePayer(feePayer, tx),\n tx =>\n instructions.reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n tx =>\n 'blockhash' in lifetimeConstraint\n ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx)\n : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),\n tx => (compiledTransaction.signatures.length ? { ...tx, signatures } : tx)\n );\n}\n","import { Address } from '@solana/addresses';\nimport { Signature } from '@solana/keys';\nimport { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport { RequestAirdropApi } from '@solana/rpc-core/dist/types/rpc-methods/requestAirdrop';\nimport { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment, LamportsUnsafeBeyond2Pow53Minus1 } from '@solana/rpc-types';\n\nimport { createDefaultSignatureOnlyRecentTransactionConfirmer } from './airdrop-confirmer';\n\ntype AirdropRequesterConfig = Readonly<{\n rpc: Rpc<RequestAirdropApi & GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>;\n}>;\n\nexport function createDefaultAirdropRequester({ rpc, rpcSubscriptions }: AirdropRequesterConfig) {\n const confirmSignatureOnlyTransaction = createDefaultSignatureOnlyRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n });\n return async function requestAirdrop(\n config: Omit<Parameters<typeof requestAndConfirmAirdrop>[0], 'confirmSignatureOnlyTransaction' | 'rpc'>\n ) {\n return await requestAndConfirmAirdrop({\n ...config,\n confirmSignatureOnlyTransaction,\n rpc,\n });\n };\n}\n\nexport async function requestAndConfirmAirdrop({\n abortSignal,\n commitment,\n confirmSignatureOnlyTransaction,\n lamports,\n recipientAddress,\n rpc,\n}: Readonly<{\n abortSignal?: AbortSignal;\n commitment: Commitment;\n confirmSignatureOnlyTransaction: ReturnType<typeof createDefaultSignatureOnlyRecentTransactionConfirmer>;\n lamports: LamportsUnsafeBeyond2Pow53Minus1;\n recipientAddress: Address;\n rpc: Rpc<RequestAirdropApi>;\n}>): Promise<Signature> {\n const airdropTransactionSignature = await rpc\n .requestAirdrop(recipientAddress, lamports, { commitment })\n .send({ abortSignal });\n await confirmSignatureOnlyTransaction({\n abortSignal,\n commitment,\n signature: airdropTransactionSignature,\n });\n return airdropTransactionSignature;\n}\n","import { Signature } from '@solana/keys';\nimport { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './transaction-confirmation-strategy-racer';\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\nimport { getTimeoutPromise } from './transaction-confirmation-strategy-timeout';\n\ninterface DefaultSignatureOnlyRecentTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>;\n}\n\ninterface WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig\n extends BaseTransactionConfirmationStrategyConfig {\n getTimeoutPromise: typeof getTimeoutPromise;\n signature: Signature;\n}\n\n/** @deprecated */\nexport function createDefaultSignatureOnlyRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultSignatureOnlyRecentTransactionConfirmerConfig) {\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions\n );\n return async function confirmSignatureOnlyRecentTransaction(\n config: Omit<\n Parameters<typeof waitForRecentTransactionConfirmationUntilTimeout>[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >\n ) {\n await waitForRecentTransactionConfirmationUntilTimeout({\n ...config,\n getRecentSignatureConfirmationPromise,\n getTimeoutPromise,\n });\n };\n}\n\n/** @deprecated */\nexport async function waitForRecentTransactionConfirmationUntilTimeout(\n config: WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig\n): Promise<void> {\n await raceStrategies(\n config.signature,\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise }) {\n return [\n getTimeoutPromise({\n abortSignal,\n commitment,\n }),\n ];\n }\n );\n}\n","import { Signature } from '@solana/keys';\nimport { Commitment } from '@solana/rpc-types';\n\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\n\nexport interface BaseTransactionConfirmationStrategyConfig {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n getRecentSignatureConfirmationPromise: ReturnType<typeof createRecentSignatureConfirmationPromiseFactory>;\n}\n\ntype WithNonNullableAbortSignal<T> = Omit<T, 'abortSignal'> & Readonly<{ abortSignal: AbortSignal }>;\n\nexport async function raceStrategies<TConfig extends BaseTransactionConfirmationStrategyConfig>(\n signature: Signature,\n config: TConfig,\n getSpecificStrategiesForRace: (config: WithNonNullableAbortSignal<TConfig>) => readonly Promise<unknown>[]\n) {\n const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;\n callerAbortSignal?.throwIfAborted();\n const abortController = new AbortController();\n if (callerAbortSignal) {\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n }\n try {\n const specificStrategies = getSpecificStrategiesForRace({\n ...config,\n abortSignal: abortController.signal,\n });\n return await Promise.race([\n getRecentSignatureConfirmationPromise({\n abortSignal: abortController.signal,\n commitment,\n signature,\n }),\n ...specificStrategies,\n ]);\n } finally {\n abortController.abort();\n }\n}\n","import { Signature } from '@solana/keys';\nimport { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\n\ntype GetRecentSignatureConfirmationPromiseFn = (config: {\n abortSignal: AbortSignal;\n commitment: Commitment;\n signature: Signature;\n}) => Promise<void>;\n\nexport function createRecentSignatureConfirmationPromiseFactory(\n rpc: Rpc<GetSignatureStatusesApi>,\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>\n): GetRecentSignatureConfirmationPromiseFn {\n return async function getRecentSignatureConfirmationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n signature,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for status changes to a signature.\n */\n const signatureStatusNotifications = await rpcSubscriptions\n .signatureNotifications(signature, { commitment })\n .subscribe({ abortSignal: abortController.signal });\n const signatureDidCommitPromise = (async () => {\n for await (const signatureStatusNotification of signatureStatusNotifications) {\n if (signatureStatusNotification.value.err) {\n // TODO: Coded error.\n throw new Error(`The transaction with signature \\`${signature}\\` failed.`, {\n cause: signatureStatusNotification.value.err,\n });\n } else {\n return;\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current status.\n * This will only yield a result if the signature is still in the status cache.\n */\n const signatureStatusLookupPromise = (async () => {\n const { value: signatureStatusResults } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: abortController.signal });\n const signatureStatus = signatureStatusResults[0];\n if (\n signatureStatus &&\n signatureStatus.confirmationStatus &&\n commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0\n ) {\n return;\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await Promise.race([signatureDidCommitPromise, signatureStatusLookupPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import { Commitment } from '@solana/rpc-types';\n\ntype Config = Readonly<{\n abortSignal: AbortSignal;\n commitment: Commitment;\n}>;\n\nexport async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }: Config) {\n return await new Promise((_, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n clearTimeout(timeoutId);\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n callerAbortSignal.addEventListener('abort', handleAbort);\n const timeoutMs = commitment === 'processed' ? 30_000 : 60_000;\n const startMs = performance.now();\n const timeoutId =\n // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure\n // elapsed time instead of active time.\n // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static\n setTimeout(() => {\n const elapsedMs = performance.now() - startMs;\n reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, 'TimeoutError'));\n }, timeoutMs);\n });\n}\n","import { pipe } from '@solana/functional';\nimport {\n createSolanaRpcApi,\n createSolanaRpcSubscriptionsApi,\n createSolanaRpcSubscriptionsApi_UNSTABLE,\n SolanaRpcMethods,\n SolanaRpcSubscriptions,\n SolanaRpcSubscriptionsUnstable,\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// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\n\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\nimport { getRpcSubscriptionsWithSubscriptionCoalescing } from './rpc-subscription-coalescer';\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 pipe(\n createJsonSubscriptionRpc({\n ...config,\n api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG),\n }),\n rpcSubscriptions =>\n getRpcSubscriptionsWithSubscriptionCoalescing({\n getDeduplicationKey: (...args) => fastStableStringify(args),\n rpcSubscriptions,\n })\n );\n}\n\nexport function createSolanaRpcSubscriptions_UNSTABLE(\n config: Omit<Parameters<typeof createJsonSubscriptionRpc>[0], 'api'>\n): RpcSubscriptions<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return createJsonSubscriptionRpc({\n ...config,\n api: createSolanaRpcSubscriptionsApi_UNSTABLE(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","export type KeyPathWildcard = { readonly __brand: unique symbol };\n\nexport const KEYPATH_WILDCARD = {} as KeyPathWildcard;\n","import { IRpcSubscriptionsApi } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { KeyPath } from './response-patcher';\nimport { KEYPATH_WILDCARD } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\nimport { SolanaRpcSubscriptions, SolanaRpcSubscriptionsUnstable } from './rpc-subscriptions';\n\n// Numeric values nested in `jsonParsed` accounts\nconst 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 ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'olderTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'newerTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n];\nconst 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\ntype AllowedNumericKeypaths<TApi> = Partial<Record<keyof TApi, readonly KeyPath[]>>;\n\nlet memoizedNotificationKeypaths: AllowedNumericKeypaths<\n IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>\n>;\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 IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>\n> {\n if (!memoizedNotificationKeypaths) {\n memoizedNotificationKeypaths = {\n accountNotifications: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n blockNotifications: [\n ['value', 'block', 'blockTime'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['value', 'block', 'transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'index',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\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 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlySignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlyUnsignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numRequiredSignatures',\n ],\n ['value', 'block', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n programNotifications: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n };\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 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 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 { AccountNotificationsApi } from './account-notifications';\nimport { BlockNotificationsApi } from './block-notifications';\nimport { LogsNotificationsApi } from './logs-notifications';\nimport { ProgramNotificationsApi } from './program-notifications';\nimport { RootNotificationsApi } from './root-notifications';\nimport { SignatureNotificationsApi } from './signature-notifications';\nimport { SlotNotificationsApi } from './slot-notifications';\nimport { SlotsUpdatesNotificationsApi } from './slots-updates-notifications';\nimport { VoteNotificationsApi } from './vote-notifications';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcSubscriptions = AccountNotificationsApi &\n BlockNotificationsApi &\n LogsNotificationsApi &\n ProgramNotificationsApi &\n RootNotificationsApi &\n SignatureNotificationsApi &\n SlotNotificationsApi;\nexport type SolanaRpcSubscriptionsUnstable = SlotsUpdatesNotificationsApi & VoteNotificationsApi;\n\nexport function createSolanaRpcSubscriptionsApi(\n config?: Config\n): IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return new Proxy({} as IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<\n TNotificationName extends keyof IRpcSubscriptionsApi<\n SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable\n >\n >(\n ...args: Parameters<\n NonNullable<\n ProxyHandler<IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>>['get']\n >\n >\n ) {\n const [_, p] = args;\n const notificationName = p.toString() as keyof (SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable);\n return function (\n ...rawParams: Parameters<\n (SolanaRpcSubscriptions &\n SolanaRpcSubscriptionsUnstable)[TNotificationName] extends CallableFunction\n ? (SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable)[TNotificationName]\n : never\n >\n ): RpcSubscription<\n ReturnType<(SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable)[TNotificationName]>\n > {\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\nexport function createSolanaRpcSubscriptionsApi_UNSTABLE(\n config?: Config\n): IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return createSolanaRpcSubscriptionsApi(config) as IRpcSubscriptionsApi<\n SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable\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 registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\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({ abortSignal }: SubscribeOptions): Promise<AsyncIterable<TNotification>> {\n 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 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 handleConnectionCleanup() {\n abortSignal.removeEventListener('abort', handleCleanup);\n }\n registerIterableCleanup(connection, handleConnectionCleanup);\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 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 url: string;\n}>;\n\nexport function createHttpTransport({ headers, url }: Config): IRpcTransport {\n if (__DEV__ && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\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 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\nconst EXPLICIT_ABORT_TOKEN = Symbol(\n __DEV__\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly aborted by the user\"\n : undefined\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 errorAndClearAllIteratorStates(reason: unknown) {\n const errorCallbacks = [...iteratorState.values()]\n .filter((state): state is Extract<IteratorState, { __hasPolled: true }> => state.__hasPolled)\n .map(({ onError }) => onError);\n iteratorState.clear();\n errorCallbacks.forEach(cb => {\n try {\n cb(reason);\n } catch {\n /* empty */\n }\n });\n }\n function handleAbort() {\n errorAndClearAllIteratorStates(EXPLICIT_ABORT_TOKEN);\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 errorAndClearAllIteratorStates(ev);\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((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onError: reject,\n onMessage: resolve,\n });\n });\n } catch (e) {\n if (e === EXPLICIT_ABORT_TOKEN) {\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 { PendingRpcSubscription, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { getCachedAbortableIterableFactory } from './cached-abortable-iterable';\n\ntype CacheKey = string | undefined;\ntype Config<TRpcSubscriptionsMethods> = Readonly<{\n getDeduplicationKey: GetDeduplicationKeyFn;\n rpcSubscriptions: RpcSubscriptions<TRpcSubscriptionsMethods>;\n}>;\ntype GetDeduplicationKeyFn = (subscriptionMethod: string | symbol, payload: unknown) => CacheKey;\n\nconst EXPLICIT_ABORT_TOKEN = Symbol(\n __DEV__\n ? \"This symbol is thrown from a subscription's iterator when the subscription is \" +\n 'explicitly aborted by the user'\n : undefined\n);\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nexport function getRpcSubscriptionsWithSubscriptionCoalescing<TRpcSubscriptionsMethods>({\n getDeduplicationKey,\n rpcSubscriptions,\n}: Config<TRpcSubscriptionsMethods>): RpcSubscriptions<TRpcSubscriptionsMethods> {\n const cache = new Map<CacheKey, PendingRpcSubscription<unknown>>();\n return new Proxy(rpcSubscriptions, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n const subscriptionMethod = Reflect.get(target, p, receiver);\n if (typeof subscriptionMethod !== 'function') {\n return subscriptionMethod;\n }\n return function (...rawParams: unknown[]) {\n const deduplicationKey = getDeduplicationKey(p, rawParams);\n if (deduplicationKey === undefined) {\n return (subscriptionMethod as CallableFunction)(...rawParams);\n }\n if (cache.has(deduplicationKey)) {\n return cache.get(deduplicationKey)!;\n }\n const iterableFactory = getCachedAbortableIterableFactory<\n Parameters<PendingRpcSubscription<unknown>['subscribe']>,\n AsyncIterable<unknown>\n >({\n getAbortSignalFromInputArgs: ({ abortSignal }) => abortSignal,\n getCacheEntryMissingError(deduplicationKey) {\n // TODO: Coded error.\n return new Error(\n `Found no cache entry for subscription with deduplication key \\`${deduplicationKey?.toString()}\\``\n );\n },\n getCacheKeyFromInputArgs: () => deduplicationKey,\n async onCacheHit(_iterable, _config) {\n /**\n * This transport's goal is to prevent duplicate subscriptions from\n * being made. If a cached iterable] is found, do not send the subscribe\n * message again.\n */\n },\n async onCreateIterable(abortSignal, config) {\n const pendingSubscription = (subscriptionMethod as CallableFunction)(\n ...rawParams\n ) as PendingRpcSubscription<unknown>;\n const iterable = await pendingSubscription.subscribe({\n ...config,\n abortSignal,\n });\n registerIterableCleanup(iterable, () => {\n cache.delete(deduplicationKey);\n });\n return iterable;\n },\n });\n const pendingSubscription: PendingRpcSubscription<unknown> = {\n async subscribe(...args) {\n const iterable = await iterableFactory(...args);\n const { abortSignal } = args[0];\n let abortPromise;\n return {\n ...iterable,\n async *[Symbol.asyncIterator]() {\n abortPromise ||= abortSignal.aborted\n ? Promise.reject(EXPLICIT_ABORT_TOKEN)\n : new Promise<never>((_, reject) => {\n abortSignal.addEventListener('abort', () => {\n reject(EXPLICIT_ABORT_TOKEN);\n });\n });\n try {\n const iterator = iterable[Symbol.asyncIterator]();\n while (true) {\n const iteratorResult = await Promise.race([iterator.next(), abortPromise]);\n if (iteratorResult.done) {\n return;\n } else {\n yield iteratorResult.value;\n }\n }\n } catch (e) {\n if (e === EXPLICIT_ABORT_TOKEN) {\n return;\n }\n cache.delete(deduplicationKey);\n throw e;\n }\n },\n };\n },\n };\n cache.set(deduplicationKey, pendingSubscription);\n return pendingSubscription;\n };\n },\n });\n}\n","type CacheEntry<TIterable extends AsyncIterable<unknown>> = {\n abortController: AbortController;\n iterable: Promise<TIterable> | TIterable;\n purgeScheduled: boolean;\n referenceCount: number;\n};\ntype CacheKey = string | symbol;\ntype Config<TInput extends unknown[], TIterable extends AsyncIterable<unknown>> = Readonly<{\n getAbortSignalFromInputArgs: (...args: TInput) => AbortSignal;\n getCacheEntryMissingError: (cacheKey: CacheKey) => Error;\n getCacheKeyFromInputArgs: (...args: TInput) =>\n | CacheKey\n // `undefined` implies 'do not cache'\n | undefined;\n onCacheHit: (iterable: TIterable, ...args: TInput) => Promise<void>;\n onCreateIterable: (abortSignal: AbortSignal, ...args: TInput) => Promise<TIterable>;\n}>;\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nexport function getCachedAbortableIterableFactory<TInput extends unknown[], TIterable extends AsyncIterable<unknown>>({\n getAbortSignalFromInputArgs,\n getCacheEntryMissingError,\n getCacheKeyFromInputArgs,\n onCacheHit,\n onCreateIterable,\n}: Config<TInput, TIterable>): (...args: TInput) => Promise<TIterable> {\n const cache = new Map<CacheKey, CacheEntry<TIterable>>();\n function getCacheEntryOrThrow(cacheKey: CacheKey) {\n const currentCacheEntry = cache.get(cacheKey);\n if (!currentCacheEntry) {\n throw getCacheEntryMissingError(cacheKey);\n }\n return currentCacheEntry;\n }\n return async (...args: TInput) => {\n const cacheKey = getCacheKeyFromInputArgs(...args);\n const signal = getAbortSignalFromInputArgs(...args);\n if (cacheKey === undefined) {\n return await onCreateIterable(signal, ...args);\n }\n const cleanup = () => {\n cache.delete(cacheKey);\n signal.removeEventListener('abort', handleAbort);\n };\n const handleAbort = () => {\n const cacheEntry = getCacheEntryOrThrow(cacheKey);\n if (cacheEntry.purgeScheduled !== true) {\n cacheEntry.purgeScheduled = true;\n globalThis.queueMicrotask(() => {\n cacheEntry.purgeScheduled = false;\n if (cacheEntry.referenceCount === 0) {\n cacheEntry.abortController.abort();\n cleanup();\n }\n });\n }\n cacheEntry.referenceCount--;\n };\n signal.addEventListener('abort', handleAbort);\n try {\n const cacheEntry = cache.get(cacheKey);\n if (!cacheEntry) {\n const singletonAbortController = new AbortController();\n const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);\n const newCacheEntry: CacheEntry<TIterable> = {\n abortController: singletonAbortController,\n iterable: newIterablePromise,\n purgeScheduled: false,\n referenceCount: 1,\n };\n cache.set(cacheKey, newCacheEntry);\n const newIterable = await newIterablePromise;\n registerIterableCleanup(newIterable, cleanup);\n newCacheEntry.iterable = newIterable;\n return newIterable;\n } else {\n cacheEntry.referenceCount++;\n const iterableOrIterablePromise = cacheEntry.iterable;\n const cachedIterable =\n 'then' in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;\n await onCacheHit(cachedIterable, ...args);\n return cachedIterable;\n }\n } catch (e) {\n cleanup();\n throw e;\n }\n };\n}\n","import { pipe } from '@solana/functional';\nimport { 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 pipe(\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 transport => getRpcTransportWithRequestCoalescing(transport, 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\nfunction isJsonRpcPayload(payload: unknown): payload is Readonly<{ method: string; params: unknown }> {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n return (\n 'jsonrpc' in payload &&\n payload.jsonrpc === '2.0' &&\n 'method' in payload &&\n typeof payload.method === 'string' &&\n 'params' in payload\n );\n}\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n return isJsonRpcPayload(payload) ? fastStableStringify([payload.method, payload.params]) : undefined;\n}\n","import { pipe } from '@solana/functional';\nimport { createWebSocketTransport } from '@solana/rpc-transport';\nimport { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getWebSocketTransportWithAutoping } from './rpc-websocket-autopinger';\nimport { getWebSocketTransportWithConnectionSharding } from './rpc-websocket-connection-sharding';\n\nexport function createDefaultRpcSubscriptionsTransport(\n config: Omit<Parameters<typeof createWebSocketTransport>[0], 'sendBufferHighWatermark'> & {\n /**\n * You might like to open more subscriptions per connection than your RPC provider allows\n * for. Using the initial payload as input, return a shard key from this method to assign\n * subscriptions to separate connections. One socket will be opened per shard key.\n */\n getShard?: (payload: unknown) => string;\n intervalMs?: number;\n sendBufferHighWatermark?: number;\n }\n): IRpcWebSocketTransport {\n const { getShard, intervalMs, ...rest } = config;\n return pipe(\n 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 transport =>\n getWebSocketTransportWithAutoping({\n intervalMs: intervalMs ?? 5_000,\n transport,\n }),\n transport =>\n getWebSocketTransportWithConnectionSharding({\n getShard,\n transport,\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 sendPing() {\n connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);\n }\n function restartPingTimer() {\n clearInterval(intervalId);\n intervalId = setInterval(sendPing, 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 if (handleOffline) {\n globalThis.window.removeEventListener('offline', handleOffline);\n }\n if (handleOnline) {\n globalThis.window.removeEventListener('online', handleOnline);\n }\n }\n })();\n if (!__BROWSER__ || globalThis.navigator.onLine) {\n restartPingTimer();\n }\n let handleOffline;\n let handleOnline;\n if (__BROWSER__) {\n handleOffline = () => {\n clearInterval(intervalId);\n };\n handleOnline = () => {\n sendPing();\n restartPingTimer();\n };\n globalThis.window.addEventListener('offline', handleOffline);\n globalThis.window.addEventListener('online', handleOnline);\n }\n }\n return pingableConnections.get(connection)!;\n };\n}\n","import { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getCachedAbortableIterableFactory } from './cached-abortable-iterable';\n\ntype Config = Readonly<{\n /**\n * You might like to open more subscriptions per connection than your RPC provider allows for.\n * Using the initial payload as input, return a shard key from this method to assign\n * subscriptions to separate connections. One socket will be opened per shard key.\n */\n getShard?: (payload: unknown) => string | symbol;\n transport: IRpcWebSocketTransport;\n}>;\n\nconst NULL_SHARD_CACHE_KEY = Symbol(\n __DEV__ ? 'Cache key to use when there is no connection sharding strategy' : undefined\n);\n\nexport function getWebSocketTransportWithConnectionSharding({ getShard, transport }: Config): IRpcWebSocketTransport {\n return getCachedAbortableIterableFactory({\n getAbortSignalFromInputArgs: ({ signal }) => signal,\n getCacheEntryMissingError(shardKey) {\n // TODO: Coded error.\n return new Error(`Found no cache entry for connection with shard key \\`${shardKey?.toString()}\\``);\n },\n getCacheKeyFromInputArgs: ({ payload }) => (getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY),\n onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),\n onCreateIterable: (abortSignal, config) =>\n transport({\n ...config,\n signal: abortSignal,\n }),\n });\n}\n","import { Signature } from '@solana/keys';\nimport { SendTransactionApi } from '@solana/rpc-core/dist/types/rpc-methods/sendTransaction';\nimport { Rpc } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\nimport {\n BaseTransaction,\n getBase64EncodedWireTransaction,\n IDurableNonceTransaction,\n IFullySignedTransaction,\n ITransactionWithBlockhashLifetime,\n ITransactionWithFeePayer,\n} from '@solana/transactions';\n\nimport {\n createDefaultDurableNonceTransactionConfirmer,\n createDefaultRecentTransactionConfirmer,\n} from './transaction-confirmation';\n\ninterface DurableNonceTransactionSenderFactoryConfig {\n rpc: Rpc<SendTransactionApi> & Parameters<typeof createDefaultDurableNonceTransactionConfirmer>[0]['rpc'];\n rpcSubscriptions: Parameters<typeof createDefaultDurableNonceTransactionConfirmer>[0]['rpcSubscriptions'];\n}\n\ninterface TransactionWithBlockhashLifetimeSenderFactoryConfig {\n rpc: Rpc<SendTransactionApi> & Parameters<typeof createDefaultRecentTransactionConfirmer>[0]['rpc'];\n rpcSubscriptions: Parameters<typeof createDefaultRecentTransactionConfirmer>[0]['rpcSubscriptions'];\n}\n\ninterface SendAndConfirmDurableNonceTransactionConfig\n extends SendTransactionInternalConfig,\n SendTransactionConfigWithoutEncoding {\n confirmDurableNonceTransaction: ReturnType<typeof createDefaultDurableNonceTransactionConfirmer>;\n transaction: SendableTransaction & IDurableNonceTransaction;\n}\n\ninterface SendAndConfirmTransactionWithBlockhashLifetimeConfig\n extends SendTransactionInternalConfig,\n SendTransactionConfigWithoutEncoding {\n confirmRecentTransaction: ReturnType<typeof createDefaultRecentTransactionConfirmer>;\n transaction: SendableTransaction & ITransactionWithBlockhashLifetime;\n}\n\ninterface SendTransactionInternalConfig extends SendTransactionConfigWithoutEncoding {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n rpc: Rpc<SendTransactionApi>;\n transaction: SendableTransaction;\n}\n\ntype SendableTransaction = BaseTransaction &\n (ITransactionWithBlockhashLifetime | IDurableNonceTransaction) &\n ITransactionWithFeePayer &\n IFullySignedTransaction;\ntype SendTransactionConfig = Parameters<SendTransactionApi['sendTransaction']>[1];\ninterface SendTransactionConfigWithoutEncoding extends Omit<NonNullable<SendTransactionConfig>, 'encoding'> {}\n\nfunction getSendTransactionConfigWithAdjustedPreflightCommitment(\n commitment: Commitment,\n config?: SendTransactionConfigWithoutEncoding\n): SendTransactionConfigWithoutEncoding | void {\n if (\n // The developer has supplied no value for `preflightCommitment`.\n !config?.preflightCommitment &&\n // The value of `commitment` is lower than the server default of `preflightCommitment`.\n commitmentComparator(commitment, 'finalized' /* default value of `preflightCommitment` */) < 0\n ) {\n return {\n ...config,\n // In the common case, it is unlikely that you want to simulate a transaction at\n // `finalized` commitment when your standard of commitment for confirming the\n // transaction is lower. Cap the simulation commitment level to the level of the\n // confirmation commitment.\n preflightCommitment: commitment,\n };\n }\n // The commitment at which the developer wishes to confirm the transaction is at least as\n // high as the commitment at which they want to simulate it. Honour the config as-is.\n return config;\n}\n\nasync function sendTransaction_INTERNAL({\n abortSignal,\n commitment,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendTransactionInternalConfig): Promise<Signature> {\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);\n return await rpc\n .sendTransaction(base64EncodedWireTransaction, {\n ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),\n encoding: 'base64',\n })\n .send({ abortSignal });\n}\n\nexport function createDefaultDurableNonceTransactionSender({\n rpc,\n rpcSubscriptions,\n}: DurableNonceTransactionSenderFactoryConfig) {\n const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n });\n return async function sendDurableNonceTransaction(\n transaction: BaseTransaction & ITransactionWithFeePayer & IDurableNonceTransaction & IFullySignedTransaction,\n config: Omit<\n Parameters<typeof sendAndConfirmDurableNonceTransaction>[0],\n 'confirmDurableNonceTransaction' | 'rpc' | 'transaction'\n >\n ): Promise<void> {\n await sendAndConfirmDurableNonceTransaction({\n ...config,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n });\n };\n}\n\nexport function createDefaultTransactionSender({\n rpc,\n rpcSubscriptions,\n}: TransactionWithBlockhashLifetimeSenderFactoryConfig) {\n const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n });\n return async function sendTransaction(\n transaction: SendableTransaction & ITransactionWithBlockhashLifetime,\n config: Omit<\n Parameters<typeof sendAndConfirmTransaction>[0],\n 'confirmRecentTransaction' | 'rpc' | 'transaction'\n >\n ): Promise<void> {\n await sendAndConfirmTransaction({\n ...config,\n confirmRecentTransaction,\n rpc,\n transaction,\n });\n };\n}\n\nexport async function sendAndConfirmDurableNonceTransaction({\n abortSignal,\n commitment,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmDurableNonceTransactionConfig): Promise<Signature> {\n const transactionSignature = await sendTransaction_INTERNAL({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmDurableNonceTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n\nexport async function sendAndConfirmTransaction({\n abortSignal,\n commitment,\n confirmRecentTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmTransactionWithBlockhashLifetimeConfig): Promise<Signature> {\n const transactionSignature = await sendTransaction_INTERNAL({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmRecentTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n","import { Slot } from '@solana/rpc-core/dist/types/rpc-methods/common';\nimport type { GetAccountInfoApi } from '@solana/rpc-core/dist/types/rpc-methods/getAccountInfo';\nimport type { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport type { AccountNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/account-notifications';\nimport type { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport type { SlotNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/slot-notifications';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport {\n getSignatureFromTransaction,\n IDurableNonceTransaction,\n ITransactionWithFeePayer,\n ITransactionWithSignatures,\n} from '@solana/transactions';\n\nimport { createBlockHeightExceedencePromiseFactory } from './transaction-confirmation-strategy-blockheight';\nimport { createNonceInvalidationPromiseFactory } from './transaction-confirmation-strategy-nonce';\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './transaction-confirmation-strategy-racer';\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\n\ninterface DefaultDurableNonceTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi & GetAccountInfoApi>;\n rpcSubscriptions: RpcSubscriptions<AccountNotificationsApi & SignatureNotificationsApi>;\n}\n\ninterface DefaultRecentTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi & SlotNotificationsApi>;\n}\n\ninterface WaitForDurableNonceTransactionConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getNonceInvalidationPromise: ReturnType<typeof createNonceInvalidationPromiseFactory>;\n transaction: ITransactionWithFeePayer & ITransactionWithSignatures & IDurableNonceTransaction;\n}\n\ninterface WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig\n extends BaseTransactionConfirmationStrategyConfig {\n getBlockHeightExceedencePromise: ReturnType<typeof createBlockHeightExceedencePromiseFactory>;\n transaction: ITransactionWithFeePayer &\n ITransactionWithSignatures &\n Readonly<{\n lifetimeConstraint: {\n lastValidBlockHeight: Slot;\n };\n }>;\n}\n\nexport function createDefaultDurableNonceTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultDurableNonceTransactionConfirmerConfig) {\n const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions\n );\n return async function confirmDurableNonceTransaction(\n config: Omit<\n Parameters<typeof waitForDurableNonceTransactionConfirmation>[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >\n ) {\n await waitForDurableNonceTransactionConfirmation({\n ...config,\n getNonceInvalidationPromise,\n getRecentSignatureConfirmationPromise,\n });\n };\n}\n\nexport function createDefaultRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultRecentTransactionConfirmerConfig) {\n const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory(rpcSubscriptions);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions\n );\n return async function confirmRecentTransaction(\n config: Omit<\n Parameters<typeof waitForRecentTransactionConfirmation>[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >\n ) {\n await waitForRecentTransactionConfirmation({\n ...config,\n getBlockHeightExceedencePromise,\n getRecentSignatureConfirmationPromise,\n });\n };\n}\n\nexport async function waitForDurableNonceTransactionConfirmation(\n config: WaitForDurableNonceTransactionConfirmationConfig\n): Promise<void> {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {\n return [\n getNonceInvalidationPromise({\n abortSignal,\n commitment,\n currentNonceValue: transaction.lifetimeConstraint.nonce,\n nonceAccountAddress: transaction.instructions[0].accounts[0].address,\n }),\n ];\n }\n );\n}\n\nexport async function waitForRecentTransactionConfirmation(\n config: WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig\n): Promise<void> {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, getBlockHeightExceedencePromise, transaction }) {\n return [\n getBlockHeightExceedencePromise({\n abortSignal,\n lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight,\n }),\n ];\n }\n );\n}\n","import { Slot } from '@solana/rpc-core/dist/types/rpc-methods/common';\nimport type { SlotNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/slot-notifications';\nimport { RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\ntype GetBlockHeightExceedencePromiseFn = (config: {\n abortSignal: AbortSignal;\n lastValidBlockHeight: Slot;\n}) => Promise<void>;\n\nexport function createBlockHeightExceedencePromiseFactory(\n rpcSubscriptions: RpcSubscriptions<SlotNotificationsApi>\n): GetBlockHeightExceedencePromiseFn {\n return async function getBlockHeightExceedencePromise({ abortSignal: callerAbortSignal, lastValidBlockHeight }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n const slotNotifications = await rpcSubscriptions\n .slotNotifications()\n .subscribe({ abortSignal: abortController.signal });\n try {\n for await (const slotNotification of slotNotifications) {\n if (slotNotification.slot > lastValidBlockHeight) {\n // TODO: Coded error.\n throw new Error(\n 'The network has progressed past the last block for which this transaction ' +\n 'could have committed.'\n );\n }\n }\n } finally {\n abortController.abort();\n }\n };\n}\n","import { Address } from '@solana/addresses';\nimport { getBase58Decoder, getBase64Encoder } from '@solana/codecs-strings';\nimport { Base64EncodedDataResponse } from '@solana/rpc-core/dist/types/rpc-methods/common';\nimport { GetAccountInfoApi } from '@solana/rpc-core/dist/types/rpc-methods/getAccountInfo';\nimport { AccountNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/account-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment } from '@solana/rpc-types';\nimport { Nonce } from '@solana/transactions';\n\ntype GetNonceInvalidationPromiseFn = (config: {\n abortSignal: AbortSignal;\n commitment: Commitment;\n currentNonceValue: Nonce;\n nonceAccountAddress: Address;\n}) => Promise<void>;\n\nconst NONCE_VALUE_OFFSET =\n 4 + // version(u32)\n 4 + // state(u32)\n 32; // nonce authority(pubkey)\n// Then comes the nonce value.\n\nexport function createNonceInvalidationPromiseFactory(\n rpc: Rpc<GetAccountInfoApi>,\n rpcSubscriptions: RpcSubscriptions<AccountNotificationsApi>\n): GetNonceInvalidationPromiseFn {\n return async function getNonceInvalidationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n currentNonceValue,\n nonceAccountAddress,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for nonce account changes.\n */\n const accountNotifications = await rpcSubscriptions\n .accountNotifications(nonceAccountAddress, { commitment, encoding: 'base64' })\n .subscribe({ abortSignal: abortController.signal });\n const base58Decoder = getBase58Decoder();\n const base64Encoder = getBase64Encoder();\n function getNonceFromAccountData([base64EncodedBytes]: Base64EncodedDataResponse): Nonce {\n const data = base64Encoder.encode(base64EncodedBytes);\n const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);\n return base58Decoder.decode(nonceValueBytes)[0] as Nonce;\n }\n const nonceAccountDidAdvancePromise = (async () => {\n for await (const accountNotification of accountNotifications) {\n const nonceValue = getNonceFromAccountData(accountNotification.value.data);\n if (nonceValue !== currentNonceValue) {\n throw new Error(\n `The nonce \\`${currentNonceValue}\\` is no longer valid. It has advanced ` +\n `to \\`${nonceValue}\\`.`\n );\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current nonce\n * value to check if it has already been advanced.\n */\n const nonceIsAlreadyInvalidPromise = (async () => {\n const { value: nonceAccount } = await rpc\n .getAccountInfo(nonceAccountAddress, {\n commitment,\n dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },\n encoding: 'base58',\n })\n .send({ abortSignal: abortController.signal });\n if (!nonceAccount) {\n throw new Error(`No nonce account could be found at address \\`${nonceAccountAddress}\\`.`);\n }\n const nonceValue =\n // This works because we asked for the exact slice of data representing the nonce\n // value, and furthermore asked for it in `base58` encoding.\n nonceAccount.data[0] as unknown as Nonce;\n if (nonceValue !== currentNonceValue) {\n throw new Error(\n `The nonce \\`${currentNonceValue}\\` is no longer valid. It has advanced to \\`${nonceValue}\\`.`\n );\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);\n } finally {\n abortController.abort();\n }\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","../../addresses/dist/index.browser.js","../../codecs-core/src/assertions.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/codec.ts","../../codecs-core/src/combine-codec.ts","../../codecs-core/src/fix-codec.ts","../../codecs-core/src/map-codec.ts","../../codecs-numbers/src/assertions.ts","../../codecs-numbers/src/f32.ts","../../codecs-numbers/src/utils.ts","../../codecs-numbers/src/i64.ts","../../codecs-numbers/src/i8.ts","../../codecs-numbers/src/short-u16.ts","../../codecs-numbers/src/u128.ts","../../codecs-numbers/src/u16.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/baseX-reslice.ts","../../codecs-strings/src/base64.ts","../../codecs-strings/src/null-characters.ts","../../codecs-strings/src/string.ts","../../codecs-strings/src/utf8.ts","../../assertions/src/subtle-crypto.ts","../../instructions/src/roles.ts","../../keys/src/key-pair.ts","../../keys/src/private-key.ts","../../keys/src/signatures.ts","../../rpc-types/src/commitment.ts","../../rpc-types/src/lamports.ts","../../rpc-types/src/stringified-bigint.ts","../../rpc-types/src/stringified-number.ts","../../rpc-types/src/unix-timestamp.ts","../../codecs-data-structures/dist/index.browser.js","../../functional/src/pipe.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/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/transaction-version.ts","../../transactions/src/serializers/transaction.ts","../../transactions/src/compile-transaction.ts","../../transactions/src/decompile-transaction.ts","../src/airdrop.ts","../src/airdrop-confirmer.ts","../src/transaction-confirmation-strategy-racer.ts","../src/transaction-confirmation-strategy-recent-signature.ts","../src/transaction-confirmation-strategy-timeout.ts","../src/rpc.ts","../../rpc-core/src/params-patcher.ts","../../rpc-core/src/response-patcher-types.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-subscription-coalescer.ts","../src/cached-abortable-iterable.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","../src/rpc-websocket-connection-sharding.ts","../src/send-transaction.ts","../src/transaction-confirmation.ts","../src/transaction-confirmation-strategy-blockheight.ts","../src/transaction-confirmation-strategy-nonce.ts"],"names":["combineCodec","createDecoder","createEncoder","alphabet","e2","base58Encoder","e","AccountRole","signature","AccountRole2","IS_WRITABLE_BITMASK","isSignerRole","mergeRoles","address","isWritableRole","getAddressDecoder","getStructDecoder","getU8Encoder","getU8Decoder","getStructEncoder","getArrayEncoder","getArrayDecoder","mapEncoder","getShortU16Decoder","mapDecoder","getTimeoutPromise","lamports","visitNode","__DEV__","makeProxy","index_browser_default","resolve","reject","registerIterableCleanup","EXPLICIT_ABORT_TOKEN","deduplicationKey","pendingSubscription","fastStableStringify","import_fast_stable_stringify","normalizeHeaders","args","base58Decoder"],"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,U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ACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA,CAAC,SAAS,SAAS,WAAW,kBAAkB,YAAY;MAChE;MACA,sBAAsB,0BAA0B,QAAQ,CAAA,MAAK;QACzD,CAAC,SAAS,kBAAkB,WAAW,GAAG,CAAC;QAC3C,CAAC,kBAAkB,WAAW,GAAG,CAAC;MACtC,CAAC;IACL;EACJ;AACA,SAAO;AACX;AAMO,SAAS,uCAAsG;AAClH,MAAI,CAAC,0BAA0B;AAC3B,+BAA2B;MACvB,gBAAgB,0BAA0B,IAAI,CAAA,MAAK,CAAC,SAAS,GAAG,CAAC,CAAC;MAClE,UAAU;QACN,CAAC,WAAW;QACZ,CAAC,gBAAgB,kBAAkB,QAAQ,oBAAoB,kBAAkB,cAAc;QAC/F;UACI;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA,CAAC,gBAAgB,kBAAkB,QAAQ,qBAAqB,kBAAkB,cAAc;QAChG;UACI;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA,CAAC,gBAAgB,kBAAkB,QAAQ,WAAW,kBAAkB,YAAY;QACpF,CAAC,gBAAgB,kBAAkB,QAAQ,qBAAqB,kBAAkB,OAAO;QACzF;UACI;UACA;UACA;UACA;UACA;UACA;UAC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sCAAsC;AAAA,MACxC,GAAG;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,+BAA+B;AAAA,EAC3C;AAAA,EACA;AACJ,GAAwD;AACpD,QAAM,2BAA2B,wCAAwC;AAAA,IACrE;AAAA,IACA;AAAA,EACJ,CAAC;AACD,SAAO,eAAe,gBAClB,aACA,QAIa;AACb,UAAM,0BAA0B;AAAA,MAC5B,GAAG;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;AAEA,eAAsB,sCAAsC;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACP,GAAoE;AAChE,QAAM,uBAAuB,MAAM,yBAAyB;AAAA,IACxD,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ,CAAC;AACD,QAAM,+BAA+B;AAAA,IACjC;AAAA,IACA;AAAA,IACA;AAAA,EACJ,CAAC;AACD,SAAO;AACX;AAEA,eAAsB,0BAA0B;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACP,GAA6E;AACzE,QAAM,uBAAuB,MAAM,yBAAyB;AAAA,IACxD,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ,CAAC;AACD,QAAM,yBAAyB;AAAA,IAC3B;AAAA,IACA;AAAA,IACA;AAAA,EACJ,CAAC;AACD,SAAO;AACX","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/rpc-types';\nexport * from '@solana/transactions';\nexport * from './airdrop';\nexport * from './rpc';\nexport * from './rpc-transport';\nexport * from './rpc-websocket-transport';\nexport * from './send-transaction';\nexport * from './transaction-confirmation';\nexport * from './transaction-confirmation-strategy-blockheight';\nexport * from './transaction-confirmation-strategy-nonce';\nexport * from './transaction-confirmation-strategy-recent-signature';\n","import { mapEncoder, combineCodec } from '@solana/codecs-core';\nimport { getStringEncoder, getStringDecoder, getBase58Encoder, getBase58Decoder } from '@solana/codecs-strings';\nimport { assertKeyExporterIsAvailable, assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\n// src/address.ts\nvar memoizedBase58Encoder;\nvar memoizedBase58Decoder;\nfunction getMemoizedBase58Encoder() {\n if (!memoizedBase58Encoder)\n memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\nfunction getMemoizedBase58Decoder() {\n if (!memoizedBase58Decoder)\n memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\nfunction isAddress(putativeAddress) {\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 || // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\nfunction assertIsAddress(putativeAddress) {\n try {\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 || // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new Error(\"Expected input string to decode to a byte array of length 32.\");\n }\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\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(`\\`${putativeAddress}\\` is not a base-58 encoded address`, {\n cause: e\n });\n }\n}\nfunction address(putativeAddress) {\n assertIsAddress(putativeAddress);\n return putativeAddress;\n}\nfunction getAddressEncoder() {\n return mapEncoder(\n getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }),\n (putativeAddress) => address(putativeAddress)\n );\n}\nfunction getAddressDecoder() {\n return getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 });\n}\nfunction getAddressCodec() {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\n}\nfunction getAddressComparator() {\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\n// src/vendor/noble/ed25519.ts\nvar D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nvar P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;\nvar RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;\nfunction mod(a) {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x, power) {\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) {\n const x2 = x * x % P;\n const b2 = x2 * x % P;\n const b4 = pow2(b2, 2n) * b2 % P;\n const b5 = pow2(b4, 1n) * x % P;\n const b10 = pow2(b5, 5n) * b5 % P;\n const b20 = pow2(b10, 10n) * b10 % P;\n const b40 = pow2(b20, 20n) * b20 % P;\n const b80 = pow2(b40, 40n) * b40 % P;\n const b160 = pow2(b80, 80n) * b80 % P;\n const b240 = pow2(b160, 80n) * b80 % P;\n const b250 = pow2(b240, 10n) * b10 % P;\n const pow_p_5_8 = pow2(b250, 2n) * x % P;\n return pow_p_5_8;\n}\nfunction uvRatio(u, v) {\n const v3 = mod(v * v * v);\n const v7 = mod(v3 * v3 * v);\n const pow = pow_2_252_3(u * v7);\n let x = mod(u * v3 * pow);\n const vx2 = mod(v * x * x);\n const root1 = x;\n const root2 = mod(x * RM1);\n const useRoot1 = vx2 === u;\n const useRoot2 = vx2 === mod(-u);\n const noRoot = vx2 === mod(-u * RM1);\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2;\n if ((mod(x) & 1n) === 1n)\n x = mod(-x);\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\nfunction pointIsOnCurve(y, lastByte) {\n const y2 = mod(y * y);\n const u = mod(y2 - 1n);\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v);\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 128) !== 0;\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n\n// src/curve.ts\nfunction byteToHex(byte) {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\nfunction decompressPointBytes(bytes) {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, \"\");\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\nasync function compressedPointBytesAreOnCurve(bytes) {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n\n// src/program-derived-address.ts\nfunction isProgramDerivedAddress(value) {\n return Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\" && typeof value[1] === \"number\" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);\n}\nfunction assertIsProgramDerivedAddress(value) {\n const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\" && typeof value[1] === \"number\";\n if (!validFormat) {\n throw new Error(\n `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\nvar MAX_SEED_LENGTH = 32;\nvar MAX_SEEDS = 16;\nvar PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80,\n 114,\n 111,\n 103,\n 114,\n 97,\n 109,\n 68,\n 101,\n 114,\n 105,\n 118,\n 101,\n 100,\n 65,\n 100,\n 100,\n 114,\n 101,\n 115,\n 115\n];\nvar PointOnCurveError = class extends Error {\n};\nasync function createProgramDerivedAddress({ programAddress, seeds }) {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let 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 throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, []);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(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 throw new PointOnCurveError(\"Invalid seeds; point must fall off the Ed25519 curve\");\n }\n return base58EncodedAddressCodec.decode(addressBytes);\n}\nasync function getProgramDerivedAddress({\n programAddress,\n seeds\n}) {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address2 = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])]\n });\n return [address2, bumpSeed];\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n throw new Error(\"Unable to find a viable program address bump seed\");\n}\nasync function createAddressWithSeed({ baseAddress, programAddress, seed }) {\n const { encode, decode } = getAddressCodec();\n const seedBytes = typeof seed === \"string\" ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n const programAddressBytes = encode(programAddress);\n if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n const addressBytesBuffer = await crypto.subtle.digest(\n \"SHA-256\",\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n return decode(addressBytes);\n}\nasync function getAddressFromPublicKey(publicKey) {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== \"public\" || publicKey.algorithm.name !== \"Ed25519\") {\n throw new Error(\"The `CryptoKey` must be an `Ed25519` public key\");\n }\n const publicKeyBytes = await crypto.subtle.exportKey(\"raw\", publicKey);\n return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n\nexport { address, assertIsAddress, assertIsProgramDerivedAddress, createAddressWithSeed, getAddressCodec, getAddressComparator, getAddressDecoder, getAddressEncoder, getAddressFromPublicKey, getProgramDerivedAddress, isAddress, isProgramDerivedAddress };\n","/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0,\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.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 */\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 */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\ntype BaseEncoder<TFrom> = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => Uint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\nexport type FixedSizeEncoder<TFrom, TSize extends number = number> = BaseEncoder<TFrom> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeEncoder<TFrom> = BaseEncoder<TFrom> & {\n /** The total size of the encoded value in bytes. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value to a `Uint8Array`.\n */\nexport type Encoder<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>;\n\ntype BaseDecoder<TTo> = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\nexport type FixedSizeDecoder<TTo, TSize extends number = number> = BaseDecoder<TTo> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeDecoder<TTo> = BaseDecoder<TTo> & {\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a value from a `Uint8Array`.\n */\nexport type Decoder<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>;\n\nexport type FixedSizeCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number> = FixedSizeEncoder<\n TFrom,\n TSize\n> &\n FixedSizeDecoder<TTo, TSize>;\n\nexport type VariableSizeCodec<TFrom, TTo extends TFrom = TFrom> = VariableSizeEncoder<TFrom> & VariableSizeDecoder<TTo>;\n\n/**\n * An object that can encode and decode a value to and from a `Uint8Array`.\n * It supports encoding looser types than it decodes for convenience.\n * For example, a `bigint` encoder will always decode to a `bigint`\n * but can be used to encode a `number`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value. Defaults to `TFrom`.\n */\nexport type Codec<TFrom, TTo extends TFrom = TFrom> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>;\n\n/**\n * Get the encoded size of a given value in bytes.\n */\nexport function getEncodedSize<TFrom>(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number },\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/** Fills the missing `encode` function using the existing `write` function. */\nexport function createEncoder<TFrom, TSize extends number>(\n encoder: Omit<FixedSizeEncoder<TFrom, TSize>, 'encode'>,\n): FixedSizeEncoder<TFrom, TSize>;\nexport function createEncoder<TFrom>(encoder: Omit<VariableSizeEncoder<TFrom>, 'encode'>): VariableSizeEncoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom> {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/** Fills the missing `decode` function using the existing `read` function. */\nexport function createDecoder<TTo, TSize extends number>(\n decoder: Omit<FixedSizeDecoder<TTo, TSize>, 'decode'>,\n): FixedSizeDecoder<TTo, TSize>;\nexport function createDecoder<TTo>(decoder: Omit<VariableSizeDecoder<TTo>, 'decode'>): VariableSizeDecoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo> {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/** Fills the missing `encode` and `decode` function using the existing `write` and `read` functions. */\nexport function createCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number>(\n codec: Omit<FixedSizeCodec<TFrom, TTo, TSize>, 'encode' | 'decode'>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec: Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): Codec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): Codec<TFrom, TTo> {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\nexport function isFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function isFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n): decoder is FixedSizeDecoder<TTo, TSize>;\nexport function isFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n): codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function isFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\nexport function assertIsFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n message?: string,\n): asserts encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function assertIsFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n message?: string,\n): asserts decoder is FixedSizeDecoder<TTo, TSize>;\nexport function assertIsFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n message?: string,\n): asserts codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function assertIsFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n message?: string,\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string,\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n\nexport function isVariableSize<TFrom>(encoder: Encoder<TFrom>): encoder is VariableSizeEncoder<TFrom>;\nexport function isVariableSize<TTo>(decoder: Decoder<TTo>): decoder is VariableSizeDecoder<TTo>;\nexport function isVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): codec is VariableSizeCodec<TFrom, TTo>;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\nexport function assertIsVariableSize<T>(\n encoder: Encoder<T>,\n message?: string,\n): asserts encoder is VariableSizeEncoder<T>;\nexport function assertIsVariableSize<T>(\n decoder: Decoder<T>,\n message?: string,\n): asserts decoder is VariableSizeDecoder<T>;\nexport function assertIsVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n message?: string,\n): asserts codec is VariableSizeCodec<TFrom, TTo>;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string,\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string,\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a variable-size codec, got a fixed-size one.');\n }\n}\n","import {\n Codec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<TFrom, TTo extends TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n decoder: FixedSizeDecoder<TTo, TSize>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: VariableSizeEncoder<TFrom>,\n decoder: VariableSizeDecoder<TTo>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>,\n): Codec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>,\n): Codec<TFrom, TTo> {\n if (isFixedSize(encoder) !== isFixedSize(decoder)) {\n // TODO: Coded error.\n throw new Error(`Encoder and decoder must either both be fixed-size or variable-size.`);\n }\n\n if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`,\n );\n }\n\n if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`,\n );\n }\n\n return {\n ...decoder,\n ...encoder,\n decode: decoder.decode,\n encode: encoder.encode,\n read: decoder.read,\n write: encoder.write,\n };\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n Offset,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n */\nexport function fixEncoder<TFrom, TSize extends number>(\n encoder: Encoder<TFrom>,\n fixedBytes: TSize,\n): FixedSizeEncoder<TFrom, TSize> {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value: TFrom, bytes: Uint8Array, offset: Offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function as using the nested `write` function on a fixed-sized byte\n // array may result in a out-of-bounds error on the nested encoder.\n const variableByteArray = encoder.encode(value);\n const fixedByteArray =\n variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n },\n });\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n */\nexport function fixDecoder<TTo, TSize extends number>(\n decoder: Decoder<TTo>,\n fixedBytes: TSize,\n): FixedSizeDecoder<TTo, TSize> {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes: Uint8Array, offset: Offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n },\n });\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n */\nexport function fixCodec<TFrom, TTo extends TFrom, TSize extends number>(\n codec: Codec<TFrom, TTo>,\n fixedBytes: TSize,\n): FixedSizeCodec<TFrom, TTo, TSize> {\n return combineCodec(fixEncoder(codec, fixedBytes), fixDecoder(codec, fixedBytes));\n}\n","import {\n Codec,\n createCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isVariableSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<TOldFrom, TNewFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TOldFrom, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder<TNewFrom, TSize>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: VariableSizeEncoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom> {\n return createEncoder({\n ...(isVariableSize(encoder)\n ? { ...encoder, getSizeFromValue: (value: TNewFrom) => encoder.getSizeFromValue(unmap(value)) }\n : encoder),\n write: (value: TNewFrom, bytes, offset) => encoder.write(unmap(value), bytes, offset),\n });\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<TOldTo, TNewTo, TSize extends number>(\n decoder: FixedSizeDecoder<TOldTo, TSize>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder<TNewTo, TSize>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: VariableSizeDecoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo> {\n return createDecoder({\n ...decoder,\n read: (bytes: Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeCodec<TNewFrom, TTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: VariableSizeCodec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: Codec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TOldTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec<TNewFrom, TNewTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: VariableSizeCodec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo> {\n return createCodec({\n ...mapEncoder(codec, unmap),\n read: map ? mapDecoder(codec, map).read : (codec.read as unknown as Decoder<TNewTo>['read']),\n });\n}\n","/**\n * Asserts that a given number is between a given range.\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint,\n) {\n if (value < min || value > max) {\n // TODO: Coded error.\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`,\n );\n }\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number, 4> =>\n numberEncoderFactory({\n config,\n name: 'f32',\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder<number, 4> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n size: 4,\n });\n\nexport const getF32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec<number, number, 4> =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n createDecoder,\n createEncoder,\n FixedSizeDecoder,\n FixedSizeEncoder,\n Offset,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput<TSize extends number> = {\n name: string;\n size: TSize;\n config?: NumberCodecConfig;\n};\n\ntype NumberFactoryEncoderInput<TFrom, TSize extends number> = NumberFactorySharedInput<TSize> & {\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: TFrom, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput<TTo, TSize extends number> = NumberFactorySharedInput<TSize> & {\n get: (view: DataView, littleEndian?: boolean) => TTo;\n};\n\nfunction isLittleEndian(config?: NumberCodecConfig): boolean {\n return config?.endian === Endian.BIG ? false : true;\n}\n\nexport function numberEncoderFactory<TFrom extends number | bigint, TSize extends number>(\n input: NumberFactoryEncoderInput<TFrom, TSize>,\n): FixedSizeEncoder<TFrom, TSize> {\n return createEncoder({\n fixedSize: input.size,\n write(value: TFrom, bytes: Uint8Array, offset: Offset): Offset {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n },\n });\n}\n\nexport function numberDecoderFactory<TTo extends number | bigint, TSize extends number>(\n input: NumberFactoryDecoderInput<TTo, TSize>,\n): FixedSizeDecoder<TTo, TSize> {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0): [TTo, number] {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n },\n });\n}\n\n/**\n * Helper function to ensure that the ArrayBuffer is converted properly from a Uint8Array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nfunction toArrayBuffer(bytes: Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number | bigint, 8> =>\n numberEncoderFactory({\n config,\n name: 'i64',\n range: [-BigInt('0x7fffffffffffffff') - 1n, BigInt('0x7fffffffffffffff')],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8,\n });\n\nexport const getI64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder<bigint, 8> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n size: 8,\n });\n\nexport const getI64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec<number | bigint, bigint, 8> =>\n combineCodec(getI64Encoder(config), getI64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI8Encoder = (): FixedSizeEncoder<number, 1> =>\n numberEncoderFactory({\n name: 'i8',\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, value),\n size: 1,\n });\n\nexport const getI8Decoder = (): FixedSizeDecoder<number, 1> =>\n numberDecoderFactory({\n get: view => view.getInt8(0),\n name: 'i8',\n size: 1,\n });\n\nexport const getI8Codec = (): FixedSizeCodec<number, number, 1> => combineCodec(getI8Encoder(), getI8Decoder());\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n Offset,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\n\n/**\n * Encodes short u16 numbers.\n * @see {@link getShortU16Codec} for a more detailed description.\n */\nexport const getShortU16Encoder = (): VariableSizeEncoder<number> =>\n createEncoder({\n getSizeFromValue: (value: number): number => {\n if (value <= 0b01111111) return 1;\n if (value <= 0b0011111111111111) return 2;\n return 3;\n },\n maxSize: 3,\n write: (value: number, bytes: Uint8Array, offset: Offset): Offset => {\n assertNumberIsBetweenForCodec('shortU16', 0, 65535, value);\n const shortU16Bytes = [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 shortU16Bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n shortU16Bytes[ii - 1] |= 0b10000000;\n }\n }\n bytes.set(shortU16Bytes, offset);\n return offset + shortU16Bytes.length;\n },\n });\n\n/**\n * Decodes short u16 numbers.\n * @see {@link getShortU16Codec} for a more detailed description.\n */\nexport const getShortU16Decoder = (): VariableSizeDecoder<number> =>\n createDecoder({\n maxSize: 3,\n read: (bytes: Uint8Array, offset): [number, Offset] => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\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\n/**\n * Encodes and decodes short u16 numbers.\n *\n * Short u16 numbers are the same as u16, but serialized with 1 to 3 bytes.\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 */\nexport const getShortU16Codec = (): VariableSizeCodec<number> =>\n combineCodec(getShortU16Encoder(), getShortU16Decoder());\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number | bigint, 16> =>\n numberEncoderFactory({\n config,\n name: 'u128',\n range: [0, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\nexport const getU128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder<bigint, 16> =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n size: 16,\n });\n\nexport const getU128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec<number | bigint, bigint, 16> =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number, 2> =>\n numberEncoderFactory({\n config,\n name: 'u16',\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, value, le),\n size: 2,\n });\n\nexport const getU16Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder<number, 2> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n size: 2,\n });\n\nexport const getU16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec<number, number, 2> =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder<string> => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (tailChars === '') return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (tailChars === '') {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Decodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder<string> => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\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, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * A string codec 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 codecs such as base10 or base58.\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(value: string, zeroCharacter: string): [string, string] {\n const leadingZeroIndex = [...value].findIndex(c => c !== zeroCharacter);\n return leadingZeroIndex === -1 ? [value, ''] : [value.slice(0, leadingZeroIndex), value.slice(leadingZeroIndex)];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n return [...value].reduce((sum, char) => sum * base + BigInt(alphabet.indexOf(char)), 0n);\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): VariableSizeEncoder<string> =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString('0123456789abcdef', lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n const hexBytes = matches ? matches.map((byte: string) => parseInt(byte, 16)) : [];\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): VariableSizeDecoder<string> =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): VariableSizeCodec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by reslicing the bits of the byte array.\n * @see {@link getBaseXResliceCodec} for a more detailed description.\n */\nexport const getBaseXResliceEncoder = (alphabet: string, bits: number): VariableSizeEncoder<string> =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.floor((value.length * bits) / 8),\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n const charIndices = [...value].map(c => alphabet.indexOf(c));\n const reslicedBytes = reslice(charIndices, bits, 8, false);\n bytes.set(reslicedBytes, offset);\n return reslicedBytes.length + offset;\n },\n });\n\n/**\n * Decodes a string using a custom alphabet by reslicing the bits of the byte array.\n * @see {@link getBaseXResliceCodec} for a more detailed description.\n */\nexport const getBaseXResliceDecoder = (alphabet: string, bits: number): VariableSizeDecoder<string> =>\n createDecoder({\n read(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map(i => alphabet[i]).join(''), rawBytes.length];\n },\n });\n\n/**\n * A string serializer that reslices bytes into custom chunks\n * of bits that are then mapped to a custom alphabet.\n *\n * This can be used to create serializers whose alphabet\n * is a power of 2 such as base16 or base64.\n */\nexport const getBaseXResliceCodec = (alphabet: string, bits: number): VariableSizeCodec<string> =>\n combineCodec(getBaseXResliceEncoder(alphabet, bits), getBaseXResliceDecoder(alphabet, bits));\n\n/** Helper function to reslice the bits inside bytes. */\nfunction reslice(input: number[], inputBits: number, outputBits: number, useRemainder: boolean): number[] {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = (accumulator << inputBits) | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push((accumulator >> bitsInAccumulator) & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push((accumulator << (outputBits - bitsInAccumulator)) & mask);\n }\n return output;\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Encodes strings in base64. */\nexport const getBase64Encoder = (): VariableSizeEncoder<string> => {\n if (__BROWSER__) {\n return createEncoder({\n getSizeFromValue: (value: string) => {\n try {\n return (atob as Window['atob'])(value).length;\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n write(value: string, bytes, offset) {\n try {\n const bytesToAdd = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n });\n }\n\n if (__NODEJS__) {\n return createEncoder({\n getSizeFromValue: (value: string) => Buffer.from(value, 'base64').length,\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n const buffer = Buffer.from(value, 'base64');\n bytes.set(buffer, offset);\n return buffer.length + offset;\n },\n });\n }\n\n return mapEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/** Decodes strings in base64. */\nexport const getBase64Decoder = (): VariableSizeDecoder<string> => {\n if (__BROWSER__) {\n return createDecoder({\n read(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n });\n }\n\n if (__NODEJS__) {\n return createDecoder({\n read: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString('base64'), bytes.length],\n });\n }\n\n return mapDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '='),\n );\n};\n\n/** Encodes and decodes strings in base64. */\nexport const getBase64Codec = (): VariableSizeCodec<string> => combineCodec(getBase64Encoder(), getBase64Decoder());\n","/**Removes null characters from a string. */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/** Pads a string with null characters at the end. */\nexport const padNullCharacters = (value: string, chars: number) => value.padEnd(chars, '\\u0000');\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n fixDecoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoder,\n getEncodedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { getUtf8Decoder, getUtf8Encoder } from './utf8';\n\n/** Defines the config for string codecs. */\nexport type StringCodecConfig<\n TPrefix extends NumberCodec | NumberEncoder | NumberDecoder,\n TEncoding extends Codec<string> | Encoder<string> | Decoder<string>,\n> = {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberCodec} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the byte array.\n * @defaultValue u32 prefix.\n */\n size?: TPrefix | number | 'variable';\n\n /**\n * The codec to use for encoding and decoding the content.\n * @defaultValue UTF-8 encoding.\n */\n encoding?: TEncoding;\n};\n\n/** Encodes strings from a given encoding and size strategy. */\nexport function getStringEncoder<TSize extends number>(\n config: StringCodecConfig<NumberEncoder, Encoder<string>> & { size: TSize },\n): FixedSizeEncoder<string, TSize>;\nexport function getStringEncoder<TSize extends number>(\n config: StringCodecConfig<NumberEncoder, Encoder<string>> & {\n size: 'variable';\n encoding: FixedSizeEncoder<string, TSize>;\n },\n): FixedSizeEncoder<string, TSize>;\nexport function getStringEncoder(\n config?: StringCodecConfig<NumberEncoder, Encoder<string>>,\n): VariableSizeEncoder<string>;\nexport function getStringEncoder(config: StringCodecConfig<NumberEncoder, Encoder<string>> = {}): Encoder<string> {\n const size = config.size ?? getU32Encoder();\n const encoding = config.encoding ?? getUtf8Encoder();\n\n if (size === 'variable') {\n return encoding;\n }\n\n if (typeof size === 'number') {\n return fixEncoder(encoding, size);\n }\n\n return createEncoder({\n getSizeFromValue: (value: string) => {\n const contentSize = getEncodedSize(value, encoding);\n return getEncodedSize(contentSize, size) + contentSize;\n },\n write: (value: string, bytes, offset) => {\n const contentSize = getEncodedSize(value, encoding);\n offset = size.write(contentSize, bytes, offset);\n return encoding.write(value, bytes, offset);\n },\n });\n}\n\n/** Decodes strings from a given encoding and size strategy. */\nexport function getStringDecoder<TSize extends number>(\n config: StringCodecConfig<NumberDecoder, Decoder<string>> & { size: TSize },\n): FixedSizeDecoder<string, TSize>;\nexport function getStringDecoder<TSize extends number>(\n config: StringCodecConfig<NumberDecoder, Decoder<string>> & {\n size: 'variable';\n encoding: FixedSizeDecoder<string, TSize>;\n },\n): FixedSizeDecoder<string, TSize>;\nexport function getStringDecoder(\n config?: StringCodecConfig<NumberDecoder, Decoder<string>>,\n): VariableSizeDecoder<string>;\nexport function getStringDecoder(config: StringCodecConfig<NumberDecoder, Decoder<string>> = {}): Decoder<string> {\n const size = config.size ?? getU32Decoder();\n const encoding = config.encoding ?? getUtf8Decoder();\n\n if (size === 'variable') {\n return encoding;\n }\n\n if (typeof size === 'number') {\n return fixDecoder(encoding, size);\n }\n\n return createDecoder({\n read: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('string', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.read(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec('string', length, contentBytes);\n const [value, contentOffset] = encoding.read(contentBytes, 0);\n offset += contentOffset;\n return [value, offset];\n },\n });\n}\n\n/** Encodes and decodes strings from a given encoding and size strategy. */\nexport function getStringCodec<TSize extends number>(\n config: StringCodecConfig<NumberCodec, Codec<string>> & { size: TSize },\n): FixedSizeCodec<string, string, TSize>;\nexport function getStringCodec<TSize extends number>(\n config: StringCodecConfig<NumberCodec, Codec<string>> & {\n size: 'variable';\n encoding: FixedSizeCodec<string, string, TSize>;\n },\n): FixedSizeCodec<string, string, TSize>;\nexport function getStringCodec(config?: StringCodecConfig<NumberCodec, Codec<string>>): VariableSizeCodec<string>;\nexport function getStringCodec(config: StringCodecConfig<NumberCodec, Codec<string>> = {}): Codec<string> {\n return combineCodec(getStringEncoder(config), getStringDecoder(config));\n}\n","import {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from 'text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/** Encodes UTF-8 strings using the native `TextEncoder` API. */\nexport const getUtf8Encoder = (): VariableSizeEncoder<string> => {\n let textEncoder: TextEncoder;\n return createEncoder({\n getSizeFromValue: value => (textEncoder ||= new TextEncoder()).encode(value).length,\n write: (value: string, bytes, offset) => {\n const bytesToAdd = (textEncoder ||= new TextEncoder()).encode(value);\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/** Decodes UTF-8 strings using the native `TextDecoder` API. */\nexport const getUtf8Decoder = (): VariableSizeDecoder<string> => {\n let textDecoder: TextDecoder;\n return createDecoder({\n read(bytes, offset) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n });\n};\n\n/** Encodes and decodes UTF-8 strings using the native `TextEncoder` and `TextDecoder` API. */\nexport const getUtf8Codec = (): Codec<string> => combineCodec(getUtf8Encoder(), getUtf8Decoder());\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","/**\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","function addPkcs8Header(bytes: Uint8Array): Uint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\nexport async function createPrivateKeyFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKey> {\n if (bytes.byteLength !== 32) {\n // TODO: Coded error.\n throw new Error('Private key bytes must be of length 32');\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, 'Ed25519', extractable ?? false, ['sign']);\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n","export type Commitment = 'confirmed' | 'finalized' | 'processed';\n\nfunction getCommitmentScore(commitment: Commitment): number {\n switch (commitment) {\n case 'finalized':\n return 2;\n case 'confirmed':\n return 1;\n case 'processed':\n return 0;\n default:\n return ((_: never) => {\n throw new Error(`Unrecognized commitment \\`${commitment}\\`.`);\n })(commitment);\n }\n}\n\nexport function commitmentComparator(a: Commitment, b: Commitment): -1 | 0 | 1 {\n if (a === b) {\n return 0;\n }\n return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;\n}\n","// FIXME(solana-labs/solana/issues/30341) Beware that any value above 9007199254740991 may be\n// truncated or rounded because of a downcast to JavaScript `number` between your calling code and\n// the JSON-RPC transport.\nexport type LamportsUnsafeBeyond2Pow53Minus1 = bigint & { readonly __brand: unique symbol };\n\n// Largest possible value to be represented by a u64\nconst maxU64Value = 18446744073709551615n; // 2n ** 64n - 1n\n\nexport function isLamports(putativeLamports: bigint): putativeLamports is LamportsUnsafeBeyond2Pow53Minus1 {\n return putativeLamports >= 0 && putativeLamports <= maxU64Value;\n}\n\nexport function assertIsLamports(\n putativeLamports: bigint,\n): asserts putativeLamports is LamportsUnsafeBeyond2Pow53Minus1 {\n if (putativeLamports < 0) {\n // TODO: Coded error.\n throw new Error('Input for 64-bit unsigned integer cannot be negative');\n }\n\n if (putativeLamports > maxU64Value) {\n // TODO: Coded error.\n throw new Error('Input number is too large to be represented as a 64-bit unsigned integer');\n }\n}\n\nexport function lamports(putativeLamports: bigint): LamportsUnsafeBeyond2Pow53Minus1 {\n assertIsLamports(putativeLamports);\n return putativeLamports;\n}\n","export type StringifiedBigInt = string & { readonly __brand: unique symbol };\n\nexport function isStringifiedBigInt(putativeBigInt: string): putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n return true;\n } catch (_) {\n return false;\n }\n}\n\nexport function assertIsStringifiedBigInt(putativeBigInt: string): asserts putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n } catch (e) {\n throw new Error(`\\`${putativeBigInt}\\` cannot be parsed as a BigInt`, {\n cause: e,\n });\n }\n}\n\nexport function stringifiedBigInt(putativeBigInt: string): StringifiedBigInt {\n assertIsStringifiedBigInt(putativeBigInt);\n return putativeBigInt;\n}\n","export type StringifiedNumber = string & { readonly __brand: unique symbol };\n\nexport function isStringifiedNumber(putativeNumber: string): putativeNumber is StringifiedNumber {\n return !Number.isNaN(Number(putativeNumber));\n}\n\nexport function assertIsStringifiedNumber(putativeNumber: string): asserts putativeNumber is StringifiedNumber {\n if (Number.isNaN(Number(putativeNumber))) {\n throw new Error(`\\`${putativeNumber}\\` cannot be parsed as a Number`);\n }\n}\n\nexport function stringifiedNumber(putativeNumber: string): StringifiedNumber {\n assertIsStringifiedNumber(putativeNumber);\n return putativeNumber;\n}\n","export type UnixTimestamp = number & { readonly __brand: unique symbol };\n\nexport function isUnixTimestamp(putativeTimestamp: number): putativeTimestamp is UnixTimestamp {\n // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date\n if (putativeTimestamp > 8.64e15 || putativeTimestamp < -8.64e15) {\n return false;\n }\n return true;\n}\n\nexport function assertIsUnixTimestamp(putativeTimestamp: number): asserts putativeTimestamp is UnixTimestamp {\n // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date\n try {\n if (putativeTimestamp > 8.64e15 || putativeTimestamp < -8.64e15) {\n throw new Error('Expected input number to be in the range [-8.64e15, 8.64e15]');\n }\n } catch (e) {\n throw new Error(`\\`${putativeTimestamp}\\` is not a timestamp`, {\n cause: e,\n });\n }\n}\n\nexport function unixTimestamp(putativeTimestamp: number): UnixTimestamp {\n assertIsUnixTimestamp(putativeTimestamp);\n return putativeTimestamp;\n}\n","import { assertIsFixedSize, createEncoder, getEncodedSize, createDecoder, combineCodec, assertByteArrayHasEnoughBytesForCodec, mapEncoder, mapDecoder, fixEncoder, fixDecoder, assertByteArrayIsNotEmptyForCodec, isFixedSize } from '@solana/codecs-core';\nimport { getU32Encoder, getU32Decoder, getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';\n\n// src/array.ts\n\n// src/assertions.ts\nfunction assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {\n if (expected !== actual) {\n throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);\n }\n}\nfunction maxCodecSizes(sizes) {\n return sizes.reduce(\n (all, size) => all === null || size === null ? null : Math.max(all, size),\n 0\n );\n}\nfunction sumCodecSizes(sizes) {\n return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);\n}\nfunction getFixedSize(codec) {\n return isFixedSize(codec) ? codec.fixedSize : null;\n}\nfunction getMaxSize(codec) {\n return isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;\n}\n\n// src/array.ts\nfunction getArrayEncoder(item, config = {}) {\n const size = config.size ?? getU32Encoder();\n if (size === \"remainder\") {\n assertIsFixedSize(item, 'Codecs of \"remainder\" size must have fixed-size items.');\n }\n const fixedSize = computeArrayLikeCodecSize(size, getFixedSize(item));\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? void 0;\n return createEncoder({\n ...fixedSize !== null ? { fixedSize } : {\n getSizeFromValue: (array) => {\n const prefixSize = typeof size === \"object\" ? getEncodedSize(array.length, size) : 0;\n return prefixSize + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);\n },\n maxSize\n },\n write: (array, bytes, offset) => {\n if (typeof size === \"number\") {\n assertValidNumberOfItemsForCodec(\"array\", size, array.length);\n }\n if (typeof size === \"object\") {\n offset = size.write(array.length, bytes, offset);\n }\n array.forEach((value) => {\n offset = item.write(value, bytes, offset);\n });\n return offset;\n }\n });\n}\nfunction getArrayDecoder(item, config = {}) {\n const size = config.size ?? getU32Decoder();\n if (size === \"remainder\") {\n assertIsFixedSize(item, 'Codecs of \"remainder\" size must have fixed-size items.');\n }\n const itemSize = getFixedSize(item);\n const fixedSize = computeArrayLikeCodecSize(size, itemSize);\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? void 0;\n return createDecoder({\n ...fixedSize !== null ? { fixedSize } : { maxSize },\n read: (bytes, offset) => {\n const array = [];\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [array, offset];\n }\n const [resolvedSize, newOffset] = readArrayLikeCodecSize(size, itemSize, bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset2] = item.read(bytes, offset);\n offset = newOffset2;\n array.push(value);\n }\n return [array, offset];\n }\n });\n}\nfunction getArrayCodec(item, config = {}) {\n return combineCodec(getArrayEncoder(item, config), getArrayDecoder(item, config));\n}\nfunction readArrayLikeCodecSize(size, itemSize, bytes, offset) {\n if (typeof size === \"number\") {\n return [size, offset];\n }\n if (typeof size === \"object\") {\n return size.read(bytes, offset);\n }\n if (size === \"remainder\") {\n if (itemSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = Math.max(0, bytes.length - offset);\n if (remainder % itemSize !== 0) {\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${itemSize} bytes. Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. In other words, ${remainder} modulo ${itemSize} should be equal to zero.`\n );\n }\n return [remainder / itemSize, offset];\n }\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\nfunction computeArrayLikeCodecSize(size, itemSize) {\n if (typeof size !== \"number\")\n return null;\n if (size === 0)\n return 0;\n return itemSize === null ? null : itemSize * size;\n}\nfunction getBitArrayEncoder(size, config = {}) {\n const parsedConfig = typeof config === \"boolean\" ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createEncoder({\n fixedSize: size,\n write(value, bytes, offset) {\n const bytesToAdd = [];\n for (let i = 0; i < size; i += 1) {\n let byte = 0;\n for (let j = 0; j < 8; j += 1) {\n const feature = Number(value[i * 8 + j] ?? 0);\n byte |= feature << (backward ? j : 7 - j);\n }\n if (backward) {\n bytesToAdd.unshift(byte);\n } else {\n bytesToAdd.push(byte);\n }\n }\n bytes.set(bytesToAdd, offset);\n return size;\n }\n });\n}\nfunction getBitArrayDecoder(size, config = {}) {\n const parsedConfig = typeof config === \"boolean\" ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createDecoder({\n fixedSize: size,\n read(bytes, offset) {\n assertByteArrayHasEnoughBytesForCodec(\"bitArray\", size, bytes, offset);\n const booleans = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n slice.forEach((byte) => {\n for (let i = 0; i < 8; i += 1) {\n if (backward) {\n booleans.push(Boolean(byte & 1));\n byte >>= 1;\n } else {\n booleans.push(Boolean(byte & 128));\n byte <<= 1;\n }\n }\n });\n return [booleans, offset + size];\n }\n });\n}\nfunction getBitArrayCodec(size, config = {}) {\n return combineCodec(getBitArrayEncoder(size, config), getBitArrayDecoder(size, config));\n}\nfunction getBooleanEncoder(config = {}) {\n const size = config.size ?? getU8Encoder();\n assertIsFixedSize(size, \"Codec [bool] requires a fixed size.\");\n return mapEncoder(size, (value) => value ? 1 : 0);\n}\nfunction getBooleanDecoder(config = {}) {\n const size = config.size ?? getU8Decoder();\n assertIsFixedSize(size, \"Codec [bool] requires a fixed size.\");\n return mapDecoder(size, (value) => Number(value) === 1);\n}\nfunction getBooleanCodec(config = {}) {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\nfunction getBytesEncoder(config = {}) {\n const size = config.size ?? \"variable\";\n const byteEncoder = createEncoder({\n getSizeFromValue: (value) => value.length,\n write: (value, bytes, offset) => {\n bytes.set(value, offset);\n return offset + value.length;\n }\n });\n if (size === \"variable\") {\n return byteEncoder;\n }\n if (typeof size === \"number\") {\n return fixEncoder(byteEncoder, size);\n }\n return createEncoder({\n getSizeFromValue: (value) => getEncodedSize(value.length, size) + value.length,\n write: (value, bytes, offset) => {\n offset = size.write(value.length, bytes, offset);\n return byteEncoder.write(value, bytes, offset);\n }\n });\n}\nfunction getBytesDecoder(config = {}) {\n const size = config.size ?? \"variable\";\n const byteDecoder = createDecoder({\n read: (bytes, offset) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n }\n });\n if (size === \"variable\") {\n return byteDecoder;\n }\n if (typeof size === \"number\") {\n return fixDecoder(byteDecoder, size);\n }\n return createDecoder({\n read: (bytes, offset) => {\n assertByteArrayIsNotEmptyForCodec(\"bytes\", bytes, offset);\n const [lengthBigInt, lengthOffset] = size.read(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec(\"bytes\", length, contentBytes);\n const [value, contentOffset] = byteDecoder.read(contentBytes, 0);\n offset += contentOffset;\n return [value, offset];\n }\n });\n}\nfunction getBytesCodec(config = {}) {\n return combineCodec(getBytesEncoder(config), getBytesDecoder(config));\n}\nfunction getDataEnumEncoder(variants, config = {}) {\n const prefix = config.size ?? getU8Encoder();\n const fixedSize = getDataEnumFixedSize(variants, prefix);\n return createEncoder({\n ...fixedSize !== null ? { fixedSize } : {\n getSizeFromValue: (variant) => {\n const discriminator = getVariantDiscriminator(variants, variant);\n const variantEncoder = variants[discriminator][1];\n return getEncodedSize(discriminator, prefix) + getEncodedSize(variant, variantEncoder);\n },\n maxSize: getDataEnumMaxSize(variants, prefix)\n },\n write: (variant, bytes, offset) => {\n const discriminator = getVariantDiscriminator(variants, variant);\n offset = prefix.write(discriminator, bytes, offset);\n const variantEncoder = variants[discriminator][1];\n return variantEncoder.write(variant, bytes, offset);\n }\n });\n}\nfunction getDataEnumDecoder(variants, config = {}) {\n const prefix = config.size ?? getU8Decoder();\n const fixedSize = getDataEnumFixedSize(variants, prefix);\n return createDecoder({\n ...fixedSize !== null ? { fixedSize } : { maxSize: getDataEnumMaxSize(variants, prefix) },\n read: (bytes, offset) => {\n assertByteArrayIsNotEmptyForCodec(\"dataEnum\", bytes, offset);\n const [discriminator, dOffset] = prefix.read(bytes, offset);\n offset = dOffset;\n const variantField = variants[Number(discriminator)] ?? null;\n if (!variantField) {\n throw new Error(\n `Enum discriminator out of range. Expected a number between 0 and ${variants.length - 1}, got ${discriminator}.`\n );\n }\n const [variant, vOffset] = variantField[1].read(bytes, offset);\n offset = vOffset;\n return [{ __kind: variantField[0], ...variant ?? {} }, offset];\n }\n });\n}\nfunction getDataEnumCodec(variants, config = {}) {\n return combineCodec(getDataEnumEncoder(variants, config), getDataEnumDecoder(variants, config));\n}\nfunction getDataEnumFixedSize(variants, prefix) {\n if (variants.length === 0)\n return isFixedSize(prefix) ? prefix.fixedSize : null;\n if (!isFixedSize(variants[0][1]))\n return null;\n const variantSize = variants[0][1].fixedSize;\n const sameSizedVariants = variants.every(\n (variant) => isFixedSize(variant[1]) && variant[1].fixedSize === variantSize\n );\n if (!sameSizedVariants)\n return null;\n return isFixedSize(prefix) ? prefix.fixedSize + variantSize : null;\n}\nfunction getDataEnumMaxSize(variants, prefix) {\n const maxVariantSize = maxCodecSizes(variants.map(([, codec]) => getMaxSize(codec)));\n return sumCodecSizes([getMaxSize(prefix), maxVariantSize]) ?? void 0;\n}\nfunction getVariantDiscriminator(variants, variant) {\n const discriminator = variants.findIndex(([key]) => variant.__kind === key);\n if (discriminator < 0) {\n throw new Error(\n `Invalid data enum variant. Expected one of [${variants.map(([key]) => key).join(\", \")}], got \"${variant.__kind}\".`\n );\n }\n return discriminator;\n}\nfunction getTupleEncoder(items) {\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? void 0;\n return createEncoder({\n ...fixedSize === null ? {\n getSizeFromValue: (value) => items.map((item, index) => getEncodedSize(value[index], item)).reduce((all, one) => all + one, 0),\n maxSize\n } : { fixedSize },\n write: (value, bytes, offset) => {\n assertValidNumberOfItemsForCodec(\"tuple\", items.length, value.length);\n items.forEach((item, index) => {\n offset = item.write(value[index], bytes, offset);\n });\n return offset;\n }\n });\n}\nfunction getTupleDecoder(items) {\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? void 0;\n return createDecoder({\n ...fixedSize === null ? { maxSize } : { fixedSize },\n read: (bytes, offset) => {\n const values = [];\n items.forEach((item) => {\n const [newValue, newOffset] = item.read(bytes, offset);\n values.push(newValue);\n offset = newOffset;\n });\n return [values, offset];\n }\n });\n}\nfunction getTupleCodec(items) {\n return combineCodec(\n getTupleEncoder(items),\n getTupleDecoder(items)\n );\n}\n\n// src/map.ts\nfunction getMapEncoder(key, value, config = {}) {\n return mapEncoder(\n getArrayEncoder(getTupleEncoder([key, value]), config),\n (map) => [...map.entries()]\n );\n}\nfunction getMapDecoder(key, value, config = {}) {\n return mapDecoder(\n getArrayDecoder(getTupleDecoder([key, value]), config),\n (entries) => new Map(entries)\n );\n}\nfunction getMapCodec(key, value, config = {}) {\n return combineCodec(getMapEncoder(key, value, config), getMapDecoder(key, value, config));\n}\nfunction getNullableEncoder(item, config = {}) {\n const prefix = config.prefix ?? getU8Encoder();\n const fixed = config.fixed ?? false;\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item, \"Fixed nullables can only be used with fixed-size codecs.\");\n assertIsFixedSize(prefix, \"Fixed nullables can only be used with fixed-size prefix.\");\n const fixedSize = prefix.fixedSize + item.fixedSize;\n return createEncoder({\n fixedSize,\n write: (option, bytes, offset) => {\n const prefixOffset = prefix.write(Number(option !== null), bytes, offset);\n if (option !== null) {\n item.write(option, bytes, prefixOffset);\n }\n return offset + fixedSize;\n }\n });\n }\n return createEncoder({\n getSizeFromValue: (option) => getEncodedSize(Number(option !== null), prefix) + (option !== null ? getEncodedSize(option, item) : 0),\n maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? void 0,\n write: (option, bytes, offset) => {\n offset = prefix.write(Number(option !== null), bytes, offset);\n if (option !== null) {\n offset = item.write(option, bytes, offset);\n }\n return offset;\n }\n });\n}\nfunction getNullableDecoder(item, config = {}) {\n const prefix = config.prefix ?? getU8Decoder();\n const fixed = config.fixed ?? false;\n let fixedSize = null;\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item, \"Fixed nullables can only be used with fixed-size codecs.\");\n assertIsFixedSize(prefix, \"Fixed nullables can only be used with fixed-size prefix.\");\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n return createDecoder({\n ...fixedSize === null ? { maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? void 0 } : { fixedSize },\n read: (bytes, offset) => {\n if (bytes.length - offset <= 0) {\n return [null, offset];\n }\n const [isSome, prefixOffset] = prefix.read(bytes, offset);\n if (isSome === 0) {\n return [null, fixedSize !== null ? offset + fixedSize : prefixOffset];\n }\n const [value, newOffset] = item.read(bytes, prefixOffset);\n return [value, fixedSize !== null ? offset + fixedSize : newOffset];\n }\n });\n}\nfunction getNullableCodec(item, config = {}) {\n const configCast = config;\n return combineCodec(getNullableEncoder(item, configCast), getNullableDecoder(item, configCast));\n}\nfunction getScalarEnumEncoder(constructor, config = {}) {\n const prefix = config.size ?? getU8Encoder();\n const { minRange, maxRange, stringValues, enumKeys, enumValues } = getScalarEnumStats(constructor);\n return mapEncoder(prefix, (value) => {\n const isInvalidNumber = typeof value === \"number\" && (value < minRange || value > maxRange);\n const isInvalidString = typeof value === \"string\" && !stringValues.includes(value);\n if (isInvalidNumber || isInvalidString) {\n throw new Error(\n `Invalid scalar enum variant. Expected one of [${stringValues.join(\", \")}] or a number between ${minRange} and ${maxRange}, got \"${value}\".`\n );\n }\n if (typeof value === \"number\")\n return value;\n const valueIndex = enumValues.indexOf(value);\n if (valueIndex >= 0)\n return valueIndex;\n return enumKeys.indexOf(value);\n });\n}\nfunction getScalarEnumDecoder(constructor, config = {}) {\n const prefix = config.size ?? getU8Decoder();\n const { minRange, maxRange, isNumericEnum, enumValues } = getScalarEnumStats(constructor);\n return mapDecoder(prefix, (value) => {\n const valueAsNumber = Number(value);\n if (valueAsNumber < minRange || valueAsNumber > maxRange) {\n throw new Error(\n `Enum discriminator out of range. Expected a number between ${minRange} and ${maxRange}, got ${valueAsNumber}.`\n );\n }\n return isNumericEnum ? valueAsNumber : enumValues[valueAsNumber];\n });\n}\nfunction getScalarEnumCodec(constructor, config = {}) {\n return combineCodec(getScalarEnumEncoder(constructor, config), getScalarEnumDecoder(constructor, config));\n}\nfunction getScalarEnumStats(constructor) {\n const enumKeys = Object.keys(constructor);\n const enumValues = Object.values(constructor);\n const isNumericEnum = enumValues.some((v) => typeof v === \"number\");\n const minRange = 0;\n const maxRange = isNumericEnum ? enumValues.length / 2 - 1 : enumValues.length - 1;\n const stringValues = isNumericEnum ? [...enumKeys] : [.../* @__PURE__ */ new Set([...enumKeys, ...enumValues])];\n return {\n enumKeys,\n enumValues,\n isNumericEnum,\n maxRange,\n minRange,\n stringValues\n };\n}\nfunction getSetEncoder(item, config = {}) {\n return mapEncoder(getArrayEncoder(item, config), (set) => [...set]);\n}\nfunction getSetDecoder(item, config = {}) {\n return mapDecoder(getArrayDecoder(item, config), (entries) => new Set(entries));\n}\nfunction getSetCodec(item, config = {}) {\n return combineCodec(getSetEncoder(item, config), getSetDecoder(item, config));\n}\nfunction getStructEncoder(fields) {\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? void 0;\n return createEncoder({\n ...fixedSize === null ? {\n getSizeFromValue: (value) => fields.map(([key, codec]) => getEncodedSize(value[key], codec)).reduce((all, one) => all + one, 0),\n maxSize\n } : { fixedSize },\n write: (struct, bytes, offset) => {\n fields.forEach(([key, codec]) => {\n offset = codec.write(struct[key], bytes, offset);\n });\n return offset;\n }\n });\n}\nfunction getStructDecoder(fields) {\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? void 0;\n return createDecoder({\n ...fixedSize === null ? { maxSize } : { fixedSize },\n read: (bytes, offset) => {\n const struct = {};\n fields.forEach(([key, codec]) => {\n const [value, newOffset] = codec.read(bytes, offset);\n offset = newOffset;\n struct[key] = value;\n });\n return [struct, offset];\n }\n });\n}\nfunction getStructCodec(fields) {\n return combineCodec(getStructEncoder(fields), getStructDecoder(fields));\n}\nfunction getUnitEncoder() {\n return createEncoder({\n fixedSize: 0,\n write: (_value, _bytes, offset) => offset\n });\n}\nfunction getUnitDecoder() {\n return createDecoder({\n fixedSize: 0,\n read: (_bytes, offset) => [void 0, offset]\n });\n}\nfunction getUnitCodec() {\n return combineCodec(getUnitEncoder(), getUnitDecoder());\n}\n\nexport { assertValidNumberOfItemsForCodec, getArrayCodec, getArrayDecoder, getArrayEncoder, getBitArrayCodec, getBitArrayDecoder, getBitArrayEncoder, getBooleanCodec, getBooleanDecoder, getBooleanEncoder, getBytesCodec, getBytesDecoder, getBytesEncoder, getDataEnumCodec, getDataEnumDecoder, getDataEnumEncoder, getMapCodec, getMapDecoder, getMapEncoder, getNullableCodec, getNullableDecoder, getNullableEncoder, getScalarEnumCodec, getScalarEnumDecoder, getScalarEnumEncoder, getSetCodec, getSetDecoder, getSetEncoder, getStructCodec, getStructDecoder, getStructEncoder, getTupleCodec, getTupleDecoder, getTupleEncoder, getUnitCodec, getUnitDecoder, getUnitEncoder };\n","/**\n * General pipe function.\n * Provide an initial value and a list of functions to pipe it through.\n *\n * Following common implementations of pipe functions that use TypeScript,\n * this function supports a maximum arity of 10 for type safety.\n * @see https://github.com/ramda/ramda/blob/master/source/pipe.js\n * @see https://github.com/darky/rocket-pipes/blob/master/index.ts\n *\n * Note you can use nested pipes to extend this limitation, like so:\n * ```typescript\n * const myValue = pipe(\n * pipe(\n * 1,\n * (x) => x + 1,\n * (x) => x * 2,\n * (x) => x - 1,\n * ),\n * (y) => y / 3,\n * (y) => y + 1,\n * );\n * ```\n * @param init The initial value\n * @param fns Any number of functions to pipe the value through\n * @returns The final value with all functions applied\n */\nexport function pipe<TInitial>(init: TInitial): TInitial;\nexport function pipe<TInitial, R1>(init: TInitial, init_r1: (init: TInitial) => R1): R1;\nexport function pipe<TInitial, R1, R2>(init: TInitial, init_r1: (init: TInitial) => R1, r1_r2: (r1: R1) => R2): R2;\nexport function pipe<TInitial, R1, R2, R3>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n): R3;\nexport function pipe<TInitial, R1, R2, R3, R4>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n): R4;\nexport function pipe<TInitial, R1, R2, R3, R4, R5>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n): R5;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n): R6;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n): R7;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8,\n): R8;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8,\n r8_r9: (r8: R8) => R9,\n): R9;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8,\n r8_r9: (r8: R8) => R9,\n r9_r10: (r9: R9) => R10,\n): R10;\nexport function pipe<TInitial>(init: TInitial, ...fns: CallableFunction[]) {\n return fns.reduce((acc, fn) => fn(acc), init);\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 { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\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\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\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 = base58Encoder.encode(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\nfunction isTransactionWithBlockhashLifetime(\n transaction: BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime),\n): transaction is BaseTransaction & ITransactionWithBlockhashLifetime {\n const lifetimeConstraintShapeMatches =\n 'lifetimeConstraint' in transaction &&\n typeof transaction.lifetimeConstraint.blockhash === 'string' &&\n typeof transaction.lifetimeConstraint.lastValidBlockHeight === 'bigint';\n if (!lifetimeConstraintShapeMatches) return false;\n try {\n assertIsBlockhash(transaction.lifetimeConstraint.blockhash);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function assertIsTransactionWithBlockhashLifetime(\n transaction: BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime),\n): asserts transaction is BaseTransaction & ITransactionWithBlockhashLifetime {\n if (!isTransactionWithBlockhashLifetime(transaction)) {\n // TODO: Coded error.\n throw new Error('Transaction does not have a blockhash lifetime');\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 { Address } from '@solana/addresses';\nimport {\n AccountRole,\n IInstruction,\n IInstructionWithAccounts,\n IInstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nimport { ITransactionWithSignatures } from './signatures';\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> | WritableSignerAccount<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: Address<TNonceAccountAddress>;\n readonly nonceAuthorityAddress: Address<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 Address<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address<'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: Address<TNonceAccountAddress>,\n nonceAuthorityAddress: Address<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\nexport function isAdvanceNonceAccountInstruction(\n instruction: IInstruction,\n): 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 isSignerRole(instruction.accounts[2].role)\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\nfunction isAdvanceNonceAccountInstructionForNonce<\n TNonceAccountAddress extends Address = Address,\n TNonceAuthorityAddress extends Address = Address,\n>(\n instruction: AdvanceNonceAccountInstruction,\n nonceAccountAddress: TNonceAccountAddress,\n nonceAuthorityAddress: TNonceAuthorityAddress,\n): instruction is AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return (\n instruction.accounts[0].address === nonceAccountAddress &&\n instruction.accounts[2].address === nonceAuthorityAddress\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): Omit<TTransaction, keyof ITransactionWithSignatures> &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue> {\n let newInstructions: [\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[],\n ];\n\n const firstInstruction = transaction.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {\n return transaction as TTransaction &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions.slice(1),\n ];\n }\n } else {\n // we don't have an existing advance nonce instruction as the first instruction, prepend one\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions,\n ];\n }\n\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: newInstructions,\n lifetimeConstraint: {\n nonce,\n },\n } as TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n Object.freeze(out);\n return out;\n}\n","import { Address } 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: Address<TAddress>;\n}\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Address<TFeePayerAddress>,\n transaction:\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures),\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Address<TFeePayerAddress>,\n transaction: TTransaction | (TTransaction & ITransactionWithFeePayer<string>),\n): TTransaction & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Address<TFeePayerAddress>,\n transaction:\n | TTransaction\n | (TTransaction & ITransactionWithFeePayer<string>)\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & 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 { Address, getAddressComparator } 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: Address,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry | Record<never, never>,\n ) => AddressMap[Address],\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(feePayer: Address, instructions: readonly IInstruction[]): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set<Address>();\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 getAddressComparator>;\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 ||= getAddressComparator())(\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 getAddressComparator>;\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 ||= getAddressComparator();\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 Address<typeof address>,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype AddressTableLookup = Readonly<{\n lookupTableAddress: Address;\n readableIndices: readonly number[];\n writableIndices: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<Address, { readonly readableIndices: number[]; readonly writableIndices: number[] }> = {};\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(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Address,\n ...index[lookupTableAddress as unknown as Address],\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 { Address } 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<Address, 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 { Address } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Address[] {\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 { CompilableTransaction } from './compilable-transaction';\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';\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\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 { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n createEncoder,\n Decoder,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n StructToDecoderTuple,\n StructToEncoderTuple,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\nimport { CompiledMessage } from '../message';\nimport { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nfunction getCompiledMessageLegacyEncoder(): VariableSizeEncoder<CompiledMessage> {\n return getStructEncoder(getPreludeStructEncoderTuple());\n}\n\nfunction getCompiledMessageVersionedEncoder(): VariableSizeEncoder<CompiledMessage> {\n return mapEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ] as StructToEncoderTuple<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 );\n}\n\nfunction getPreludeStructEncoderTuple(): StructToEncoderTuple<CompiledMessage> {\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n ['staticAccounts', getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],\n ['lifetimeToken', getStringEncoder({ encoding: getBase58Encoder(), size: 32 })],\n ['instructions', getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })],\n ];\n}\n\nfunction getPreludeStructDecoderTuple(): StructToDecoderTuple<\n CompiledMessage & { addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups> }\n> {\n return [\n ['version', getTransactionVersionDecoder() as Decoder<number>],\n ['header', getMessageHeaderDecoder()],\n ['staticAccounts', getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],\n ['lifetimeToken', getStringDecoder({ encoding: getBase58Decoder(), size: 32 })],\n ['instructions', getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ];\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });\n}\n\nexport function getCompiledMessageEncoder(): VariableSizeEncoder<CompiledMessage> {\n return createEncoder({\n getSizeFromValue: (compiledMessage: CompiledMessage) => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);\n } else {\n return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);\n }\n },\n write: (compiledMessage, bytes, offset) => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);\n } else {\n return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);\n }\n },\n });\n}\n\nexport function getCompiledMessageDecoder(): VariableSizeDecoder<CompiledMessage> {\n return mapDecoder(getStructDecoder(getPreludeStructDecoderTuple()), ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups } as Exclude<CompiledMessage, { readonly version: 'legacy' }>;\n });\n}\n\nexport function getCompiledMessageCodec(): VariableSizeCodec<CompiledMessage> {\n return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n type Encoder,\n type VariableSizeCodec,\n type VariableSizeDecoder,\n type VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport type { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\n\ntype AddressTableLookup = ReturnType<typeof getCompiledAddressTableLookups>[number];\n\nlet memoizedAddressTableLookupEncoder: VariableSizeEncoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupEncoder(): VariableSizeEncoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupEncoder) {\n memoizedAddressTableLookupEncoder = getStructEncoder([\n ['lookupTableAddress', getAddressEncoder()],\n [\n 'writableIndices',\n getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() }) as Encoder<readonly number[]>,\n ],\n [\n 'readableIndices',\n getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() }) as Encoder<readonly number[]>,\n ],\n ]);\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: VariableSizeDecoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupDecoder(): VariableSizeDecoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupDecoder) {\n memoizedAddressTableLookupDecoder = getStructDecoder([\n ['lookupTableAddress', getAddressDecoder()],\n ['writableIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n ['readableIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n ]);\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): VariableSizeCodec<AddressTableLookup> {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport { getStructCodec, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getU8Codec, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledMessageHeader } from '../compile-header';\n\ntype MessageHeader = ReturnType<typeof getCompiledMessageHeader>;\n\nlet memoizedU8Encoder: FixedSizeEncoder<number, 1> | undefined;\nfunction getMemoizedU8Encoder(): FixedSizeEncoder<number, 1> {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nlet memoizedU8Decoder: FixedSizeDecoder<number, 1> | undefined;\nfunction getMemoizedU8Decoder(): FixedSizeDecoder<number, 1> {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nlet memoizedU8Codec: FixedSizeCodec<number, number, 1> | undefined;\nfunction getMemoizedU8Codec(): FixedSizeCodec<number, number, 1> {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nexport function getMessageHeaderEncoder(): FixedSizeEncoder<MessageHeader, 3> {\n return getStructEncoder([\n ['numSignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Encoder()],\n ]) as FixedSizeEncoder<MessageHeader, 3>;\n}\n\nexport function getMessageHeaderDecoder(): FixedSizeDecoder<MessageHeader, 3> {\n return getStructDecoder([\n ['numSignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Decoder()],\n ]) as FixedSizeDecoder<MessageHeader, 3>;\n}\n\nexport function getMessageHeaderCodec(): FixedSizeCodec<MessageHeader, MessageHeader, 3> {\n return getStructCodec([\n ['numSignerAccounts', getMemoizedU8Codec()],\n ['numReadonlySignerAccounts', getMemoizedU8Codec()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Codec()],\n ]) as FixedSizeCodec<MessageHeader, MessageHeader, 3>;\n}\n","import {\n combineCodec,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledInstructions } from '../compile-instructions';\n\ntype Instruction = ReturnType<typeof getCompiledInstructions>[number];\n\nlet memoizedGetInstructionEncoder: VariableSizeEncoder<Instruction> | undefined;\nexport function getInstructionEncoder(): VariableSizeEncoder<Instruction> {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = mapEncoder<Required<Instruction>, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder()],\n ['accountIndices', getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],\n ['data', getBytesEncoder({ size: getShortU16Encoder() })],\n ]),\n // Convert an instruction to have all fields defined\n (instruction: Instruction): Required<Instruction> => {\n if (instruction.accountIndices !== undefined && instruction.data !== undefined) {\n return instruction as Required<Instruction>;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0),\n } as Required<Instruction>;\n },\n );\n }\n\n return memoizedGetInstructionEncoder;\n}\n\nlet memoizedGetInstructionDecoder: VariableSizeDecoder<Instruction> | undefined;\nexport function getInstructionDecoder(): VariableSizeDecoder<Instruction> {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = mapDecoder<Required<Instruction>, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder()],\n ['accountIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n ['data', getBytesDecoder({ size: getShortU16Decoder() })],\n ]),\n // Convert an instruction to exclude optional fields if they are empty\n (instruction: Required<Instruction>): Instruction => {\n if (instruction.accountIndices.length && instruction.data.byteLength) {\n return instruction;\n }\n const { accountIndices, data, ...rest } = instruction;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n },\n );\n }\n return memoizedGetInstructionDecoder;\n}\n\nexport function getInstructionCodec(): VariableSizeCodec<Instruction> {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { TransactionVersion } from '../types';\n\nconst VERSION_FLAG_MASK = 0x80;\n\nexport function getTransactionVersionEncoder(): VariableSizeEncoder<TransactionVersion> {\n return createEncoder({\n getSizeFromValue: value => (value === 'legacy' ? 0 : 1),\n maxSize: 1,\n write: (value, bytes, offset) => {\n if (value === 'legacy') {\n return offset;\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 bytes.set([value | VERSION_FLAG_MASK], offset);\n return offset + 1;\n },\n });\n}\n\nexport function getTransactionVersionDecoder(): VariableSizeDecoder<TransactionVersion> {\n return createDecoder({\n maxSize: 1,\n read: (bytes, offset) => {\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 });\n}\n\nexport function getTransactionVersionCodec(): VariableSizeCodec<TransactionVersion> {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import {\n combineCodec,\n FixedSizeDecoder,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { CompilableTransaction } from '../compilable-transaction';\nimport { CompiledTransaction, getCompiledTransaction } from '../compile-transaction';\nimport { decompileTransaction } from '../decompile-transaction';\nimport { ITransactionWithSignatures } from '../signatures';\nimport { getCompiledMessageDecoder, getCompiledMessageEncoder } from './message';\n\nfunction getCompiledTransactionEncoder(): VariableSizeEncoder<CompiledTransaction> {\n return getStructEncoder([\n ['signatures', getArrayEncoder(getBytesEncoder({ size: 64 }), { size: getShortU16Encoder() })],\n ['compiledMessage', getCompiledMessageEncoder()],\n ]);\n}\n\nfunction getCompiledTransactionDecoder(): VariableSizeDecoder<CompiledTransaction> {\n return getStructDecoder([\n [\n 'signatures',\n getArrayDecoder(getBytesDecoder({ size: 64 }) as FixedSizeDecoder<SignatureBytes, 64>, {\n size: getShortU16Decoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageDecoder()],\n ]);\n}\n\nexport function getTransactionEncoder(): VariableSizeEncoder<\n CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n> {\n return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);\n}\n\nexport function getTransactionDecoder(\n lastValidBlockHeight?: bigint,\n): VariableSizeDecoder<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return mapDecoder(getCompiledTransactionDecoder(), compiledTransaction =>\n decompileTransaction(compiledTransaction, lastValidBlockHeight),\n );\n}\n\nexport function getTransactionCodec(\n lastValidBlockHeight?: bigint,\n): VariableSizeCodec<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));\n}\n","import { SignatureBytes } from '@solana/keys';\n\nimport { CompilableTransaction } from './compilable-transaction';\nimport { CompiledMessage, compileMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\n\nexport type CompiledTransaction = Readonly<{\n compiledMessage: CompiledMessage;\n signatures: SignatureBytes[];\n}>;\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 { Address, assertIsAddress } from '@solana/addresses';\nimport { pipe } from '@solana/functional';\nimport { AccountRole, IAccountMeta, IInstruction } from '@solana/instructions';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { Blockhash, setTransactionLifetimeUsingBlockhash } from './blockhash';\nimport { CompilableTransaction } from './compilable-transaction';\nimport { CompiledTransaction } from './compile-transaction';\nimport { createTransaction } from './create-transaction';\nimport { isAdvanceNonceAccountInstruction, Nonce, setTransactionLifetimeUsingDurableNonce } from './durable-nonce';\nimport { setTransactionFeePayer } from './fee-payer';\nimport { appendTransactionInstruction } from './instructions';\nimport { CompiledMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\nimport { TransactionVersion } from './types';\n\nfunction getAccountMetas(message: CompiledMessage): IAccountMeta[] {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts =\n message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n\n const accountMetas: IAccountMeta[] = [];\n\n let accountIndex = 0;\n for (let i = 0; i < numWritableSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlySignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY,\n });\n accountIndex++;\n }\n\n return accountMetas;\n}\n\nfunction convertInstruction(\n instruction: CompiledMessage['instructions'][0],\n accountMetas: IAccountMeta[],\n): IInstruction {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n // TODO coded error\n throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);\n }\n\n const accounts = instruction.accountIndices?.map(accountIndex => accountMetas[accountIndex]);\n const { data } = instruction;\n\n return {\n programAddress,\n ...(accounts && accounts.length ? { accounts } : {}),\n ...(data && data.length ? { data } : {}),\n };\n}\n\ntype LifetimeConstraint =\n | {\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n }\n | {\n nonce: Nonce;\n nonceAccountAddress: Address;\n nonceAuthorityAddress: Address;\n };\n\nfunction getLifetimeConstraint(\n messageLifetimeToken: string,\n firstInstruction?: IInstruction,\n lastValidBlockHeight?: bigint,\n): LifetimeConstraint {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n // first instruction is not advance durable nonce, so use blockhash lifetime constraint\n return {\n blockhash: messageLifetimeToken as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n } else {\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = firstInstruction.accounts![0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = firstInstruction.accounts![2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n return {\n nonce: messageLifetimeToken as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n }\n}\n\nfunction convertSignatures(compiledTransaction: CompiledTransaction): ITransactionWithSignatures['signatures'] {\n const {\n compiledMessage: { staticAccounts },\n signatures,\n } = compiledTransaction;\n return signatures.reduce((acc, sig, index) => {\n // compiled transaction includes a fake all 0 signature if it hasn't been signed\n // we don't store those for the new tx model. So just skip if it's all 0s\n const allZeros = sig.every(byte => byte === 0);\n if (allZeros) return acc;\n\n const address = staticAccounts[index];\n return { ...acc, [address]: sig as SignatureBytes };\n }, {});\n}\n\nexport function decompileTransaction(\n compiledTransaction: CompiledTransaction,\n lastValidBlockHeight?: bigint,\n): CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures) {\n const { compiledMessage } = compiledTransaction;\n\n // TODO: add support for address lookup tables\n if ('addressTableLookups' in compiledMessage && compiledMessage.addressTableLookups!.length > 0) {\n // TODO: coded error\n throw new Error('Cannot convert transaction with addressTableLookups');\n }\n\n const feePayer = compiledMessage.staticAccounts[0];\n // TODO: coded error\n if (!feePayer) throw new Error('No fee payer set in CompiledTransaction');\n\n const accountMetas = getAccountMetas(compiledMessage);\n\n const instructions: IInstruction[] = compiledMessage.instructions.map(compiledInstruction =>\n convertInstruction(compiledInstruction, accountMetas),\n );\n\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledMessage.lifetimeToken,\n firstInstruction,\n lastValidBlockHeight,\n );\n\n const signatures = convertSignatures(compiledTransaction);\n\n return pipe(\n createTransaction({ version: compiledMessage.version as TransactionVersion }),\n tx => setTransactionFeePayer(feePayer, tx),\n tx =>\n instructions.reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n tx =>\n 'blockhash' in lifetimeConstraint\n ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx)\n : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),\n tx => (compiledTransaction.signatures.length ? { ...tx, signatures } : tx),\n );\n}\n","import { Address } from '@solana/addresses';\nimport { Signature } from '@solana/keys';\nimport type { GetSignatureStatusesApi, RequestAirdropApi, SignatureNotificationsApi } from '@solana/rpc-core';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport';\nimport { Commitment, LamportsUnsafeBeyond2Pow53Minus1 } from '@solana/rpc-types';\n\nimport { createDefaultSignatureOnlyRecentTransactionConfirmer } from './airdrop-confirmer';\n\ntype AirdropRequesterConfig = Readonly<{\n rpc: Rpc<RequestAirdropApi & GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>;\n}>;\n\nexport function createDefaultAirdropRequester({ rpc, rpcSubscriptions }: AirdropRequesterConfig) {\n const confirmSignatureOnlyTransaction = createDefaultSignatureOnlyRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n });\n return async function requestAirdrop(\n config: Omit<Parameters<typeof requestAndConfirmAirdrop>[0], 'confirmSignatureOnlyTransaction' | 'rpc'>,\n ) {\n return await requestAndConfirmAirdrop({\n ...config,\n confirmSignatureOnlyTransaction,\n rpc,\n });\n };\n}\n\nexport async function requestAndConfirmAirdrop({\n abortSignal,\n commitment,\n confirmSignatureOnlyTransaction,\n lamports,\n recipientAddress,\n rpc,\n}: Readonly<{\n abortSignal?: AbortSignal;\n commitment: Commitment;\n confirmSignatureOnlyTransaction: ReturnType<typeof createDefaultSignatureOnlyRecentTransactionConfirmer>;\n lamports: LamportsUnsafeBeyond2Pow53Minus1;\n recipientAddress: Address;\n rpc: Rpc<RequestAirdropApi>;\n}>): Promise<Signature> {\n const airdropTransactionSignature = await rpc\n .requestAirdrop(recipientAddress, lamports, { commitment })\n .send({ abortSignal });\n await confirmSignatureOnlyTransaction({\n abortSignal,\n commitment,\n signature: airdropTransactionSignature,\n });\n return airdropTransactionSignature;\n}\n","import { Signature } from '@solana/keys';\nimport type { GetSignatureStatusesApi, SignatureNotificationsApi } from '@solana/rpc-core';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport';\n\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './transaction-confirmation-strategy-racer';\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\nimport { getTimeoutPromise } from './transaction-confirmation-strategy-timeout';\n\ninterface DefaultSignatureOnlyRecentTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>;\n}\n\ninterface WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig\n extends BaseTransactionConfirmationStrategyConfig {\n getTimeoutPromise: typeof getTimeoutPromise;\n signature: Signature;\n}\n\n/** @deprecated */\nexport function createDefaultSignatureOnlyRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultSignatureOnlyRecentTransactionConfirmerConfig) {\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions,\n );\n return async function confirmSignatureOnlyRecentTransaction(\n config: Omit<\n Parameters<typeof waitForRecentTransactionConfirmationUntilTimeout>[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmationUntilTimeout({\n ...config,\n getRecentSignatureConfirmationPromise,\n getTimeoutPromise,\n });\n };\n}\n\n/** @deprecated */\nexport async function waitForRecentTransactionConfirmationUntilTimeout(\n config: WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig,\n): Promise<void> {\n await raceStrategies(\n config.signature,\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise }) {\n return [\n getTimeoutPromise({\n abortSignal,\n commitment,\n }),\n ];\n },\n );\n}\n","import { Signature } from '@solana/keys';\nimport { Commitment } from '@solana/rpc-types';\n\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\n\nexport interface BaseTransactionConfirmationStrategyConfig {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n getRecentSignatureConfirmationPromise: ReturnType<typeof createRecentSignatureConfirmationPromiseFactory>;\n}\n\ntype WithNonNullableAbortSignal<T> = Omit<T, 'abortSignal'> & Readonly<{ abortSignal: AbortSignal }>;\n\nexport async function raceStrategies<TConfig extends BaseTransactionConfirmationStrategyConfig>(\n signature: Signature,\n config: TConfig,\n getSpecificStrategiesForRace: (config: WithNonNullableAbortSignal<TConfig>) => readonly Promise<unknown>[],\n) {\n const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;\n callerAbortSignal?.throwIfAborted();\n const abortController = new AbortController();\n if (callerAbortSignal) {\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n }\n try {\n const specificStrategies = getSpecificStrategiesForRace({\n ...config,\n abortSignal: abortController.signal,\n });\n return await Promise.race([\n getRecentSignatureConfirmationPromise({\n abortSignal: abortController.signal,\n commitment,\n signature,\n }),\n ...specificStrategies,\n ]);\n } finally {\n abortController.abort();\n }\n}\n","import { Signature } from '@solana/keys';\nimport type { GetSignatureStatusesApi, SignatureNotificationsApi } from '@solana/rpc-core';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\n\ntype GetRecentSignatureConfirmationPromiseFn = (config: {\n abortSignal: AbortSignal;\n commitment: Commitment;\n signature: Signature;\n}) => Promise<void>;\n\nexport function createRecentSignatureConfirmationPromiseFactory(\n rpc: Rpc<GetSignatureStatusesApi>,\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>,\n): GetRecentSignatureConfirmationPromiseFn {\n return async function getRecentSignatureConfirmationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n signature,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for status changes to a signature.\n */\n const signatureStatusNotifications = await rpcSubscriptions\n .signatureNotifications(signature, { commitment })\n .subscribe({ abortSignal: abortController.signal });\n const signatureDidCommitPromise = (async () => {\n for await (const signatureStatusNotification of signatureStatusNotifications) {\n if (signatureStatusNotification.value.err) {\n // TODO: Coded error.\n throw new Error(`The transaction with signature \\`${signature}\\` failed.`, {\n cause: signatureStatusNotification.value.err,\n });\n } else {\n return;\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current status.\n * This will only yield a result if the signature is still in the status cache.\n */\n const signatureStatusLookupPromise = (async () => {\n const { value: signatureStatusResults } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: abortController.signal });\n const signatureStatus = signatureStatusResults[0];\n if (\n signatureStatus &&\n signatureStatus.confirmationStatus &&\n commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0\n ) {\n return;\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await Promise.race([signatureDidCommitPromise, signatureStatusLookupPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import { Commitment } from '@solana/rpc-types';\n\ntype Config = Readonly<{\n abortSignal: AbortSignal;\n commitment: Commitment;\n}>;\n\nexport async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }: Config) {\n return await new Promise((_, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n clearTimeout(timeoutId);\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n callerAbortSignal.addEventListener('abort', handleAbort);\n const timeoutMs = commitment === 'processed' ? 30_000 : 60_000;\n const startMs = performance.now();\n const timeoutId =\n // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure\n // elapsed time instead of active time.\n // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static\n setTimeout(() => {\n const elapsedMs = performance.now() - startMs;\n reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, 'TimeoutError'));\n }, timeoutMs);\n });\n}\n","import { pipe } from '@solana/functional';\nimport {\n createSolanaRpcApi,\n createSolanaRpcSubscriptionsApi,\n createSolanaRpcSubscriptionsApi_UNSTABLE,\n SolanaRpcMethods,\n SolanaRpcSubscriptions,\n SolanaRpcSubscriptionsUnstable,\n} from '@solana/rpc-core';\nimport { createJsonRpc, createJsonSubscriptionRpc, type Rpc, type RpcSubscriptions } from '@solana/rpc-transport';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\n\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\nimport { getRpcSubscriptionsWithSubscriptionCoalescing } from './rpc-subscription-coalescer';\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 pipe(\n createJsonSubscriptionRpc({\n ...config,\n api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG),\n }),\n rpcSubscriptions =>\n getRpcSubscriptionsWithSubscriptionCoalescing({\n getDeduplicationKey: (...args) => fastStableStringify(args),\n rpcSubscriptions,\n }),\n );\n}\n\nexport function createSolanaRpcSubscriptions_UNSTABLE(\n config: Omit<Parameters<typeof createJsonSubscriptionRpc>[0], 'api'>,\n): RpcSubscriptions<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return createJsonSubscriptionRpc({\n ...config,\n api: createSolanaRpcSubscriptionsApi_UNSTABLE(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","export type KeyPathWildcard = { readonly __brand: unique symbol };\n\nexport const KEYPATH_WILDCARD = {} as KeyPathWildcard;\n","import type { IRpcSubscriptionsApi } from '@solana/rpc-transport';\n\nimport { KeyPath } from './response-patcher';\nimport { KEYPATH_WILDCARD } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\nimport { SolanaRpcSubscriptions, SolanaRpcSubscriptionsUnstable } from './rpc-subscriptions';\n\n// Numeric values nested in `jsonParsed` accounts\nconst 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 ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'olderTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'newerTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n];\nconst 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\ntype AllowedNumericKeypaths<TApi> = Partial<Record<keyof TApi, readonly KeyPath[]>>;\n\nlet memoizedNotificationKeypaths: AllowedNumericKeypaths<\n IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>\n>;\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 IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>\n> {\n if (!memoizedNotificationKeypaths) {\n memoizedNotificationKeypaths = {\n accountNotifications: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n blockNotifications: [\n ['value', 'block', 'blockTime'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['value', 'block', 'transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'index',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\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 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlySignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlyUnsignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numRequiredSignatures',\n ],\n ['value', 'block', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n programNotifications: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n };\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 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 type { IRpcApi, RpcRequest } from '@solana/rpc-transport';\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 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\nexport type {\n GetAccountInfoApi,\n GetBlockApi,\n GetProgramAccountsApi,\n GetSignatureStatusesApi,\n GetTransactionApi,\n RequestAirdropApi,\n SendTransactionApi,\n};\n\nexport type {\n Base64EncodedDataResponse,\n DataSlice,\n GetProgramAccountsDatasizeFilter,\n GetProgramAccountsMemcmpFilter,\n Slot,\n} from './common';\n","import type { IRpcSubscriptionsApi, RpcSubscription } from '@solana/rpc-transport';\n\nimport { patchParamsForSolanaLabsRpc } from '../params-patcher';\nimport { patchResponseForSolanaLabsRpcSubscriptions } from '../response-patcher';\nimport { AccountNotificationsApi } from './account-notifications';\nimport { BlockNotificationsApi } from './block-notifications';\nimport { LogsNotificationsApi } from './logs-notifications';\nimport { ProgramNotificationsApi } from './program-notifications';\nimport { RootNotificationsApi } from './root-notifications';\nimport { SignatureNotificationsApi } from './signature-notifications';\nimport { SlotNotificationsApi } from './slot-notifications';\nimport { SlotsUpdatesNotificationsApi } from './slots-updates-notifications';\nimport { VoteNotificationsApi } from './vote-notifications';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcSubscriptions = AccountNotificationsApi &\n BlockNotificationsApi &\n LogsNotificationsApi &\n ProgramNotificationsApi &\n RootNotificationsApi &\n SignatureNotificationsApi &\n SlotNotificationsApi;\nexport type SolanaRpcSubscriptionsUnstable = SlotsUpdatesNotificationsApi & VoteNotificationsApi;\n\nexport function createSolanaRpcSubscriptionsApi(\n config?: Config,\n): IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return new Proxy({} as IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<\n TNotificationName extends keyof IRpcSubscriptionsApi<\n SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable\n >,\n >(\n ...args: Parameters<\n NonNullable<\n ProxyHandler<IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>>['get']\n >\n >\n ) {\n const [_, p] = args;\n const notificationName = p.toString() as keyof (SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable);\n return function (\n ...rawParams: Parameters<\n (SolanaRpcSubscriptions &\n SolanaRpcSubscriptionsUnstable)[TNotificationName] extends CallableFunction\n ? (SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable)[TNotificationName]\n : never\n >\n ): RpcSubscription<\n ReturnType<(SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable)[TNotificationName]>\n > {\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\nexport function createSolanaRpcSubscriptionsApi_UNSTABLE(\n config?: Config,\n): IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return createSolanaRpcSubscriptionsApi(config) as IRpcSubscriptionsApi<\n SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable\n >;\n}\n\nexport type { AccountNotificationsApi, SignatureNotificationsApi, SlotNotificationsApi };\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 registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\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({ abortSignal }: SubscribeOptions): Promise<AsyncIterable<TNotification>> {\n 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 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 handleConnectionCleanup() {\n abortSignal.removeEventListener('abort', handleCleanup);\n }\n registerIterableCleanup(connection, handleConnectionCleanup);\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 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 url: string;\n}>;\n\nexport function createHttpTransport({ headers, url }: Config): IRpcTransport {\n if (__DEV__ && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\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 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\nconst EXPLICIT_ABORT_TOKEN = Symbol(\n __DEV__\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly aborted by the user\"\n : undefined,\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 errorAndClearAllIteratorStates(reason: unknown) {\n const errorCallbacks = [...iteratorState.values()]\n .filter((state): state is Extract<IteratorState, { __hasPolled: true }> => state.__hasPolled)\n .map(({ onError }) => onError);\n iteratorState.clear();\n errorCallbacks.forEach(cb => {\n try {\n cb(reason);\n } catch {\n /* empty */\n }\n });\n }\n function handleAbort() {\n errorAndClearAllIteratorStates(EXPLICIT_ABORT_TOKEN);\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 errorAndClearAllIteratorStates(ev);\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((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onError: reject,\n onMessage: resolve,\n });\n });\n } catch (e) {\n if (e === EXPLICIT_ABORT_TOKEN) {\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 { PendingRpcSubscription, RpcSubscriptions } from '@solana/rpc-transport';\n\nimport { getCachedAbortableIterableFactory } from './cached-abortable-iterable';\n\ntype CacheKey = string | undefined;\ntype Config<TRpcSubscriptionsMethods> = Readonly<{\n getDeduplicationKey: GetDeduplicationKeyFn;\n rpcSubscriptions: RpcSubscriptions<TRpcSubscriptionsMethods>;\n}>;\ntype GetDeduplicationKeyFn = (subscriptionMethod: string | symbol, payload: unknown) => CacheKey;\n\nconst EXPLICIT_ABORT_TOKEN = Symbol(\n __DEV__\n ? \"This symbol is thrown from a subscription's iterator when the subscription is \" +\n 'explicitly aborted by the user'\n : undefined,\n);\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nexport function getRpcSubscriptionsWithSubscriptionCoalescing<TRpcSubscriptionsMethods>({\n getDeduplicationKey,\n rpcSubscriptions,\n}: Config<TRpcSubscriptionsMethods>): RpcSubscriptions<TRpcSubscriptionsMethods> {\n const cache = new Map<CacheKey, PendingRpcSubscription<unknown>>();\n return new Proxy(rpcSubscriptions, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n const subscriptionMethod = Reflect.get(target, p, receiver);\n if (typeof subscriptionMethod !== 'function') {\n return subscriptionMethod;\n }\n return function (...rawParams: unknown[]) {\n const deduplicationKey = getDeduplicationKey(p, rawParams);\n if (deduplicationKey === undefined) {\n return (subscriptionMethod as CallableFunction)(...rawParams);\n }\n if (cache.has(deduplicationKey)) {\n return cache.get(deduplicationKey)!;\n }\n const iterableFactory = getCachedAbortableIterableFactory<\n Parameters<PendingRpcSubscription<unknown>['subscribe']>,\n AsyncIterable<unknown>\n >({\n getAbortSignalFromInputArgs: ({ abortSignal }) => abortSignal,\n getCacheEntryMissingError(deduplicationKey) {\n // TODO: Coded error.\n return new Error(\n `Found no cache entry for subscription with deduplication key \\`${deduplicationKey?.toString()}\\``,\n );\n },\n getCacheKeyFromInputArgs: () => deduplicationKey,\n async onCacheHit(_iterable, _config) {\n /**\n * This transport's goal is to prevent duplicate subscriptions from\n * being made. If a cached iterable] is found, do not send the subscribe\n * message again.\n */\n },\n async onCreateIterable(abortSignal, config) {\n const pendingSubscription = (subscriptionMethod as CallableFunction)(\n ...rawParams,\n ) as PendingRpcSubscription<unknown>;\n const iterable = await pendingSubscription.subscribe({\n ...config,\n abortSignal,\n });\n registerIterableCleanup(iterable, () => {\n cache.delete(deduplicationKey);\n });\n return iterable;\n },\n });\n const pendingSubscription: PendingRpcSubscription<unknown> = {\n async subscribe(...args) {\n const iterable = await iterableFactory(...args);\n const { abortSignal } = args[0];\n let abortPromise;\n return {\n ...iterable,\n async *[Symbol.asyncIterator]() {\n abortPromise ||= abortSignal.aborted\n ? Promise.reject(EXPLICIT_ABORT_TOKEN)\n : new Promise<never>((_, reject) => {\n abortSignal.addEventListener('abort', () => {\n reject(EXPLICIT_ABORT_TOKEN);\n });\n });\n try {\n const iterator = iterable[Symbol.asyncIterator]();\n while (true) {\n const iteratorResult = await Promise.race([iterator.next(), abortPromise]);\n if (iteratorResult.done) {\n return;\n } else {\n yield iteratorResult.value;\n }\n }\n } catch (e) {\n if (e === EXPLICIT_ABORT_TOKEN) {\n return;\n }\n cache.delete(deduplicationKey);\n throw e;\n }\n },\n };\n },\n };\n cache.set(deduplicationKey, pendingSubscription);\n return pendingSubscription;\n };\n },\n });\n}\n","type CacheEntry<TIterable extends AsyncIterable<unknown>> = {\n abortController: AbortController;\n iterable: Promise<TIterable> | TIterable;\n purgeScheduled: boolean;\n referenceCount: number;\n};\ntype CacheKey = string | symbol;\ntype Config<TInput extends unknown[], TIterable extends AsyncIterable<unknown>> = Readonly<{\n getAbortSignalFromInputArgs: (...args: TInput) => AbortSignal;\n getCacheEntryMissingError: (cacheKey: CacheKey) => Error;\n getCacheKeyFromInputArgs: (...args: TInput) =>\n | CacheKey\n // `undefined` implies 'do not cache'\n | undefined;\n onCacheHit: (iterable: TIterable, ...args: TInput) => Promise<void>;\n onCreateIterable: (abortSignal: AbortSignal, ...args: TInput) => Promise<TIterable>;\n}>;\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nexport function getCachedAbortableIterableFactory<TInput extends unknown[], TIterable extends AsyncIterable<unknown>>({\n getAbortSignalFromInputArgs,\n getCacheEntryMissingError,\n getCacheKeyFromInputArgs,\n onCacheHit,\n onCreateIterable,\n}: Config<TInput, TIterable>): (...args: TInput) => Promise<TIterable> {\n const cache = new Map<CacheKey, CacheEntry<TIterable>>();\n function getCacheEntryOrThrow(cacheKey: CacheKey) {\n const currentCacheEntry = cache.get(cacheKey);\n if (!currentCacheEntry) {\n throw getCacheEntryMissingError(cacheKey);\n }\n return currentCacheEntry;\n }\n return async (...args: TInput) => {\n const cacheKey = getCacheKeyFromInputArgs(...args);\n const signal = getAbortSignalFromInputArgs(...args);\n if (cacheKey === undefined) {\n return await onCreateIterable(signal, ...args);\n }\n const cleanup = () => {\n cache.delete(cacheKey);\n signal.removeEventListener('abort', handleAbort);\n };\n const handleAbort = () => {\n const cacheEntry = getCacheEntryOrThrow(cacheKey);\n if (cacheEntry.purgeScheduled !== true) {\n cacheEntry.purgeScheduled = true;\n globalThis.queueMicrotask(() => {\n cacheEntry.purgeScheduled = false;\n if (cacheEntry.referenceCount === 0) {\n cacheEntry.abortController.abort();\n cleanup();\n }\n });\n }\n cacheEntry.referenceCount--;\n };\n signal.addEventListener('abort', handleAbort);\n try {\n const cacheEntry = cache.get(cacheKey);\n if (!cacheEntry) {\n const singletonAbortController = new AbortController();\n const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);\n const newCacheEntry: CacheEntry<TIterable> = {\n abortController: singletonAbortController,\n iterable: newIterablePromise,\n purgeScheduled: false,\n referenceCount: 1,\n };\n cache.set(cacheKey, newCacheEntry);\n const newIterable = await newIterablePromise;\n registerIterableCleanup(newIterable, cleanup);\n newCacheEntry.iterable = newIterable;\n return newIterable;\n } else {\n cacheEntry.referenceCount++;\n const iterableOrIterablePromise = cacheEntry.iterable;\n const cachedIterable =\n 'then' in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;\n await onCacheHit(cachedIterable, ...args);\n return cachedIterable;\n }\n } catch (e) {\n cleanup();\n throw e;\n }\n };\n}\n","import { pipe } from '@solana/functional';\nimport { createHttpTransport, type IRpcTransport } from '@solana/rpc-transport';\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 pipe(\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 transport => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey),\n );\n}\n","import type { IRpcTransport } from '@solana/rpc-transport';\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\nfunction isJsonRpcPayload(payload: unknown): payload is Readonly<{ method: string; params: unknown }> {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n return (\n 'jsonrpc' in payload &&\n payload.jsonrpc === '2.0' &&\n 'method' in payload &&\n typeof payload.method === 'string' &&\n 'params' in payload\n );\n}\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n return isJsonRpcPayload(payload) ? fastStableStringify([payload.method, payload.params]) : undefined;\n}\n","import { pipe } from '@solana/functional';\nimport { createWebSocketTransport, type IRpcWebSocketTransport } from '@solana/rpc-transport';\n\nimport { getWebSocketTransportWithAutoping } from './rpc-websocket-autopinger';\nimport { getWebSocketTransportWithConnectionSharding } from './rpc-websocket-connection-sharding';\n\nexport function createDefaultRpcSubscriptionsTransport(\n config: Omit<Parameters<typeof createWebSocketTransport>[0], 'sendBufferHighWatermark'> & {\n /**\n * You might like to open more subscriptions per connection than your RPC provider allows\n * for. Using the initial payload as input, return a shard key from this method to assign\n * subscriptions to separate connections. One socket will be opened per shard key.\n */\n getShard?: (payload: unknown) => string;\n intervalMs?: number;\n sendBufferHighWatermark?: number;\n },\n): IRpcWebSocketTransport {\n const { getShard, intervalMs, ...rest } = config;\n return pipe(\n 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 transport =>\n getWebSocketTransportWithAutoping({\n intervalMs: intervalMs ?? 5_000,\n transport,\n }),\n transport =>\n getWebSocketTransportWithConnectionSharding({\n getShard,\n transport,\n }),\n );\n}\n","import type { IRpcWebSocketTransport } from '@solana/rpc-transport';\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: number | undefined;\n function sendPing() {\n connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);\n }\n function restartPingTimer() {\n clearInterval(intervalId);\n intervalId = setInterval(sendPing, 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 if (handleOffline) {\n globalThis.window.removeEventListener('offline', handleOffline);\n }\n if (handleOnline) {\n globalThis.window.removeEventListener('online', handleOnline);\n }\n }\n })();\n if (!__BROWSER__ || globalThis.navigator.onLine) {\n restartPingTimer();\n }\n let handleOffline;\n let handleOnline;\n if (__BROWSER__) {\n handleOffline = () => {\n clearInterval(intervalId);\n };\n handleOnline = () => {\n sendPing();\n restartPingTimer();\n };\n globalThis.window.addEventListener('offline', handleOffline);\n globalThis.window.addEventListener('online', handleOnline);\n }\n }\n return pingableConnections.get(connection)!;\n };\n}\n","import type { IRpcWebSocketTransport } from '@solana/rpc-transport';\n\nimport { getCachedAbortableIterableFactory } from './cached-abortable-iterable';\n\ntype Config = Readonly<{\n /**\n * You might like to open more subscriptions per connection than your RPC provider allows for.\n * Using the initial payload as input, return a shard key from this method to assign\n * subscriptions to separate connections. One socket will be opened per shard key.\n */\n getShard?: (payload: unknown) => string | symbol;\n transport: IRpcWebSocketTransport;\n}>;\n\nconst NULL_SHARD_CACHE_KEY = Symbol(\n __DEV__ ? 'Cache key to use when there is no connection sharding strategy' : undefined,\n);\n\nexport function getWebSocketTransportWithConnectionSharding({ getShard, transport }: Config): IRpcWebSocketTransport {\n return getCachedAbortableIterableFactory({\n getAbortSignalFromInputArgs: ({ signal }) => signal,\n getCacheEntryMissingError(shardKey) {\n // TODO: Coded error.\n return new Error(`Found no cache entry for connection with shard key \\`${shardKey?.toString()}\\``);\n },\n getCacheKeyFromInputArgs: ({ payload }) => (getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY),\n onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),\n onCreateIterable: (abortSignal, config) =>\n transport({\n ...config,\n signal: abortSignal,\n }),\n });\n}\n","import { Signature } from '@solana/keys';\nimport type { SendTransactionApi } from '@solana/rpc-core';\nimport type { Rpc } from '@solana/rpc-transport';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\nimport {\n BaseTransaction,\n getBase64EncodedWireTransaction,\n IDurableNonceTransaction,\n IFullySignedTransaction,\n ITransactionWithBlockhashLifetime,\n ITransactionWithFeePayer,\n} from '@solana/transactions';\n\nimport {\n createDefaultDurableNonceTransactionConfirmer,\n createDefaultRecentTransactionConfirmer,\n} from './transaction-confirmation';\n\ninterface DurableNonceTransactionSenderFactoryConfig {\n rpc: Rpc<SendTransactionApi> & Parameters<typeof createDefaultDurableNonceTransactionConfirmer>[0]['rpc'];\n rpcSubscriptions: Parameters<typeof createDefaultDurableNonceTransactionConfirmer>[0]['rpcSubscriptions'];\n}\n\ninterface TransactionWithBlockhashLifetimeSenderFactoryConfig {\n rpc: Rpc<SendTransactionApi> & Parameters<typeof createDefaultRecentTransactionConfirmer>[0]['rpc'];\n rpcSubscriptions: Parameters<typeof createDefaultRecentTransactionConfirmer>[0]['rpcSubscriptions'];\n}\n\ninterface SendAndConfirmDurableNonceTransactionConfig\n extends SendTransactionInternalConfig,\n SendTransactionConfigWithoutEncoding {\n confirmDurableNonceTransaction: ReturnType<typeof createDefaultDurableNonceTransactionConfirmer>;\n transaction: SendableTransaction & IDurableNonceTransaction;\n}\n\ninterface SendAndConfirmTransactionWithBlockhashLifetimeConfig\n extends SendTransactionInternalConfig,\n SendTransactionConfigWithoutEncoding {\n confirmRecentTransaction: ReturnType<typeof createDefaultRecentTransactionConfirmer>;\n transaction: SendableTransaction & ITransactionWithBlockhashLifetime;\n}\n\ninterface SendTransactionInternalConfig extends SendTransactionConfigWithoutEncoding {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n rpc: Rpc<SendTransactionApi>;\n transaction: SendableTransaction;\n}\n\ntype SendableTransaction = BaseTransaction &\n (ITransactionWithBlockhashLifetime | IDurableNonceTransaction) &\n ITransactionWithFeePayer &\n IFullySignedTransaction;\ntype SendTransactionConfig = Parameters<SendTransactionApi['sendTransaction']>[1];\ninterface SendTransactionConfigWithoutEncoding extends Omit<NonNullable<SendTransactionConfig>, 'encoding'> {}\n\nfunction getSendTransactionConfigWithAdjustedPreflightCommitment(\n commitment: Commitment,\n config?: SendTransactionConfigWithoutEncoding,\n): SendTransactionConfigWithoutEncoding | void {\n if (\n // The developer has supplied no value for `preflightCommitment`.\n !config?.preflightCommitment &&\n // The value of `commitment` is lower than the server default of `preflightCommitment`.\n commitmentComparator(commitment, 'finalized' /* default value of `preflightCommitment` */) < 0\n ) {\n return {\n ...config,\n // In the common case, it is unlikely that you want to simulate a transaction at\n // `finalized` commitment when your standard of commitment for confirming the\n // transaction is lower. Cap the simulation commitment level to the level of the\n // confirmation commitment.\n preflightCommitment: commitment,\n };\n }\n // The commitment at which the developer wishes to confirm the transaction is at least as\n // high as the commitment at which they want to simulate it. Honour the config as-is.\n return config;\n}\n\nasync function sendTransaction_INTERNAL({\n abortSignal,\n commitment,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendTransactionInternalConfig): Promise<Signature> {\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);\n return await rpc\n .sendTransaction(base64EncodedWireTransaction, {\n ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),\n encoding: 'base64',\n })\n .send({ abortSignal });\n}\n\nexport function createDefaultDurableNonceTransactionSender({\n rpc,\n rpcSubscriptions,\n}: DurableNonceTransactionSenderFactoryConfig) {\n const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n });\n return async function sendDurableNonceTransaction(\n transaction: BaseTransaction & ITransactionWithFeePayer & IDurableNonceTransaction & IFullySignedTransaction,\n config: Omit<\n Parameters<typeof sendAndConfirmDurableNonceTransaction>[0],\n 'confirmDurableNonceTransaction' | 'rpc' | 'transaction'\n >,\n ): Promise<void> {\n await sendAndConfirmDurableNonceTransaction({\n ...config,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n });\n };\n}\n\nexport function createDefaultTransactionSender({\n rpc,\n rpcSubscriptions,\n}: TransactionWithBlockhashLifetimeSenderFactoryConfig) {\n const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n });\n return async function sendTransaction(\n transaction: SendableTransaction & ITransactionWithBlockhashLifetime,\n config: Omit<\n Parameters<typeof sendAndConfirmTransaction>[0],\n 'confirmRecentTransaction' | 'rpc' | 'transaction'\n >,\n ): Promise<void> {\n await sendAndConfirmTransaction({\n ...config,\n confirmRecentTransaction,\n rpc,\n transaction,\n });\n };\n}\n\nexport async function sendAndConfirmDurableNonceTransaction({\n abortSignal,\n commitment,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmDurableNonceTransactionConfig): Promise<Signature> {\n const transactionSignature = await sendTransaction_INTERNAL({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmDurableNonceTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n\nexport async function sendAndConfirmTransaction({\n abortSignal,\n commitment,\n confirmRecentTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmTransactionWithBlockhashLifetimeConfig): Promise<Signature> {\n const transactionSignature = await sendTransaction_INTERNAL({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmRecentTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n","import type {\n AccountNotificationsApi,\n GetAccountInfoApi,\n GetSignatureStatusesApi,\n SignatureNotificationsApi,\n Slot,\n SlotNotificationsApi,\n} from '@solana/rpc-core';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport';\nimport {\n getSignatureFromTransaction,\n IDurableNonceTransaction,\n ITransactionWithFeePayer,\n ITransactionWithSignatures,\n} from '@solana/transactions';\n\nimport { createBlockHeightExceedencePromiseFactory } from './transaction-confirmation-strategy-blockheight';\nimport { createNonceInvalidationPromiseFactory } from './transaction-confirmation-strategy-nonce';\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './transaction-confirmation-strategy-racer';\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\n\ninterface DefaultDurableNonceTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi & GetAccountInfoApi>;\n rpcSubscriptions: RpcSubscriptions<AccountNotificationsApi & SignatureNotificationsApi>;\n}\n\ninterface DefaultRecentTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi & SlotNotificationsApi>;\n}\n\ninterface WaitForDurableNonceTransactionConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getNonceInvalidationPromise: ReturnType<typeof createNonceInvalidationPromiseFactory>;\n transaction: ITransactionWithFeePayer & ITransactionWithSignatures & IDurableNonceTransaction;\n}\n\ninterface WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig\n extends BaseTransactionConfirmationStrategyConfig {\n getBlockHeightExceedencePromise: ReturnType<typeof createBlockHeightExceedencePromiseFactory>;\n transaction: ITransactionWithFeePayer &\n ITransactionWithSignatures &\n Readonly<{\n lifetimeConstraint: {\n lastValidBlockHeight: Slot;\n };\n }>;\n}\n\nexport function createDefaultDurableNonceTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultDurableNonceTransactionConfirmerConfig) {\n const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions,\n );\n return async function confirmDurableNonceTransaction(\n config: Omit<\n Parameters<typeof waitForDurableNonceTransactionConfirmation>[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n await waitForDurableNonceTransactionConfirmation({\n ...config,\n getNonceInvalidationPromise,\n getRecentSignatureConfirmationPromise,\n });\n };\n}\n\nexport function createDefaultRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultRecentTransactionConfirmerConfig) {\n const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory(rpcSubscriptions);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions,\n );\n return async function confirmRecentTransaction(\n config: Omit<\n Parameters<typeof waitForRecentTransactionConfirmation>[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmation({\n ...config,\n getBlockHeightExceedencePromise,\n getRecentSignatureConfirmationPromise,\n });\n };\n}\n\nexport async function waitForDurableNonceTransactionConfirmation(\n config: WaitForDurableNonceTransactionConfirmationConfig,\n): Promise<void> {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {\n return [\n getNonceInvalidationPromise({\n abortSignal,\n commitment,\n currentNonceValue: transaction.lifetimeConstraint.nonce,\n nonceAccountAddress: transaction.instructions[0].accounts[0].address,\n }),\n ];\n },\n );\n}\n\nexport async function waitForRecentTransactionConfirmation(\n config: WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig,\n): Promise<void> {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, getBlockHeightExceedencePromise, transaction }) {\n return [\n getBlockHeightExceedencePromise({\n abortSignal,\n lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight,\n }),\n ];\n },\n );\n}\n","import type { Slot, SlotNotificationsApi } from '@solana/rpc-core';\nimport type { RpcSubscriptions } from '@solana/rpc-transport';\n\ntype GetBlockHeightExceedencePromiseFn = (config: {\n abortSignal: AbortSignal;\n lastValidBlockHeight: Slot;\n}) => Promise<void>;\n\nexport function createBlockHeightExceedencePromiseFactory(\n rpcSubscriptions: RpcSubscriptions<SlotNotificationsApi>,\n): GetBlockHeightExceedencePromiseFn {\n return async function getBlockHeightExceedencePromise({ abortSignal: callerAbortSignal, lastValidBlockHeight }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n const slotNotifications = await rpcSubscriptions\n .slotNotifications()\n .subscribe({ abortSignal: abortController.signal });\n try {\n for await (const slotNotification of slotNotifications) {\n if (slotNotification.slot > lastValidBlockHeight) {\n // TODO: Coded error.\n throw new Error(\n 'The network has progressed past the last block for which this transaction ' +\n 'could have committed.',\n );\n }\n }\n } finally {\n abortController.abort();\n }\n };\n}\n","import { Address } from '@solana/addresses';\nimport { getBase58Decoder, getBase64Encoder } from '@solana/codecs-strings';\nimport type { AccountNotificationsApi, Base64EncodedDataResponse, GetAccountInfoApi } from '@solana/rpc-core';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport';\nimport { Commitment } from '@solana/rpc-types';\nimport { Nonce } from '@solana/transactions';\n\ntype GetNonceInvalidationPromiseFn = (config: {\n abortSignal: AbortSignal;\n commitment: Commitment;\n currentNonceValue: Nonce;\n nonceAccountAddress: Address;\n}) => Promise<void>;\n\nconst NONCE_VALUE_OFFSET =\n 4 + // version(u32)\n 4 + // state(u32)\n 32; // nonce authority(pubkey)\n// Then comes the nonce value.\n\nexport function createNonceInvalidationPromiseFactory(\n rpc: Rpc<GetAccountInfoApi>,\n rpcSubscriptions: RpcSubscriptions<AccountNotificationsApi>,\n): GetNonceInvalidationPromiseFn {\n return async function getNonceInvalidationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n currentNonceValue,\n nonceAccountAddress,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for nonce account changes.\n */\n const accountNotifications = await rpcSubscriptions\n .accountNotifications(nonceAccountAddress, { commitment, encoding: 'base64' })\n .subscribe({ abortSignal: abortController.signal });\n const base58Decoder = getBase58Decoder();\n const base64Encoder = getBase64Encoder();\n function getNonceFromAccountData([base64EncodedBytes]: Base64EncodedDataResponse): Nonce {\n const data = base64Encoder.encode(base64EncodedBytes);\n const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);\n return base58Decoder.decode(nonceValueBytes) as Nonce;\n }\n const nonceAccountDidAdvancePromise = (async () => {\n for await (const accountNotification of accountNotifications) {\n const nonceValue = getNonceFromAccountData(accountNotification.value.data);\n if (nonceValue !== currentNonceValue) {\n throw new Error(\n `The nonce \\`${currentNonceValue}\\` is no longer valid. It has advanced ` +\n `to \\`${nonceValue}\\`.`,\n );\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current nonce\n * value to check if it has already been advanced.\n */\n const nonceIsAlreadyInvalidPromise = (async () => {\n const { value: nonceAccount } = await rpc\n .getAccountInfo(nonceAccountAddress, {\n commitment,\n dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },\n encoding: 'base58',\n })\n .send({ abortSignal: abortController.signal });\n if (!nonceAccount) {\n throw new Error(`No nonce account could be found at address \\`${nonceAccountAddress}\\`.`);\n }\n const nonceValue =\n // This works because we asked for the exact slice of data representing the nonce\n // value, and furthermore asked for it in `base58` encoding.\n nonceAccount.data[0] as unknown as Nonce;\n if (nonceValue !== currentNonceValue) {\n throw new Error(\n `The nonce \\`${currentNonceValue}\\` is no longer valid. It has advanced to \\`${nonceValue}\\`.`,\n );\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n"]}