@solana/web3.js 2.0.0-experimental.95bfd9f → 2.0.0-experimental.9741939
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +1155 -43
- package/dist/index.browser.cjs +776 -11
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.js +750 -11
- package/dist/index.browser.js.map +1 -1
- package/dist/index.development.js +3181 -1022
- package/dist/index.development.js.map +1 -1
- package/dist/index.native.js +739 -11
- package/dist/index.native.js.map +1 -1
- package/dist/index.node.cjs +765 -11
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.js +739 -11
- package/dist/index.node.js.map +1 -1
- package/dist/index.production.min.js +82 -26
- package/dist/types/airdrop-confirmer.d.ts +19 -0
- package/dist/types/airdrop-confirmer.d.ts.map +1 -0
- package/dist/types/airdrop.d.ts +21 -0
- package/dist/types/airdrop.d.ts.map +1 -0
- package/dist/types/cached-abortable-iterable.d.ts +11 -0
- package/dist/types/cached-abortable-iterable.d.ts.map +1 -0
- package/dist/types/index.d.ts +11 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/rpc-request-coalescer.d.ts +1 -1
- package/dist/types/rpc-request-coalescer.d.ts.map +1 -1
- package/dist/types/rpc-request-deduplication.d.ts.map +1 -1
- package/dist/types/rpc-subscription-coalescer.d.ts +10 -0
- package/dist/types/rpc-subscription-coalescer.d.ts.map +1 -0
- package/dist/types/rpc-transport.d.ts +1 -2
- package/dist/types/rpc-transport.d.ts.map +1 -1
- package/dist/types/rpc-websocket-autopinger.d.ts +8 -0
- package/dist/types/rpc-websocket-autopinger.d.ts.map +1 -0
- package/dist/types/rpc-websocket-connection-sharding.d.ts +13 -0
- package/dist/types/rpc-websocket-connection-sharding.d.ts.map +1 -0
- package/dist/types/rpc-websocket-transport.d.ts +12 -0
- package/dist/types/rpc-websocket-transport.d.ts.map +1 -0
- package/dist/types/rpc.d.ts +4 -3
- package/dist/types/rpc.d.ts.map +1 -1
- package/dist/types/send-transaction.d.ts +38 -0
- package/dist/types/send-transaction.d.ts.map +1 -0
- package/dist/types/transaction-confirmation-strategy-blockheight.d.ts +9 -0
- package/dist/types/transaction-confirmation-strategy-blockheight.d.ts.map +1 -0
- package/dist/types/transaction-confirmation-strategy-nonce.d.ts +14 -0
- package/dist/types/transaction-confirmation-strategy-nonce.d.ts.map +1 -0
- package/dist/types/transaction-confirmation-strategy-racer.d.ts +14 -0
- package/dist/types/transaction-confirmation-strategy-racer.d.ts.map +1 -0
- package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts +12 -0
- package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts.map +1 -0
- package/dist/types/transaction-confirmation-strategy-timeout.d.ts +8 -0
- package/dist/types/transaction-confirmation-strategy-timeout.d.ts.map +1 -0
- package/dist/types/transaction-confirmation.d.ts +32 -0
- package/dist/types/transaction-confirmation.d.ts.map +1 -0
- package/package.json +25 -24
|
@@ -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","../../instructions/src/roles.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/fixSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/mapSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/baseX.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/base58.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/nullCharacters.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/utf8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/common.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u32.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/shortU16.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/sumSerializerSizes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/array.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/string.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/struct.ts","../../keys/src/base58.ts","../../keys/src/guard.ts","../../keys/src/key-pair.ts","../../keys/src/pubkey.ts","../../keys/src/signatures.ts","../../transactions/dist/index.browser.js","../src/rpc.ts","../../rpc-core/src/params-patcher.ts","../../rpc-core/src/response-patcher-allowed-numeric-values.ts","../../rpc-core/src/response-patcher.ts","../../rpc-core/src/rpc-methods/index.ts","../../rpc-transport/src/json-rpc-errors.ts","../../rpc-transport/src/json-rpc-message-id.ts","../../rpc-transport/src/json-rpc-message.ts","../../rpc-transport/src/json-rpc.ts","../../fetch-impl/src/index.browser.ts","../../rpc-transport/src/transports/http/http-transport-errors.ts","../../rpc-transport/src/transports/http/http-transport-headers.ts","../../rpc-transport/src/transports/http/http-transport.ts","../src/rpc-default-config.ts","../src/rpc-integer-overflow-error.ts","../src/rpc-transport.ts","../src/rpc-request-coalescer.ts","../src/rpc-request-deduplication.ts"],"names":["AccountRole","mergeBytes","bytesArr","totalLength","reduce","total","arr","length","result","Uint8Array","offset","forEach","set","padBytes","bytes","paddedBytes","fill","fixBytes","slice","DeserializingEmptyBufferError","Error","constructor","serializer","name","NotEnoughBytesError","expected","actual","ExpectedFixedSizeSerializerError","message","fixSerializer","fixedBytes","description","fixedSize","maxSize","serialize","value","deserialize","buffer","mapSerializer","unmap","map","InvalidBaseStringError","base","cause","baseX","alphabet","baseBigInt","BigInt","match","RegExp","chars","trailIndex","findIndex","c","leadingZeroes","Array","from","tailChars","base10Number","baseXPower","i","indexOf","tailBytes","unshift","Number","concat","n","repeat","sum","byte","join","base58","removeNullCharacters","replace","utf8","TextEncoder","encode","TextDecoder","decode","Endian","NumberOutOfRangeError","RangeError","min","max","numberFactory","input","littleEndian","defaultDescription","size","options","endian","Little","range","assertRange","ArrayBuffer","DataView","assertEnoughBytes","view","toDataView","get","toArrayBuffer","array","byteOffset","byteLength","u8","setUint8","getUint8","u32","le","setUint32","getUint32","shortU16","ii","alignedValue","nextSevenBits","byteCount","byteIndex","currentByte","InvalidNumberOfItemsError","InvalidArrayLikeRemainderSizeError","remainderSize","itemSize","UnrecognizedArrayLikeSerializerSizeError","JSON","stringify","sumSerializerSizes","sizes","all","getResolvedSize","childrenSizes","childrenSize","remainder","getSizeDescription","getSizeFromChildren","getSizePrefix","realSize","item","v","resolvedSize","newOffset","values","push","byteSerializer","contentBytes","lengthBytes","lengthBigInt","lengthOffset","contentBuffer","contentOffset","string","encoding","struct","fields","fieldDescriptions","String","field","fieldBytes","key","e","__DEV__","AccountRole2","IS_WRITABLE_BITMASK","isSignerRole","isWritableRole","mergeRoles","visitNode","index_browser_default","fastStableStringify","normalizeHeaders"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;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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AAAA,EACJ;AACJ;;;AChEA;AAEA,mCAAgC;AAEzB,SAAS,oCAAoC,SAAsC;AACtF,MAAI,WAAW,QAAQ,OAAO,YAAY,YAAY,MAAM,QAAQ,OAAO,GAAG;AAC1E;AAAA,EACJ;AACA,MAAI,aAAa,WAAW,QAAQ,YAAY,SAAS,YAAY,WAAW,YAAY,SAAS;AACjG,eAAO,6BAAAS,SAAoB,CAAC,QAAQ,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAC/D;AACJ;;;AFFA,SAASC,kBACL,SACiD;AACjD,QAAM,MAA8B,CAAC;AACrC,aAAW,cAAc,SAAS;AAC9B,QAAI,WAAW,YAAY,CAAC,IAAI,QAAQ,UAAU;AAAA,EACtD;AACA,SAAO;AACX;AAEO,SAAS,0BAA0B,QAAkE;AACxG,SAAO;AAAA,IACH,oBAAoB;AAAA,MAChB,GAAG;AAAA,MACH,SAAS;AAAA,QACL,GAAI,OAAO,UAAUA,kBAAiB,OAAO,OAAO,IAAI;AAAA,QACxD,GAAI;AAAA;AAAA,UAEA,iBAAiB,MAAM,yBAAiB;AAAA,QAC5C;AAAA,MACJ;AAAA,IACJ,CAAC;AAAA,IACD;AAAA,EACJ;AACJ","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","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/instructions';\nexport * from '@solana/keys';\nexport * from '@solana/transactions';\nexport * from './rpc';\nexport * from './rpc-transport';\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","export * from '@metaplex-foundation/umi-serializers-core';\nexport * from '@metaplex-foundation/umi-serializers-encodings';\nexport * from '@metaplex-foundation/umi-serializers-numbers';\nexport { array } from './array.mjs';\nexport { bitArray } from './bitArray.mjs';\nexport { bool } from './bool.mjs';\nexport { bytes } from './bytes.mjs';\nexport { dataEnum } from './dataEnum.mjs';\nexport { EnumDiscriminatorOutOfRangeError, InvalidArrayLikeRemainderSizeError, InvalidDataEnumVariantError, InvalidNumberOfItemsError, InvalidScalarEnumVariantError, UnrecognizedArrayLikeSerializerSizeError } from './errors.mjs';\nexport { map } from './map.mjs';\nexport { nullable } from './nullable.mjs';\nexport { option } from './option.mjs';\nexport { publicKey } from './publicKey.mjs';\nexport { scalarEnum } from './scalarEnum.mjs';\nexport { set } from './set.mjs';\nexport { string } from './string.mjs';\nexport { struct } from './struct.mjs';\nexport { tuple } from './tuple.mjs';\nexport { unit } from './unit.mjs';\nexport { maxSerializerSizes } from './maxSerializerSizes.mjs';\nexport { sumSerializerSizes } from './sumSerializerSizes.mjs';\n//# sourceMappingURL=index.mjs.map\n","export { fixBytes, mergeBytes, padBytes } from './bytes.mjs';\nexport { DeserializingEmptyBufferError, ExpectedFixedSizeSerializerError, NotEnoughBytesError } from './errors.mjs';\nexport { fixSerializer } from './fixSerializer.mjs';\nexport { mapSerializer } from './mapSerializer.mjs';\nexport { reverseSerializer } from './reverseSerializer.mjs';\n//# sourceMappingURL=index.mjs.map\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * @category Utils\n */\nexport const mergeBytes = (bytesArr: Uint8Array[]): Uint8Array => {\n const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n bytesArr.forEach((arr) => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n * @category Utils\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n * @category Utils\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.slice(0, length), length);\n","/** @category Errors */\nexport class DeserializingEmptyBufferError extends Error {\n readonly name: string = 'DeserializingEmptyBufferError';\n\n constructor(serializer: string) {\n super(`Serializer [${serializer}] cannot deserialize empty buffers.`);\n }\n}\n\n/** @category Errors */\nexport class NotEnoughBytesError extends Error {\n readonly name: string = 'NotEnoughBytesError';\n\n constructor(\n serializer: string,\n expected: bigint | number,\n actual: bigint | number\n ) {\n super(\n `Serializer [${serializer}] expected ${expected} bytes, got ${actual}.`\n );\n }\n}\n\n/** @category Errors */\nexport class ExpectedFixedSizeSerializerError extends Error {\n readonly name: string = 'ExpectedFixedSizeSerializerError';\n\n constructor(message?: string) {\n message ??= 'Expected a fixed-size serializer, got a variable-size one.';\n super(message);\n }\n}\n","import { fixBytes } from './bytes';\nimport { Serializer } from './common';\nimport { NotEnoughBytesError } from './errors';\n\n/**\n * Creates a fixed-size serializer from a given serializer.\n *\n * @param serializer - The serializer to wrap into a fixed-size serializer.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the serializer.\n *\n * @category Serializers\n */\nexport function fixSerializer<T, U extends T = T>(\n serializer: Serializer<T, U>,\n fixedBytes: number,\n description?: string\n): Serializer<T, U> {\n return {\n description:\n description ?? `fixed(${fixedBytes}, ${serializer.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n serialize: (value: T) => fixBytes(serializer.serialize(value), fixedBytes),\n deserialize: (buffer: Uint8Array, offset = 0) => {\n // Slice the buffer to the fixed size.\n buffer = buffer.slice(offset, offset + fixedBytes);\n // Ensure we have enough bytes.\n if (buffer.length < fixedBytes) {\n throw new NotEnoughBytesError(\n 'fixSerializer',\n fixedBytes,\n buffer.length\n );\n }\n // If the nested serializer is fixed-size, pad and truncate the buffer accordingly.\n if (serializer.fixedSize !== null) {\n buffer = fixBytes(buffer, serializer.fixedSize);\n }\n // Deserialize the value using the nested serializer.\n const [value] = serializer.deserialize(buffer, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n","import { Serializer } from './common';\n\n/**\n * Converts a serializer A to a serializer B by mapping their values.\n * @category Serializers\n */\nexport function mapSerializer<NewFrom, OldFrom, To extends NewFrom & OldFrom>(\n serializer: Serializer<OldFrom, To>,\n unmap: (value: NewFrom) => OldFrom\n): Serializer<NewFrom, To>;\nexport function mapSerializer<\n NewFrom,\n OldFrom,\n NewTo extends NewFrom = NewFrom,\n OldTo extends OldFrom = OldFrom\n>(\n serializer: Serializer<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map: (value: OldTo, buffer: Uint8Array, offset: number) => NewTo\n): Serializer<NewFrom, NewTo>;\nexport function mapSerializer<\n NewFrom,\n OldFrom,\n NewTo extends NewFrom = NewFrom,\n OldTo extends OldFrom = OldFrom\n>(\n serializer: Serializer<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map?: (value: OldTo, buffer: Uint8Array, offset: number) => NewTo\n): Serializer<NewFrom, NewTo> {\n return {\n description: serializer.description,\n fixedSize: serializer.fixedSize,\n maxSize: serializer.maxSize,\n serialize: (value: NewFrom) => serializer.serialize(unmap(value)),\n deserialize: (buffer: Uint8Array, offset = 0) => {\n const [value, length] = serializer.deserialize(buffer, offset);\n return map\n ? [map(value, buffer, offset), length]\n : [value as any, length];\n },\n };\n}\n","export { base10 } from './base10.mjs';\nexport { base16 } from './base16.mjs';\nexport { base58 } from './base58.mjs';\nexport { base64 } from './base64.mjs';\nexport { baseX } from './baseX.mjs';\nexport { InvalidBaseStringError } from './errors.mjs';\nexport { padNullCharacters, removeNullCharacters } from './nullCharacters.mjs';\nexport { utf8 } from './utf8.mjs';\n//# sourceMappingURL=index.mjs.map\n","/** @category Errors */\nexport class InvalidBaseStringError extends Error {\n readonly name: string = 'InvalidBaseStringError';\n\n readonly cause?: Error;\n\n constructor(value: string, base: number, cause?: Error) {\n const message = `Expected a string of base ${base}, got [${value}].`;\n super(message);\n this.cause = cause;\n }\n}\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { InvalidBaseStringError } from './errors';\n\n/**\n * A string serializer that uses a custom alphabet.\n * This can be used to create serializers for base58, base64, etc.\n * @category Serializers\n */\nexport const baseX = (alphabet: string): Serializer<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n serialize(value: string): Uint8Array {\n // Check if the value is valid.\n if (!value.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new InvalidBaseStringError(value, base);\n }\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex((c) => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n deserialize(buffer, offset = 0): [string, number] {\n if (buffer.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n const bytes = buffer.slice(offset);\n let trailIndex = bytes.findIndex((n) => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, buffer.length];\n\n // From bytes to base10.\n let base10Number = bytes\n .slice(trailIndex)\n .reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), buffer.length];\n },\n };\n};\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { baseX } from './baseX';\n\n/**\n * A string serializer that uses base58 encoding.\n * @category Serializers\n */\nexport const base58: Serializer<string> = baseX(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n","/**\n * Removes null characters from a string.\n * @category Utils\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters at the end.\n * @category Utils\n */\nexport const padNullCharacters = (value: string, chars: number) =>\n value.padEnd(chars, '\\u0000');\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { removeNullCharacters } from './nullCharacters';\n\n/**\n * A string serializer that uses UTF-8 encoding\n * using the native `TextEncoder` API.\n * @category Serializers\n */\nexport const utf8: Serializer<string> = {\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n serialize(value: string) {\n return new TextEncoder().encode(value);\n },\n deserialize(buffer, offset = 0) {\n const value = new TextDecoder().decode(buffer.slice(offset));\n return [removeNullCharacters(value), buffer.length];\n },\n};\n","export { Endian } from './common.mjs';\nexport { NumberOutOfRangeError } from './errors.mjs';\nexport { f32 } from './f32.mjs';\nexport { f64 } from './f64.mjs';\nexport { i8 } from './i8.mjs';\nexport { i16 } from './i16.mjs';\nexport { i32 } from './i32.mjs';\nexport { i64 } from './i64.mjs';\nexport { i128 } from './i128.mjs';\nexport { u8 } from './u8.mjs';\nexport { u16 } from './u16.mjs';\nexport { u32 } from './u32.mjs';\nexport { u64 } from './u64.mjs';\nexport { u128 } from './u128.mjs';\nexport { shortU16 } from './shortU16.mjs';\n//# sourceMappingURL=index.mjs.map\n","import {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\n\n/**\n * Defines a serializer for numbers and bigints.\n * @category Serializers\n */\nexport type NumberSerializer =\n | Serializer<number>\n | Serializer<number | bigint, bigint>;\n\n/**\n * Defines the options for u8 and i8 serializers.\n * @category Serializers\n */\nexport type SingleByteNumberSerializerOptions = BaseSerializerOptions;\n\n/**\n * Defines the options for number serializers that use more than one byte.\n * @category Serializers\n */\nexport type NumberSerializerOptions = BaseSerializerOptions & {\n /**\n * Whether the serializer should use little-endian or big-endian encoding.\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the endianness of a number serializer.\n * @category Serializers\n */\nexport enum Endian {\n Little = 'le',\n Big = 'be',\n}\n","/** @category Errors */\nexport class NumberOutOfRangeError extends RangeError {\n readonly name: string = 'NumberOutOfRangeError';\n\n constructor(\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n actual: number | bigint\n ) {\n super(\n `Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`\n );\n }\n}\n","import {\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport {\n Endian,\n NumberSerializer,\n NumberSerializerOptions,\n SingleByteNumberSerializerOptions,\n} from './common';\nimport { NumberOutOfRangeError } from './errors';\n\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number | bigint, bigint>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number | bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): NumberSerializer {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian =\n !('endian' in input.options) || input.options.endian === Endian.Little;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n maxSize: input.size,\n serialize(value: number | bigint): Uint8Array {\n if (input.range) {\n assertRange(input.name, input.range[0], input.range[1], value);\n }\n const buffer = new ArrayBuffer(input.size);\n input.set(new DataView(buffer), value, littleEndian);\n return new Uint8Array(buffer);\n },\n deserialize(bytes, offset = 0): [number | bigint, number] {\n const slice = bytes.slice(offset, offset + input.size);\n assertEnoughBytes('i8', slice, input.size);\n const view = toDataView(slice);\n return [input.get(view, littleEndian), offset + input.size];\n },\n } as NumberSerializer;\n}\n\n/**\n * Helper function to ensure that the array buffer is converted properly from a uint8array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n * @param {Uint8Array} array Uint8array that's being converted into an array buffer\n * @returns {ArrayBuffer} An array buffer that's necessary to construct a data view\n */\nexport const toArrayBuffer = (array: Uint8Array): ArrayBuffer =>\n array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);\n\nexport const toDataView = (array: Uint8Array): DataView =>\n new DataView(toArrayBuffer(array));\n\nexport const assertRange = (\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) => {\n if (value < min || value > max) {\n throw new NumberOutOfRangeError(serializer, min, max, value);\n }\n};\n\nexport const assertEnoughBytes = (\n serializer: string,\n bytes: Uint8Array,\n expected: number\n) => {\n if (bytes.length === 0) {\n throw new DeserializingEmptyBufferError(serializer);\n }\n if (bytes.length < expected) {\n throw new NotEnoughBytesError(serializer, expected, bytes.length);\n }\n};\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { SingleByteNumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u8 = (\n options: SingleByteNumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u8',\n size: 1,\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n get: (view) => view.getUint8(0),\n options,\n });\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u32 = (\n options: NumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u32',\n size: 4,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n get: (view, le) => view.getUint32(0, le),\n options,\n });\n","/* eslint-disable no-bitwise */\nimport {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { assertRange } from './utils';\n\n/**\n * Defines the options for the shortU16 serializer.\n * @category Serializers\n */\nexport type ShortU16SerializerOptions = BaseSerializerOptions;\n\n/**\n * Same as u16, but serialized with 1 to 3 bytes.\n *\n * If the value is above 0x7f, the top bit is set and the remaining\n * value is stored in the next bytes. Each byte follows the same\n * pattern until the 3rd byte. The 3rd byte, if needed, uses\n * all 8 bits to store the last byte of the original value.\n *\n * @category Serializers\n */\nexport const shortU16 = (\n options: ShortU16SerializerOptions = {}\n): Serializer<number> => ({\n description: options.description ?? 'shortU16',\n fixedSize: null,\n maxSize: 3,\n serialize: (value: number): Uint8Array => {\n assertRange('shortU16', 0, 65535, value);\n const bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = value >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n bytes[ii - 1] |= 0b10000000;\n }\n }\n return new Uint8Array(bytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0): [number, number] => {\n let value = 0;\n let byteCount = 0;\n while (\n ++byteCount // eslint-disable-line no-plusplus\n ) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n});\n","/** @category Errors */\nexport class InvalidNumberOfItemsError extends Error {\n readonly name = 'InvalidNumberOfItemsError';\n\n constructor(\n serializer: string,\n expected: number | bigint,\n actual: number | bigint\n ) {\n super(`Expected [${serializer}] to have ${expected} items, got ${actual}.`);\n }\n}\n\n/** @category Errors */\nexport class InvalidArrayLikeRemainderSizeError extends Error {\n readonly name = 'InvalidArrayLikeRemainderSizeError';\n\n constructor(remainderSize: number | bigint, itemSize: number | bigint) {\n super(\n `The remainder of the buffer (${remainderSize} bytes) cannot be split into chunks of ${itemSize} bytes. ` +\n `Serializers of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainderSize} modulo ${itemSize} should be equal to zero.`\n );\n }\n}\n\n/** @category Errors */\nexport class UnrecognizedArrayLikeSerializerSizeError extends Error {\n readonly name = 'UnrecognizedArrayLikeSerializerSizeError';\n\n constructor(size: never) {\n super(`Unrecognized array-like serializer size: ${JSON.stringify(size)}`);\n }\n}\n\n/** @category Errors */\nexport class InvalidDataEnumVariantError extends Error {\n readonly name = 'InvalidDataEnumVariantError';\n\n constructor(invalidVariant: string, validVariants: string[]) {\n super(\n `Invalid data enum variant. ` +\n `Expected one of [${validVariants.join(', ')}], ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class InvalidScalarEnumVariantError extends Error {\n readonly name = 'InvalidScalarEnumVariantError';\n\n constructor(\n invalidVariant: string | number | bigint,\n validVariants: string[],\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Invalid scalar enum variant. ` +\n `Expected one of [${validVariants.join(', ')}] ` +\n `or a number between ${min} and ${max}, ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class EnumDiscriminatorOutOfRangeError extends RangeError {\n readonly name = 'EnumDiscriminatorOutOfRangeError';\n\n constructor(\n discriminator: number | bigint,\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Enum discriminator out of range. ` +\n `Expected a number between ${min} and ${max}, got ${discriminator}.`\n );\n }\n}\n","export function sumSerializerSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : all + size),\n 0 as number | null\n );\n}\n","import { ExpectedFixedSizeSerializerError } from '@metaplex-foundation/umi-serializers-core';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport {\n InvalidArrayLikeRemainderSizeError,\n UnrecognizedArrayLikeSerializerSizeError,\n} from './errors';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\nexport function getResolvedSize(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: number\n): [number | bigint, number] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.deserialize(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumSerializerSizes(childrenSizes);\n if (childrenSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n throw new InvalidArrayLikeRemainderSizeError(remainder, childrenSize);\n }\n return [remainder / childrenSize, offset];\n }\n\n throw new UnrecognizedArrayLikeSerializerSizeError(size);\n}\n\nexport function getSizeDescription(\n size: ArrayLikeSerializerSize | string\n): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getSizeFromChildren(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumSerializerSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getSizePrefix(\n size: ArrayLikeSerializerSize,\n realSize: number\n): Uint8Array {\n return typeof size === 'object' ? size.serialize(realSize) : new Uint8Array();\n}\n","import {\n BaseSerializerOptions,\n ExpectedFixedSizeSerializerError,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { u32 } from '@metaplex-foundation/umi-serializers-numbers';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport { InvalidNumberOfItemsError } from './errors';\nimport {\n getResolvedSize,\n getSizeDescription,\n getSizeFromChildren,\n getSizePrefix,\n} from './utils';\n\n/**\n * Defines the options for array serializers.\n * @category Serializers\n */\nexport type ArraySerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the array.\n * @defaultValue `u32()`\n */\n size?: ArrayLikeSerializerSize;\n};\n\n/**\n * Creates a serializer for an array of items.\n *\n * @param item - The serializer to use for the array's items.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function array<T, U extends T = T>(\n item: Serializer<T, U>,\n options: ArraySerializerOptions = {}\n): Serializer<T[], U[]> {\n const size = options.size ?? u32();\n if (size === 'remainder' && item.fixedSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n return {\n description:\n options.description ??\n `array(${item.description}; ${getSizeDescription(size)})`,\n fixedSize: getSizeFromChildren(size, [item.fixedSize]),\n maxSize: getSizeFromChildren(size, [item.maxSize]),\n serialize: (value: T[]) => {\n if (typeof size === 'number' && value.length !== size) {\n throw new InvalidNumberOfItemsError('array', size, value.length);\n }\n return mergeBytes([\n getSizePrefix(size, value.length),\n ...value.map((v) => item.serialize(v)),\n ]);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = getResolvedSize(\n size,\n [item.fixedSize],\n bytes,\n offset\n );\n offset = newOffset;\n const values: U[] = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.deserialize(bytes, offset);\n values.push(value);\n offset = newOffset;\n }\n return [values, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializer } from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for bytes serializers.\n * @category Serializers\n */\nexport type BytesSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the buffer. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the buffer with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `'variable'`\n */\n size?: NumberSerializer | number | 'variable';\n};\n\n/**\n * Creates a serializer that passes the buffer as-is.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function bytes(\n options: BytesSerializerOptions = {}\n): Serializer<Uint8Array> {\n const size = options.size ?? 'variable';\n const description =\n options.description ?? `bytes(${getSizeDescription(size)})`;\n\n const byteSerializer: Serializer<Uint8Array> = {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => new Uint8Array(value),\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n };\n\n if (size === 'variable') {\n return byteSerializer;\n }\n\n if (typeof size === 'number') {\n return fixSerializer(byteSerializer, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => {\n const contentBytes = byteSerializer.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('bytes');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('bytes', length, contentBuffer.length);\n }\n const [value, contentOffset] = byteSerializer.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { utf8 } from '@metaplex-foundation/umi-serializers-encodings';\nimport {\n NumberSerializer,\n u32,\n} from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for string serializers.\n * @category Serializers\n */\nexport type StringSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `u32()`\n */\n size?: NumberSerializer | number | 'variable';\n /**\n * The string serializer to use for encoding and decoding the content.\n * @defaultValue `utf8`\n */\n encoding?: Serializer<string>;\n};\n\n/**\n * Creates a string serializer.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function string(\n options: StringSerializerOptions = {}\n): Serializer<string> {\n const size = options.size ?? u32();\n const encoding = options.encoding ?? utf8;\n const description =\n options.description ??\n `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixSerializer(encoding, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: string) => {\n const contentBytes = encoding.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('string');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('string', length, contentBuffer.length);\n }\n const [value, contentOffset] = encoding.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\n/**\n * Get the name and serializer of each field in a struct.\n * @category Serializers\n */\nexport type StructToSerializerTuple<T extends object, U extends T> = Array<\n {\n [K in keyof T]: [K, Serializer<T[K], U[K]>];\n }[keyof T]\n>;\n\n/**\n * Defines the options for struct serializers.\n * @category Serializers\n */\nexport type StructSerializerOptions = BaseSerializerOptions;\n\n/**\n * Creates a serializer for a custom object.\n *\n * @param fields - The name and serializer of each field.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function struct<T extends object, U extends T = T>(\n fields: StructToSerializerTuple<T, U>,\n options: StructSerializerOptions = {}\n): Serializer<T, U> {\n const fieldDescriptions = fields\n .map(([name, serializer]) => `${String(name)}: ${serializer.description}`)\n .join(', ');\n return {\n description: options.description ?? `struct(${fieldDescriptions})`,\n fixedSize: sumSerializerSizes(fields.map(([, field]) => field.fixedSize)),\n maxSize: sumSerializerSizes(fields.map(([, field]) => field.maxSize)),\n serialize: (struct: T) => {\n const fieldBytes = fields.map(([key, serializer]) =>\n serializer.serialize(struct[key])\n );\n return mergeBytes(fieldBytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const struct: Partial<U> = {};\n fields.forEach(([key, serializer]) => {\n const [value, newOffset] = serializer.deserialize(bytes, offset);\n offset = newOffset;\n struct[key] = value;\n });\n return [struct as U, offset];\n },\n };\n}\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","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 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 { assertKeyGenerationIsAvailable } from './guard';\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 { Base58EncodedAddress, getBase58EncodedAddressCodec } from './base58';\nimport { assertKeyExporterIsAvailable } from './guard';\n\nexport async function getBase58EncodedAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from './guard';\n\nexport type Ed25519Signature = Uint8Array & { readonly __ed25519Signature: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n","import { base58, struct, array, bytes, shortU16, mapSerializer, string, u8 } from '@metaplex-foundation/umi-serializers';\nimport { getBase58EncodedAddressFromPublicKey, signBytes, getBase58EncodedAddressComparator, getBase58EncodedAddressCodec } from '@solana/keys';\n\n// ../build-scripts/env-shim.ts\nvar __DEV__ = /* @__PURE__ */ (() => process[\"env\"].NODE_ENV === \"development\")();\nfunction assertIsBlockhash(putativeBlockhash) {\n try {\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 || // 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 const bytes3 = base58.serialize(putativeBlockhash);\n const numBytes = bytes3.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\n// src/create-transaction.ts\nfunction createTransaction({\n version\n}) {\n const out = {\n instructions: [],\n version\n };\n Object.freeze(out);\n return out;\n}\n\n// src/fee-payer.ts\nfunction setTransactionFeePayer(feePayer, transaction) {\n if (\"feePayer\" in transaction && feePayer === transaction.feePayer) {\n return transaction;\n }\n let out;\n if (\"signatures\" in transaction) {\n const {\n signatures: _,\n // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n out = {\n ...unsignedTransaction,\n feePayer\n };\n } else {\n out = {\n ...transaction,\n feePayer\n };\n }\n Object.freeze(out);\n return out;\n}\n\n// src/instructions.ts\nfunction replaceInstructions(transaction, nextInstructions) {\n let out;\n if (\"signatures\" in transaction) {\n const {\n signatures: _,\n // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n out = {\n ...unsignedTransaction,\n instructions: nextInstructions\n };\n } else {\n out = {\n ...transaction,\n instructions: nextInstructions\n };\n }\n return out;\n}\nfunction appendTransactionInstruction(instruction, transaction) {\n const nextInstructions = [...transaction.instructions, instruction];\n const out = replaceInstructions(transaction, nextInstructions);\n Object.freeze(out);\n return out;\n}\nfunction prependTransactionInstruction(instruction, transaction) {\n const nextInstructions = [instruction, ...transaction.instructions];\n const out = replaceInstructions(transaction, nextInstructions);\n Object.freeze(out);\n return out;\n}\n\n// ../instructions/dist/index.browser.js\nvar AccountRole = /* @__PURE__ */ ((AccountRole2) => {\n AccountRole2[AccountRole2[\"WRITABLE_SIGNER\"] = /* 3 */\n 3] = \"WRITABLE_SIGNER\";\n AccountRole2[AccountRole2[\"READONLY_SIGNER\"] = /* 2 */\n 2] = \"READONLY_SIGNER\";\n AccountRole2[AccountRole2[\"WRITABLE\"] = /* 1 */\n 1] = \"WRITABLE\";\n AccountRole2[AccountRole2[\"READONLY\"] = /* 0 */\n 0] = \"READONLY\";\n return AccountRole2;\n})(AccountRole || {});\nvar IS_WRITABLE_BITMASK = 1;\nfunction isSignerRole(role) {\n return role >= 2;\n}\nfunction isWritableRole(role) {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\nfunction mergeRoles(roleA, roleB) {\n return roleA | roleB;\n}\nfunction upsert(addressMap, address, update) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\nvar TYPE = Symbol(\"AddressMapTypeProperty\");\nfunction getAddressMapFromInstructions(feePayer, instructions) {\n const addressMap = {\n [feePayer]: { [TYPE]: 0 /* FEE_PAYER */, role: AccountRole.WRITABLE_SIGNER }\n };\n const addressesOfInvokedPrograms = /* @__PURE__ */ new Set();\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 0 /* FEE_PAYER */:\n throw new Error(\n `This transaction includes an address (\\`${instruction.programAddress}\\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`\n );\n default:\n throw new Error(\n `This transaction includes an address (\\`${instruction.programAddress}\\`) which is both invoked and marked writable. Program addresses may not be writable.`\n );\n }\n }\n if (entry[TYPE] === 2 /* STATIC */) {\n return entry;\n }\n }\n return { [TYPE]: 2 /* STATIC */, role: AccountRole.READONLY };\n });\n let addressComparator;\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 0 /* FEE_PAYER */:\n return entry;\n case 1 /* 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 && // ...and sorts before the existing one.\n (addressComparator || (addressComparator = getBase58EncodedAddressComparator()))(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress\n ) < 0\n );\n if (shouldReplaceEntry) {\n return {\n [TYPE]: 1 /* LOOKUP_TABLE */,\n ...accountMeta,\n role: nextRole\n };\n }\n } else if (isSignerRole(accountMeta.role)) {\n return {\n [TYPE]: 2 /* STATIC */,\n role: nextRole\n };\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole\n };\n } else {\n return entry;\n }\n }\n case 2 /* 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 throw new Error(\n `This transaction includes an address (\\`${account.address}\\`) which is both invoked and marked writable. Program addresses may not be writable.`\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole\n };\n } else {\n return entry;\n }\n } else if (\"lookupTableAddress\" in accountMeta && // 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 return {\n ...accountMeta,\n [TYPE]: 1 /* LOOKUP_TABLE */,\n role: nextRole\n };\n } else {\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole\n };\n } else {\n return entry;\n }\n }\n }\n }\n }\n if (\"lookupTableAddress\" in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: 1 /* LOOKUP_TABLE */\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: 2 /* STATIC */\n };\n }\n });\n }\n }\n return addressMap;\n}\nfunction getOrderedAccountsFromAddressMap(addressMap) {\n let addressComparator;\n const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === 0 /* FEE_PAYER */) {\n return -1;\n } else if (rightEntry[TYPE] === 0 /* FEE_PAYER */) {\n return 1;\n } else if (leftEntry[TYPE] === 2 /* STATIC */) {\n return -1;\n } else if (rightEntry[TYPE] === 2 /* STATIC */) {\n return 1;\n }\n }\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 addressComparator || (addressComparator = getBase58EncodedAddressComparator());\n if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n }).map(([address, addressMeta]) => ({\n address,\n ...addressMeta\n }));\n return orderedAccounts;\n}\nfunction getCompiledAddressTableLookups(orderedAccounts) {\n var _a;\n const index = {};\n for (const account of orderedAccounts) {\n if (!(\"lookupTableAddress\" in account)) {\n continue;\n }\n const entry = index[_a = account.lookupTableAddress] || (index[_a] = {\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).sort(getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({\n lookupTableAddress,\n ...index[lookupTableAddress]\n }));\n}\n\n// src/compile-header.ts\nfunction getCompiledMessageHeader(orderedAccounts) {\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\n// src/compile-instructions.ts\nfunction getAccountIndex(orderedAccounts) {\n const out = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\nfunction getCompiledInstructions(instructions, orderedAccounts) {\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\n// src/compile-lifetime-token.ts\nfunction getCompiledLifetimeToken(lifetimeConstraint) {\n if (\"nonce\" in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n\n// src/compile-static-accounts.ts\nfunction getCompiledStaticAccounts(orderedAccounts) {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => \"lookupTableAddress\" in account);\n const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n\n// src/message.ts\nfunction compileMessage(transaction) {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...transaction.version !== \"legacy\" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : 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}\nfunction getAddressTableLookupCodec() {\n return struct(\n [\n [\n \"lookupTableAddress\",\n getBase58EncodedAddressCodec(\n __DEV__ ? {\n description: \"The address of the address lookup table account from which instruction addresses should be looked up\"\n } : void 0\n )\n ],\n [\n \"writableIndices\",\n array(u8(), {\n ...__DEV__ ? {\n description: \"The indices of the accounts in the lookup table that should be loaded as writeable\"\n } : null,\n size: shortU16()\n })\n ],\n [\n \"readableIndices\",\n array(u8(), {\n ...__DEV__ ? {\n description: \"The indices of the accounts in the lookup table that should be loaded as read-only\"\n } : void 0,\n size: shortU16()\n })\n ]\n ],\n __DEV__ ? {\n description: \"A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it\"\n } : void 0\n );\n}\nfunction getMessageHeaderCodec() {\n return struct(\n [\n [\n \"numSignerAccounts\",\n u8(\n __DEV__ ? {\n description: \"The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction\"\n } : void 0\n )\n ],\n [\n \"numReadonlySignerAccounts\",\n u8(\n __DEV__ ? {\n description: \"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 } : void 0\n )\n ],\n [\n \"numReadonlyNonSignerAccounts\",\n u8(\n __DEV__ ? {\n description: \"The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable\"\n } : void 0\n )\n ]\n ],\n __DEV__ ? {\n description: \"The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses\"\n } : void 0\n );\n}\nfunction getInstructionCodec() {\n return mapSerializer(\n struct([\n [\n \"programAddressIndex\",\n u8(\n __DEV__ ? {\n description: \"The index of the program being called, according to the well-ordered accounts list for this transaction\"\n } : void 0\n )\n ],\n [\n \"addressIndices\",\n array(\n u8({\n description: __DEV__ ? \"The index of an account, according to the well-ordered accounts list for this transaction\" : \"\"\n }),\n {\n description: __DEV__ ? \"An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them\" : \"\",\n size: shortU16()\n }\n )\n ],\n [\n \"data\",\n bytes({\n description: __DEV__ ? \"An optional buffer of data passed to the instruction\" : \"\",\n size: shortU16()\n })\n ]\n ]),\n (value) => {\n if (value.addressIndices !== void 0 && value.data !== void 0) {\n return value;\n }\n return {\n ...value,\n addressIndices: value.addressIndices ?? [],\n data: value.data ?? new Uint8Array(0)\n };\n },\n (value) => {\n if (value.addressIndices.length && value.data.byteLength) {\n return value;\n }\n const { addressIndices, data, ...rest } = value;\n return {\n ...rest,\n ...addressIndices.length ? { addressIndices } : null,\n ...data.byteLength ? { data } : null\n };\n }\n );\n}\n\n// src/serializers/unimplemented.ts\nfunction getError(type, name) {\n const functionSuffix = name + type[0].toUpperCase() + type.slice(1);\n return new Error(\n `No ${type} exists for ${name}. Use \\`get${functionSuffix}()\\` if you need a ${type}, and \\`get${name}Codec()\\` if you need to both encode and decode ${name}`\n );\n}\nfunction getUnimplementedDecoder(name) {\n return () => {\n throw getError(\"decoder\", name);\n };\n}\n\n// src/serializers/transaction-version.ts\nvar VERSION_FLAG_MASK = 128;\nvar BASE_CONFIG = {\n description: __DEV__ ? \"A single byte that encodes the version of the transaction\" : \"\",\n fixedSize: null,\n maxSize: 1\n};\nfunction deserialize(bytes3, offset = 0) {\n const firstByte = bytes3[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n return [\"legacy\", offset];\n } else {\n const version = firstByte ^ VERSION_FLAG_MASK;\n return [version, offset + 1];\n }\n}\nfunction serialize(value) {\n if (value === \"legacy\") {\n return new Uint8Array();\n }\n if (value < 0 || value > 127) {\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}\nfunction getTransactionVersionCodec() {\n return {\n ...BASE_CONFIG,\n deserialize,\n serialize\n };\n}\n\n// src/serializers/message.ts\nvar BASE_CONFIG2 = {\n description: __DEV__ ? \"The wire format of a Solana transaction message\" : \"\",\n fixedSize: null,\n maxSize: null\n};\nfunction serialize2(compiledMessage) {\n if (compiledMessage.version === \"legacy\") {\n return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage);\n } else {\n return mapSerializer(\n struct([\n ...getPreludeStructSerializerTuple(),\n [\"addressTableLookups\", getAddressTableLookupsSerializer()]\n ]),\n (value) => {\n if (value.version === \"legacy\") {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? []\n };\n }\n ).serialize(compiledMessage);\n }\n}\nfunction getPreludeStructSerializerTuple() {\n return [\n [\"version\", getTransactionVersionCodec()],\n [\"header\", getMessageHeaderCodec()],\n [\n \"staticAccounts\",\n array(getBase58EncodedAddressCodec(), {\n description: __DEV__ ? \"A compact-array of static account addresses belonging to this transaction\" : \"\",\n size: shortU16()\n })\n ],\n [\n \"lifetimeToken\",\n string({\n description: __DEV__ ? \"A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)\" : \"\",\n encoding: base58,\n size: 32\n })\n ],\n [\n \"instructions\",\n array(getInstructionCodec(), {\n description: __DEV__ ? \"A compact-array of instructions belonging to this transaction\" : \"\",\n size: shortU16()\n })\n ]\n ];\n}\nfunction getAddressTableLookupsSerializer() {\n return array(getAddressTableLookupCodec(), {\n ...__DEV__ ? { description: \"A compact array of address table lookups belonging to this transaction\" } : null,\n size: shortU16()\n });\n}\nfunction getCompiledMessageEncoder() {\n return {\n ...BASE_CONFIG2,\n deserialize: getUnimplementedDecoder(\"CompiledMessage\"),\n serialize: serialize2\n };\n}\n\n// src/signatures.ts\nasync function getCompiledMessageSignature(message, secretKey) {\n const wireMessageBytes = getCompiledMessageEncoder().serialize(message);\n const signature = await signBytes(secretKey, wireMessageBytes);\n return signature;\n}\nasync function signTransaction(keyPair, transaction) {\n const compiledMessage = compileMessage(transaction);\n const [signerPublicKey, signature] = await Promise.all([\n getBase58EncodedAddressFromPublicKey(keyPair.publicKey),\n getCompiledMessageSignature(compiledMessage, keyPair.privateKey)\n ]);\n const nextSignatures = {\n ...\"signatures\" in transaction ? transaction.signatures : null,\n ...{ [signerPublicKey]: signature }\n };\n const out = {\n ...transaction,\n signatures: nextSignatures\n };\n Object.freeze(out);\n return out;\n}\n\n// src/compile-transaction.ts\nfunction getCompiledTransaction(transaction) {\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] = 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\n// src/serializers/transaction.ts\nvar BASE_CONFIG3 = {\n description: __DEV__ ? \"The wire format of a Solana transaction\" : \"\",\n fixedSize: null,\n maxSize: null\n};\nfunction serialize3(transaction) {\n const compiledTransaction = getCompiledTransaction(transaction);\n return struct([\n [\n \"signatures\",\n array(bytes({ size: 64 }), {\n ...__DEV__ ? { description: \"A compact array of 64-byte, base-64 encoded Ed25519 signatures\" } : null,\n size: shortU16()\n })\n ],\n [\"compiledMessage\", getCompiledMessageEncoder()]\n ]).serialize(compiledTransaction);\n}\nfunction getTransactionEncoder() {\n return {\n ...BASE_CONFIG3,\n deserialize: getUnimplementedDecoder(\"CompiledMessage\"),\n serialize: serialize3\n };\n}\n\n// src/wire-transaction.ts\nfunction getBase64EncodedWireTransaction(transaction) {\n const wireTransactionBytes = getTransactionEncoder().serialize(transaction);\n {\n return btoa(String.fromCharCode(...wireTransactionBytes));\n }\n}\n\nexport { appendTransactionInstruction, assertIsBlockhash, createTransaction, getBase64EncodedWireTransaction, prependTransactionInstruction, setTransactionFeePayer, signTransaction };\n","import { createSolanaRpcApi, SolanaRpcMethods } from '@solana/rpc-core';\nimport { createJsonRpc } from '@solana/rpc-transport';\nimport type { Rpc } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\n\nexport function createSolanaRpc(config: Omit<Parameters<typeof createJsonRpc>[0], 'api'>): Rpc<SolanaRpcMethods> {\n return createJsonRpc<SolanaRpcMethods>({\n ...config,\n api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n });\n}\n","type IntegerOverflowHandler = (keyPath: (number | string)[], value: bigint) => void;\ntype Patched<T> = T extends object ? { [Property in keyof T]: Patched<T[Property]> } : T extends bigint ? number : T;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction visitNode<T>(value: T, keyPath: (number | string)[], onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n if (Array.isArray(value)) {\n return value.map((element, ii) =>\n visitNode(element, [...keyPath, ii], onIntegerOverflow)\n ) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const propName in value) {\n if (Object.prototype.hasOwnProperty.call(value, propName)) {\n out[propName] = visitNode(value[propName], [...keyPath, propName], onIntegerOverflow);\n }\n }\n return out as TypescriptBug33014;\n } else if (typeof value === 'bigint') {\n // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // downcasting `bigints` to `numbers`.\n if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {\n onIntegerOverflow(keyPath, value);\n }\n return Number(value) as TypescriptBug33014;\n } else {\n return value as TypescriptBug33014;\n }\n}\n\nexport function patchParamsForSolanaLabsRpc<T>(params: T, onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n return visitNode(params, [], onIntegerOverflow);\n}\n","import { KeyPath } from './response-patcher';\nimport { KEYPATH_WILDCARD } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nexport const ALLOWED_NUMERIC_KEYPATHS: Partial<\n Record<keyof ReturnType<typeof createSolanaRpcApi>, readonly KeyPath[]>\n> = {\n getAccountInfo: [\n // parsed AddressTableLookup account\n ['value', 'data', 'parsed', 'info', 'lastExtendedSlotStartIndex'],\n // parsed Config account\n ['value', 'data', 'parsed', 'info', 'slashPenalty'],\n ['value', 'data', 'parsed', 'info', 'warmupCooldownRate'],\n // parsed Token/Token22 token account\n ['value', 'data', 'parsed', 'info', 'tokenAmount', 'decimals'],\n ['value', 'data', 'parsed', 'info', 'tokenAmount', 'uiAmount'],\n ['value', 'data', 'parsed', 'info', 'rentExemptReserve', 'decimals'],\n ['value', 'data', 'parsed', 'info', 'delegatedAmount', 'decimals'],\n [\n 'value',\n 'data',\n 'parsed',\n 'info',\n 'extensions',\n KEYPATH_WILDCARD,\n 'state',\n 'olderTransferFee',\n 'transferFeeBasisPoints',\n ],\n [\n 'value',\n 'data',\n 'parsed',\n 'info',\n 'extensions',\n KEYPATH_WILDCARD,\n 'state',\n 'newerTransferFee',\n 'transferFeeBasisPoints',\n ],\n ['value', 'data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['value', 'data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n // parsed Token/Token22 mint account\n ['value', 'data', 'parsed', 'info', 'decimals'],\n // parsed Token/Token22 multisig account\n ['value', 'data', 'parsed', 'info', 'numRequiredSigners'],\n ['value', 'data', 'parsed', 'info', 'numValidSigners'],\n // parsed Stake account\n ['value', 'data', 'parsed', 'info', 'stake', 'delegation', 'warmupCooldownRate'],\n // parsed Sysvar rent account\n ['value', 'data', 'parsed', 'info', 'exemptionThreshold'],\n ['value', 'data', 'parsed', 'info', 'burnPercent'],\n // parsed Vote account\n ['value', 'data', 'parsed', 'info', 'commission'],\n ['value', 'data', 'parsed', 'info', 'votes', KEYPATH_WILDCARD, 'confirmationCount'],\n ],\n getBlockTime: [[]],\n getInflationReward: [[KEYPATH_WILDCARD, 'commission']],\n getRecentPerformanceSamples: [[KEYPATH_WILDCARD, 'samplePeriodSecs']],\n getTokenLargestAccounts: [\n ['value', KEYPATH_WILDCARD, 'decimals'],\n ['value', KEYPATH_WILDCARD, '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 ['meta', 'innerInstructions', KEYPATH_WILDCARD, 'instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['transaction', 'message', 'addressTableLookups', KEYPATH_WILDCARD, 'writableIndexes', KEYPATH_WILDCARD],\n ['transaction', 'message', 'addressTableLookups', KEYPATH_WILDCARD, 'readonlyIndexes', KEYPATH_WILDCARD],\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 getVoteAccounts: [\n ['current', KEYPATH_WILDCARD, 'commission'],\n ['delinquent', KEYPATH_WILDCARD, 'commission'],\n ],\n};\n","import { ALLOWED_NUMERIC_KEYPATHS } from './response-patcher-allowed-numeric-values';\nimport { KEYPATH_WILDCARD, KeyPathWildcard } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\n\nexport type KeyPath = ReadonlyArray<KeyPathWildcard | number | string | KeyPath>;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction getNextAllowedKeypaths(keyPaths: readonly KeyPath[], property: number | string) {\n return keyPaths\n .filter(keyPath => (keyPath[0] === KEYPATH_WILDCARD && typeof property === 'number') || keyPath[0] === property)\n .map(keyPath => keyPath.slice(1));\n}\n\nfunction visitNode<T>(value: unknown, allowedKeypaths: readonly KeyPath[]): T {\n if (Array.isArray(value)) {\n return value.map((element, ii) => {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, ii);\n return visitNode(element, nextAllowedKeypaths);\n }) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const [propName, innerValue] of Object.entries(value)) {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, propName);\n out[propName] = visitNode(innerValue, nextAllowedKeypaths);\n }\n return out as TypescriptBug33014;\n } else if (\n typeof value === 'number' &&\n // The presence of an allowed keypath on the route to this value implies it's allowlisted;\n // Upcast the value to `bigint` unless an allowed keypath is present.\n allowedKeypaths.length === 0 &&\n // 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 ? ALLOWED_NUMERIC_KEYPATHS[methodName] : undefined;\n return visitNode(rawResponse, allowedKeypaths ?? []);\n}\n","import { IRpcApi, RpcRequest } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { patchParamsForSolanaLabsRpc } from '../params-patcher';\nimport { patchResponseForSolanaLabsRpc } from '../response-patcher';\nimport { GetAccountInfoApi } from './getAccountInfo';\nimport { GetBalanceApi } from './getBalance';\nimport { GetBlockHeightApi } from './getBlockHeight';\nimport { GetBlockProductionApi } from './getBlockProduction';\nimport { GetBlocksApi } from './getBlocks';\nimport { GetBlockTimeApi } from './getBlockTime';\nimport { GetEpochInfoApi } from './getEpochInfo';\nimport { GetEpochScheduleApi } from './getEpochSchedule';\nimport { GetFirstAvailableBlockApi } from './getFirstAvailableBlock';\nimport { GetInflationRewardApi } from './getInflationReward';\nimport { GetLatestBlockhashApi } from './getLatestBlockhash';\nimport { GetMaxRetransmitSlotApi } from './getMaxRetransmitSlot';\nimport { GetMaxShredInsertSlotApi } from './getMaxShredInsertSlot';\nimport { GetRecentPerformanceSamplesApi } from './getRecentPerformanceSamples';\nimport { GetSignaturesForAddressApi } from './getSignaturesForAddress';\nimport { GetSlotApi } from './getSlot';\nimport { GetSlotLeadersApi } from './getSlotLeaders';\nimport { GetStakeMinimumDelegationApi } from './getStakeMinimumDelegation';\nimport { GetSupplyApi } from './getSupply';\nimport { GetTokenLargestAccountsApi } from './getTokenLargestAccounts';\nimport { GetTransactionApi } from './getTransaction';\nimport { GetTransactionCountApi } from './getTransactionCount';\nimport { GetVoteAccountsApi } from './getVoteAccounts';\nimport { IsBlockhashValidApi } from './isBlockhashValid';\nimport { MinimumLedgerSlotApi } from './minimumLedgerSlot';\nimport { RequestAirdropApi } from './requestAirdrop';\nimport { SendTransactionApi } from './sendTransaction';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcMethods = GetAccountInfoApi &\n GetBalanceApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlockTimeApi &\n GetEpochInfoApi &\n GetEpochScheduleApi &\n GetFirstAvailableBlockApi &\n GetInflationRewardApi &\n GetLatestBlockhashApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetRecentPerformanceSamplesApi &\n GetSignaturesForAddressApi &\n GetSlotApi &\n GetSlotLeadersApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTokenLargestAccountsApi &\n GetTransactionApi &\n GetTransactionCountApi &\n GetVoteAccountsApi &\n IsBlockhashValidApi &\n MinimumLedgerSlotApi &\n RequestAirdropApi &\n SendTransactionApi;\n\nexport function createSolanaRpcApi(config?: Config): IRpcApi<SolanaRpcMethods> {\n return new Proxy({} as IRpcApi<SolanaRpcMethods>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<TMethodName extends keyof IRpcApi<SolanaRpcMethods>>(\n ...args: Parameters<NonNullable<ProxyHandler<IRpcApi<SolanaRpcMethods>>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof SolanaRpcMethods;\n return function (\n ...rawParams: Parameters<\n SolanaRpcMethods[TMethodName] extends CallableFunction ? SolanaRpcMethods[TMethodName] : never\n >\n ): RpcRequest<ReturnType<SolanaRpcMethods[TMethodName]>> {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n const params = patchParamsForSolanaLabsRpc(\n rawParams,\n handleIntegerOverflow\n ? (keyPath, value) => handleIntegerOverflow(methodName, keyPath, value)\n : undefined\n );\n return {\n methodName,\n params,\n responseProcessor: rawResponse => patchResponseForSolanaLabsRpc(rawResponse, methodName),\n };\n };\n },\n });\n}\n","// Keep in sync with https://github.com/solana-labs/solana/blob/master/rpc-client-api/src/custom_error.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nexport const SolanaJsonRpcErrorCode = {\n JSON_RPC_INVALID_PARAMS: -32602,\n JSON_RPC_SCAN_ERROR: -32012,\n JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016,\n JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n} as const;\ntype SolanaJsonRpcErrorCodeEnum = (typeof SolanaJsonRpcErrorCode)[keyof typeof SolanaJsonRpcErrorCode];\n\ntype SolanaJsonRpcErrorDetails = Readonly<{\n code: number;\n data?: unknown;\n message: string;\n}>;\n\nexport class SolanaJsonRpcError extends Error {\n readonly code: SolanaJsonRpcErrorCodeEnum;\n readonly data: unknown;\n constructor(details: SolanaJsonRpcErrorDetails) {\n super(`JSON-RPC 2.0 error (${details.code}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.code = details.code as SolanaJsonRpcErrorCodeEnum;\n this.data = details.data;\n }\n get name() {\n return 'SolanaJsonRpcError';\n }\n}\n","let _nextMessageId = 0;\nexport function getNextMessageId() {\n const id = _nextMessageId;\n _nextMessageId = (_nextMessageId + 1) % Number.MAX_SAFE_INTEGER;\n return id;\n}\n","import { getNextMessageId } from './json-rpc-message-id';\n\nexport function createJsonRpcMessage<TParams>(method: string, params: TParams) {\n return {\n id: getNextMessageId(),\n jsonrpc: '2.0',\n method,\n params,\n };\n}\n","import { SolanaJsonRpcError } from './json-rpc-errors';\nimport { createJsonRpcMessage } from './json-rpc-message';\nimport { PendingRpcRequest, Rpc, RpcConfig, RpcRequest, SendOptions } from './json-rpc-types';\n\ninterface IHasIdentifier {\n readonly id: number;\n}\ntype JsonRpcResponse<TResponse> = IHasIdentifier &\n Readonly<{ result: TResponse } | { error: { code: number; message: string; data?: unknown } }>;\n\nfunction createPendingRpcRequest<TRpcMethods, TResponse>(\n rpcConfig: RpcConfig<TRpcMethods>,\n pendingRequest: RpcRequest<TResponse>\n): PendingRpcRequest<TResponse> {\n return {\n async send(options?: SendOptions): Promise<TResponse> {\n const { methodName, params, responseProcessor } = pendingRequest;\n const payload = createJsonRpcMessage(methodName, params);\n const response = await rpcConfig.transport<JsonRpcResponse<unknown>>({\n payload,\n signal: options?.abortSignal,\n });\n if ('error' in response) {\n throw new SolanaJsonRpcError(response.error);\n } else {\n return (responseProcessor ? responseProcessor(response.result) : response.result) as TResponse;\n }\n },\n };\n}\n\nfunction makeProxy<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const createRpcRequest = Reflect.get(target, methodName, receiver);\n const newRequest = createRpcRequest\n ? createRpcRequest(...rawParams)\n : { methodName, params: rawParams };\n return createPendingRpcRequest(rpcConfig, newRequest);\n };\n },\n }) as Rpc<TRpcMethods>;\n}\n\nexport function createJsonRpc<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return makeProxy(rpcConfig);\n}\n","export default globalThis.fetch;\n","type SolanaHttpErrorDetails = Readonly<{\n statusCode: number;\n message: string;\n}>;\n\nexport class SolanaHttpError extends Error {\n readonly statusCode: number;\n constructor(details: SolanaHttpErrorDetails) {\n super(`HTTP error (${details.statusCode}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.statusCode = details.statusCode;\n }\n get name() {\n return 'SolanaHttpError';\n }\n}\n","export type AllowedHttpRequestHeaders = Readonly<\n { [headerName: string]: string } & {\n // Someone can still sneak a forbidden header past Typescript if they do something like\n // fOo-BaR, but at that point they deserve the runtime failure.\n [K in DisallowedHeaders | ForbiddenHeaders as\n | K // `Foo-Bar`\n | Capitalize<Lowercase<K>> // `Foo-bar`\n | Lowercase<K> // `foo-bar`\n | Uncapitalize<K> // `foo-Bar`\n // `FOO-BAR`\n | Uppercase<K>]?: never;\n }\n>;\n// These are headers that we simply don't allow the developer to override because they're\n// fundamental to the operation of the JSON-RPC transport.\ntype DisallowedHeaders = 'Accept' | 'Content-Length' | 'Content-Type' | 'Solana-Client';\ntype ForbiddenHeaders =\n | 'Accept-Charset'\n | 'Accept-Encoding'\n | 'Access-Control-Request-Headers'\n | 'Access-Control-Request-Method'\n | 'Connection'\n | 'Content-Length'\n | 'Cookie'\n | 'Date'\n | 'DNT'\n | 'Expect'\n | 'Host'\n | 'Keep-Alive'\n | 'Origin'\n | 'Permissions-Policy'\n // No currently available Typescript technique allows you to match on a prefix.\n // | 'Proxy-'\n // | 'Sec-'\n | 'Referer'\n | 'TE'\n | 'Trailer'\n | 'Transfer-Encoding'\n | 'Upgrade'\n | 'Via';\n\n// These are headers which are fundamental to the JSON-RPC transport, and must not be modified.\nconst DISALLOWED_HEADERS: Record<string, boolean> = {\n accept: true,\n 'content-length': true,\n 'content-type': true,\n};\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS: Record<string, boolean> = {\n 'accept-charset': true,\n 'accept-encoding': true,\n 'access-control-request-headers': true,\n 'access-control-request-method': true,\n connection: true,\n 'content-length': true,\n cookie: true,\n date: true,\n dnt: true,\n expect: true,\n host: true,\n 'keep-alive': true,\n origin: true,\n 'permissions-policy': true,\n // No currently available Typescript technique allows you to match on a prefix.\n // 'proxy-':true,\n // 'sec-':true,\n referer: true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n via: true,\n};\n\nexport function assertIsAllowedHttpRequestHeaders(\n headers: Record<string, string>\n): asserts headers is AllowedHttpRequestHeaders {\n const badHeaders = Object.keys(headers).filter(headerName => {\n const lowercaseHeaderName = headerName.toLowerCase();\n return (\n DISALLOWED_HEADERS[headerName.toLowerCase()] === true ||\n FORBIDDEN_HEADERS[headerName.toLowerCase()] === true ||\n lowercaseHeaderName.startsWith('proxy-') ||\n lowercaseHeaderName.startsWith('sec-')\n );\n });\n if (badHeaders.length > 0) {\n throw new Error(\n `${badHeaders.length > 1 ? 'These headers are' : 'This header is'} forbidden: ` +\n `\\`${badHeaders.join('`, `')}\\`. Learn more at ` +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.'\n );\n }\n}\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers, such as those defined\n * in the `DisallowedHeaders` type.\n */\nexport function normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n","import type { Agent as NodeHttpAgent } from 'node:http';\nimport type { Agent as NodeHttpsAgent } from 'node:https';\n\nimport fetchImpl from 'fetch-impl';\n\nimport { IRpcTransport } from '../transport-types';\nimport { SolanaHttpError } from './http-transport-errors';\nimport {\n AllowedHttpRequestHeaders,\n assertIsAllowedHttpRequestHeaders,\n normalizeHeaders,\n} from './http-transport-headers';\n\ntype Config = Readonly<{\n headers?: AllowedHttpRequestHeaders;\n httpAgentNodeOnly?: NodeHttpAgent | NodeHttpsAgent | ((parsedUrl: URL) => NodeHttpAgent | NodeHttpsAgent);\n url: string;\n}>;\n\nexport function createHttpTransport({ httpAgentNodeOnly, headers, url }: Config): IRpcTransport {\n if (__DEV__ && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\n }\n const agent = __NODEJS__ ? httpAgentNodeOnly : undefined;\n if (__DEV__ && httpAgentNodeOnly != null) {\n console.warn(\n 'createHttpTransport(): The `httpAgentNodeOnly` config you supplied has been ' +\n 'ignored; HTTP agents are only usable in Node environments.'\n );\n }\n const customHeaders = headers && normalizeHeaders(headers);\n return async function makeHttpRequest<TResponse>({\n payload,\n signal,\n }: Parameters<IRpcTransport>[0]): Promise<TResponse> {\n const body = JSON.stringify(payload);\n const requestInfo = {\n agent,\n body,\n headers: {\n ...customHeaders,\n // Keep these headers lowercase so they will override any user-supplied headers above.\n accept: 'application/json',\n 'content-length': body.length.toString(),\n 'content-type': 'application/json; charset=utf-8',\n },\n method: 'POST',\n signal,\n };\n const response = await fetchImpl(url, requestInfo);\n if (!response.ok) {\n throw new SolanaHttpError({\n message: response.statusText,\n statusCode: response.status,\n });\n }\n return (await response.json()) as TResponse;\n };\n}\n","import { createSolanaRpcApi } from '@solana/rpc-core';\n\nimport { SolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\nexport const DEFAULT_RPC_CONFIG: Partial<Parameters<typeof createSolanaRpcApi>[0]> = {\n onIntegerOverflow(methodName, keyPath, value) {\n throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);\n },\n};\n","export class SolanaJsonRpcIntegerOverflowError extends Error {\n readonly methodName: string;\n readonly keyPath: (number | string)[];\n readonly value: bigint;\n constructor(methodName: string, keyPath: (number | string)[], value: bigint) {\n const argPosition = (typeof keyPath[0] === 'number' ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;\n let ordinal = '';\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n ordinal = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n ordinal = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n ordinal = argPosition + 'rd';\n } else {\n ordinal = argPosition + 'th';\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : null;\n super(\n `The ${ordinal} argument to the \\`${methodName}\\` RPC method` +\n `${path ? ` at path \\`${path}\\`` : ''} was \\`${value}\\`. This number is ` +\n 'unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.'\n );\n this.keyPath = keyPath;\n this.methodName = methodName;\n this.value = value;\n }\n get name() {\n return 'SolanaJsonRpcIntegerOverflowError';\n }\n}\n","import { createHttpTransport } from '@solana/rpc-transport';\nimport { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getRpcTransportWithRequestCoalescing } from './rpc-request-coalescer';\nimport { getSolanaRpcPayloadDeduplicationKey } from './rpc-request-deduplication';\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers.\n */\nfunction normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n\nexport function createDefaultRpcTransport(config: Parameters<typeof createHttpTransport>[0]): IRpcTransport {\n return getRpcTransportWithRequestCoalescing(\n createHttpTransport({\n ...config,\n headers: {\n ...(config.headers ? normalizeHeaders(config.headers) : undefined),\n ...({\n // Keep these headers lowercase so they will override any user-supplied headers above.\n 'solana-client': `js/${__VERSION__}` ?? 'UNKNOWN',\n } as { [overrideHeader: string]: string }),\n },\n }),\n getSolanaRpcPayloadDeduplicationKey\n );\n}\n","import { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\ntype CoalescedRequest = {\n readonly abortController: AbortController;\n numConsumers: number;\n readonly responsePromise: Promise<unknown>;\n};\n\ntype GetDeduplicationKeyFn = (payload: unknown) => string | undefined;\n\nexport function getRpcTransportWithRequestCoalescing(\n transport: IRpcTransport,\n getDeduplicationKey: GetDeduplicationKeyFn\n): IRpcTransport {\n let coalescedRequestsByDeduplicationKey: Record<string, CoalescedRequest> | undefined;\n return async function makeCoalescedHttpRequest<TResponse>(\n config: Parameters<IRpcTransport>[0]\n ): Promise<TResponse> {\n const { payload, signal } = config;\n const deduplicationKey = getDeduplicationKey(payload);\n if (deduplicationKey === undefined) {\n return await transport(config);\n }\n if (!coalescedRequestsByDeduplicationKey) {\n Promise.resolve().then(() => {\n coalescedRequestsByDeduplicationKey = undefined;\n });\n coalescedRequestsByDeduplicationKey = {};\n }\n if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {\n const abortController = new AbortController();\n coalescedRequestsByDeduplicationKey[deduplicationKey] = {\n abortController,\n numConsumers: 0,\n responsePromise: transport<TResponse>({\n ...config,\n signal: abortController.signal,\n }),\n };\n }\n const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];\n coalescedRequest.numConsumers++;\n if (signal) {\n const responsePromise = coalescedRequest.responsePromise as Promise<TResponse>;\n return await new Promise<TResponse>((resolve, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n signal.removeEventListener('abort', handleAbort);\n coalescedRequest.numConsumers -= 1;\n if (coalescedRequest.numConsumers === 0) {\n const abortController = coalescedRequest.abortController;\n abortController.abort();\n }\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n signal.addEventListener('abort', handleAbort);\n responsePromise.then(resolve).finally(() => {\n signal.removeEventListener('abort', handleAbort);\n });\n });\n } else {\n return (await coalescedRequest.responsePromise) as TResponse;\n }\n };\n}\n","// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return;\n }\n if ('jsonrpc' in payload && payload.jsonrpc === '2.0' && 'method' in payload && 'params' in payload) {\n return fastStableStringify([payload.method, payload.params]);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../build-scripts/env-shim.ts","../../../node_modules/.pnpm/fast-stable-stringify@1.0.0/node_modules/fast-stable-stringify/index.js","../src/index.ts","../../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","../../addresses/src/address.ts","../../addresses/src/program-derived-address.ts","../../addresses/src/vendor/noble/ed25519.ts","../../addresses/src/curve.ts","../../addresses/src/public-key.ts","../../instructions/src/roles.ts","../../keys/src/key-pair.ts","../../keys/src/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/src/array.ts","../../codecs-data-structures/src/utils.ts","../../codecs-data-structures/src/bit-array.ts","../../codecs-data-structures/src/boolean.ts","../../codecs-data-structures/src/bytes.ts","../../codecs-data-structures/src/nullable.ts","../../codecs-data-structures/src/scalar-enum.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","createDecoder","createEncoder","alphabet","e2","base58Encoder","e","address","AccountRole","signature","assertIsFixedSize","getEncodedSize","mapDecoder","mapEncoder","getU8Decoder","AccountRole2","IS_WRITABLE_BITMASK","isSignerRole","mergeRoles","isWritableRole","getAddressDecoder","getStructDecoder","getU8Encoder","getStructEncoder","getArrayEncoder","getArrayDecoder","getShortU16Decoder","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,UAAI,GAAG,KAAK,KAAK,MAAM,KAAK,SAAS;AACrC,UAAI,QAAQ,MAAM;AACjB,eAAO;AAAA,MACR;AACA,UAAI,QAAQ,OAAO;AAClB,eAAO;AAAA,MACR;AACA,cAAQ,OAAO,KAAK;AAAA,QACnB,KAAK;AACJ,cAAI,QAAQ,MAAM;AACjB,mBAAO;AAAA,UACR,WAAW,IAAI,UAAU,OAAO,IAAI,WAAW,YAAY;AAC1D,mBAAO,UAAU,IAAI,OAAO,G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QAAQ,UAAU,QAAQ,SAAS,cAAc,oBAAoB;;EAEtE,CAAC,QAAQ,UAAU,QAAQ,oBAAoB;EAC/C,CAAC,QAAQ,UAAU,QAAQ,aAAa;;EAExC,CAAC,QAAQ,UAAU,QAAQ,YAAY;EACvC,CAAC,QAAQ,UAAU,QAAQ,SAAS,kBAAkB,mBAAmB;AAC7E;AAIA,IAAI;AAGJ,IAAI;AAMG,SAAS,2CAEd;AACE,MAAI,CAAC,8BAA8B;AAC/B,mCAA+B;MAC3B,sBAAsB,0BAA0B,IAAI,CAAA,MAAK,CAAC,SAAS,GAAG,CAAC,CAAC;MACxE,oBAAoB;QAChB,CAAC,SAAS,SAAS,WAAW;QAC9B;UACI;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;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;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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","/**\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","import {\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n mapEncoder,\n} 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(): FixedSizeEncoder<Address, 32> {\n return mapEncoder(getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }), putativeAddress =>\n address(putativeAddress),\n );\n}\n\nexport function getAddressDecoder(): FixedSizeDecoder<Address, 32> {\n return getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 }) as FixedSizeDecoder<Address, 32>;\n}\n\nexport function getAddressCodec(): FixedSizeCodec<Address, Address, 32> {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\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","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);\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);\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: Uint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport async function compressedPointBytesAreOnCurve(bytes: Uint8Array): Promise<boolean> {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { 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 return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\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 {\n assertIsFixedSize,\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n Offset,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { getFixedSize, getMaxSize } 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> =\n | TPrefix\n | number\n | 'remainder';\n\n/** Defines the configs for array codecs. */\nexport type ArrayCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = {\n /**\n * The size of the array.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\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<TFrom>(\n item: Encoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> & { size: 0 },\n): FixedSizeEncoder<TFrom[], 0>;\nexport function getArrayEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> & { size: number },\n): FixedSizeEncoder<TFrom[]>;\nexport function getArrayEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> & { size: 'remainder' },\n): VariableSizeEncoder<TFrom[]>;\nexport function getArrayEncoder<TFrom>(\n item: Encoder<TFrom>,\n config?: ArrayCodecConfig<NumberEncoder> & { size?: number | NumberEncoder },\n): VariableSizeEncoder<TFrom[]>;\nexport function getArrayEncoder<TFrom>(\n item: Encoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> = {},\n): Encoder<TFrom[]> {\n const size = config.size ?? getU32Encoder();\n if (size === 'remainder') {\n assertIsFixedSize(item, 'Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n const fixedSize = computeArrayLikeCodecSize(size, getFixedSize(item));\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize !== null\n ? { fixedSize }\n : {\n getSizeFromValue: (array: TFrom[]) => {\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: TFrom[], 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}\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<TTo>(\n item: Decoder<TTo>,\n config: ArrayCodecConfig<NumberDecoder> & { size: 0 },\n): FixedSizeDecoder<TTo[], 0>;\nexport function getArrayDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: ArrayCodecConfig<NumberDecoder> & { size: number },\n): FixedSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: ArrayCodecConfig<NumberDecoder> & { size: 'remainder' },\n): VariableSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(\n item: Decoder<TTo>,\n config?: ArrayCodecConfig<NumberDecoder> & { size?: number | NumberDecoder },\n): VariableSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(item: Decoder<TTo>, config: ArrayCodecConfig<NumberDecoder> = {}): Decoder<TTo[]> {\n const size = config.size ?? getU32Decoder();\n if (size === 'remainder') {\n assertIsFixedSize(item, 'Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n const itemSize = getFixedSize(item);\n const fixedSize = computeArrayLikeCodecSize(size, itemSize);\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize !== null ? { fixedSize } : { maxSize }),\n read: (bytes: Uint8Array, offset) => {\n const array: TTo[] = [];\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, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, 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<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> & { size: 0 },\n): FixedSizeCodec<TFrom[], TTo[], 0>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> & { size: number },\n): FixedSizeCodec<TFrom[], TTo[]>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> & { size: 'remainder' },\n): VariableSizeCodec<TFrom[], TTo[]>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config?: ArrayCodecConfig<NumberCodec> & { size?: number | NumberCodec },\n): VariableSizeCodec<TFrom[], TTo[]>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> = {},\n): Codec<TFrom[], TTo[]> {\n return combineCodec(getArrayEncoder(item, config as object), getArrayDecoder(item, config as object));\n}\n\nfunction readArrayLikeCodecSize(\n size: ArrayLikeCodecSize<NumberDecoder>,\n itemSize: 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.read(bytes, offset);\n }\n\n if (size === 'remainder') {\n if (itemSize === null) {\n // TODO: Coded error.\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 // TODO: Coded error.\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${itemSize} bytes. ` +\n `Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainder} modulo ${itemSize} should be equal to zero.`,\n );\n }\n return [remainder / itemSize, offset];\n }\n\n // TODO: Coded error.\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\n\nfunction computeArrayLikeCodecSize(size: object | number | 'remainder', itemSize: number | null): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n return itemSize === null ? null : itemSize * size;\n}\n","import { isFixedSize } from '@solana/codecs-core';\n\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\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\nexport function getFixedSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : null;\n}\n\nexport function getMaxSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from '@solana/codecs-core';\n\n/** Defines the config for bitArray codecs. */\nexport type BitArrayCodecConfig = {\n /**\n * Whether to read the bits in reverse order.\n * @defaultValue `false`\n */\n backward?: boolean;\n};\n\n/**\n * Encodes an array of booleans into bits.\n *\n * @param size - The amount of bytes to use for the bit array.\n * @param config - A set of config for the encoder.\n */\nexport function getBitArrayEncoder<TSize extends number>(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeEncoder<boolean[], TSize> {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createEncoder({\n fixedSize: size,\n write(value: boolean[], bytes, offset) {\n const bytesToAdd: number[] = [];\n\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\n bytes.set(bytesToAdd, offset);\n return size;\n },\n });\n}\n\n/**\n * Decodes bits into an array of booleans.\n *\n * @param size - The amount of bytes to use for the bit array.\n * @param config - A set of config for the decoder.\n */\nexport function getBitArrayDecoder<TSize extends number>(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeDecoder<boolean[], TSize> {\n const parsedConfig: BitArrayCodecConfig = 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: boolean[] = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n\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 & 0b1000_0000));\n byte <<= 1;\n }\n }\n });\n\n return [booleans, offset + size];\n },\n });\n}\n\n/**\n * An array of boolean codec that converts booleans to bits and vice versa.\n *\n * @param size - The amount of bytes to use for the bit array.\n * @param config - A set of config for the codec.\n */\nexport function getBitArrayCodec<TSize extends number>(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeCodec<boolean[], boolean[], TSize> {\n return combineCodec(getBitArrayEncoder(size, config), getBitArrayDecoder(size, config));\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n mapDecoder,\n mapEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\n/** Defines the config for boolean codecs. */\nexport type BooleanCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = {\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(): FixedSizeEncoder<boolean, 1>;\nexport function getBooleanEncoder<TSize extends number>(\n config: BooleanCodecConfig<NumberEncoder> & { size: FixedSizeNumberEncoder<TSize> },\n): FixedSizeEncoder<boolean, TSize>;\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder>): Encoder<boolean>;\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder> = {}): Encoder<boolean> {\n const size = config.size ?? getU8Encoder();\n assertIsFixedSize(size, 'Codec [bool] requires a fixed size.');\n return mapEncoder(size, (value: boolean) => (value ? 1 : 0));\n}\n\n/**\n * Decodes booleans.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBooleanDecoder(): FixedSizeDecoder<boolean, 1>;\nexport function getBooleanDecoder<TSize extends number>(\n config: BooleanCodecConfig<NumberDecoder> & { size: FixedSizeNumberDecoder<TSize> },\n): FixedSizeDecoder<boolean, TSize>;\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder>): Decoder<boolean>;\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder> = {}): Decoder<boolean> {\n const size = config.size ?? getU8Decoder();\n assertIsFixedSize(size, 'Codec [bool] requires a fixed size.');\n return mapDecoder(size, (value: number | bigint): boolean => Number(value) === 1);\n}\n\n/**\n * Creates a boolean codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBooleanCodec(): FixedSizeCodec<boolean, boolean, 1>;\nexport function getBooleanCodec<TSize extends number>(\n config: BooleanCodecConfig<NumberCodec> & { size: FixedSizeNumberCodec<TSize> },\n): FixedSizeCodec<boolean, boolean, TSize>;\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec>): Codec<boolean>;\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec> = {}): Codec<boolean> {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\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 { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/** Defines the config for bytes codecs. */\nexport type BytesCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = {\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<TSize extends number>(\n config: BytesCodecConfig<NumberEncoder> & { size: TSize },\n): FixedSizeEncoder<Uint8Array, TSize>;\nexport function getBytesEncoder(config?: BytesCodecConfig<NumberEncoder>): VariableSizeEncoder<Uint8Array>;\nexport function getBytesEncoder(config: BytesCodecConfig<NumberEncoder> = {}): Encoder<Uint8Array> {\n const size = config.size ?? 'variable';\n\n const byteEncoder: Encoder<Uint8Array> = createEncoder({\n getSizeFromValue: (value: Uint8Array) => value.length,\n write: (value: Uint8Array, bytes, offset) => {\n bytes.set(value, offset);\n return offset + value.length;\n },\n });\n\n if (size === 'variable') {\n return byteEncoder;\n }\n\n if (typeof size === 'number') {\n return fixEncoder(byteEncoder, size);\n }\n\n return createEncoder({\n getSizeFromValue: (value: Uint8Array) => getEncodedSize(value.length, size) + value.length,\n write: (value: Uint8Array, bytes, offset) => {\n offset = size.write(value.length, bytes, offset);\n return byteEncoder.write(value, bytes, offset);\n },\n });\n}\n\n/**\n * Decodes sized bytes.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBytesDecoder<TSize extends number>(\n config: BytesCodecConfig<NumberDecoder> & { size: TSize },\n): FixedSizeDecoder<Uint8Array, TSize>;\nexport function getBytesDecoder(config?: BytesCodecConfig<NumberDecoder>): VariableSizeDecoder<Uint8Array>;\nexport function getBytesDecoder(config: BytesCodecConfig<NumberDecoder> = {}): Decoder<Uint8Array> {\n const size = config.size ?? 'variable';\n\n const byteDecoder: Decoder<Uint8Array> = createDecoder({\n read: (bytes: Uint8Array, offset) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n });\n\n if (size === 'variable') {\n return byteDecoder;\n }\n\n if (typeof size === 'number') {\n return fixDecoder(byteDecoder, size);\n }\n\n return createDecoder({\n read: (bytes: Uint8Array, 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}\n\n/**\n * Creates a sized bytes codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBytesCodec<TSize extends number>(\n config: BytesCodecConfig<NumberCodec> & { size: TSize },\n): FixedSizeCodec<Uint8Array, Uint8Array, TSize>;\nexport function getBytesCodec(config?: BytesCodecConfig<NumberCodec>): VariableSizeCodec<Uint8Array>;\nexport function getBytesCodec(config: BytesCodecConfig<NumberCodec> = {}): Codec<Uint8Array> {\n return combineCodec(getBytesEncoder(config), getBytesDecoder(config));\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { getMaxSize, sumCodecSizes } from './utils';\n\n/** Defines the config for nullable codecs. */\nexport type NullableCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `null` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param config - A set of config for the encoder.\n */\nexport function getNullableEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: NullableCodecConfig<FixedSizeNumberEncoder> & { fixed: true },\n): FixedSizeEncoder<TFrom | null>;\nexport function getNullableEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom, 0>,\n config?: NullableCodecConfig<FixedSizeNumberEncoder>,\n): FixedSizeEncoder<TFrom | null>;\nexport function getNullableEncoder<TFrom>(\n item: Encoder<TFrom>,\n config?: NullableCodecConfig<NumberEncoder> & { fixed?: false },\n): VariableSizeEncoder<TFrom | null>;\nexport function getNullableEncoder<TFrom>(\n item: Encoder<TFrom>,\n config: NullableCodecConfig<NumberEncoder> = {},\n): Encoder<TFrom | null> {\n const prefix = config.prefix ?? getU8Encoder();\n const fixed = config.fixed ?? false;\n\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: TFrom | null, 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\n return createEncoder({\n getSizeFromValue: (option: TFrom | null) =>\n getEncodedSize(Number(option !== null), prefix) + (option !== null ? getEncodedSize(option, item) : 0),\n maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined,\n write: (option: TFrom | null, 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}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param config - A set of config for the decoder.\n */\nexport function getNullableDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: NullableCodecConfig<FixedSizeNumberDecoder> & { fixed: true },\n): FixedSizeDecoder<TTo | null>;\nexport function getNullableDecoder<TTo>(\n item: FixedSizeDecoder<TTo, 0>,\n config?: NullableCodecConfig<FixedSizeNumberDecoder>,\n): FixedSizeDecoder<TTo | null>;\nexport function getNullableDecoder<TTo>(\n item: Decoder<TTo>,\n config?: NullableCodecConfig<NumberDecoder> & { fixed?: false },\n): VariableSizeDecoder<TTo | null>;\nexport function getNullableDecoder<TTo>(\n item: Decoder<TTo>,\n config: NullableCodecConfig<NumberDecoder> = {},\n): Decoder<TTo | null> {\n const prefix = config.prefix ?? getU8Decoder();\n const fixed = config.fixed ?? false;\n\n let fixedSize: number | null = 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\n return createDecoder({\n ...(fixedSize === null\n ? { maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined }\n : { fixedSize }),\n read: (bytes: Uint8Array, 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}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param config - A set of config for the codec.\n */\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: NullableCodecConfig<FixedSizeNumberCodec> & { fixed: true },\n): FixedSizeCodec<TFrom | null, TTo | null>;\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo, 0>,\n config?: NullableCodecConfig<FixedSizeNumberCodec>,\n): FixedSizeCodec<TFrom | null, TTo | null>;\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config?: NullableCodecConfig<NumberCodec> & { fixed?: false },\n): VariableSizeCodec<TFrom | null, TTo | null>;\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: NullableCodecConfig<NumberCodec> = {},\n): Codec<TFrom | null, TTo | null> {\n const configCast = config as NullableCodecConfig<NumberCodec> & { fixed?: false };\n return combineCodec(getNullableEncoder<TFrom>(item, configCast), getNullableDecoder<TTo>(item, configCast));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} 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 /**\n * The codec to use for the enum discriminator.\n * @defaultValue u8 discriminator.\n */\n size?: TDiscriminator;\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<TFrom, TFromConstructor extends ScalarEnum<TFrom>>(\n constructor: TFromConstructor,\n): FixedSizeEncoder<TFrom, 1>;\nexport function getScalarEnumEncoder<TFrom, TFromConstructor extends ScalarEnum<TFrom>, TSize extends number>(\n constructor: TFromConstructor,\n config: ScalarEnumCodecConfig<NumberEncoder> & { size: FixedSizeNumberEncoder<TSize> },\n): FixedSizeEncoder<TFrom, TSize>;\nexport function getScalarEnumEncoder<TFrom, TFromConstructor extends ScalarEnum<TFrom>>(\n constructor: TFromConstructor,\n config?: ScalarEnumCodecConfig<NumberEncoder>,\n): VariableSizeEncoder<TFrom>;\nexport function getScalarEnumEncoder<TFrom, TFromConstructor extends ScalarEnum<TFrom>>(\n constructor: TFromConstructor,\n config: ScalarEnumCodecConfig<NumberEncoder> = {},\n): Encoder<TFrom> {\n const prefix = config.size ?? getU8Encoder();\n const { minRange, maxRange, stringValues, enumKeys, enumValues } = getScalarEnumStats(constructor);\n return mapEncoder(prefix, (value: TFrom): number => {\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 value;\n const valueIndex = enumValues.indexOf(value);\n if (valueIndex >= 0) return valueIndex;\n return enumKeys.indexOf(value as string);\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<TTo, TToConstructor extends ScalarEnum<TTo>>(\n constructor: TToConstructor,\n): FixedSizeDecoder<TTo, 1>;\nexport function getScalarEnumDecoder<TTo, TToConstructor extends ScalarEnum<TTo>, TSize extends number>(\n constructor: TToConstructor,\n config: ScalarEnumCodecConfig<NumberDecoder> & { size: FixedSizeNumberDecoder<TSize> },\n): FixedSizeDecoder<TTo, TSize>;\nexport function getScalarEnumDecoder<TTo, TToConstructor extends ScalarEnum<TTo>>(\n constructor: TToConstructor,\n config?: ScalarEnumCodecConfig<NumberDecoder>,\n): VariableSizeDecoder<TTo>;\nexport function getScalarEnumDecoder<TTo, TToConstructor extends ScalarEnum<TTo>>(\n constructor: TToConstructor,\n config: ScalarEnumCodecConfig<NumberDecoder> = {},\n): Decoder<TTo> {\n const prefix = config.size ?? getU8Decoder();\n const { minRange, maxRange, isNumericEnum, enumValues } = getScalarEnumStats(constructor);\n return mapDecoder(prefix, (value: number | bigint): TTo => {\n const valueAsNumber = Number(value);\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 TTo;\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<TFrom, TFromConstructor extends ScalarEnum<TFrom>>(\n constructor: TFromConstructor,\n): FixedSizeCodec<TFrom, TFrom, 1>;\nexport function getScalarEnumCodec<TFrom, TFromConstructor extends ScalarEnum<TFrom>, TSize extends number>(\n constructor: TFromConstructor,\n config: ScalarEnumCodecConfig<NumberCodec> & { size: FixedSizeNumberCodec<TSize> },\n): FixedSizeCodec<TFrom, TFrom, TSize>;\nexport function getScalarEnumCodec<TFrom, TFromConstructor extends ScalarEnum<TFrom>>(\n constructor: TFromConstructor,\n config?: ScalarEnumCodecConfig<NumberCodec>,\n): VariableSizeCodec<TFrom>;\nexport function getScalarEnumCodec<TFrom, TFromConstructor extends ScalarEnum<TFrom>>(\n constructor: TFromConstructor,\n config: ScalarEnumCodecConfig<NumberCodec> = {},\n): Codec<TFrom> {\n return combineCodec(getScalarEnumEncoder(constructor, config), getScalarEnumDecoder(constructor, config));\n}\n\nfunction getScalarEnumStats<TFrom>(constructor: ScalarEnum<TFrom>): {\n enumKeys: string[];\n enumValues: TFrom[];\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 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 enumKeys,\n enumValues,\n isNumericEnum,\n maxRange,\n minRange,\n stringValues,\n };\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\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"]}
|