@solana/web3.js 2.0.0-development → 2.0.0-experimental.0099b2a
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 +4 -4
- package/dist/index.browser.cjs +779 -10
- 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 +3531 -395
- package/dist/index.development.js.map +1 -1
- package/dist/index.native.js +737 -11
- package/dist/index.native.js.map +1 -1
- package/dist/index.node.cjs +768 -10
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.js +737 -11
- package/dist/index.node.js.map +1 -1
- package/dist/index.production.min.js +78 -16
- package/dist/types/airdrop-confirmer.d.ts +20 -0
- package/dist/types/airdrop.d.ts +23 -0
- package/dist/types/cached-abortable-iterable.d.ts +11 -0
- package/dist/types/index.d.ts +10 -0
- package/dist/types/rpc-subscription-coalescer.d.ts +10 -0
- package/dist/types/rpc-websocket-autopinger.d.ts +8 -0
- package/dist/types/rpc-websocket-connection-sharding.d.ts +13 -0
- package/dist/types/rpc-websocket-transport.d.ts +13 -0
- package/dist/types/rpc.d.ts +5 -3
- package/dist/types/send-transaction.d.ts +37 -0
- package/dist/types/transaction-confirmation-strategy-blockheight.d.ts +10 -0
- package/dist/types/transaction-confirmation-strategy-nonce.d.ts +15 -0
- package/dist/types/transaction-confirmation-strategy-racer.d.ts +14 -0
- package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts +13 -0
- package/dist/types/transaction-confirmation-strategy-timeout.d.ts +8 -0
- package/dist/types/transaction-confirmation.d.ts +37 -0
- package/package.json +24 -22
|
@@ -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.2/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-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/u32.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/src/string.ts","../../keys/src/base58.ts","../../keys/src/guard.ts","../../keys/src/key-pair.ts","../../keys/src/pubkey.ts","../src/rpc.ts","../../rpc-core/src/params-patcher.ts","../../rpc-core/src/response-patcher-allowed-numeric-values.ts","../../rpc-core/src/response-patcher.ts","../../rpc-core/src/rpc-methods/index.ts","../../rpc-transport/src/json-rpc-errors.ts","../../rpc-transport/src/json-rpc-message-id.ts","../../rpc-transport/src/json-rpc-message.ts","../../rpc-transport/src/json-rpc.ts","../../fetch-impl/src/index.browser.ts","../../rpc-transport/src/transports/http/http-transport-errors.ts","../../rpc-transport/src/transports/http/http-transport-headers.ts","../../rpc-transport/src/transports/http/http-transport.ts","../src/rpc-default-config.ts","../src/rpc-integer-overflow-error.ts","../src/rpc-transport.ts","../src/rpc-request-coalescer.ts","../src/rpc-request-deduplication.ts"],"names":["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","fixSerializer","fixedBytes","description","fixedSize","maxSize","serialize","value","deserialize","buffer","InvalidBaseStringError","base","cause","message","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","u32","le","setUint32","getUint32","getSizeDescription","string","encoding","contentBytes","lengthBytes","lengthBigInt","lengthOffset","contentBuffer","contentOffset","e","__DEV__","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,UAAU,KAAK,aAAa;AACpC,UAAI,GAAG,KAAK,KAAK,MAAM,KAAK,SAAS;AACrC,UAAI,QAAQ,MAAM;AACjB,eAAO;AAAA,MACR;AACA,UAAI,QAAQ,OAAO;AAClB,eAAO;AAAA,MACR;AACA,cAAQ,OAAO,KAAK;AAAA,QACnB,KAAK;AACJ,cAAI,QAAQ,MAAM;AACjB,mBAAO;AAAA,UACR,WAAW,IAAI,UAAU,OAAO,IAAI,WAAW,YAAY;AAC1D,mBAAO,UAAU,IAAI,OAAO,GAAG,WAAW;AAAA,UAC3C,OAAO;AACN,oBAAQ,YAAY,KAAK,GAAG;AAC5B,gBAAI,UAAU,kBAAkB;AAC/B,oBAAM;AACN,oBAAM,IAAI,SAAS;AACnB,mBAAI,IAAI,GAAG,IAAI,KAAK,KAAK;AACxB,uBAAO,UAAU,IAAI,CAAC,GAAG,IAAI,IAAI;AAAA,cAClC;AACA,kBAAI,MAAM,IAAI;AACb,uBAAO,UAAU,IAAI,CAAC,GAAG,IAAI;AAAA,cAC9B;AACA,qBAAO,MAAM;AAAA,Y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O,iBAAiB,SAAS,WAAW;AAC5C,wBAAgB,KAAK,OAAO,EAAE,QAAQ,MAAM;AACxC,iBAAO,oBAAoB,SAAS,WAAW;AAAA,QACnD,CAAC;AAAA,MACL,CAAC;AAAA,IACL,OAAO;AACH,aAAQ,MAAM,iBAAiB;AAAA,IACnC;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,6BAAAG,SAAoB,CAAC,QAAQ,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAC/D;AACJ;;;AFFA,SAASC,kBACL,SACiD;AACjD,QAAM,MAA8B,CAAC;AACrC,aAAW,cAAc,SAAS;AAC9B,QAAI,WAAW,YAAY,CAAC,IAAI,QAAQ,UAAU;AAAA,EACtD;AACA,SAAO;AACX;AAEO,SAAS,0BAA0B,QAAkE;AACxG,SAAO;AAAA,IACH,oBAAoB;AAAA,MAChB,GAAG;AAAA,MACH,SAAS;AAAA,QACL,GAAI,OAAO,UAAUA,kBAAiB,OAAO,OAAO,IAAI;AAAA,QACxD,GAAI;AAAA;AAAA,UAEA,iBAAiB,MAAM,yBAAiB;AAAA,QAC5C;AAAA,MACJ;AAAA,IACJ,CAAC;AAAA,IACD;AAAA,EACJ;AACJ","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","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 './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","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 { 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","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 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 { 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('This runtime does not support the generation of Ed25519 keypairs');\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 { 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';\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\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/combine-codec.ts","../../codecs-core/src/fix-codec.ts","../../codecs-core/src/map-codec.ts","../../codecs-numbers/src/assertions.ts","../../codecs-numbers/src/f32.ts","../../codecs-numbers/src/utils.ts","../../codecs-numbers/src/i64.ts","../../codecs-numbers/src/i8.ts","../../codecs-numbers/src/short-u16.ts","../../codecs-numbers/src/u128.ts","../../codecs-numbers/src/u16.ts","../../codecs-numbers/src/u32.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/baseX-reslice.ts","../../codecs-strings/src/base64.ts","../../codecs-strings/src/null-characters.ts","../../codecs-strings/src/string.ts","../../codecs-strings/src/utf8.ts","../../text-encoding-impl/src/index.browser.ts","../../assertions/src/subtle-crypto.ts","../../addresses/src/address.ts","../../addresses/src/vendor/noble/ed25519.ts","../../addresses/src/curve.ts","../../addresses/src/program-derived-address.ts","../../addresses/src/public-key.ts","../../instructions/src/roles.ts","../../keys/src/key-pair.ts","../../keys/src/signatures.ts","../../rpc-types/src/commitment.ts","../../rpc-types/src/lamports.ts","../../rpc-types/src/stringified-bigint.ts","../../rpc-types/src/stringified-number.ts","../../rpc-types/src/unix-timestamp.ts","../../codecs-data-structures/dist/index.browser.js","../../functional/src/pipe.ts","../../transactions/src/unsigned-transaction.ts","../../transactions/src/blockhash.ts","../../transactions/src/create-transaction.ts","../../transactions/src/durable-nonce.ts","../../transactions/src/fee-payer.ts","../../transactions/src/instructions.ts","../../transactions/src/serializers/transaction.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/compile-transaction.ts","../../transactions/src/decompile-transaction.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/signatures.ts","../src/airdrop.ts","../src/airdrop-confirmer.ts","../src/transaction-confirmation-strategy-racer.ts","../src/transaction-confirmation-strategy-recent-signature.ts","../src/transaction-confirmation-strategy-timeout.ts","../src/rpc.ts","../../rpc-core/src/params-patcher.ts","../../rpc-core/src/response-patcher-types.ts","../../rpc-core/src/response-patcher-allowed-numeric-values.ts","../../rpc-core/src/response-patcher.ts","../../rpc-core/src/rpc-methods/index.ts","../../rpc-core/src/rpc-subscriptions/index.ts","../../rpc-transport/src/json-rpc-errors.ts","../../rpc-transport/src/json-rpc-message-id.ts","../../rpc-transport/src/json-rpc-message.ts","../../rpc-transport/src/json-rpc.ts","../../rpc-transport/src/json-rpc-subscription.ts","../../fetch-impl/src/index.browser.ts","../../rpc-transport/src/transports/http/http-transport-errors.ts","../../rpc-transport/src/transports/http/http-transport-headers.ts","../../rpc-transport/src/transports/http/http-transport.ts","../../ws-impl/src/index.browser.ts","../../rpc-transport/src/transports/websocket/websocket-connection.ts","../../rpc-transport/src/transports/websocket/websocket-transport.ts","../src/rpc-default-config.ts","../src/rpc-integer-overflow-error.ts","../src/rpc-subscription-coalescer.ts","../src/cached-abortable-iterable.ts","../src/rpc-transport.ts","../src/rpc-request-coalescer.ts","../src/rpc-request-deduplication.ts","../src/rpc-websocket-transport.ts","../src/rpc-websocket-autopinger.ts","../src/rpc-websocket-connection-sharding.ts","../src/send-transaction.ts","../src/transaction-confirmation.ts","../src/transaction-confirmation-strategy-blockheight.ts","../src/transaction-confirmation-strategy-nonce.ts"],"names":["combineCodec","alphabet","e2","base58Encoder","e","address","encode","decode","AccountRole","__DEV__","AccountRole2","IS_WRITABLE_BITMASK","isSignerRole","isWritableRole","mergeRoles","getArrayEncoder","getBytesDecoder","getStructDecoder","getStructEncoder","getShortU16Decoder","getShortU16Encoder","getAddressComparator","getAddressDecoder","getU8Encoder","getU8Decoder","getArrayDecoder","getAddressEncoder","getBase58Encoder","mapDecoder","mapEncoder","getBase58Decoder","getTimeoutPromise","lamports","visitNode","makeProxy","index_browser_default","resolve","reject","registerIterableCleanup","EXPLICIT_ABORT_TOKEN","deduplicationKey","pendingSubscription","fastStableStringify","import_fast_stable_stringify","normalizeHeaders","args","base58Decoder","transactionSignature"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA,QAAI,cAAc,OAAO,UAAU;AACnC,QAAI,UAAU,OAAO,QAAQ,SAAS,KAAK;AACzC,UAAI,OAAO,CAAC;AACZ,eAAS,QAAQ,KAAK;AACrB,aAAK,KAAK,IAAI;AAAA,MACf;AACA,aAAO;AAAA,IACR;AAED,aAAS,UAAU,KAAK,aAAa;AACpC,UAAI,GAAG,KAAK,KAAK,MAAM,KAAK,SAAS;AACrC,UAAI,QAAQ,MAAM;AACjB,eAAO;AAAA,MACR;AACA,UAAI,QAAQ,OAAO;AAClB,eAAO;AAAA,MACR;AACA,cAAQ,OAAO,KAAK;AAAA,QACnB,KAAK;AACJ,cAAI,QAAQ,MAAM;AACjB,mBAAO;AAAA,UACR,WAAW,IAAI,UAAU,OAAO,IAAI,WAAW,YAAY;AAC1D,mBAAO,UAAU,IAAI,OAAO,GAAG,WAAW;AAAA,UAC3C,OAAO;AACN,oBAAQ,YAAY,KAAK,GAAG;AAC5B,gBAAI,UAAU,kBAAkB;AAC/B,oBAAM;AACN,oBAAM,IAAI,SAAS;AACnB,mBAAI,IAAI,GAAG,IAAI,KAAK,KAAK;AACxB,uBAAO,UAAU,IAAI,CAAC,GAAG,IAAI,IAAI;AAAA,cAClC;AACA,kBAAI,MAAM,IAAI;AACb,uBAAO,UAAU,IAAI,CAAC,GAAG,IAAI;AAAA,cAC9B;AACA,qBAAO,MAAM;AA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AAQ,WAAW,kBAAkB,YAAY;QACtG;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA,CAAC,SAAS,SAAS,WAAW,kBAAkB,YAAY;MAChE;MACA,sBAAsB,0BAA0B,QAAQ,CAAA,MAAK;QACzD,CAAC,SAAS,kBAAkB,WAAW,GAAG,CAAC;QAC3C,CAAC,kBAAkB,WAAW,GAAG,CAAC;MACtC,CAAC;IACL;EACJ;AACA,SAAO;AACX;AAMO,SAAS,uCAAsG;AAClH,MAAI,CAAC,0BAA0B;AAC3B,+BAA2B;MACvB,gBAAgB,0BAA0B,IAAI,CAAA,MAAK,CAAC,SAAS,GAAG,CAAC,CAAC;MAClE,UAAU;QACN,CAAC,WAAW;QACZ,CAAC,gBAAgB,kBAAkB,QAAQ,oBAAoB,kBAAkB,cAAc;QAC/F;UACI;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA,CAAC,gBAAgB,kBAAkB,QAAQ,qBAAqB,kBAAkB,cAAc;QAChG;UACI;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA,CAAC,gBAAgB,kBAAkB,QAAQ,WAAW,kBAAkB,YAAY;QACpF,CAAC,g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CAA8C;AAAA,IACjF;AAAA,IACA;AAAA,EACJ,CAAC;AACD,SAAO,eAAe,4BAClB,aACA,QAIa;AACb,UAAM,sCAAsC;AAAA,MACxC,GAAG;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,+BAA+B;AAAA,EAC3C;AAAA,EACA;AACJ,GAAwD;AACpD,QAAM,2BAA2B,wCAAwC;AAAA,IACrE;AAAA,IACA;AAAA,EACJ,CAAC;AACD,SAAO,eAAe,gBAClB,aACA,QAIa;AACb,UAAM,0BAA0B;AAAA,MAC5B,GAAG;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;AAEA,eAAsB,sCAAsC;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACP,GAA+E;AAC3E,QAAMC,wBAAuB,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,SAAOA;AACX;AAEA,eAAsB,0BAA0B;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACP,GAAwF;AACpF,QAAMA,wBAAuB,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,SAAOA;AACX","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","var objToString = Object.prototype.toString;\nvar objKeys = Object.keys || function(obj) {\n\t\tvar keys = [];\n\t\tfor (var name in obj) {\n\t\t\tkeys.push(name);\n\t\t}\n\t\treturn keys;\n\t};\n\nfunction stringify(val, isArrayProp) {\n\tvar i, max, str, keys, key, propVal, toStr;\n\tif (val === true) {\n\t\treturn \"true\";\n\t}\n\tif (val === false) {\n\t\treturn \"false\";\n\t}\n\tswitch (typeof val) {\n\t\tcase \"object\":\n\t\t\tif (val === null) {\n\t\t\t\treturn null;\n\t\t\t} else if (val.toJSON && typeof val.toJSON === \"function\") {\n\t\t\t\treturn stringify(val.toJSON(), isArrayProp);\n\t\t\t} else {\n\t\t\t\ttoStr = objToString.call(val);\n\t\t\t\tif (toStr === \"[object Array]\") {\n\t\t\t\t\tstr = '[';\n\t\t\t\t\tmax = val.length - 1;\n\t\t\t\t\tfor(i = 0; i < max; i++) {\n\t\t\t\t\t\tstr += stringify(val[i], true) + ',';\n\t\t\t\t\t}\n\t\t\t\t\tif (max > -1) {\n\t\t\t\t\t\tstr += stringify(val[i], true);\n\t\t\t\t\t}\n\t\t\t\t\treturn str + ']';\n\t\t\t\t} else if (toStr === \"[object Object]\") {\n\t\t\t\t\t// only object is left\n\t\t\t\t\tkeys = objKeys(val).sort();\n\t\t\t\t\tmax = keys.length;\n\t\t\t\t\tstr = \"\";\n\t\t\t\t\ti = 0;\n\t\t\t\t\twhile (i < max) {\n\t\t\t\t\t\tkey = keys[i];\n\t\t\t\t\t\tpropVal = stringify(val[key], false);\n\t\t\t\t\t\tif (propVal !== undefined) {\n\t\t\t\t\t\t\tif (str) {\n\t\t\t\t\t\t\t\tstr += ',';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstr += JSON.stringify(key) + ':' + propVal;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\treturn '{' + str + '}';\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON.stringify(val);\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"function\":\n\t\tcase \"undefined\":\n\t\t\treturn isArrayProp ? null : undefined;\n\t\tcase \"string\":\n\t\t\treturn JSON.stringify(val);\n\t\tdefault:\n\t\t\treturn isFinite(val) ? val : null;\n\t}\n}\n\nmodule.exports = function(val) {\n\tvar returnVal = stringify(val, false);\n\tif (returnVal !== undefined) {\n\t\treturn ''+ returnVal;\n\t}\n};\n","export * from '@solana/addresses';\nexport * from '@solana/instructions';\nexport * from '@solana/keys';\nexport * from '@solana/rpc-types';\nexport * from '@solana/transactions';\nexport * from './airdrop';\nexport * from './rpc';\nexport * from './rpc-transport';\nexport * from './rpc-websocket-transport';\nexport * from './send-transaction';\nexport * from './transaction-confirmation';\nexport * from './transaction-confirmation-strategy-blockheight';\nexport * from './transaction-confirmation-strategy-nonce';\nexport * from './transaction-confirmation-strategy-recent-signature';\n","import { CodecData } from './codec';\n\n/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n\n/**\n * Asserts that a given codec is fixed-size codec.\n */\nexport function assertFixedSizeCodec(\n data: Pick<CodecData, 'fixedSize'>,\n message?: string\n): asserts data is { fixedSize: number } {\n if (data.fixedSize === null) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<From, To extends From = From>(\n encoder: Encoder<From>,\n decoder: Decoder<To>,\n description?: string\n): Codec<From, To> {\n if (encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`\n );\n }\n\n if (encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`\n );\n }\n\n if (description === undefined && encoder.description !== decoder.description) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. ` +\n `Pass a custom description as a third argument if you want to override the description and bypass this error.`\n );\n }\n\n return {\n decode: decoder.decode,\n description: description ?? encoder.description,\n encode: encoder.encode,\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport { Codec, CodecData, Decoder, Encoder } from './codec';\nimport { combineCodec } from './combine-codec';\n\nfunction fixCodecHelper(data: CodecData, fixedBytes: number, description?: string): CodecData {\n return {\n description: description ?? `fixed(${fixedBytes}, ${data.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n };\n}\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @param description - A custom description for the encoder.\n */\nexport function fixEncoder<T>(encoder: Encoder<T>, fixedBytes: number, description?: string): Encoder<T> {\n return {\n ...fixCodecHelper(encoder, fixedBytes, description),\n encode: (value: T) => fixBytes(encoder.encode(value), fixedBytes),\n };\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the decoder.\n */\nexport function fixDecoder<T>(decoder: Decoder<T>, fixedBytes: number, description?: string): Decoder<T> {\n return {\n ...fixCodecHelper(decoder, fixedBytes, description),\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (decoder.fixedSize !== null) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.decode(bytes, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @param description - A custom description for the codec.\n */\nexport function fixCodec<T, U extends T = T>(\n codec: Codec<T, U>,\n fixedBytes: number,\n description?: string\n): Codec<T, U> {\n return combineCodec(fixEncoder(codec, fixedBytes, description), fixDecoder(codec, fixedBytes, description));\n}\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<T, U>(encoder: Encoder<T>, unmap: (value: U) => T): Encoder<U> {\n return {\n description: encoder.description,\n encode: (value: U) => encoder.encode(unmap(value)),\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<T, U>(\n decoder: Decoder<T>,\n map: (value: T, bytes: Uint8Array, offset: number) => U\n): Decoder<U> {\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n const [value, length] = decoder.decode(bytes, offset);\n return [map(value, bytes, offset), length];\n },\n description: decoder.description,\n fixedSize: decoder.fixedSize,\n maxSize: decoder.maxSize,\n };\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<NewFrom, OldFrom, To extends NewFrom & OldFrom>(\n codec: Codec<OldFrom, To>,\n unmap: (value: NewFrom) => OldFrom\n): Codec<NewFrom, To>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map?: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo> {\n return {\n decode: map ? mapDecoder(codec, map).decode : (codec.decode as unknown as Decoder<NewTo>['decode']),\n description: codec.description,\n encode: mapEncoder(codec, unmap).encode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n };\n}\n","/**\n * Asserts that a given number is between a given range.\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) {\n if (value < min || value > max) {\n // TODO: Coded error.\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`\n );\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'f32',\n options,\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n options,\n size: 4,\n });\n\nexport const getF32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getF32Encoder(options), getF32Decoder(options));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n CodecData,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecOptions, SingleByteNumberCodecOptions } from './common';\n\ntype NumberFactorySharedInput = {\n name: string;\n size: number;\n options: SingleByteNumberCodecOptions | NumberCodecOptions;\n};\n\ntype NumberFactoryEncoderInput<T> = NumberFactorySharedInput & {\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: T, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput<T> = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => T;\n};\n\nfunction sharedNumberFactory(input: NumberFactorySharedInput): CodecData & { littleEndian: boolean | undefined } {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian = !('endian' in input.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 littleEndian,\n maxSize: input.size,\n };\n}\n\nexport function numberEncoderFactory<T extends number | bigint>(input: NumberFactoryEncoderInput<T>): Encoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n description: codecData.description,\n encode(value: T): Uint8Array {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, codecData.littleEndian);\n return new Uint8Array(arrayBuffer);\n },\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\nexport function numberDecoderFactory<T extends number | bigint>(input: NumberFactoryDecoderInput<T>): Decoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n decode(bytes, offset = 0): [T, number] {\n assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, codecData.littleEndian), offset + input.size];\n },\n description: codecData.description,\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\n/**\n * Helper function to ensure that the ArrayBuffer is converted properly from a Uint8Array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nfunction toArrayBuffer(bytes: Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI64Encoder = (options: NumberCodecOptions = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n name: 'i64',\n options,\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 = (options: NumberCodecOptions = {}): Decoder<bigint> =>\n numberDecoderFactory({\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n options,\n size: 8,\n });\n\nexport const getI64Codec = (options: NumberCodecOptions = {}): Codec<number | bigint, bigint> =>\n combineCodec(getI64Encoder(options), getI64Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { SingleByteNumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI8Encoder = (options: SingleByteNumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'i8',\n options,\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, value),\n size: 1,\n });\n\nexport const getI8Decoder = (options: SingleByteNumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: view => view.getInt8(0),\n name: 'i8',\n options,\n size: 1,\n });\n\nexport const getI8Codec = (options: SingleByteNumberCodecOptions = {}): Codec<number> =>\n combineCodec(getI8Encoder(options), getI8Decoder(options));\n","import { BaseCodecOptions, Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\n\n/**\n * Defines the options for the shortU16 serializer.\n */\nexport type ShortU16CodecOptions = BaseCodecOptions;\n\n/**\n * Encodes short u16 numbers.\n * @see {@link getShortU16Codec} for a more detailed description.\n */\nexport const getShortU16Encoder = (options: ShortU16CodecOptions = {}): Encoder<number> => ({\n description: options.description ?? 'shortU16',\n encode: (value: number): Uint8Array => {\n assertNumberIsBetweenForCodec('shortU16', 0, 65535, value);\n const bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = value >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n bytes[ii - 1] |= 0b10000000;\n }\n }\n return new Uint8Array(bytes);\n },\n fixedSize: null,\n maxSize: 3,\n});\n\n/**\n * Decodes short u16 numbers.\n * @see {@link getShortU16Codec} for a more detailed description.\n */\nexport const getShortU16Decoder = (options: ShortU16CodecOptions = {}): Decoder<number> => ({\n decode: (bytes: Uint8Array, offset = 0): [number, number] => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n description: options.description ?? 'shortU16',\n fixedSize: null,\n maxSize: 3,\n});\n\n/**\n * Encodes and decodes short u16 numbers.\n *\n * Short u16 numbers are the same as u16, but serialized with 1 to 3 bytes.\n * If the value is above 0x7f, the top bit is set and the remaining\n * value is stored in the next bytes. Each byte follows the same\n * pattern until the 3rd byte. The 3rd byte, if needed, uses\n * all 8 bits to store the last byte of the original value.\n */\nexport const getShortU16Codec = (options: ShortU16CodecOptions = {}): Codec<number> =>\n combineCodec(getShortU16Encoder(options), getShortU16Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (options: NumberCodecOptions = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n name: 'u128',\n options,\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 = (options: NumberCodecOptions = {}): Decoder<bigint> =>\n numberDecoderFactory({\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 options,\n size: 16,\n });\n\nexport const getU128Codec = (options: NumberCodecOptions = {}): Codec<number | bigint, bigint> =>\n combineCodec(getU128Encoder(options), getU128Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u16',\n options,\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, value, le),\n size: 2,\n });\n\nexport const getU16Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n options,\n size: 2,\n });\n\nexport const getU16Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU16Encoder(options), getU16Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u32',\n options,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, value, le),\n size: 4,\n });\n\nexport const getU32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n options,\n size: 4,\n });\n\nexport const getU32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU32Encoder(options), getU32Decoder(options));\n","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXEncoder = (alphabet: string): Encoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n encode(value: string): Uint8Array {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex(c => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * Decodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXDecoder = (alphabet: string): Decoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n decode(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), rawBytes.length];\n },\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * A string codec that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create codecs such as base10 or base58.\n */\nexport const getBaseXCodec = (alphabet: string): Codec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): Encoder<string> => ({\n description: 'base16',\n encode(value: string) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString('0123456789abcdef', lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n return Uint8Array.from(matches ? matches.map((byte: string) => parseInt(byte, 16)) : []);\n },\n fixedSize: null,\n maxSize: null,\n});\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): Decoder<string> => ({\n decode(bytes, offset = 0) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n description: 'base16',\n fixedSize: null,\n maxSize: null,\n});\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): Codec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by reslicing the bits of the byte array.\n * @see {@link getBaseXResliceCodec} for a more detailed description.\n */\nexport const getBaseXResliceEncoder = (alphabet: string, bits: number): Encoder<string> => ({\n description: `base${alphabet.length}`,\n encode(value: string): Uint8Array {\n assertValidBaseString(alphabet, value);\n if (value === '') return new Uint8Array();\n const charIndices = [...value].map(c => alphabet.indexOf(c));\n return new Uint8Array(reslice(charIndices, bits, 8, false));\n },\n fixedSize: null,\n maxSize: null,\n});\n\n/**\n * Decodes a string using a custom alphabet by reslicing the bits of the byte array.\n * @see {@link getBaseXResliceCodec} for a more detailed description.\n */\nexport const getBaseXResliceDecoder = (alphabet: string, bits: number): Decoder<string> => ({\n decode(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map(i => alphabet[i]).join(''), rawBytes.length];\n },\n description: `base${alphabet.length}`,\n fixedSize: null,\n maxSize: null,\n});\n\n/**\n * A string serializer that reslices bytes into custom chunks\n * of bits that are then mapped to a custom alphabet.\n *\n * This can be used to create serializers whose alphabet\n * is a power of 2 such as base16 or base64.\n */\nexport const getBaseXResliceCodec = (alphabet: string, bits: number): Codec<string> =>\n combineCodec(getBaseXResliceEncoder(alphabet, bits), getBaseXResliceDecoder(alphabet, bits));\n\n/** Helper function to reslice the bits inside bytes. */\nfunction reslice(input: number[], inputBits: number, outputBits: number, useRemainder: boolean): number[] {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = (accumulator << inputBits) | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push((accumulator >> bitsInAccumulator) & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push((accumulator << (outputBits - bitsInAccumulator)) & mask);\n }\n return output;\n}\n","import { combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Encodes strings in base64. */\nexport const getBase64Encoder = (): Encoder<string> => {\n if (__BROWSER__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n try {\n const bytes = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n return new Uint8Array(bytes);\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n return new Uint8Array(Buffer.from(value, 'base64'));\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/** Decodes strings in base64. */\nexport const getBase64Decoder = (): Decoder<string> => {\n if (__BROWSER__) {\n return {\n decode(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n decode: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString('base64'), bytes.length],\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '=')\n );\n};\n\n/** Encodes and decodes strings in base64. */\nexport const getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());\n","/**Removes null characters from a string. */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/** Pads a string with null characters at the end. */\nexport const padNullCharacters = (value: string, chars: number) => value.padEnd(chars, '\\u0000');\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixDecoder,\n fixEncoder,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { getUtf8Decoder, getUtf8Encoder } from './utf8';\n\n/** Defines the options for string codecs. */\nexport type StringCodecOptions<\n TPrefix extends NumberCodec | NumberEncoder | NumberDecoder,\n TEncoding extends Codec<string> | Encoder<string> | Decoder<string>\n> = BaseCodecOptions & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberCodec} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the byte array.\n * @defaultValue u32 prefix.\n */\n size?: TPrefix | number | 'variable';\n\n /**\n * The codec to use for encoding and decoding the content.\n * @defaultValue UTF-8 encoding.\n */\n encoding?: TEncoding;\n};\n\n/** Encodes strings from a given encoding and size strategy. */\nexport const getStringEncoder = (options: StringCodecOptions<NumberEncoder, Encoder<string>> = {}): Encoder<string> => {\n const size = options.size ?? getU32Encoder();\n const encoding = options.encoding ?? getUtf8Encoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixEncoder(encoding, size, description);\n }\n\n return {\n description,\n encode: (value: string) => {\n const contentBytes = encoding.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes strings from a given encoding and size strategy. */\nexport const getStringDecoder = (options: StringCodecOptions<NumberDecoder, Decoder<string>> = {}): Decoder<string> => {\n const size = options.size ?? getU32Decoder();\n const encoding = options.encoding ?? getUtf8Decoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixDecoder(encoding, size, description);\n }\n\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('string', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec('string', length, contentBytes);\n const [value, contentOffset] = encoding.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n },\n description,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes strings from a given encoding and size strategy. */\nexport const getStringCodec = (options: StringCodecOptions<NumberCodec, Codec<string>> = {}): Codec<string> =>\n combineCodec(getStringEncoder(options), getStringDecoder(options));\n\nfunction getSizeDescription(size: CodecData | number | 'variable'): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from 'text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/** Encodes UTF-8 strings using the native `TextEncoder` API. */\nexport const getUtf8Encoder = (): Encoder<string> => {\n let textEncoder: TextEncoder;\n return {\n description: 'utf8',\n encode: (value: string) => new Uint8Array((textEncoder ||= new TextEncoder()).encode(value)),\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes UTF-8 strings using the native `TextDecoder` API. */\nexport const getUtf8Decoder = (): Decoder<string> => {\n let textDecoder: TextDecoder;\n return {\n decode(bytes, offset = 0) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes UTF-8 strings using the native `TextEncoder` and `TextDecoder` API. */\nexport const getUtf8Codec = (): Codec<string> => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapEncoder } from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nexport type Base58EncodedAddress<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(\n putativeBase58EncodedAddress: string\n): putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\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 return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(\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 base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(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 address<TAddress extends string = string>(\n putativeBase58EncodedAddress: TAddress\n): Base58EncodedAddress<TAddress> {\n assertIsAddress(putativeBase58EncodedAddress);\n return putativeBase58EncodedAddress as Base58EncodedAddress<TAddress>;\n}\n\nexport function getAddressEncoder(config?: Readonly<{ description: string }>): Encoder<Base58EncodedAddress> {\n return mapEncoder(\n getStringEncoder({\n description: config?.description ?? 'Base58EncodedAddress',\n encoding: getMemoizedBase58Encoder(),\n size: 32,\n }),\n putativeAddress => address(putativeAddress)\n );\n}\n\nexport function getAddressDecoder(config?: Readonly<{ description: string }>): Decoder<Base58EncodedAddress> {\n return getStringDecoder({\n description: config?.description ?? 'Base58EncodedAddress',\n encoding: getMemoizedBase58Decoder(),\n size: 32,\n }) as Decoder<Base58EncodedAddress>;\n}\n\nexport function getAddressCodec(config?: Readonly<{ description: string }>): Codec<Base58EncodedAddress> {\n return combineCodec(getAddressEncoder(config), getAddressDecoder(config));\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: Uint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport async function compressedPointBytesAreOnCurve(bytes: Uint8Array): Promise<boolean> {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\nimport { assertIsAddress, Base58EncodedAddress, 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 [Base58EncodedAddress<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: [Base58EncodedAddress, 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: Base58EncodedAddress;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Base58EncodedAddress;\n programAddress: Base58EncodedAddress;\n seed: Seed;\n}>;\n\ntype Seed = string | Uint8Array;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\n// TODO: Coded error.\nclass PointOnCurveError extends Error {}\n\nasync function createProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<Base58EncodedAddress> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n // TODO: Coded error.\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n // TODO: Coded error.\n throw new PointOnCurveError('Invalid seeds; point must fall off the Ed25519 curve');\n }\n return base58EncodedAddressCodec.decode(addressBytes)[0];\n}\n\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<ProgramDerivedAddress> {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n // TODO: Coded error.\n throw new Error('Unable to find a viable program address bump seed');\n}\n\nexport async function createAddressWithSeed({\n baseAddress,\n programAddress,\n seed,\n}: SeedInput): Promise<Base58EncodedAddress> {\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])\n ) {\n // TODO: Coded error.\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes)[0];\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Base58EncodedAddress, getAddressDecoder } from './address';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n","/**\n * Quick primer on bitwise operations: https://stackoverflow.com/a/1436448/802047\n */\n\nexport enum AccountRole {\n // Bitflag guide: is signer ⌄⌄ is writable\n WRITABLE_SIGNER = /* 3 */ 0b11, // prettier-ignore\n READONLY_SIGNER = /* 2 */ 0b10, // prettier-ignore\n WRITABLE = /* 1 */ 0b01, // prettier-ignore\n READONLY = /* 0 */ 0b00, // prettier-ignore\n}\n\nconst IS_SIGNER_BITMASK = 0b10;\nconst IS_WRITABLE_BITMASK = 0b01;\n\nexport function downgradeRoleToNonSigner(role: AccountRole.READONLY_SIGNER): AccountRole.READONLY;\nexport function downgradeRoleToNonSigner(role: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole {\n return role & ~IS_SIGNER_BITMASK;\n}\n\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE): AccountRole.READONLY;\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE_SIGNER): AccountRole.READONLY_SIGNER;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole {\n return role & ~IS_WRITABLE_BITMASK;\n}\n\nexport function isSignerRole(role: AccountRole): role is AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER {\n return role >= AccountRole.READONLY_SIGNER;\n}\n\nexport function isWritableRole(role: AccountRole): role is AccountRole.WRITABLE | AccountRole.WRITABLE_SIGNER {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\n\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE_SIGNER, roleB: AccountRole): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.READONLY_SIGNER): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY, roleB: AccountRole.READONLY): AccountRole.READONLY; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole {\n return roleA | roleB;\n}\n\nexport function upgradeRoleToSigner(role: AccountRole.READONLY): AccountRole.READONLY_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole {\n return role | IS_SIGNER_BITMASK;\n}\n\nexport function upgradeRoleToWritable(role: AccountRole.READONLY): AccountRole.WRITABLE;\nexport function upgradeRoleToWritable(role: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole {\n return role | IS_WRITABLE_BITMASK;\n}\n","import { assertKeyGenerationIsAvailable } from '@solana/assertions';\n\nexport async function generateKeyPair(): Promise<CryptoKeyPair> {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ 'Ed25519', // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify']\n );\n return keyPair as CryptoKeyPair;\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n","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 { mergeBytes, combineCodec, assertByteArrayHasEnoughBytesForCodec, assertFixedSizeCodec, assertByteArrayIsNotEmptyForCodec, fixEncoder, fixDecoder, fixBytes } from '@solana/codecs-core';\nimport { getU32Encoder, getU32Decoder, getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';\n\n// src/array.ts\n\n// src/utils.ts\nfunction maxCodecSizes(sizes) {\n return sizes.reduce(\n (all, size) => all === null || size === null ? null : Math.max(all, size),\n 0\n );\n}\nfunction sumCodecSizes(sizes) {\n return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);\n}\n\n// src/array-like-codec-size.ts\nfunction decodeArrayLikeCodecSize(size, childrenSizes, bytes, offset) {\n if (typeof size === \"number\") {\n return [size, offset];\n }\n if (typeof size === \"object\") {\n return size.decode(bytes, offset);\n }\n if (size === \"remainder\") {\n const childrenSize = sumCodecSizes(childrenSizes);\n if (childrenSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${childrenSize} bytes. Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. In other words, ${remainder} modulo ${childrenSize} should be equal to zero.`\n );\n }\n return [remainder / childrenSize, offset];\n }\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\nfunction getArrayLikeCodecSizeDescription(size) {\n return typeof size === \"object\" ? size.description : `${size}`;\n}\nfunction getArrayLikeCodecSizeFromChildren(size, childrenSizes) {\n if (typeof size !== \"number\")\n return null;\n if (size === 0)\n return 0;\n const childrenSize = sumCodecSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\nfunction getArrayLikeCodecSizePrefix(size, realSize) {\n return typeof size === \"object\" ? size.encode(realSize) : new Uint8Array();\n}\n\n// src/assertions.ts\nfunction assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {\n if (expected !== actual) {\n throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);\n }\n}\n\n// src/array.ts\nfunction arrayCodecHelper(item, size, description) {\n if (size === \"remainder\" && item.fixedSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n return {\n description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize])\n };\n}\nfunction getArrayEncoder(item, options = {}) {\n const size = options.size ?? getU32Encoder();\n return {\n ...arrayCodecHelper(item, size, options.description),\n encode: (value) => {\n if (typeof size === \"number\") {\n assertValidNumberOfItemsForCodec(\"array\", size, value.length);\n }\n return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map((v) => item.encode(v))]);\n }\n };\n}\nfunction getArrayDecoder(item, options = {}) {\n const size = options.size ?? getU32Decoder();\n return {\n ...arrayCodecHelper(item, size, options.description),\n decode: (bytes, offset = 0) => {\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n const values = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset2] = item.decode(bytes, offset);\n values.push(value);\n offset = newOffset2;\n }\n return [values, offset];\n }\n };\n}\nfunction getArrayCodec(item, options = {}) {\n return combineCodec(getArrayEncoder(item, options), getArrayDecoder(item, options));\n}\nvar getBitArrayEncoder = (size, options = {}) => {\n const parsedOptions = typeof options === \"boolean\" ? { backward: options } : options;\n const backward = parsedOptions.backward ?? false;\n const backwardSuffix = backward ? \"; backward\" : \"\";\n return {\n description: parsedOptions.description ?? `bitArray(${size}${backwardSuffix})`,\n encode(value) {\n const bytes = [];\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 bytes.unshift(byte);\n } else {\n bytes.push(byte);\n }\n }\n return new Uint8Array(bytes);\n },\n fixedSize: size,\n maxSize: size\n };\n};\nvar getBitArrayDecoder = (size, options = {}) => {\n const parsedOptions = typeof options === \"boolean\" ? { backward: options } : options;\n const backward = parsedOptions.backward ?? false;\n const backwardSuffix = backward ? \"; backward\" : \"\";\n return {\n decode(bytes, offset = 0) {\n assertByteArrayHasEnoughBytesForCodec(\"bitArray\", size, bytes, offset);\n const booleans = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n slice.forEach((byte) => {\n for (let i = 0; i < 8; i += 1) {\n if (backward) {\n booleans.push(Boolean(byte & 1));\n byte >>= 1;\n } else {\n booleans.push(Boolean(byte & 128));\n byte <<= 1;\n }\n }\n });\n return [booleans, offset + size];\n },\n description: parsedOptions.description ?? `bitArray(${size}${backwardSuffix})`,\n fixedSize: size,\n maxSize: size\n };\n};\nvar getBitArrayCodec = (size, options = {}) => combineCodec(getBitArrayEncoder(size, options), getBitArrayDecoder(size, options));\nfunction getBooleanEncoder(options = {}) {\n const size = options.size ?? getU8Encoder();\n assertFixedSizeCodec(size, \"Codec [bool] requires a fixed size.\");\n return {\n description: options.description ?? `bool(${size.description})`,\n encode: (value) => size.encode(value ? 1 : 0),\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize\n };\n}\nfunction getBooleanDecoder(options = {}) {\n const size = options.size ?? getU8Decoder();\n assertFixedSizeCodec(size, \"Codec [bool] requires a fixed size.\");\n return {\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"bool\", bytes, offset);\n const [value, vOffset] = size.decode(bytes, offset);\n return [value === 1, vOffset];\n },\n description: options.description ?? `bool(${size.description})`,\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize\n };\n}\nfunction getBooleanCodec(options = {}) {\n return combineCodec(getBooleanEncoder(options), getBooleanDecoder(options));\n}\nfunction getBytesEncoder(options = {}) {\n const size = options.size ?? \"variable\";\n const sizeDescription = typeof size === \"object\" ? size.description : `${size}`;\n const description = options.description ?? `bytes(${sizeDescription})`;\n const byteEncoder = {\n description,\n encode: (value) => value,\n fixedSize: null,\n maxSize: null\n };\n if (size === \"variable\") {\n return byteEncoder;\n }\n if (typeof size === \"number\") {\n return fixEncoder(byteEncoder, size, description);\n }\n return {\n ...byteEncoder,\n encode: (value) => {\n const contentBytes = byteEncoder.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n }\n };\n}\nfunction getBytesDecoder(options = {}) {\n const size = options.size ?? \"variable\";\n const sizeDescription = typeof size === \"object\" ? size.description : `${size}`;\n const description = options.description ?? `bytes(${sizeDescription})`;\n const byteDecoder = {\n decode: (bytes, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n description,\n fixedSize: null,\n maxSize: null\n };\n if (size === \"variable\") {\n return byteDecoder;\n }\n if (typeof size === \"number\") {\n return fixDecoder(byteDecoder, size, description);\n }\n return {\n ...byteDecoder,\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"bytes\", bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec(\"bytes\", length, contentBytes);\n const [value, contentOffset] = byteDecoder.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n }\n };\n}\nfunction getBytesCodec(options = {}) {\n return combineCodec(getBytesEncoder(options), getBytesDecoder(options));\n}\nfunction dataEnumCodecHelper(variants, prefix, description) {\n const fieldDescriptions = variants.map(([name, codec]) => `${String(name)}${codec ? `: ${codec.description}` : \"\"}`).join(\", \");\n const allVariantHaveTheSameFixedSize = variants.every((one, _i, all) => one[1].fixedSize === all[0][1].fixedSize);\n const fixedVariantSize = allVariantHaveTheSameFixedSize ? variants[0][1].fixedSize : null;\n const maxVariantSize = maxCodecSizes(variants.map(([, field]) => field.maxSize));\n return {\n description: description ?? `dataEnum(${fieldDescriptions}; ${prefix.description})`,\n fixedSize: variants.length === 0 ? prefix.fixedSize : sumCodecSizes([prefix.fixedSize, fixedVariantSize]),\n maxSize: variants.length === 0 ? prefix.maxSize : sumCodecSizes([prefix.maxSize, maxVariantSize])\n };\n}\nfunction getDataEnumEncoder(variants, options = {}) {\n const prefix = options.size ?? getU8Encoder();\n return {\n ...dataEnumCodecHelper(variants, prefix, options.description),\n encode: (variant) => {\n const discriminator = variants.findIndex(([key]) => variant.__kind === key);\n if (discriminator < 0) {\n throw new Error(\n `Invalid data enum variant. Expected one of [${variants.map(([key]) => key).join(\", \")}], got \"${variant.__kind}\".`\n );\n }\n const variantPrefix = prefix.encode(discriminator);\n const variantSerializer = variants[discriminator][1];\n const variantBytes = variantSerializer.encode(variant);\n return mergeBytes([variantPrefix, variantBytes]);\n }\n };\n}\nfunction getDataEnumDecoder(variants, options = {}) {\n const prefix = options.size ?? getU8Decoder();\n return {\n ...dataEnumCodecHelper(variants, prefix, options.description),\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"dataEnum\", bytes, offset);\n const [discriminator, dOffset] = prefix.decode(bytes, offset);\n offset = dOffset;\n const variantField = variants[Number(discriminator)] ?? null;\n if (!variantField) {\n throw new Error(\n `Enum discriminator out of range. Expected a number between 0 and ${variants.length - 1}, got ${discriminator}.`\n );\n }\n const [variant, vOffset] = variantField[1].decode(bytes, offset);\n offset = vOffset;\n return [{ __kind: variantField[0], ...variant ?? {} }, offset];\n }\n };\n}\nfunction getDataEnumCodec(variants, options = {}) {\n return combineCodec(getDataEnumEncoder(variants, options), getDataEnumDecoder(variants, options));\n}\nfunction mapCodecHelper(key, value, size, description) {\n if (size === \"remainder\" && (key.fixedSize === null || value.fixedSize === null)) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n return {\n description: description ?? `map(${key.description}, ${value.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [key.fixedSize, value.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [key.maxSize, value.maxSize])\n };\n}\nfunction getMapEncoder(key, value, options = {}) {\n const size = options.size ?? getU32Encoder();\n return {\n ...mapCodecHelper(key, value, size, options.description),\n encode: (map) => {\n if (typeof size === \"number\") {\n assertValidNumberOfItemsForCodec(\"map\", size, map.size);\n }\n const itemBytes = Array.from(map, ([k, v]) => mergeBytes([key.encode(k), value.encode(v)]));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, map.size), ...itemBytes]);\n }\n };\n}\nfunction getMapDecoder(key, value, options = {}) {\n const size = options.size ?? getU32Decoder();\n return {\n ...mapCodecHelper(key, value, size, options.description),\n decode: (bytes, offset = 0) => {\n const map = /* @__PURE__ */ new Map();\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [map, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(\n size,\n [key.fixedSize, value.fixedSize],\n bytes,\n offset\n );\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [decodedKey, kOffset] = key.decode(bytes, offset);\n offset = kOffset;\n const [decodedValue, vOffset] = value.decode(bytes, offset);\n offset = vOffset;\n map.set(decodedKey, decodedValue);\n }\n return [map, offset];\n }\n };\n}\nfunction getMapCodec(key, value, options = {}) {\n return combineCodec(getMapEncoder(key, value, options), getMapDecoder(key, value, options));\n}\nfunction nullableCodecHelper(item, prefix, fixed, description) {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, \"Fixed nullables can only be used with fixed-size codecs.\");\n assertFixedSizeCodec(prefix, \"Fixed nullables can only be used with fixed-size prefix.\");\n descriptionSuffix += \"; fixed\";\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n return {\n description: description ?? `nullable(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize])\n };\n}\nfunction getNullableEncoder(item, options = {}) {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...nullableCodecHelper(item, prefix, fixed, options.description),\n encode: (option) => {\n const prefixByte = prefix.encode(Number(option !== null));\n let itemBytes = option !== null ? item.encode(option) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n }\n };\n}\nfunction getNullableDecoder(item, options = {}) {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...nullableCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [null, offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [null, fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [value, fixed ? fixedOffset : offset];\n }\n };\n}\nfunction getNullableCodec(item, options = {}) {\n return combineCodec(getNullableEncoder(item, options), getNullableDecoder(item, options));\n}\nfunction scalarEnumCoderHelper(constructor, prefix, description) {\n const enumKeys = Object.keys(constructor);\n const enumValues = Object.values(constructor);\n const isNumericEnum = enumValues.some((v) => typeof v === \"number\");\n const valueDescriptions = enumValues.filter((v) => typeof v === \"string\").join(\", \");\n const minRange = 0;\n const maxRange = isNumericEnum ? enumValues.length / 2 - 1 : enumValues.length - 1;\n const stringValues = isNumericEnum ? [...enumKeys] : [.../* @__PURE__ */ new Set([...enumKeys, ...enumValues])];\n return {\n description: description ?? `enum(${valueDescriptions}; ${prefix.description})`,\n enumKeys,\n enumValues,\n fixedSize: prefix.fixedSize,\n isNumericEnum,\n maxRange,\n maxSize: prefix.maxSize,\n minRange,\n stringValues\n };\n}\nfunction getScalarEnumEncoder(constructor, options = {}) {\n const prefix = options.size ?? getU8Encoder();\n const { description, fixedSize, maxSize, minRange, maxRange, stringValues, enumKeys, enumValues } = scalarEnumCoderHelper(constructor, prefix, options.description);\n return {\n description,\n encode: (value) => {\n const isInvalidNumber = typeof value === \"number\" && (value < minRange || value > maxRange);\n const isInvalidString = typeof value === \"string\" && !stringValues.includes(value);\n if (isInvalidNumber || isInvalidString) {\n throw new Error(\n `Invalid scalar enum variant. Expected one of [${stringValues.join(\", \")}] or a number between ${minRange} and ${maxRange}, got \"${value}\".`\n );\n }\n if (typeof value === \"number\")\n return prefix.encode(value);\n const valueIndex = enumValues.indexOf(value);\n if (valueIndex >= 0)\n return prefix.encode(valueIndex);\n return prefix.encode(enumKeys.indexOf(value));\n },\n fixedSize,\n maxSize\n };\n}\nfunction getScalarEnumDecoder(constructor, options = {}) {\n const prefix = options.size ?? getU8Decoder();\n const { description, fixedSize, maxSize, minRange, maxRange, isNumericEnum, enumValues } = scalarEnumCoderHelper(\n constructor,\n prefix,\n options.description\n );\n return {\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"enum\", bytes, offset);\n const [value, newOffset] = prefix.decode(bytes, offset);\n const valueAsNumber = Number(value);\n offset = newOffset;\n if (valueAsNumber < minRange || valueAsNumber > maxRange) {\n throw new Error(\n `Enum discriminator out of range. Expected a number between ${minRange} and ${maxRange}, got ${valueAsNumber}.`\n );\n }\n return [isNumericEnum ? valueAsNumber : enumValues[valueAsNumber], offset];\n },\n description,\n fixedSize,\n maxSize\n };\n}\nfunction getScalarEnumCodec(constructor, options = {}) {\n return combineCodec(getScalarEnumEncoder(constructor, options), getScalarEnumDecoder(constructor, options));\n}\nfunction setCodecHelper(item, size, description) {\n if (size === \"remainder\" && item.fixedSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n return {\n description: description ?? `set(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize])\n };\n}\nfunction getSetEncoder(item, options = {}) {\n const size = options.size ?? getU32Encoder();\n return {\n ...setCodecHelper(item, size, options.description),\n encode: (set) => {\n if (typeof size === \"number\" && set.size !== size) {\n assertValidNumberOfItemsForCodec(\"set\", size, set.size);\n }\n const itemBytes = Array.from(set, (value) => item.encode(value));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, set.size), ...itemBytes]);\n }\n };\n}\nfunction getSetDecoder(item, options = {}) {\n const size = options.size ?? getU32Decoder();\n return {\n ...setCodecHelper(item, size, options.description),\n decode: (bytes, offset = 0) => {\n const set = /* @__PURE__ */ new Set();\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [set, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset2] = item.decode(bytes, offset);\n offset = newOffset2;\n set.add(value);\n }\n return [set, offset];\n }\n };\n}\nfunction getSetCodec(item, options = {}) {\n return combineCodec(getSetEncoder(item, options), getSetDecoder(item, options));\n}\nfunction structCodecHelper(fields, description) {\n const fieldDescriptions = fields.map(([name, codec]) => `${String(name)}: ${codec.description}`).join(\", \");\n return {\n description: description ?? `struct(${fieldDescriptions})`,\n fixedSize: sumCodecSizes(fields.map(([, field]) => field.fixedSize)),\n maxSize: sumCodecSizes(fields.map(([, field]) => field.maxSize))\n };\n}\nfunction getStructEncoder(fields, options = {}) {\n return {\n ...structCodecHelper(fields, options.description),\n encode: (struct) => {\n const fieldBytes = fields.map(([key, codec]) => codec.encode(struct[key]));\n return mergeBytes(fieldBytes);\n }\n };\n}\nfunction getStructDecoder(fields, options = {}) {\n return {\n ...structCodecHelper(fields, options.description),\n decode: (bytes, offset = 0) => {\n const struct = {};\n fields.forEach(([key, codec]) => {\n const [value, newOffset] = codec.decode(bytes, offset);\n offset = newOffset;\n struct[key] = value;\n });\n return [struct, offset];\n }\n };\n}\nfunction getStructCodec(fields, options = {}) {\n return combineCodec(getStructEncoder(fields, options), getStructDecoder(fields, options));\n}\nfunction tupleCodecHelper(items, description) {\n const itemDescriptions = items.map((item) => item.description).join(\", \");\n return {\n description: description ?? `tuple(${itemDescriptions})`,\n fixedSize: sumCodecSizes(items.map((item) => item.fixedSize)),\n maxSize: sumCodecSizes(items.map((item) => item.maxSize))\n };\n}\nfunction getTupleEncoder(items, options = {}) {\n return {\n ...tupleCodecHelper(items, options.description),\n encode: (value) => {\n assertValidNumberOfItemsForCodec(\"tuple\", items.length, value.length);\n return mergeBytes(items.map((item, index) => item.encode(value[index])));\n }\n };\n}\nfunction getTupleDecoder(items, options = {}) {\n return {\n ...tupleCodecHelper(items, options.description),\n decode: (bytes, offset = 0) => {\n const values = [];\n items.forEach((codec) => {\n const [newValue, newOffset] = codec.decode(bytes, offset);\n values.push(newValue);\n offset = newOffset;\n });\n return [values, offset];\n }\n };\n}\nfunction getTupleCodec(items, options = {}) {\n return combineCodec(\n getTupleEncoder(items, options),\n getTupleDecoder(items, options)\n );\n}\nfunction getUnitEncoder(options = {}) {\n return {\n description: options.description ?? \"unit\",\n encode: () => new Uint8Array(),\n fixedSize: 0,\n maxSize: 0\n };\n}\nfunction getUnitDecoder(options = {}) {\n return {\n decode: (_bytes, offset = 0) => [void 0, offset],\n description: options.description ?? \"unit\",\n fixedSize: 0,\n maxSize: 0\n };\n}\nfunction getUnitCodec(options = {}) {\n return combineCodec(getUnitEncoder(options), getUnitDecoder(options));\n}\n\nexport { assertValidNumberOfItemsForCodec, decodeArrayLikeCodecSize, getArrayCodec, getArrayDecoder, getArrayEncoder, getArrayLikeCodecSizeDescription, getArrayLikeCodecSizeFromChildren, getArrayLikeCodecSizePrefix, getBitArrayCodec, getBitArrayDecoder, getBitArrayEncoder, getBooleanCodec, getBooleanDecoder, getBooleanEncoder, getBytesCodec, getBytesDecoder, getBytesEncoder, getDataEnumCodec, getDataEnumDecoder, getDataEnumEncoder, getMapCodec, getMapDecoder, getMapEncoder, getNullableCodec, getNullableDecoder, getNullableEncoder, getScalarEnumCodec, getScalarEnumDecoder, getScalarEnumEncoder, getSetCodec, getSetDecoder, getSetEncoder, getStructCodec, getStructDecoder, getStructEncoder, getTupleCodec, getTupleDecoder, getTupleEncoder, getUnitCodec, getUnitDecoder, getUnitEncoder };\n","/**\n * General pipe function.\n * Provide an initial value and a list of functions to pipe it through.\n *\n * Following common implementations of pipe functions that use TypeScript,\n * this function supports a maximum arity of 10 for type safety.\n * @see https://github.com/ramda/ramda/blob/master/source/pipe.js\n * @see https://github.com/darky/rocket-pipes/blob/master/index.ts\n *\n * Note you can use nested pipes to extend this limitation, like so:\n * ```typescript\n * const myValue = pipe(\n * pipe(\n * 1,\n * (x) => x + 1,\n * (x) => x * 2,\n * (x) => x - 1,\n * ),\n * (y) => y / 3,\n * (y) => y + 1,\n * );\n * ```\n * @param init The initial value\n * @param fns Any number of functions to pipe the value through\n * @returns The final value with all functions applied\n */\nexport function pipe<TInitial>(init: TInitial): TInitial;\nexport function pipe<TInitial, R1>(init: TInitial, init_r1: (init: TInitial) => R1): R1;\nexport function pipe<TInitial, R1, R2>(init: TInitial, init_r1: (init: TInitial) => R1, r1_r2: (r1: R1) => R2): R2;\nexport function pipe<TInitial, R1, R2, R3>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3\n): R3;\nexport function pipe<TInitial, R1, R2, R3, R4>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4\n): R4;\nexport function pipe<TInitial, R1, R2, R3, R4, R5>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5\n): R5;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6\n): R6;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7\n): R7;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8\n): R8;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8,\n r8_r9: (r8: R8) => R9\n): R9;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8,\n r8_r9: (r8: R8) => R9,\n r9_r10: (r9: R9) => R10\n): R10;\nexport function pipe<TInitial>(init: TInitial, ...fns: CallableFunction[]) {\n return fns.reduce((acc, fn) => fn(acc), init);\n}\n","import { ITransactionWithSignatures } from '.';\nimport { BaseTransaction } from './types';\n\nexport function getUnsignedTransaction<TTransaction extends BaseTransaction>(\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction & ITransactionWithSignatures, keyof ITransactionWithSignatures> {\n if ('signatures' in transaction) {\n // The implication of the lifetime constraint changing is that any existing signatures are invalid.\n const {\n signatures: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n","import { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport type Blockhash = string & { readonly __brand: unique symbol };\n\ntype BlockhashLifetimeConstraint = Readonly<{\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n}>;\n\nexport interface ITransactionWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 ||\n // Highest value (32 bytes of 255)\n putativeBlockhash.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeBlockhash);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBlockhash}\\` is not a blockhash`, {\n cause: e,\n });\n }\n}\n\nexport function setTransactionLifetimeUsingBlockhash<TTransaction extends BaseTransaction & IDurableNonceTransaction>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures | 'lifetimeConstraint'> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash<\n TTransaction extends BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n) {\n if (\n 'lifetimeConstraint' in transaction &&\n transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n lifetimeConstraint: blockhashLifetimeConstraint,\n };\n Object.freeze(out);\n return out;\n}\n","import { Transaction, TransactionVersion } from './types';\n\ntype TransactionConfig<TVersion extends TransactionVersion> = Readonly<{\n version: TVersion;\n}>;\n\nexport function createTransaction<TVersion extends TransactionVersion>(\n config: TransactionConfig<TVersion>\n): Extract<Transaction, { version: TVersion }>;\nexport function createTransaction<TVersion extends TransactionVersion>({\n version,\n}: TransactionConfig<TVersion>): Transaction {\n const out: Transaction = {\n instructions: [],\n version,\n };\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport {\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: Base58EncodedAddress<TNonceAccountAddress>;\n readonly nonceAuthorityAddress: Base58EncodedAddress<TNonceAuthorityAddress>;\n}>;\nexport type Nonce<TNonceValue extends string = string> = TNonceValue & { readonly __brand: unique symbol };\ntype NonceLifetimeConstraint<TNonceValue extends string = string> = Readonly<{\n nonce: Nonce<TNonceValue>;\n}>;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Base58EncodedAddress<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS =\n '11111111111111111111111111111111' as Base58EncodedAddress<'11111111111111111111111111111111'>;\n\nexport interface IDurableNonceTransaction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint<TNonceValue>;\n}\n\nexport function assertIsDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): asserts transaction is BaseTransaction & IDurableNonceTransaction {\n if (!isDurableNonceTransaction(transaction)) {\n // TODO: Coded error.\n throw new Error('Transaction is not a durable nonce transaction');\n }\n}\n\nfunction createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n>(\n nonceAccountAddress: Base58EncodedAddress<TNonceAccountAddress>,\n nonceAuthorityAddress: Base58EncodedAddress<TNonceAuthorityAddress>\n): AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\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 Base58EncodedAddress = Base58EncodedAddress,\n TNonceAuthorityAddress extends Base58EncodedAddress = Base58EncodedAddress\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 { Base58EncodedAddress } from '@solana/addresses';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport interface ITransactionWithFeePayer<TAddress extends string = string> {\n readonly feePayer: Base58EncodedAddress<TAddress>;\n}\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction: TTransaction | (TTransaction & ITransactionWithFeePayer<string>)\n): TTransaction & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | TTransaction\n | (TTransaction & ITransactionWithFeePayer<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 { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { Ed25519Signature } from '@solana/keys';\n\nimport { getCompiledTransaction } from '../compile-transaction';\nimport { decompileTransaction } from '../decompile-transaction';\nimport { compileMessage } from '../message';\nimport { ITransactionWithSignatures } from '../signatures';\nimport { getCompiledMessageDecoder, getCompiledMessageEncoder } from './message';\n\ntype CompilableTransaction = Parameters<typeof compileMessage>[0];\ntype CompiledTransaction = ReturnType<typeof getCompiledTransaction>;\n\nconst signaturesDescription = __DEV__ ? 'A compact array of 64-byte, base-64 encoded Ed25519 signatures' : 'signatures';\nconst transactionDescription = __DEV__ ? 'The wire format of a Solana transaction' : 'transaction';\n\nfunction getCompiledTransactionEncoder(): Encoder<CompiledTransaction> {\n return getStructEncoder(\n [\n [\n 'signatures',\n getArrayEncoder(getBytesEncoder({ size: 64 }), {\n description: signaturesDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageEncoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nfunction getSignatureDecoder(): Decoder<Ed25519Signature> {\n return mapDecoder(getBytesDecoder({ size: 64 }), bytes => bytes as Ed25519Signature);\n}\n\nfunction getCompiledTransactionDecoder(): Decoder<CompiledTransaction> {\n return getStructDecoder(\n [\n [\n 'signatures',\n getArrayDecoder(getSignatureDecoder(), {\n description: signaturesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageDecoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nexport function getTransactionEncoder(): Encoder<\n CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n> {\n return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);\n}\n\nexport function getTransactionDecoder(\n lastValidBlockHeight?: bigint\n): Decoder<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return mapDecoder(getCompiledTransactionDecoder(), compiledTransaction =>\n decompileTransaction(compiledTransaction, lastValidBlockHeight)\n );\n}\n\nexport function getTransactionCodec(\n lastValidBlockHeight?: bigint\n): Codec<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));\n}\n","import { Base58EncodedAddress, 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: Base58EncodedAddress,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry | Record<never, never>\n ) => AddressMap[Base58EncodedAddress]\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(\n feePayer: Base58EncodedAddress,\n instructions: readonly IInstruction[]\n): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set<Base58EncodedAddress>();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and set as the fee payer. Program addresses may not pay fees.'\n );\n default:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and marked writable. Program addresses may not be writable.'\n );\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType<typeof 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 Base58EncodedAddress<typeof address>,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Base58EncodedAddress, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype AddressTableLookup = Readonly<{\n lookupTableAddress: Base58EncodedAddress;\n readableIndices: readonly number[];\n writableIndices: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Base58EncodedAddress,\n { readonly readableIndices: number[]; readonly writableIndices: number[] }\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readableIndices: [],\n writableIndices: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndices.push(account.addressIndex);\n } else {\n entry.readableIndices.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Base58EncodedAddress,\n ...index[lookupTableAddress as unknown as Base58EncodedAddress],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype MessageHeader = Readonly<{\n numReadonlyNonSignerAccounts: number;\n numReadonlySignerAccounts: number;\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport { IInstruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n accountIndices?: number[];\n data?: Uint8Array;\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record<Base58EncodedAddress, number> = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly IInstruction[],\n orderedAccounts: OrderedAccounts\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { IDurableNonceTransaction, ITransactionWithBlockhashLifetime } from './index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (ITransactionWithBlockhashLifetime | IDurableNonceTransaction)['lifetimeConstraint']\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Base58EncodedAddress[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { ITransactionWithBlockhashLifetime } from './blockhash';\nimport { getCompiledAddressTableLookups } from './compile-address-table-lookups';\nimport { getCompiledMessageHeader } from './compile-header';\nimport { getCompiledInstructions } from './compile-instructions';\nimport { getCompiledLifetimeToken } from './compile-lifetime-token';\nimport { getCompiledStaticAccounts } from './compile-static-accounts';\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithFeePayer } from './fee-payer';\nimport { BaseTransaction } from './types';\n\ntype BaseCompiledMessage = Readonly<{\n header: ReturnType<typeof getCompiledMessageHeader>;\n instructions: ReturnType<typeof getCompiledInstructions>;\n lifetimeToken: ReturnType<typeof getCompiledLifetimeToken>;\n staticAccounts: ReturnType<typeof getCompiledStaticAccounts>;\n}>;\n\ntype CompilableTransaction = BaseTransaction &\n ITransactionWithFeePayer &\n (ITransactionWithBlockhashLifetime | IDurableNonceTransaction);\n\nexport type CompiledMessage = LegacyCompiledMessage | VersionedCompiledMessage;\n\ntype LegacyCompiledMessage = BaseCompiledMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledMessage = BaseCompiledMessage &\n Readonly<{\n addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups>;\n version: number;\n }>;\n\nexport function compileMessage(\n transaction: CompilableTransaction & Readonly<{ version: 'legacy' }>\n): LegacyCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): VersionedCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): CompiledMessage {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...(transaction.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),\n lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transaction.version,\n };\n}\n","import { Ed25519Signature } from '@solana/keys';\n\nimport { CompiledMessage, compileMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\n\ntype CompiledTransaction = Readonly<{\n compiledMessage: CompiledMessage;\n signatures: Ed25519Signature[];\n}>;\n\ntype CompilableTransaction = Parameters<typeof compileMessage>[0];\n\nexport function getCompiledTransaction(\n transaction: CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n): CompiledTransaction {\n const compiledMessage = compileMessage(transaction);\n let signatures;\n if ('signatures' in transaction) {\n signatures = [];\n for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {\n signatures[ii] =\n transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));\n }\n } else {\n signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));\n }\n return {\n compiledMessage,\n signatures,\n };\n}\n","import { assertIsAddress, Base58EncodedAddress } from '@solana/addresses';\nimport { pipe } from '@solana/functional';\nimport { AccountRole, IAccountMeta, IInstruction } from '@solana/instructions';\nimport { Ed25519Signature } from '@solana/keys';\n\nimport { Blockhash, setTransactionLifetimeUsingBlockhash } from './blockhash';\nimport { getCompiledTransaction } 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\ntype CompiledTransaction = ReturnType<typeof getCompiledTransaction>;\ntype CompilableTransaction = Parameters<typeof getCompiledTransaction>[0];\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: Base58EncodedAddress;\n nonceAuthorityAddress: Base58EncodedAddress;\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 Ed25519Signature };\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 { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n StructToDecoderTuple,\n StructToEncoderTuple,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\nimport { CompiledMessage } from '../message';\nimport { SerializedMessageBytes } from '../types';\nimport { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nconst staticAccountsDescription = __DEV__\n ? 'A compact-array of static account addresses belonging to this transaction'\n : 'staticAccounts';\nconst lifetimeTokenDescription = __DEV__\n ? 'A 32-byte token that specifies the lifetime of this transaction (eg. a ' +\n 'recent blockhash, or a durable nonce)'\n : 'lifetimeToken';\nconst instructionsDescription = __DEV__\n ? 'A compact-array of instructions belonging to this transaction'\n : 'instructions';\nconst addressTableLookupsDescription = __DEV__\n ? 'A compact array of address table lookups belonging to this transaction'\n : 'addressTableLookups';\n\nfunction getCompiledMessageLegacyEncoder(): Encoder<CompiledMessage> {\n return getStructEncoder(getPreludeStructEncoderTuple());\n}\n\nfunction getCompiledMessageVersionedEncoder(): Encoder<CompiledMessage> {\n return mapEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ] as StructToEncoderTuple<CompiledMessage>),\n (value: CompiledMessage) => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n } as Exclude<CompiledMessage, { readonly version: 'legacy' }>;\n }\n );\n}\n\nfunction getPreludeStructEncoderTuple(): StructToEncoderTuple<CompiledMessage> {\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n [\n 'staticAccounts',\n getArrayEncoder(getAddressEncoder(), {\n description: staticAccountsDescription,\n size: getShortU16Encoder(),\n }),\n ],\n [\n 'lifetimeToken',\n getStringEncoder({\n description: lifetimeTokenDescription,\n encoding: getBase58Encoder(),\n size: 32,\n }),\n ],\n [\n 'instructions',\n getArrayEncoder(getInstructionEncoder(), {\n description: instructionsDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ];\n}\n\nfunction getPreludeStructDecoderTuple(): StructToDecoderTuple<\n CompiledMessage & { addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups> }\n> {\n return [\n ['version', getTransactionVersionDecoder() as Decoder<number>],\n ['header', getMessageHeaderDecoder()],\n [\n 'staticAccounts',\n getArrayDecoder(getAddressDecoder(), {\n description: staticAccountsDescription,\n size: getShortU16Decoder(),\n }),\n ],\n [\n 'lifetimeToken',\n getStringDecoder({\n description: lifetimeTokenDescription,\n encoding: getBase58Decoder(),\n size: 32,\n }),\n ],\n [\n 'instructions',\n getArrayDecoder(getInstructionDecoder(), {\n description: instructionsDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ];\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Encoder(),\n });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Decoder(),\n });\n}\n\nconst messageDescription = __DEV__ ? 'The wire format of a Solana transaction message' : 'message';\n\nexport function getCompiledMessageEncoder(): Encoder<CompiledMessage> {\n return {\n description: messageDescription,\n encode: compiledMessage => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().encode(compiledMessage) as SerializedMessageBytes;\n } else {\n return getCompiledMessageVersionedEncoder().encode(compiledMessage) as SerializedMessageBytes;\n }\n },\n fixedSize: null,\n maxSize: null,\n };\n}\n\nexport function getCompiledMessageDecoder(): Decoder<CompiledMessage> {\n return mapDecoder(\n getStructDecoder(getPreludeStructDecoderTuple(), {\n description: messageDescription,\n }),\n ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups } as Exclude<\n CompiledMessage,\n { readonly version: 'legacy' }\n >;\n }\n );\n}\n\nexport function getCompiledMessageCodec(): Codec<CompiledMessage> {\n return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport { type Codec, combineCodec, type Decoder, type Encoder } from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport type { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\n\ntype AddressTableLookup = ReturnType<typeof getCompiledAddressTableLookups>[number];\n\nconst lookupTableAddressDescription = __DEV__\n ? 'The address of the address lookup table account from which instruction addresses should be looked up'\n : 'lookupTableAddress';\n\nconst writableIndicesDescription = __DEV__\n ? 'The indices of the accounts in the lookup table that should be loaded as writeable'\n : 'writableIndices';\n\nconst readableIndicesDescription = __DEV__\n ? 'The indices of the accounts in the lookup table that should be loaded as read-only'\n : 'readableIndices';\n\nconst addressTableLookupDescription = __DEV__\n ? 'A pointer to the address of an address lookup table, along with the ' +\n 'readonly/writeable indices of the addresses that should be loaded from it'\n : 'addressTableLookup';\n\nlet memoizedAddressTableLookupEncoder: Encoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupEncoder(): Encoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupEncoder) {\n memoizedAddressTableLookupEncoder = getStructEncoder(\n [\n ['lookupTableAddress', getAddressEncoder({ description: lookupTableAddressDescription })],\n [\n 'writableIndices',\n getArrayEncoder(getU8Encoder(), {\n description: writableIndicesDescription,\n size: getShortU16Encoder(),\n }) as Encoder<readonly number[]>,\n ],\n [\n 'readableIndices',\n getArrayEncoder(getU8Encoder(), {\n description: readableIndicesDescription,\n size: getShortU16Encoder(),\n }) as Encoder<readonly number[]>,\n ],\n ],\n { description: addressTableLookupDescription }\n );\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: Decoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupDecoder(): Decoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupDecoder) {\n memoizedAddressTableLookupDecoder = getStructDecoder(\n [\n ['lookupTableAddress', getAddressDecoder({ description: lookupTableAddressDescription })],\n [\n 'writableIndices',\n getArrayDecoder(getU8Decoder(), {\n description: writableIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n [\n 'readableIndices',\n getArrayDecoder(getU8Decoder(), {\n description: readableIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ],\n { description: addressTableLookupDescription }\n );\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): Codec<AddressTableLookup> {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { Codec, Decoder, Encoder } from '@solana/codecs-core';\nimport { getStructCodec, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getU8Codec, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledMessageHeader } from '../compile-header';\n\ntype MessageHeader = ReturnType<typeof getCompiledMessageHeader>;\n\nlet memoizedU8Encoder: Encoder<number> | undefined;\nfunction getMemoizedU8Encoder(): Encoder<number> {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nfunction getMemoizedU8EncoderDescription(description?: string): Encoder<number> {\n const encoder = getMemoizedU8Encoder();\n return {\n ...encoder,\n description: description ?? encoder.description,\n };\n}\n\nlet memoizedU8Decoder: Decoder<number> | undefined;\nfunction getMemoizedU8Decoder(): Decoder<number> {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nfunction getMemoizedU8DecoderDescription(description?: string): Decoder<number> {\n const decoder = getMemoizedU8Decoder();\n return {\n ...decoder,\n description: description ?? decoder.description,\n };\n}\n\nlet memoizedU8Codec: Codec<number> | undefined;\nfunction getMemoizedU8Codec(): Codec<number> {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nfunction getMemoizedU8CodecDescription(description?: string): Codec<number> {\n const codec = getMemoizedU8Codec();\n return {\n ...codec,\n description: description ?? codec.description,\n };\n}\n\nconst numSignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction'\n : undefined;\n\nconst numReadonlySignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable'\n : undefined;\n\nconst numReadonlyNonSignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable'\n : undefined;\n\nconst messageHeaderDescription = __DEV__\n ? 'The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses'\n : undefined;\n\nexport function getMessageHeaderEncoder(): Encoder<MessageHeader> {\n return getStructEncoder(\n [\n ['numSignerAccounts', getMemoizedU8EncoderDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n\nexport function getMessageHeaderDecoder(): Decoder<MessageHeader> {\n return getStructDecoder(\n [\n ['numSignerAccounts', getMemoizedU8DecoderDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n\nexport function getMessageHeaderCodec(): Codec<MessageHeader> {\n return getStructCodec(\n [\n ['numSignerAccounts', getMemoizedU8CodecDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8CodecDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8CodecDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledInstructions } from '../compile-instructions';\n\ntype Instruction = ReturnType<typeof getCompiledInstructions>[number];\n\nconst programAddressIndexDescription = __DEV__\n ? 'The index of the program being called, according to the well-ordered accounts list for this transaction'\n : 'programAddressIndex';\n\nconst accountIndexDescription = __DEV__\n ? 'The index of an account, according to the well-ordered accounts list for this transaction'\n : undefined;\n\nconst accountIndicesDescription = __DEV__\n ? 'An optional list of account indices, according to the ' +\n 'well-ordered accounts list for this transaction, in the order in ' +\n 'which the program being called expects them'\n : 'accountIndices';\n\nconst dataDescription = __DEV__ ? 'An optional buffer of data passed to the instruction' : 'data';\n\nlet memoizedGetInstructionEncoder: Encoder<Instruction> | undefined;\nexport function getInstructionEncoder(): Encoder<Instruction> {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = mapEncoder<Required<Instruction>, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder({ description: programAddressIndexDescription })],\n [\n 'accountIndices',\n getArrayEncoder(getU8Encoder({ description: accountIndexDescription }), {\n description: accountIndicesDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ['data', getBytesEncoder({ description: dataDescription, size: getShortU16Encoder() })],\n ]),\n // Convert an instruction to have all fields defined\n (instruction: Instruction): Required<Instruction> => {\n if (instruction.accountIndices !== undefined && instruction.data !== undefined) {\n return instruction as Required<Instruction>;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0),\n } as Required<Instruction>;\n }\n );\n }\n\n return memoizedGetInstructionEncoder;\n}\n\nlet memoizedGetInstructionDecoder: Decoder<Instruction> | undefined;\nexport function getInstructionDecoder(): Decoder<Instruction> {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = mapDecoder<Required<Instruction>, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder({ description: programAddressIndexDescription })],\n [\n 'accountIndices',\n getArrayDecoder(getU8Decoder({ description: accountIndexDescription }), {\n description: accountIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['data', getBytesDecoder({ description: dataDescription, size: getShortU16Decoder() })],\n ]),\n // Convert an instruction to exclude optional fields if they are empty\n (instruction: Required<Instruction>): Instruction => {\n if (instruction.accountIndices.length && instruction.data.byteLength) {\n return instruction;\n }\n const { accountIndices, data, ...rest } = instruction;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n }\n );\n }\n return memoizedGetInstructionDecoder;\n}\n\nexport function getInstructionCodec(): Codec<Instruction> {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { TransactionVersion } from '../types';\n\nconst VERSION_FLAG_MASK = 0x80;\n\nconst BASE_CONFIG = {\n description: __DEV__ ? 'A single byte that encodes the version of the transaction' : '',\n fixedSize: null,\n maxSize: 1,\n} as const;\n\nfunction decode(bytes: Uint8Array, offset = 0): [TransactionVersion, number] {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n // No version flag set; it's a legacy (unversioned) transaction.\n return ['legacy', offset];\n } else {\n const version = (firstByte ^ VERSION_FLAG_MASK) as TransactionVersion;\n return [version, offset + 1];\n }\n}\n\nfunction encode(value: TransactionVersion): Uint8Array {\n if (value === 'legacy') {\n return new Uint8Array();\n }\n if (value < 0 || value > 127) {\n // TODO: Coded error.\n throw new Error(`Transaction version must be in the range [0, 127]. \\`${value}\\` given.`);\n }\n return new Uint8Array([value | VERSION_FLAG_MASK]);\n}\n\nexport function getTransactionVersionDecoder(): Decoder<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n decode,\n };\n}\n\nexport function getTransactionVersionEncoder(): Encoder<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n encode,\n };\n}\n\nexport function getTransactionVersionCodec(): Codec<TransactionVersion> {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { Base58EncodedAddress, getAddressFromPublicKey } from '@solana/addresses';\nimport { Decoder, Encoder } from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\nimport { isSignerRole } from '@solana/instructions';\nimport { Ed25519Signature, signBytes } from '@solana/keys';\n\nimport { ITransactionWithFeePayer } from './fee-payer';\nimport { compileMessage } from './message';\nimport { getCompiledMessageEncoder } from './serializers/message';\n\nexport interface IFullySignedTransaction extends ITransactionWithSignatures {\n readonly __brand: unique symbol;\n}\nexport interface ITransactionWithSignatures {\n readonly signatures: Readonly<Record<Base58EncodedAddress, Ed25519Signature>>;\n}\n\nexport type TransactionSignature = string & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\nlet base58Decoder: Decoder<string> | undefined;\n\nexport function assertIsTransactionSignature(\n putativeTransactionSignature: string\n): asserts putativeTransactionSignature is TransactionSignature {\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 putativeTransactionSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeTransactionSignature.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(putativeTransactionSignature);\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(`\\`${putativeTransactionSignature}\\` is not a transaction signature`, {\n cause: e,\n });\n }\n}\n\nexport function isTransactionSignature(\n putativeTransactionSignature: string\n): putativeTransactionSignature is TransactionSignature {\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 putativeTransactionSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeTransactionSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeTransactionSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport function getSignatureFromTransaction(\n transaction: ITransactionWithFeePayer & ITransactionWithSignatures\n): TransactionSignature {\n if (!base58Decoder) base58Decoder = getBase58Decoder();\n\n const signatureBytes = transaction.signatures[transaction.feePayer];\n if (!signatureBytes) {\n // TODO: Coded error.\n throw new Error(\n \"Could not determine this transaction's signature. Make sure that the transaction \" +\n 'has been signed by its fee payer.'\n );\n }\n const transactionSignature = base58Decoder.decode(signatureBytes)[0];\n return transactionSignature as TransactionSignature;\n}\n\nexport async function signTransaction<TTransaction extends Parameters<typeof compileMessage>[0]>(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Promise<TTransaction & ITransactionWithSignatures> {\n const compiledMessage = compileMessage(transaction);\n const nextSignatures: Record<Base58EncodedAddress, Ed25519Signature> =\n 'signatures' in transaction ? { ...transaction.signatures } : {};\n const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);\n const publicKeySignaturePairs = await Promise.all(\n keyPairs.map(keyPair =>\n Promise.all([getAddressFromPublicKey(keyPair.publicKey), signBytes(keyPair.privateKey, wireMessageBytes)])\n )\n );\n for (const [signerPublicKey, signature] of publicKeySignaturePairs) {\n nextSignatures[signerPublicKey] = signature;\n }\n const out = {\n ...transaction,\n signatures: nextSignatures,\n };\n Object.freeze(out);\n return out;\n}\n\nexport function transactionSignature(putativeTransactionSignature: string): TransactionSignature {\n assertIsTransactionSignature(putativeTransactionSignature);\n return putativeTransactionSignature;\n}\n\nexport function assertTransactionIsFullySigned<TTransaction extends Parameters<typeof compileMessage>[0]>(\n transaction: TTransaction & ITransactionWithSignatures\n): asserts transaction is TTransaction & IFullySignedTransaction {\n const signerAddressesFromInstructions = transaction.instructions\n .flatMap(i => i.accounts?.filter(a => isSignerRole(a.role)) ?? [])\n .map(a => a.address);\n const requiredSigners = new Set([transaction.feePayer, ...signerAddressesFromInstructions]);\n\n requiredSigners.forEach(address => {\n if (!transaction.signatures[address]) {\n // TODO coded error\n throw new Error(`Transaction is missing signature for address \\`${address}\\``);\n }\n });\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport { RequestAirdropApi } from '@solana/rpc-core/dist/types/rpc-methods/requestAirdrop';\nimport { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment, LamportsUnsafeBeyond2Pow53Minus1 } from '@solana/rpc-types';\nimport { TransactionSignature } from '@solana/transactions';\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: Base58EncodedAddress;\n rpc: Rpc<RequestAirdropApi>;\n}>): Promise<TransactionSignature> {\n const airdropTransactionSignature = (await rpc\n .requestAirdrop(recipientAddress, lamports, { commitment })\n .send({ abortSignal })) as unknown as TransactionSignature; // FIXME(#1709)\n await confirmSignatureOnlyTransaction({\n abortSignal,\n commitment,\n signature: airdropTransactionSignature,\n });\n return airdropTransactionSignature;\n}\n","import { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { TransactionSignature } from '@solana/transactions';\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: TransactionSignature;\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 { Commitment } from '@solana/rpc-types';\nimport { TransactionSignature } from '@solana/transactions';\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: TransactionSignature,\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 { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\nimport { TransactionSignature } from '@solana/transactions';\n\ntype GetRecentSignatureConfirmationPromiseFn = (config: {\n abortSignal: AbortSignal;\n commitment: Commitment;\n signature: TransactionSignature;\n}) => Promise<void>;\n\nexport function createRecentSignatureConfirmationPromiseFactory(\n rpc: Rpc<GetSignatureStatusesApi>,\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>\n): GetRecentSignatureConfirmationPromiseFn {\n return async function getRecentSignatureConfirmationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n signature,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for status changes to a signature.\n */\n const signatureStatusNotifications = await rpcSubscriptions\n .signatureNotifications(signature, { commitment })\n .subscribe({ abortSignal: abortController.signal });\n const signatureDidCommitPromise = (async () => {\n for await (const signatureStatusNotification of signatureStatusNotifications) {\n if (signatureStatusNotification.value.err) {\n // TODO: Coded error.\n throw new Error(`The transaction with signature \\`${signature}\\` failed.`, {\n cause: signatureStatusNotification.value.err,\n });\n } else {\n return;\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current status.\n * This will only yield a result if the signature is still in the status cache.\n */\n const signatureStatusLookupPromise = (async () => {\n const { value: signatureStatusResults } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: abortController.signal });\n const signatureStatus = signatureStatusResults[0];\n if (\n signatureStatus &&\n signatureStatus.confirmationStatus &&\n commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0\n ) {\n return;\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await Promise.race([signatureDidCommitPromise, signatureStatusLookupPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import { Commitment } from '@solana/rpc-types';\n\ntype Config = Readonly<{\n abortSignal: AbortSignal;\n commitment: Commitment;\n}>;\n\nexport async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }: Config) {\n return await new Promise((_, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n clearTimeout(timeoutId);\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n callerAbortSignal.addEventListener('abort', handleAbort);\n const timeoutMs = commitment === 'processed' ? 30_000 : 60_000;\n const startMs = performance.now();\n const timeoutId =\n // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure\n // elapsed time instead of active time.\n // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static\n setTimeout(() => {\n const elapsedMs = performance.now() - startMs;\n reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, 'TimeoutError'));\n }, timeoutMs);\n });\n}\n","import { pipe } from '@solana/functional';\nimport {\n createSolanaRpcApi,\n createSolanaRpcSubscriptionsApi,\n createSolanaRpcSubscriptionsApi_UNSTABLE,\n SolanaRpcMethods,\n SolanaRpcSubscriptions,\n SolanaRpcSubscriptionsUnstable,\n} from '@solana/rpc-core';\nimport { createJsonRpc, createJsonSubscriptionRpc } from '@solana/rpc-transport';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\n\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\nimport { getRpcSubscriptionsWithSubscriptionCoalescing } from './rpc-subscription-coalescer';\n\nexport function createSolanaRpc(config: Omit<Parameters<typeof createJsonRpc>[0], 'api'>): Rpc<SolanaRpcMethods> {\n return createJsonRpc({\n ...config,\n api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n });\n}\n\nexport function createSolanaRpcSubscriptions(\n config: Omit<Parameters<typeof createJsonSubscriptionRpc>[0], 'api'>\n): RpcSubscriptions<SolanaRpcSubscriptions> {\n return pipe(\n createJsonSubscriptionRpc({\n ...config,\n api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG),\n }),\n rpcSubscriptions =>\n getRpcSubscriptionsWithSubscriptionCoalescing({\n getDeduplicationKey: (...args) => fastStableStringify(args),\n rpcSubscriptions,\n })\n );\n}\n\nexport function createSolanaRpcSubscriptions_UNSTABLE(\n config: Omit<Parameters<typeof createJsonSubscriptionRpc>[0], 'api'>\n): RpcSubscriptions<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return createJsonSubscriptionRpc({\n ...config,\n api: createSolanaRpcSubscriptionsApi_UNSTABLE(DEFAULT_RPC_CONFIG),\n });\n}\n","type IntegerOverflowHandler = (keyPath: (number | string)[], value: bigint) => void;\ntype Patched<T> = T extends object ? { [Property in keyof T]: Patched<T[Property]> } : T extends bigint ? number : T;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction visitNode<T>(value: T, keyPath: (number | string)[], onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n if (Array.isArray(value)) {\n return value.map((element, ii) =>\n visitNode(element, [...keyPath, ii], onIntegerOverflow)\n ) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const propName in value) {\n if (Object.prototype.hasOwnProperty.call(value, propName)) {\n out[propName] = visitNode(value[propName], [...keyPath, propName], onIntegerOverflow);\n }\n }\n return out as TypescriptBug33014;\n } else if (typeof value === 'bigint') {\n // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // downcasting `bigints` to `numbers`.\n if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {\n onIntegerOverflow(keyPath, value);\n }\n return Number(value) as TypescriptBug33014;\n } else {\n return value as TypescriptBug33014;\n }\n}\n\nexport function patchParamsForSolanaLabsRpc<T>(params: T, onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n return visitNode(params, [], onIntegerOverflow);\n}\n","export type KeyPathWildcard = { readonly __brand: unique symbol };\n\nexport const KEYPATH_WILDCARD = {} as KeyPathWildcard;\n","import { IRpcSubscriptionsApi } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { KeyPath } from './response-patcher';\nimport { KEYPATH_WILDCARD } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\nimport { SolanaRpcSubscriptions, SolanaRpcSubscriptionsUnstable } from './rpc-subscriptions';\n\n// Numeric values nested in `jsonParsed` accounts\nconst jsonParsedTokenAccountsConfigs = [\n // parsed Token/Token22 token account\n ['data', 'parsed', 'info', 'tokenAmount', 'decimals'],\n ['data', 'parsed', 'info', 'tokenAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'decimals'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'uiAmount'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'decimals'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'olderTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'newerTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n];\nconst jsonParsedAccountsConfigs = [\n ...jsonParsedTokenAccountsConfigs,\n // parsed AddressTableLookup account\n ['data', 'parsed', 'info', 'lastExtendedSlotStartIndex'],\n // parsed Config account\n ['data', 'parsed', 'info', 'slashPenalty'],\n ['data', 'parsed', 'info', 'warmupCooldownRate'],\n // parsed Token/Token22 mint account\n ['data', 'parsed', 'info', 'decimals'],\n // parsed Token/Token22 multisig account\n ['data', 'parsed', 'info', 'numRequiredSigners'],\n ['data', 'parsed', 'info', 'numValidSigners'],\n // parsed Stake account\n ['data', 'parsed', 'info', 'stake', 'delegation', 'warmupCooldownRate'],\n // parsed Sysvar rent account\n ['data', 'parsed', 'info', 'exemptionThreshold'],\n ['data', 'parsed', 'info', 'burnPercent'],\n // parsed Vote account\n ['data', 'parsed', 'info', 'commission'],\n ['data', 'parsed', 'info', 'votes', KEYPATH_WILDCARD, 'confirmationCount'],\n];\n\ntype AllowedNumericKeypaths<TApi> = Partial<Record<keyof TApi, readonly KeyPath[]>>;\n\nlet memoizedNotificationKeypaths: AllowedNumericKeypaths<\n IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>\n>;\nlet memoizedResponseKeypaths: AllowedNumericKeypaths<ReturnType<typeof createSolanaRpcApi>>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nexport function getAllowedNumericKeypathsForNotification(): AllowedNumericKeypaths<\n IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>\n> {\n if (!memoizedNotificationKeypaths) {\n memoizedNotificationKeypaths = {\n accountNotifications: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n blockNotifications: [\n ['value', 'block', 'blockTime'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['value', 'block', 'transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'index',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlySignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlyUnsignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numRequiredSignatures',\n ],\n ['value', 'block', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n programNotifications: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n };\n }\n return memoizedNotificationKeypaths;\n}\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nexport function getAllowedNumericKeypathsForResponse(): AllowedNumericKeypaths<ReturnType<typeof createSolanaRpcApi>> {\n if (!memoizedResponseKeypaths) {\n memoizedResponseKeypaths = {\n getAccountInfo: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n getBlock: [\n ['blockTime'],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'innerInstructions', KEYPATH_WILDCARD, 'index'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', 'header', 'numReadonlySignedAccounts'],\n ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', 'header', 'numReadonlyUnsignedAccounts'],\n ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', 'header', 'numRequiredSignatures'],\n ['rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n getBlockTime: [[]],\n getClusterNodes: [\n [KEYPATH_WILDCARD, 'featureSet'],\n [KEYPATH_WILDCARD, 'shredVersion'],\n ],\n getInflationGovernor: [['initial'], ['foundation'], ['foundationTerm'], ['taper'], ['terminal']],\n getInflationRate: [['foundation'], ['total'], ['validator']],\n getInflationReward: [[KEYPATH_WILDCARD, 'commission']],\n getMultipleAccounts: jsonParsedAccountsConfigs.map(c => ['value', KEYPATH_WILDCARD, ...c]),\n getProgramAccounts: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n getRecentPerformanceSamples: [[KEYPATH_WILDCARD, 'samplePeriodSecs']],\n getTokenAccountBalance: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenLargestAccounts: [\n ['value', KEYPATH_WILDCARD, 'decimals'],\n ['value', KEYPATH_WILDCARD, 'uiAmount'],\n ],\n getTokenSupply: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTransaction: [\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ['meta', 'innerInstructions', KEYPATH_WILDCARD, 'index'],\n ['meta', 'innerInstructions', KEYPATH_WILDCARD, 'instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n [\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n ['transaction', 'message', 'instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['transaction', 'message', 'instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['transaction', 'message', 'header', 'numReadonlySignedAccounts'],\n ['transaction', 'message', 'header', 'numReadonlyUnsignedAccounts'],\n ['transaction', 'message', 'header', 'numRequiredSignatures'],\n ],\n getVersion: [['feature-set']],\n getVoteAccounts: [\n ['current', KEYPATH_WILDCARD, 'commission'],\n ['delinquent', KEYPATH_WILDCARD, 'commission'],\n ],\n simulateTransaction: jsonParsedAccountsConfigs.map(c => ['value', 'accounts', KEYPATH_WILDCARD, ...c]),\n };\n }\n return memoizedResponseKeypaths;\n}\n","import {\n getAllowedNumericKeypathsForNotification,\n getAllowedNumericKeypathsForResponse,\n} from './response-patcher-allowed-numeric-values';\nimport { KEYPATH_WILDCARD, KeyPathWildcard } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\nimport { createSolanaRpcSubscriptionsApi } from './rpc-subscriptions';\n\nexport type KeyPath = ReadonlyArray<KeyPathWildcard | number | string | KeyPath>;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction getNextAllowedKeypaths(keyPaths: readonly KeyPath[], property: number | string) {\n return keyPaths\n .filter(keyPath => (keyPath[0] === KEYPATH_WILDCARD && typeof property === 'number') || keyPath[0] === property)\n .map(keyPath => keyPath.slice(1));\n}\n\nfunction visitNode<T>(value: unknown, allowedKeypaths: readonly KeyPath[]): T {\n if (Array.isArray(value)) {\n return value.map((element, ii) => {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, ii);\n return visitNode(element, nextAllowedKeypaths);\n }) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const [propName, innerValue] of Object.entries(value)) {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, propName);\n out[propName] = visitNode(innerValue, nextAllowedKeypaths);\n }\n return out as TypescriptBug33014;\n } else if (\n typeof value === 'number' &&\n // The presence of an allowed keypath on the route to this value implies it's allowlisted;\n // Upcast the value to `bigint` unless an allowed keypath is present.\n allowedKeypaths.length === 0 &&\n // Only try to upcast an Integer to `bigint`\n Number.isInteger(value)\n ) {\n // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // upcasting `numbers` to `bigints`.\n return BigInt(value) as TypescriptBug33014;\n } else {\n return value as TypescriptBug33014;\n }\n}\n\nexport function patchResponseForSolanaLabsRpc<T>(\n rawResponse: unknown,\n methodName?: keyof ReturnType<typeof createSolanaRpcApi>\n): T {\n const allowedKeypaths = methodName ? getAllowedNumericKeypathsForResponse()[methodName] : undefined;\n return visitNode(rawResponse, allowedKeypaths ?? []);\n}\n\nexport function patchResponseForSolanaLabsRpcSubscriptions<T>(\n rawResponse: unknown,\n methodName?: keyof ReturnType<typeof createSolanaRpcSubscriptionsApi>\n): T {\n const allowedKeypaths = methodName ? getAllowedNumericKeypathsForNotification()[methodName] : undefined;\n return visitNode(rawResponse, allowedKeypaths ?? []);\n}\n","import { IRpcApi, RpcRequest } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { patchParamsForSolanaLabsRpc } from '../params-patcher';\nimport { patchResponseForSolanaLabsRpc } from '../response-patcher';\nimport { GetAccountInfoApi } from './getAccountInfo';\nimport { GetBalanceApi } from './getBalance';\nimport { GetBlockApi } from './getBlock';\nimport { GetBlockCommitmentApi } from './getBlockCommitment';\nimport { GetBlockHeightApi } from './getBlockHeight';\nimport { GetBlockProductionApi } from './getBlockProduction';\nimport { GetBlocksApi } from './getBlocks';\nimport { GetBlocksWithLimitApi } from './getBlocksWithLimit';\nimport { GetBlockTimeApi } from './getBlockTime';\nimport { GetClusterNodesApi } from './getClusterNodes';\nimport { GetEpochInfoApi } from './getEpochInfo';\nimport { GetEpochScheduleApi } from './getEpochSchedule';\nimport { GetFeeForMessageApi } from './getFeeForMessage';\nimport { GetFirstAvailableBlockApi } from './getFirstAvailableBlock';\nimport { GetGenesisHashApi } from './getGenesisHash';\nimport { GetHealthApi } from './getHealth';\nimport { GetHighestSnapshotSlotApi } from './getHighestSnapshotSlot';\nimport { GetIdentityApi } from './getIdentity';\nimport { GetInflationGovernorApi } from './getInflationGovernor';\nimport { GetInflationRateApi } from './getInflationRate';\nimport { GetInflationRewardApi } from './getInflationReward';\nimport { GetLargestAccountsApi } from './getLargestAccounts';\nimport { GetLatestBlockhashApi } from './getLatestBlockhash';\nimport { GetLeaderScheduleApi } from './getLeaderSchedule';\nimport { GetMaxRetransmitSlotApi } from './getMaxRetransmitSlot';\nimport { GetMaxShredInsertSlotApi } from './getMaxShredInsertSlot';\nimport { GetMinimumBalanceForRentExemptionApi } from './getMinimumBalanceForRentExemption';\nimport { GetMultipleAccountsApi } from './getMultipleAccounts';\nimport { GetProgramAccountsApi } from './getProgramAccounts';\nimport { GetRecentPerformanceSamplesApi } from './getRecentPerformanceSamples';\nimport { GetRecentPrioritizationFeesApi } from './getRecentPrioritizationFees';\nimport { GetSignaturesForAddressApi } from './getSignaturesForAddress';\nimport { GetSignatureStatusesApi } from './getSignatureStatuses';\nimport { GetSlotApi } from './getSlot';\nimport { GetSlotLeaderApi } from './getSlotLeader';\nimport { GetSlotLeadersApi } from './getSlotLeaders';\nimport { GetStakeActivationApi } from './getStakeActivation';\nimport { GetStakeMinimumDelegationApi } from './getStakeMinimumDelegation';\nimport { GetSupplyApi } from './getSupply';\nimport { GetTokenAccountBalanceApi } from './getTokenAccountBalance';\nimport { GetTokenAccountsByDelegateApi } from './getTokenAccountsByDelegate';\nimport { GetTokenAccountsByOwnerApi } from './getTokenAccountsByOwner';\nimport { GetTokenLargestAccountsApi } from './getTokenLargestAccounts';\nimport { GetTokenSupplyApi } from './getTokenSupply';\nimport { GetTransactionApi } from './getTransaction';\nimport { GetTransactionCountApi } from './getTransactionCount';\nimport { GetVersionApi } from './getVersion';\nimport { GetVoteAccountsApi } from './getVoteAccounts';\nimport { IsBlockhashValidApi } from './isBlockhashValid';\nimport { MinimumLedgerSlotApi } from './minimumLedgerSlot';\nimport { RequestAirdropApi } from './requestAirdrop';\nimport { SendTransactionApi } from './sendTransaction';\nimport { SimulateTransactionApi } from './simulateTransaction';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcMethods = GetAccountInfoApi &\n GetBalanceApi &\n GetBlockApi &\n GetBlockCommitmentApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlocksWithLimitApi &\n GetBlockTimeApi &\n GetClusterNodesApi &\n GetEpochInfoApi &\n GetEpochScheduleApi &\n GetFeeForMessageApi &\n GetFirstAvailableBlockApi &\n GetGenesisHashApi &\n GetHealthApi &\n GetHighestSnapshotSlotApi &\n GetIdentityApi &\n GetInflationGovernorApi &\n GetInflationRateApi &\n GetInflationRewardApi &\n GetLargestAccountsApi &\n GetLatestBlockhashApi &\n GetLeaderScheduleApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetMinimumBalanceForRentExemptionApi &\n GetMultipleAccountsApi &\n GetProgramAccountsApi &\n GetRecentPerformanceSamplesApi &\n GetRecentPrioritizationFeesApi &\n GetSignaturesForAddressApi &\n GetSignatureStatusesApi &\n GetSlotApi &\n GetSlotLeaderApi &\n GetSlotLeadersApi &\n GetStakeActivationApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTokenAccountBalanceApi &\n GetTokenAccountsByDelegateApi &\n GetTokenAccountsByOwnerApi &\n GetTokenLargestAccountsApi &\n GetTokenSupplyApi &\n GetTransactionApi &\n GetTransactionCountApi &\n GetVersionApi &\n GetVoteAccountsApi &\n IsBlockhashValidApi &\n MinimumLedgerSlotApi &\n RequestAirdropApi &\n SendTransactionApi &\n SimulateTransactionApi;\n\nexport function createSolanaRpcApi(config?: Config): IRpcApi<SolanaRpcMethods> {\n return new Proxy({} as IRpcApi<SolanaRpcMethods>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<TMethodName extends keyof IRpcApi<SolanaRpcMethods>>(\n ...args: Parameters<NonNullable<ProxyHandler<IRpcApi<SolanaRpcMethods>>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof SolanaRpcMethods;\n return function (\n ...rawParams: Parameters<\n SolanaRpcMethods[TMethodName] extends CallableFunction ? SolanaRpcMethods[TMethodName] : never\n >\n ): RpcRequest<ReturnType<SolanaRpcMethods[TMethodName]>> {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n const params = patchParamsForSolanaLabsRpc(\n rawParams,\n handleIntegerOverflow\n ? (keyPath, value) => handleIntegerOverflow(methodName, keyPath, value)\n : undefined\n );\n return {\n methodName,\n params,\n responseProcessor: rawResponse => patchResponseForSolanaLabsRpc(rawResponse, methodName),\n };\n };\n },\n });\n}\n","import { IRpcSubscriptionsApi, RpcSubscription } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { patchParamsForSolanaLabsRpc } from '../params-patcher';\nimport { patchResponseForSolanaLabsRpcSubscriptions } from '../response-patcher';\nimport { AccountNotificationsApi } from './account-notifications';\nimport { BlockNotificationsApi } from './block-notifications';\nimport { LogsNotificationsApi } from './logs-notifications';\nimport { ProgramNotificationsApi } from './program-notifications';\nimport { RootNotificationsApi } from './root-notifications';\nimport { SignatureNotificationsApi } from './signature-notifications';\nimport { SlotNotificationsApi } from './slot-notifications';\nimport { SlotsUpdatesNotificationsApi } from './slots-updates-notifications';\nimport { VoteNotificationsApi } from './vote-notifications';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcSubscriptions = AccountNotificationsApi &\n BlockNotificationsApi &\n LogsNotificationsApi &\n ProgramNotificationsApi &\n RootNotificationsApi &\n SignatureNotificationsApi &\n SlotNotificationsApi;\nexport type SolanaRpcSubscriptionsUnstable = SlotsUpdatesNotificationsApi & VoteNotificationsApi;\n\nexport function createSolanaRpcSubscriptionsApi(\n config?: Config\n): IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return new Proxy({} as IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<\n TNotificationName extends keyof IRpcSubscriptionsApi<\n SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable\n >\n >(\n ...args: Parameters<\n NonNullable<\n ProxyHandler<IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>>['get']\n >\n >\n ) {\n const [_, p] = args;\n const notificationName = p.toString() as keyof (SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable);\n return function (\n ...rawParams: Parameters<\n (SolanaRpcSubscriptions &\n SolanaRpcSubscriptionsUnstable)[TNotificationName] extends CallableFunction\n ? (SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable)[TNotificationName]\n : never\n >\n ): RpcSubscription<\n ReturnType<(SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable)[TNotificationName]>\n > {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n const params = patchParamsForSolanaLabsRpc(\n rawParams,\n handleIntegerOverflow\n ? (keyPath, value) => handleIntegerOverflow(notificationName, keyPath, value)\n : undefined\n );\n return {\n params,\n responseProcessor: rawResponse =>\n patchResponseForSolanaLabsRpcSubscriptions(rawResponse, notificationName),\n subscribeMethodName: notificationName.replace(/Notifications$/, 'Subscribe'),\n unsubscribeMethodName: notificationName.replace(/Notifications$/, 'Unsubscribe'),\n };\n };\n },\n });\n}\n\nexport function createSolanaRpcSubscriptionsApi_UNSTABLE(\n config?: Config\n): IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return createSolanaRpcSubscriptionsApi(config) as IRpcSubscriptionsApi<\n SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable\n >;\n}\n","// Keep in sync with https://github.com/solana-labs/solana/blob/master/rpc-client-api/src/custom_error.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nexport const SolanaJsonRpcErrorCode = {\n JSON_RPC_INVALID_PARAMS: -32602,\n JSON_RPC_SCAN_ERROR: -32012,\n JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016,\n JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n} as const;\ntype SolanaJsonRpcErrorCodeEnum = (typeof SolanaJsonRpcErrorCode)[keyof typeof SolanaJsonRpcErrorCode];\n\ntype SolanaJsonRpcErrorDetails = Readonly<{\n code: number;\n data?: unknown;\n message: string;\n}>;\n\nexport class SolanaJsonRpcError extends Error {\n readonly code: SolanaJsonRpcErrorCodeEnum;\n readonly data: unknown;\n constructor(details: SolanaJsonRpcErrorDetails) {\n super(`JSON-RPC 2.0 error (${details.code}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.code = details.code as SolanaJsonRpcErrorCodeEnum;\n this.data = details.data;\n }\n get name() {\n return 'SolanaJsonRpcError';\n }\n}\n","let _nextMessageId = 0;\nexport function getNextMessageId() {\n const id = _nextMessageId;\n _nextMessageId = (_nextMessageId + 1) % Number.MAX_SAFE_INTEGER;\n return id;\n}\n","import { getNextMessageId } from './json-rpc-message-id';\n\nexport function createJsonRpcMessage<TParams>(method: string, params: TParams) {\n return {\n id: getNextMessageId(),\n jsonrpc: '2.0',\n method,\n params,\n };\n}\n","import { SolanaJsonRpcError } from './json-rpc-errors';\nimport { createJsonRpcMessage } from './json-rpc-message';\nimport { PendingRpcRequest, Rpc, RpcConfig, RpcRequest, SendOptions } from './json-rpc-types';\n\ninterface IHasIdentifier {\n readonly id: number;\n}\nexport type JsonRpcResponse<TResponse> = IHasIdentifier &\n Readonly<{ result: TResponse } | { error: { code: number; message: string; data?: unknown } }>;\n\nfunction createPendingRpcRequest<TRpcMethods, TResponse>(\n rpcConfig: RpcConfig<TRpcMethods>,\n pendingRequest: RpcRequest<TResponse>\n): PendingRpcRequest<TResponse> {\n return {\n async send(options?: SendOptions): Promise<TResponse> {\n const { methodName, params, responseProcessor } = pendingRequest;\n const payload = createJsonRpcMessage(methodName, params);\n const response = await rpcConfig.transport<JsonRpcResponse<unknown>>({\n payload,\n signal: options?.abortSignal,\n });\n if ('error' in response) {\n throw new SolanaJsonRpcError(response.error);\n } else {\n return (responseProcessor ? responseProcessor(response.result) : response.result) as TResponse;\n }\n },\n };\n}\n\nfunction makeProxy<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const createRpcRequest = Reflect.get(target, methodName, receiver);\n const newRequest = createRpcRequest\n ? createRpcRequest(...rawParams)\n : { methodName, params: rawParams };\n return createPendingRpcRequest(rpcConfig, newRequest);\n };\n },\n }) as Rpc<TRpcMethods>;\n}\n\nexport function createJsonRpc<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return makeProxy(rpcConfig);\n}\n","import { JsonRpcResponse } from './json-rpc';\nimport { SolanaJsonRpcError } from './json-rpc-errors';\nimport { createJsonRpcMessage } from './json-rpc-message';\nimport {\n PendingRpcSubscription,\n RpcSubscription,\n RpcSubscriptionConfig,\n RpcSubscriptions,\n SubscribeOptions,\n} from './json-rpc-types';\n\ntype JsonRpcNotification<TNotification> = Readonly<{\n params: Readonly<{\n result: TNotification;\n subscription: number;\n }>;\n}>;\ntype SubscriptionId = number;\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nfunction createPendingRpcSubscription<TRpcSubscriptionMethods, TNotification>(\n rpcConfig: RpcSubscriptionConfig<TRpcSubscriptionMethods>,\n { params, subscribeMethodName, unsubscribeMethodName, responseProcessor }: RpcSubscription<TNotification>\n): PendingRpcSubscription<TNotification> {\n return {\n async subscribe({ abortSignal }: SubscribeOptions): Promise<AsyncIterable<TNotification>> {\n abortSignal.throwIfAborted();\n let subscriptionId: number | undefined;\n function handleCleanup() {\n if (subscriptionId !== undefined) {\n const payload = createJsonRpcMessage(unsubscribeMethodName, [subscriptionId]);\n connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload).finally(() => {\n connectionAbortController.abort();\n });\n } else {\n connectionAbortController.abort();\n }\n }\n abortSignal.addEventListener('abort', handleCleanup);\n /**\n * STEP 1: Send the subscribe message.\n */\n const connectionAbortController = new AbortController();\n const subscribeMessage = createJsonRpcMessage(subscribeMethodName, params);\n const connection = await rpcConfig.transport({\n payload: subscribeMessage,\n signal: connectionAbortController.signal,\n });\n function handleConnectionCleanup() {\n abortSignal.removeEventListener('abort', handleCleanup);\n }\n registerIterableCleanup(connection, handleConnectionCleanup);\n /**\n * STEP 2: Wait for the acknowledgement from the server with the subscription id.\n */\n for await (const message of connection as AsyncIterable<\n JsonRpcNotification<unknown> | JsonRpcResponse<SubscriptionId>\n >) {\n if ('id' in message && message.id === subscribeMessage.id) {\n if ('error' in message) {\n throw new SolanaJsonRpcError(message.error);\n } else {\n subscriptionId = message.result as SubscriptionId;\n break;\n }\n }\n }\n if (subscriptionId == null) {\n // TODO: Coded error.\n throw new Error('Failed to obtain a subscription id from the server');\n }\n /**\n * STEP 3: Return an iterable that yields notifications for this subscription id.\n */\n return {\n async *[Symbol.asyncIterator]() {\n for await (const message of connection as AsyncIterable<\n JsonRpcNotification<unknown> | JsonRpcResponse<SubscriptionId>\n >) {\n if (!('params' in message) || message.params.subscription !== subscriptionId) {\n continue;\n }\n const notification = message.params.result as TNotification;\n yield responseProcessor ? responseProcessor(notification) : notification;\n }\n },\n };\n },\n };\n}\n\nfunction makeProxy<TRpcSubscriptionMethods>(\n rpcConfig: RpcSubscriptionConfig<TRpcSubscriptionMethods>\n): RpcSubscriptions<TRpcSubscriptionMethods> {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const createRpcSubscription = Reflect.get(target, methodName, receiver);\n if (p.toString().endsWith('Notifications') === false && !createRpcSubscription) {\n // TODO: Coded error.\n throw new Error(\n \"Either the notification name must end in 'Notifications' or the API \" +\n 'must supply a subscription creator function to map between the ' +\n 'notification name and the subscribe/unsubscribe method names.'\n );\n }\n const newRequest = createRpcSubscription\n ? createRpcSubscription(...rawParams)\n : {\n params: rawParams,\n subscribeMethodName: methodName.replace(/Notifications$/, 'Subscribe'),\n unsubscribeMethodName: methodName.replace(/Notifications$/, 'Unsubscribe'),\n };\n return createPendingRpcSubscription(rpcConfig, newRequest);\n };\n },\n }) as RpcSubscriptions<TRpcSubscriptionMethods>;\n}\n\nexport function createJsonSubscriptionRpc<TRpcSubscriptionMethods>(\n rpcConfig: RpcSubscriptionConfig<TRpcSubscriptionMethods>\n): RpcSubscriptions<TRpcSubscriptionMethods> {\n return makeProxy(rpcConfig);\n}\n","export default globalThis.fetch;\n","type SolanaHttpErrorDetails = Readonly<{\n statusCode: number;\n message: string;\n}>;\n\nexport class SolanaHttpError extends Error {\n readonly statusCode: number;\n constructor(details: SolanaHttpErrorDetails) {\n super(`HTTP error (${details.statusCode}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.statusCode = details.statusCode;\n }\n get name() {\n return 'SolanaHttpError';\n }\n}\n","export type AllowedHttpRequestHeaders = Readonly<\n { [headerName: string]: string } & {\n // Someone can still sneak a forbidden header past Typescript if they do something like\n // fOo-BaR, but at that point they deserve the runtime failure.\n [K in DisallowedHeaders | ForbiddenHeaders as\n | K // `Foo-Bar`\n | Capitalize<Lowercase<K>> // `Foo-bar`\n | Lowercase<K> // `foo-bar`\n | Uncapitalize<K> // `foo-Bar`\n // `FOO-BAR`\n | Uppercase<K>]?: never;\n }\n>;\n// These are headers that we simply don't allow the developer to override because they're\n// fundamental to the operation of the JSON-RPC transport.\ntype DisallowedHeaders = 'Accept' | 'Content-Length' | 'Content-Type' | 'Solana-Client';\ntype ForbiddenHeaders =\n | 'Accept-Charset'\n | 'Accept-Encoding'\n | 'Access-Control-Request-Headers'\n | 'Access-Control-Request-Method'\n | 'Connection'\n | 'Content-Length'\n | 'Cookie'\n | 'Date'\n | 'DNT'\n | 'Expect'\n | 'Host'\n | 'Keep-Alive'\n | 'Origin'\n | 'Permissions-Policy'\n // No currently available Typescript technique allows you to match on a prefix.\n // | 'Proxy-'\n // | 'Sec-'\n | 'Referer'\n | 'TE'\n | 'Trailer'\n | 'Transfer-Encoding'\n | 'Upgrade'\n | 'Via';\n\n// These are headers which are fundamental to the JSON-RPC transport, and must not be modified.\nconst DISALLOWED_HEADERS: Record<string, boolean> = {\n accept: true,\n 'content-length': true,\n 'content-type': true,\n};\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS: Record<string, boolean> = {\n 'accept-charset': true,\n 'accept-encoding': true,\n 'access-control-request-headers': true,\n 'access-control-request-method': true,\n connection: true,\n 'content-length': true,\n cookie: true,\n date: true,\n dnt: true,\n expect: true,\n host: true,\n 'keep-alive': true,\n origin: true,\n 'permissions-policy': true,\n // No currently available Typescript technique allows you to match on a prefix.\n // 'proxy-':true,\n // 'sec-':true,\n referer: true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n via: true,\n};\n\nexport function assertIsAllowedHttpRequestHeaders(\n headers: Record<string, string>\n): asserts headers is AllowedHttpRequestHeaders {\n const badHeaders = Object.keys(headers).filter(headerName => {\n const lowercaseHeaderName = headerName.toLowerCase();\n return (\n DISALLOWED_HEADERS[headerName.toLowerCase()] === true ||\n FORBIDDEN_HEADERS[headerName.toLowerCase()] === true ||\n lowercaseHeaderName.startsWith('proxy-') ||\n lowercaseHeaderName.startsWith('sec-')\n );\n });\n if (badHeaders.length > 0) {\n throw new Error(\n `${badHeaders.length > 1 ? 'These headers are' : 'This header is'} forbidden: ` +\n `\\`${badHeaders.join('`, `')}\\`. Learn more at ` +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.'\n );\n }\n}\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers, such as those defined\n * in the `DisallowedHeaders` type.\n */\nexport function normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n","import type { Agent as NodeHttpAgent } from 'node:http';\nimport type { Agent as NodeHttpsAgent } from 'node:https';\n\nimport fetchImpl from 'fetch-impl';\n\nimport { IRpcTransport } from '../transport-types';\nimport { SolanaHttpError } from './http-transport-errors';\nimport {\n AllowedHttpRequestHeaders,\n assertIsAllowedHttpRequestHeaders,\n normalizeHeaders,\n} from './http-transport-headers';\n\ntype Config = Readonly<{\n headers?: AllowedHttpRequestHeaders;\n httpAgentNodeOnly?: NodeHttpAgent | NodeHttpsAgent | ((parsedUrl: URL) => NodeHttpAgent | NodeHttpsAgent);\n url: string;\n}>;\n\nexport function createHttpTransport({ httpAgentNodeOnly, headers, url }: Config): IRpcTransport {\n if (__DEV__ && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\n }\n const agent = __NODEJS__ ? httpAgentNodeOnly : undefined;\n if (__DEV__ && httpAgentNodeOnly != null) {\n console.warn(\n 'createHttpTransport(): The `httpAgentNodeOnly` config you supplied has been ' +\n 'ignored; HTTP agents are only usable in Node environments.'\n );\n }\n const customHeaders = headers && normalizeHeaders(headers);\n return async function makeHttpRequest<TResponse>({\n payload,\n signal,\n }: Parameters<IRpcTransport>[0]): Promise<TResponse> {\n const body = JSON.stringify(payload);\n const requestInfo = {\n agent,\n body,\n headers: {\n ...customHeaders,\n // Keep these headers lowercase so they will override any user-supplied headers above.\n accept: 'application/json',\n 'content-length': body.length.toString(),\n 'content-type': 'application/json; charset=utf-8',\n },\n method: 'POST',\n signal,\n };\n const response = await fetchImpl(url, requestInfo);\n if (!response.ok) {\n throw new SolanaHttpError({\n message: response.statusText,\n statusCode: response.status,\n });\n }\n return (await response.json()) as TResponse;\n };\n}\n","export default globalThis.WebSocket;\n","import WebSocket from 'ws-impl';\n\ntype Config = Readonly<{\n sendBufferHighWatermark: number;\n signal: AbortSignal;\n url: string;\n}>;\ntype IteratorKey = symbol;\ntype IteratorState =\n | {\n __hasPolled: true;\n onMessage: Parameters<ConstructorParameters<typeof Promise>[0]>[0];\n onError: Parameters<ConstructorParameters<typeof Promise>[0]>[1];\n }\n | {\n __hasPolled: false;\n queuedMessages: unknown[];\n };\nexport type RpcWebSocketConnection = Readonly<{\n send(payload: unknown): Promise<void>;\n [Symbol.asyncIterator](): AsyncGenerator<unknown>;\n}>;\n\nconst EXPLICIT_ABORT_TOKEN = Symbol(\n __DEV__\n ? \"This symbol is thrown from a socket's iterator when the connection is explicity aborted by the user\"\n : undefined\n);\n\nexport async function createWebSocketConnection({\n sendBufferHighWatermark,\n signal,\n url,\n}: Config): Promise<RpcWebSocketConnection> {\n return new Promise((resolve, reject) => {\n signal.addEventListener('abort', handleAbort, { once: true });\n const iteratorState: Map<IteratorKey, IteratorState> = new Map();\n function errorAndClearAllIteratorStates(reason: unknown) {\n const errorCallbacks = [...iteratorState.values()]\n .filter((state): state is Extract<IteratorState, { __hasPolled: true }> => state.__hasPolled)\n .map(({ onError }) => onError);\n iteratorState.clear();\n errorCallbacks.forEach(cb => {\n try {\n cb(reason);\n } catch {\n /* empty */\n }\n });\n }\n function handleAbort() {\n errorAndClearAllIteratorStates(EXPLICIT_ABORT_TOKEN);\n if (webSocket.readyState !== WebSocket.CLOSED && webSocket.readyState !== WebSocket.CLOSING) {\n webSocket.close(1000);\n }\n }\n function handleClose(ev: CloseEvent) {\n bufferDrainWatcher?.onCancel();\n signal.removeEventListener('abort', handleAbort);\n webSocket.removeEventListener('close', handleClose);\n webSocket.removeEventListener('error', handleError);\n webSocket.removeEventListener('open', handleOpen);\n webSocket.removeEventListener('message', handleMessage);\n errorAndClearAllIteratorStates(ev);\n }\n function handleError(ev: Event) {\n if (!hasConnected) {\n reject(\n // TODO: Coded error\n new Error('WebSocket failed to connect', { cause: ev })\n );\n }\n }\n let hasConnected = false;\n let bufferDrainWatcher: Readonly<{ onCancel(): void; promise: Promise<void> }> | undefined;\n function handleOpen() {\n hasConnected = true;\n resolve({\n async send(payload: unknown) {\n const message = JSON.stringify(payload);\n if (\n !bufferDrainWatcher &&\n webSocket.readyState === WebSocket.OPEN &&\n webSocket.bufferedAmount > sendBufferHighWatermark\n ) {\n let onCancel: () => void;\n const promise = new Promise<void>((resolve, reject) => {\n const intervalId = setInterval(() => {\n if (\n webSocket.readyState !== WebSocket.OPEN ||\n !(webSocket.bufferedAmount > sendBufferHighWatermark)\n ) {\n clearInterval(intervalId);\n bufferDrainWatcher = undefined;\n resolve();\n }\n }, 16);\n onCancel = () => {\n bufferDrainWatcher = undefined;\n clearInterval(intervalId);\n reject(\n // TODO: Coded error\n new Error('WebSocket was closed before payload could be sent')\n );\n };\n });\n bufferDrainWatcher = {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n onCancel,\n promise,\n };\n }\n if (bufferDrainWatcher) {\n await bufferDrainWatcher.promise;\n }\n webSocket.send(message);\n },\n async *[Symbol.asyncIterator]() {\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new Error('Invariant: WebSocket message iterator is missing state storage');\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new Error(\n 'Invariant: WebSocket message iterator state is corrupt; ' +\n 'iterated without first resolving existing message promise'\n );\n }\n const queuedMessages = state.queuedMessages;\n if (queuedMessages.length) {\n state.queuedMessages = [];\n yield* queuedMessages;\n } else {\n try {\n yield await new Promise((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onError: reject,\n onMessage: resolve,\n });\n });\n } catch (e) {\n if (e === EXPLICIT_ABORT_TOKEN) {\n return;\n } else {\n // TODO: Coded error.\n throw new Error('WebSocket connection closed', { cause: e });\n }\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n });\n }\n function handleMessage({ data }: MessageEvent) {\n const message = JSON.parse(data);\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onMessage } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });\n onMessage(message);\n } else {\n state.queuedMessages.push(message);\n }\n });\n }\n const webSocket = new WebSocket(url);\n webSocket.addEventListener('close', handleClose);\n webSocket.addEventListener('error', handleError);\n webSocket.addEventListener('open', handleOpen);\n webSocket.addEventListener('message', handleMessage);\n });\n}\n","import { IRpcWebSocketTransport } from '../transport-types';\nimport { createWebSocketConnection } from './websocket-connection';\n\ntype Config = Readonly<{\n sendBufferHighWatermark: number;\n url: string;\n}>;\n\nexport function createWebSocketTransport({ sendBufferHighWatermark, url }: Config): IRpcWebSocketTransport {\n if (/^wss?:/i.test(url) === false) {\n const protocolMatch = url.match(/^([^:]+):/);\n throw new DOMException(\n protocolMatch\n ? `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${protocolMatch[1]}:' is not allowed.`\n : `Failed to construct 'WebSocket': The URL '${url}' is invalid.`\n );\n }\n return async function sendWebSocketMessage({ payload, signal }: Parameters<IRpcWebSocketTransport>[0]) {\n signal?.throwIfAborted();\n const connection = await createWebSocketConnection({\n sendBufferHighWatermark,\n signal,\n url,\n });\n signal?.throwIfAborted();\n await connection.send(payload);\n return {\n [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),\n send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: connection.send.bind(connection),\n };\n };\n}\n","import { createSolanaRpcApi } from '@solana/rpc-core';\n\nimport { SolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\nexport const DEFAULT_RPC_CONFIG: Partial<Parameters<typeof createSolanaRpcApi>[0]> = {\n onIntegerOverflow(methodName, keyPath, value) {\n throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);\n },\n};\n","export class SolanaJsonRpcIntegerOverflowError extends Error {\n readonly methodName: string;\n readonly keyPath: (number | string)[];\n readonly value: bigint;\n constructor(methodName: string, keyPath: (number | string)[], value: bigint) {\n const argPosition = (typeof keyPath[0] === 'number' ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;\n let ordinal = '';\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n ordinal = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n ordinal = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n ordinal = argPosition + 'rd';\n } else {\n ordinal = argPosition + 'th';\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : null;\n super(\n `The ${ordinal} argument to the \\`${methodName}\\` RPC method` +\n `${path ? ` at path \\`${path}\\`` : ''} was \\`${value}\\`. This number is ` +\n 'unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.'\n );\n this.keyPath = keyPath;\n this.methodName = methodName;\n this.value = value;\n }\n get name() {\n return 'SolanaJsonRpcIntegerOverflowError';\n }\n}\n","import { PendingRpcSubscription, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { getCachedAbortableIterableFactory } from './cached-abortable-iterable';\n\ntype CacheKey = string | undefined;\ntype Config<TRpcSubscriptionsMethods> = Readonly<{\n getDeduplicationKey: GetDeduplicationKeyFn;\n rpcSubscriptions: RpcSubscriptions<TRpcSubscriptionsMethods>;\n}>;\ntype GetDeduplicationKeyFn = (subscriptionMethod: string | symbol, payload: unknown) => CacheKey;\n\nconst EXPLICIT_ABORT_TOKEN = Symbol(\n __DEV__\n ? \"This symbol is thrown from a subscription's iterator when the subscription is \" +\n 'explicitly aborted by the user'\n : undefined\n);\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nexport function getRpcSubscriptionsWithSubscriptionCoalescing<TRpcSubscriptionsMethods>({\n getDeduplicationKey,\n rpcSubscriptions,\n}: Config<TRpcSubscriptionsMethods>): RpcSubscriptions<TRpcSubscriptionsMethods> {\n const cache = new Map<CacheKey, PendingRpcSubscription<unknown>>();\n return new Proxy(rpcSubscriptions, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n const subscriptionMethod = Reflect.get(target, p, receiver);\n if (typeof subscriptionMethod !== 'function') {\n return subscriptionMethod;\n }\n return function (...rawParams: unknown[]) {\n const deduplicationKey = getDeduplicationKey(p, rawParams);\n if (deduplicationKey === undefined) {\n return (subscriptionMethod as CallableFunction)(...rawParams);\n }\n if (cache.has(deduplicationKey)) {\n return cache.get(deduplicationKey)!;\n }\n const iterableFactory = getCachedAbortableIterableFactory<\n Parameters<PendingRpcSubscription<unknown>['subscribe']>,\n AsyncIterable<unknown>\n >({\n getAbortSignalFromInputArgs: ({ abortSignal }) => abortSignal,\n getCacheEntryMissingError(deduplicationKey) {\n // TODO: Coded error.\n return new Error(\n `Found no cache entry for subscription with deduplication key \\`${deduplicationKey?.toString()}\\``\n );\n },\n getCacheKeyFromInputArgs: () => deduplicationKey,\n async onCacheHit(_iterable, _config) {\n /**\n * This transport's goal is to prevent duplicate subscriptions from\n * being made. If a cached iterable] is found, do not send the subscribe\n * message again.\n */\n },\n async onCreateIterable(abortSignal, config) {\n const pendingSubscription = (subscriptionMethod as CallableFunction)(\n ...rawParams\n ) as PendingRpcSubscription<unknown>;\n const iterable = await pendingSubscription.subscribe({\n ...config,\n abortSignal,\n });\n registerIterableCleanup(iterable, () => {\n cache.delete(deduplicationKey);\n });\n return iterable;\n },\n });\n const pendingSubscription: PendingRpcSubscription<unknown> = {\n async subscribe(...args) {\n const iterable = await iterableFactory(...args);\n const { abortSignal } = args[0];\n let abortPromise;\n return {\n ...iterable,\n async *[Symbol.asyncIterator]() {\n abortPromise ||= abortSignal.aborted\n ? Promise.reject(EXPLICIT_ABORT_TOKEN)\n : new Promise<never>((_, reject) => {\n abortSignal.addEventListener('abort', () => {\n reject(EXPLICIT_ABORT_TOKEN);\n });\n });\n try {\n const iterator = iterable[Symbol.asyncIterator]();\n while (true) {\n const iteratorResult = await Promise.race([iterator.next(), abortPromise]);\n if (iteratorResult.done) {\n return;\n } else {\n yield iteratorResult.value;\n }\n }\n } catch (e) {\n if (e === EXPLICIT_ABORT_TOKEN) {\n return;\n }\n cache.delete(deduplicationKey);\n throw e;\n }\n },\n };\n },\n };\n cache.set(deduplicationKey, pendingSubscription);\n return pendingSubscription;\n };\n },\n });\n}\n","type CacheEntry<TIterable extends AsyncIterable<unknown>> = {\n abortController: AbortController;\n iterable: Promise<TIterable> | TIterable;\n purgeScheduled: boolean;\n referenceCount: number;\n};\ntype CacheKey = string | symbol;\ntype Config<TInput extends unknown[], TIterable extends AsyncIterable<unknown>> = Readonly<{\n getAbortSignalFromInputArgs: (...args: TInput) => AbortSignal;\n getCacheEntryMissingError: (cacheKey: CacheKey) => Error;\n getCacheKeyFromInputArgs: (...args: TInput) =>\n | CacheKey\n // `undefined` implies 'do not cache'\n | undefined;\n onCacheHit: (iterable: TIterable, ...args: TInput) => Promise<void>;\n onCreateIterable: (abortSignal: AbortSignal, ...args: TInput) => Promise<TIterable>;\n}>;\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nexport function getCachedAbortableIterableFactory<TInput extends unknown[], TIterable extends AsyncIterable<unknown>>({\n getAbortSignalFromInputArgs,\n getCacheEntryMissingError,\n getCacheKeyFromInputArgs,\n onCacheHit,\n onCreateIterable,\n}: Config<TInput, TIterable>): (...args: TInput) => Promise<TIterable> {\n const cache = new Map<CacheKey, CacheEntry<TIterable>>();\n function getCacheEntryOrThrow(cacheKey: CacheKey) {\n const currentCacheEntry = cache.get(cacheKey);\n if (!currentCacheEntry) {\n throw getCacheEntryMissingError(cacheKey);\n }\n return currentCacheEntry;\n }\n return async (...args: TInput) => {\n const cacheKey = getCacheKeyFromInputArgs(...args);\n const signal = getAbortSignalFromInputArgs(...args);\n if (cacheKey === undefined) {\n return await onCreateIterable(signal, ...args);\n }\n const cleanup = () => {\n cache.delete(cacheKey);\n signal.removeEventListener('abort', handleAbort);\n };\n const handleAbort = () => {\n const cacheEntry = getCacheEntryOrThrow(cacheKey);\n if (cacheEntry.purgeScheduled !== true) {\n cacheEntry.purgeScheduled = true;\n globalThis.queueMicrotask(() => {\n cacheEntry.purgeScheduled = false;\n if (cacheEntry.referenceCount === 0) {\n cacheEntry.abortController.abort();\n cleanup();\n }\n });\n }\n cacheEntry.referenceCount--;\n };\n signal.addEventListener('abort', handleAbort);\n try {\n const cacheEntry = cache.get(cacheKey);\n if (!cacheEntry) {\n const singletonAbortController = new AbortController();\n const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);\n const newCacheEntry: CacheEntry<TIterable> = {\n abortController: singletonAbortController,\n iterable: newIterablePromise,\n purgeScheduled: false,\n referenceCount: 1,\n };\n cache.set(cacheKey, newCacheEntry);\n const newIterable = await newIterablePromise;\n registerIterableCleanup(newIterable, cleanup);\n newCacheEntry.iterable = newIterable;\n return newIterable;\n } else {\n cacheEntry.referenceCount++;\n const iterableOrIterablePromise = cacheEntry.iterable;\n const cachedIterable =\n 'then' in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;\n await onCacheHit(cachedIterable, ...args);\n return cachedIterable;\n }\n } catch (e) {\n cleanup();\n throw e;\n }\n };\n}\n","import { pipe } from '@solana/functional';\nimport { createHttpTransport } from '@solana/rpc-transport';\nimport { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getRpcTransportWithRequestCoalescing } from './rpc-request-coalescer';\nimport { getSolanaRpcPayloadDeduplicationKey } from './rpc-request-deduplication';\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers.\n */\nfunction normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n\nexport function createDefaultRpcTransport(config: Parameters<typeof createHttpTransport>[0]): IRpcTransport {\n return pipe(\n createHttpTransport({\n ...config,\n headers: {\n ...(config.headers ? normalizeHeaders(config.headers) : undefined),\n ...({\n // Keep these headers lowercase so they will override any user-supplied headers above.\n 'solana-client': `js/${__VERSION__}` ?? 'UNKNOWN',\n } as { [overrideHeader: string]: string }),\n },\n }),\n transport => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)\n );\n}\n","import { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\ntype CoalescedRequest = {\n readonly abortController: AbortController;\n numConsumers: number;\n readonly responsePromise: Promise<unknown>;\n};\n\ntype GetDeduplicationKeyFn = (payload: unknown) => string | undefined;\n\nexport function getRpcTransportWithRequestCoalescing(\n transport: IRpcTransport,\n getDeduplicationKey: GetDeduplicationKeyFn\n): IRpcTransport {\n let coalescedRequestsByDeduplicationKey: Record<string, CoalescedRequest> | undefined;\n return async function makeCoalescedHttpRequest<TResponse>(\n config: Parameters<IRpcTransport>[0]\n ): Promise<TResponse> {\n const { payload, signal } = config;\n const deduplicationKey = getDeduplicationKey(payload);\n if (deduplicationKey === undefined) {\n return await transport(config);\n }\n if (!coalescedRequestsByDeduplicationKey) {\n Promise.resolve().then(() => {\n coalescedRequestsByDeduplicationKey = undefined;\n });\n coalescedRequestsByDeduplicationKey = {};\n }\n if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {\n const abortController = new AbortController();\n coalescedRequestsByDeduplicationKey[deduplicationKey] = {\n abortController,\n numConsumers: 0,\n responsePromise: transport<TResponse>({\n ...config,\n signal: abortController.signal,\n }),\n };\n }\n const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];\n coalescedRequest.numConsumers++;\n if (signal) {\n const responsePromise = coalescedRequest.responsePromise as Promise<TResponse>;\n return await new Promise<TResponse>((resolve, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n signal.removeEventListener('abort', handleAbort);\n coalescedRequest.numConsumers -= 1;\n if (coalescedRequest.numConsumers === 0) {\n const abortController = coalescedRequest.abortController;\n abortController.abort();\n }\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n signal.addEventListener('abort', handleAbort);\n responsePromise.then(resolve).finally(() => {\n signal.removeEventListener('abort', handleAbort);\n });\n });\n } else {\n return (await coalescedRequest.responsePromise) as TResponse;\n }\n };\n}\n","// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\n\nfunction isJsonRpcPayload(payload: unknown): payload is Readonly<{ method: string; params: unknown }> {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n return (\n 'jsonrpc' in payload &&\n payload.jsonrpc === '2.0' &&\n 'method' in payload &&\n typeof payload.method === 'string' &&\n 'params' in payload\n );\n}\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n return isJsonRpcPayload(payload) ? fastStableStringify([payload.method, payload.params]) : undefined;\n}\n","import { pipe } from '@solana/functional';\nimport { createWebSocketTransport } from '@solana/rpc-transport';\nimport { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getWebSocketTransportWithAutoping } from './rpc-websocket-autopinger';\nimport { getWebSocketTransportWithConnectionSharding } from './rpc-websocket-connection-sharding';\n\nexport function createDefaultRpcSubscriptionsTransport(\n config: Omit<Parameters<typeof createWebSocketTransport>[0], 'sendBufferHighWatermark'> & {\n /**\n * You might like to open more subscriptions per connection than your RPC provider allows\n * for. Using the initial payload as input, return a shard key from this method to assign\n * subscriptions to separate connections. One socket will be opened per shard key.\n */\n getShard?: (payload: unknown) => string;\n intervalMs?: number;\n sendBufferHighWatermark?: number;\n }\n): IRpcWebSocketTransport {\n const { getShard, intervalMs, ...rest } = config;\n return pipe(\n createWebSocketTransport({\n ...rest,\n sendBufferHighWatermark:\n config.sendBufferHighWatermark ??\n // Let 128KB of data into the WebSocket buffer before buffering it in the app.\n 131_072,\n }),\n transport =>\n getWebSocketTransportWithAutoping({\n intervalMs: intervalMs ?? 5_000,\n transport,\n }),\n transport =>\n getWebSocketTransportWithConnectionSharding({\n getShard,\n transport,\n })\n );\n}\n","import { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\ntype Config = Readonly<{\n intervalMs: number;\n transport: IRpcWebSocketTransport;\n}>;\n\nconst PING_PAYLOAD = {\n jsonrpc: '2.0',\n method: 'ping',\n} as const;\n\nexport function getWebSocketTransportWithAutoping({ intervalMs, transport }: Config): IRpcWebSocketTransport {\n const pingableConnections = new Map<\n Awaited<ReturnType<IRpcWebSocketTransport>>,\n Awaited<ReturnType<IRpcWebSocketTransport>>\n >();\n return async (...args) => {\n const connection = await transport(...args);\n let intervalId: string | number | NodeJS.Timeout | undefined;\n function sendPing() {\n connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);\n }\n function restartPingTimer() {\n clearInterval(intervalId);\n intervalId = setInterval(sendPing, intervalMs);\n }\n if (pingableConnections.has(connection) === false) {\n pingableConnections.set(connection, {\n [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),\n send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: (\n ...args: Parameters<typeof connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED>\n ) => {\n restartPingTimer();\n return connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(...args);\n },\n });\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of connection) {\n restartPingTimer();\n }\n } catch {\n /* empty */\n } finally {\n pingableConnections.delete(connection);\n clearInterval(intervalId);\n if (handleOffline) {\n globalThis.window.removeEventListener('offline', handleOffline);\n }\n if (handleOnline) {\n globalThis.window.removeEventListener('online', handleOnline);\n }\n }\n })();\n if (!__BROWSER__ || globalThis.navigator.onLine) {\n restartPingTimer();\n }\n let handleOffline;\n let handleOnline;\n if (__BROWSER__) {\n handleOffline = () => {\n clearInterval(intervalId);\n };\n handleOnline = () => {\n sendPing();\n restartPingTimer();\n };\n globalThis.window.addEventListener('offline', handleOffline);\n globalThis.window.addEventListener('online', handleOnline);\n }\n }\n return pingableConnections.get(connection)!;\n };\n}\n","import { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getCachedAbortableIterableFactory } from './cached-abortable-iterable';\n\ntype Config = Readonly<{\n /**\n * You might like to open more subscriptions per connection than your RPC provider allows for.\n * Using the initial payload as input, return a shard key from this method to assign\n * subscriptions to separate connections. One socket will be opened per shard key.\n */\n getShard?: (payload: unknown) => string | symbol;\n transport: IRpcWebSocketTransport;\n}>;\n\nconst NULL_SHARD_CACHE_KEY = Symbol(\n __DEV__ ? 'Cache key to use when there is no connection sharding strategy' : undefined\n);\n\nexport function getWebSocketTransportWithConnectionSharding({ getShard, transport }: Config): IRpcWebSocketTransport {\n return getCachedAbortableIterableFactory({\n getAbortSignalFromInputArgs: ({ signal }) => signal,\n getCacheEntryMissingError(shardKey) {\n // TODO: Coded error.\n return new Error(`Found no cache entry for connection with shard key \\`${shardKey?.toString()}\\``);\n },\n getCacheKeyFromInputArgs: ({ payload }) => (getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY),\n onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),\n onCreateIterable: (abortSignal, config) =>\n transport({\n ...config,\n signal: abortSignal,\n }),\n });\n}\n","import { SendTransactionApi } from '@solana/rpc-core/dist/types/rpc-methods/sendTransaction';\nimport { Rpc } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\nimport {\n BaseTransaction,\n getBase64EncodedWireTransaction,\n IDurableNonceTransaction,\n IFullySignedTransaction,\n ITransactionWithBlockhashLifetime,\n ITransactionWithFeePayer,\n TransactionSignature,\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<TransactionSignature> {\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);\n return (await rpc\n .sendTransaction(base64EncodedWireTransaction, {\n ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),\n encoding: 'base64',\n })\n .send({ abortSignal })) as unknown as TransactionSignature; // FIXME(#1709)\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<TransactionSignature> {\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<TransactionSignature> {\n const transactionSignature = await sendTransaction_INTERNAL({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmRecentTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n","import { Slot } from '@solana/rpc-core/dist/types/rpc-methods/common';\nimport type { GetAccountInfoApi } from '@solana/rpc-core/dist/types/rpc-methods/getAccountInfo';\nimport type { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport type { AccountNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/account-notifications';\nimport type { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport type { SlotNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/slot-notifications';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport {\n getSignatureFromTransaction,\n IDurableNonceTransaction,\n ITransactionWithFeePayer,\n ITransactionWithSignatures,\n} from '@solana/transactions';\n\nimport { createBlockHeightExceedencePromiseFactory } from './transaction-confirmation-strategy-blockheight';\nimport { createNonceInvalidationPromiseFactory } from './transaction-confirmation-strategy-nonce';\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './transaction-confirmation-strategy-racer';\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\n\ninterface DefaultDurableNonceTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi & GetAccountInfoApi>;\n rpcSubscriptions: RpcSubscriptions<AccountNotificationsApi & SignatureNotificationsApi>;\n}\n\ninterface DefaultRecentTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi & SlotNotificationsApi>;\n}\n\ninterface WaitForDurableNonceTransactionConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getNonceInvalidationPromise: ReturnType<typeof createNonceInvalidationPromiseFactory>;\n transaction: ITransactionWithFeePayer & ITransactionWithSignatures & IDurableNonceTransaction;\n}\n\ninterface WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig\n extends BaseTransactionConfirmationStrategyConfig {\n getBlockHeightExceedencePromise: ReturnType<typeof createBlockHeightExceedencePromiseFactory>;\n transaction: ITransactionWithFeePayer &\n ITransactionWithSignatures &\n Readonly<{\n lifetimeConstraint: {\n lastValidBlockHeight: Slot;\n };\n }>;\n}\n\nexport function createDefaultDurableNonceTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultDurableNonceTransactionConfirmerConfig) {\n const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions\n );\n return async function confirmDurableNonceTransaction(\n config: Omit<\n Parameters<typeof waitForDurableNonceTransactionConfirmation>[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >\n ) {\n await waitForDurableNonceTransactionConfirmation({\n ...config,\n getNonceInvalidationPromise,\n getRecentSignatureConfirmationPromise,\n });\n };\n}\n\nexport function createDefaultRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultRecentTransactionConfirmerConfig) {\n const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory(rpcSubscriptions);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions\n );\n return async function confirmRecentTransaction(\n config: Omit<\n Parameters<typeof waitForRecentTransactionConfirmation>[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >\n ) {\n await waitForRecentTransactionConfirmation({\n ...config,\n getBlockHeightExceedencePromise,\n getRecentSignatureConfirmationPromise,\n });\n };\n}\n\nexport async function waitForDurableNonceTransactionConfirmation(\n config: WaitForDurableNonceTransactionConfirmationConfig\n): Promise<void> {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {\n return [\n getNonceInvalidationPromise({\n abortSignal,\n commitment,\n currentNonceValue: transaction.lifetimeConstraint.nonce,\n nonceAccountAddress: transaction.instructions[0].accounts[0].address,\n }),\n ];\n }\n );\n}\n\nexport async function waitForRecentTransactionConfirmation(\n config: WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig\n): Promise<void> {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, getBlockHeightExceedencePromise, transaction }) {\n return [\n getBlockHeightExceedencePromise({\n abortSignal,\n lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight,\n }),\n ];\n }\n );\n}\n","import { Slot } from '@solana/rpc-core/dist/types/rpc-methods/common';\nimport type { SlotNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/slot-notifications';\nimport { RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\ntype GetBlockHeightExceedencePromiseFn = (config: {\n abortSignal: AbortSignal;\n lastValidBlockHeight: Slot;\n}) => Promise<void>;\n\nexport function createBlockHeightExceedencePromiseFactory(\n rpcSubscriptions: RpcSubscriptions<SlotNotificationsApi>\n): GetBlockHeightExceedencePromiseFn {\n return async function getBlockHeightExceedencePromise({ abortSignal: callerAbortSignal, lastValidBlockHeight }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n const slotNotifications = await rpcSubscriptions\n .slotNotifications()\n .subscribe({ abortSignal: abortController.signal });\n try {\n for await (const slotNotification of slotNotifications) {\n if (slotNotification.slot > lastValidBlockHeight) {\n // TODO: Coded error.\n throw new Error(\n 'The network has progressed past the last block for which this transaction ' +\n 'could have committed.'\n );\n }\n }\n } finally {\n abortController.abort();\n }\n };\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport { getBase58Decoder, getBase64Encoder } from '@solana/codecs-strings';\nimport { Base64EncodedDataResponse } from '@solana/rpc-core/dist/types/rpc-methods/common';\nimport { GetAccountInfoApi } from '@solana/rpc-core/dist/types/rpc-methods/getAccountInfo';\nimport { AccountNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/account-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment } from '@solana/rpc-types';\nimport { Nonce } from '@solana/transactions';\n\ntype GetNonceInvalidationPromiseFn = (config: {\n abortSignal: AbortSignal;\n commitment: Commitment;\n currentNonceValue: Nonce;\n nonceAccountAddress: Base58EncodedAddress;\n}) => Promise<void>;\n\nconst NONCE_VALUE_OFFSET =\n 4 + // version(u32)\n 4 + // state(u32)\n 32; // nonce authority(pubkey)\n// Then comes the nonce value.\n\nexport function createNonceInvalidationPromiseFactory(\n rpc: Rpc<GetAccountInfoApi>,\n rpcSubscriptions: RpcSubscriptions<AccountNotificationsApi>\n): GetNonceInvalidationPromiseFn {\n return async function getNonceInvalidationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n currentNonceValue,\n nonceAccountAddress,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for nonce account changes.\n */\n const accountNotifications = await rpcSubscriptions\n .accountNotifications(nonceAccountAddress, { commitment, encoding: 'base64' })\n .subscribe({ abortSignal: abortController.signal });\n const base58Decoder = getBase58Decoder();\n const base64Encoder = getBase64Encoder();\n function getNonceFromAccountData([base64EncodedBytes]: Base64EncodedDataResponse): Nonce {\n const data = base64Encoder.encode(base64EncodedBytes);\n const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);\n return base58Decoder.decode(nonceValueBytes)[0] as Nonce;\n }\n const nonceAccountDidAdvancePromise = (async () => {\n for await (const accountNotification of accountNotifications) {\n const nonceValue = getNonceFromAccountData(accountNotification.value.data);\n if (nonceValue !== currentNonceValue) {\n throw new Error(\n `The nonce \\`${currentNonceValue}\\` is no longer valid. It has advanced ` +\n `to \\`${nonceValue}\\`.`\n );\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current nonce\n * value to check if it has already been advanced.\n */\n const nonceIsAlreadyInvalidPromise = (async () => {\n const { value: nonceAccount } = await rpc\n .getAccountInfo(nonceAccountAddress, {\n commitment,\n dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },\n encoding: 'base58',\n })\n .send({ abortSignal: abortController.signal });\n if (!nonceAccount) {\n throw new Error(`No nonce account could be found at address \\`${nonceAccountAddress}\\`.`);\n }\n const nonceValue =\n // This works because we asked for the exact slice of data representing the nonce\n // value, and furthermore asked for it in `base58` encoding.\n nonceAccount.data[0] as unknown as Nonce;\n if (nonceValue !== currentNonceValue) {\n throw new Error(\n `The nonce \\`${currentNonceValue}\\` is no longer valid. It has advanced to \\`${nonceValue}\\`.`\n );\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n"]}
|