@solana/web3.js 2.0.0-experimental.e09b513 → 2.0.0-experimental.e662875

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1155 -43
  3. package/dist/index.browser.cjs +765 -8
  4. package/dist/index.browser.cjs.map +1 -1
  5. package/dist/index.browser.js +746 -11
  6. package/dist/index.browser.js.map +1 -1
  7. package/dist/index.development.js +2677 -802
  8. package/dist/index.development.js.map +1 -1
  9. package/dist/index.native.js +735 -13
  10. package/dist/index.native.js.map +1 -1
  11. package/dist/index.node.cjs +754 -8
  12. package/dist/index.node.cjs.map +1 -1
  13. package/dist/index.node.js +735 -11
  14. package/dist/index.node.js.map +1 -1
  15. package/dist/index.production.min.js +76 -31
  16. package/dist/types/airdrop-confirmer.d.ts +20 -0
  17. package/dist/types/airdrop-confirmer.d.ts.map +1 -0
  18. package/dist/types/airdrop.d.ts +23 -0
  19. package/dist/types/airdrop.d.ts.map +1 -0
  20. package/dist/types/cached-abortable-iterable.d.ts +11 -0
  21. package/dist/types/cached-abortable-iterable.d.ts.map +1 -0
  22. package/dist/types/index.d.ts +8 -0
  23. package/dist/types/index.d.ts.map +1 -1
  24. package/dist/types/rpc-request-deduplication.d.ts.map +1 -1
  25. package/dist/types/rpc-subscription-coalescer.d.ts +10 -0
  26. package/dist/types/rpc-subscription-coalescer.d.ts.map +1 -0
  27. package/dist/types/rpc-transport.d.ts.map +1 -1
  28. package/dist/types/rpc-websocket-autopinger.d.ts +8 -0
  29. package/dist/types/rpc-websocket-autopinger.d.ts.map +1 -0
  30. package/dist/types/rpc-websocket-connection-sharding.d.ts +13 -0
  31. package/dist/types/rpc-websocket-connection-sharding.d.ts.map +1 -0
  32. package/dist/types/rpc-websocket-transport.d.ts +13 -0
  33. package/dist/types/rpc-websocket-transport.d.ts.map +1 -0
  34. package/dist/types/rpc.d.ts +5 -3
  35. package/dist/types/rpc.d.ts.map +1 -1
  36. package/dist/types/send-transaction.d.ts +38 -0
  37. package/dist/types/send-transaction.d.ts.map +1 -0
  38. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts +10 -0
  39. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts.map +1 -0
  40. package/dist/types/transaction-confirmation-strategy-nonce.d.ts +15 -0
  41. package/dist/types/transaction-confirmation-strategy-nonce.d.ts.map +1 -0
  42. package/dist/types/transaction-confirmation-strategy-racer.d.ts +14 -0
  43. package/dist/types/transaction-confirmation-strategy-racer.d.ts.map +1 -0
  44. package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts +13 -0
  45. package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts.map +1 -0
  46. package/dist/types/transaction-confirmation-strategy-timeout.d.ts +8 -0
  47. package/dist/types/transaction-confirmation-strategy-timeout.d.ts.map +1 -0
  48. package/dist/types/transaction-confirmation.d.ts +37 -0
  49. package/dist/types/transaction-confirmation.d.ts.map +1 -0
  50. package/package.json +21 -18
@@ -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","../../addresses/dist/index.browser.js","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/fixSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/mapSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/baseX.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/base58.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/nullCharacters.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/utf8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/index.mjs","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/common.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u32.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/shortU16.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/sumSerializerSizes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/array.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/string.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/src/struct.ts","../../assertions/src/subtle-crypto.ts","../../instructions/src/roles.ts","../../keys/src/key-pair.ts","../../keys/src/signatures.ts","../../transactions/src/unsigned-transaction.ts","../../transactions/src/blockhash.ts","../../transactions/src/create-transaction.ts","../../transactions/src/durable-nonce.ts","../../transactions/src/fee-payer.ts","../../transactions/src/instructions.ts","../../transactions/src/signatures.ts","../../transactions/src/accounts.ts","../../transactions/src/compile-address-table-lookups.ts","../../transactions/src/compile-header.ts","../../transactions/src/compile-instructions.ts","../../transactions/src/compile-lifetime-token.ts","../../transactions/src/compile-static-accounts.ts","../../transactions/src/message.ts","../../transactions/src/serializers/message.ts","../../transactions/src/serializers/address-table-lookup.ts","../../transactions/src/serializers/header.ts","../../transactions/src/serializers/instruction.ts","../../transactions/src/serializers/unimplemented.ts","../../transactions/src/serializers/transaction-version.ts","../../transactions/src/serializers/transaction.ts","../../transactions/src/compile-transaction.ts","../src/rpc.ts","../../rpc-core/src/params-patcher.ts","../../rpc-core/src/response-patcher-allowed-numeric-values.ts","../../rpc-core/src/response-patcher.ts","../../rpc-core/src/rpc-methods/index.ts","../../rpc-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","../../ws-impl/src/index.browser.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":["mergeBytes","bytesArr","totalLength","reduce","total","arr","length","result","Uint8Array","offset","forEach","set","padBytes","bytes","paddedBytes","fill","fixBytes","slice","DeserializingEmptyBufferError","Error","constructor","serializer","name","NotEnoughBytesError","expected","actual","ExpectedFixedSizeSerializerError","message","fixSerializer","fixedBytes","description","fixedSize","maxSize","serialize","value","deserialize","buffer","mapSerializer","unmap","map","InvalidBaseStringError","base","cause","baseX","alphabet","baseBigInt","BigInt","match","RegExp","chars","trailIndex","findIndex","c","leadingZeroes","Array","from","tailChars","base10Number","baseXPower","i","indexOf","tailBytes","unshift","Number","concat","n","repeat","sum","byte","join","base58","removeNullCharacters","replace","utf8","TextEncoder","encode","TextDecoder","decode","Endian","NumberOutOfRangeError","RangeError","min","max","numberFactory","input","littleEndian","defaultDescription","size","options","endian","Little","range","assertRange","ArrayBuffer","DataView","assertEnoughBytes","view","toDataView","get","toArrayBuffer","array","byteOffset","byteLength","u8","setUint8","getUint8","u32","le","setUint32","getUint32","shortU16","ii","alignedValue","nextSevenBits","byteCount","byteIndex","currentByte","InvalidNumberOfItemsError","InvalidArrayLikeRemainderSizeError","remainderSize","itemSize","UnrecognizedArrayLikeSerializerSizeError","JSON","stringify","sumSerializerSizes","sizes","all","getResolvedSize","childrenSizes","childrenSize","remainder","getSizeDescription","getSizeFromChildren","getSizePrefix","realSize","item","v","resolvedSize","newOffset","values","push","byteSerializer","contentBytes","lengthBytes","lengthBigInt","lengthOffset","contentBuffer","contentOffset","string","encoding","struct","fields","fieldDescriptions","String","field","fieldBytes","key","__DEV__","e","AccountRole","AccountRole2","IS_WRITABLE_BITMASK","isSignerRole","isWritableRole","mergeRoles","getBase58EncodedAddressComparator","BASE_CONFIG","visitNode","index_browser_default","fastStableStringify","normalizeHeaders"],"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;AAAA,YACd,WAAW,UAAU,mBAAmB;AAEvC,qBAAO,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ever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","var objToString = Object.prototype.toString;\nvar objKeys = Object.keys || function(obj) {\n\t\tvar keys = [];\n\t\tfor (var name in obj) {\n\t\t\tkeys.push(name);\n\t\t}\n\t\treturn keys;\n\t};\n\nfunction stringify(val, isArrayProp) {\n\tvar i, max, str, keys, key, propVal, toStr;\n\tif (val === true) {\n\t\treturn \"true\";\n\t}\n\tif (val === false) {\n\t\treturn \"false\";\n\t}\n\tswitch (typeof val) {\n\t\tcase \"object\":\n\t\t\tif (val === null) {\n\t\t\t\treturn null;\n\t\t\t} else if (val.toJSON && typeof val.toJSON === \"function\") {\n\t\t\t\treturn stringify(val.toJSON(), isArrayProp);\n\t\t\t} else {\n\t\t\t\ttoStr = objToString.call(val);\n\t\t\t\tif (toStr === \"[object Array]\") {\n\t\t\t\t\tstr = '[';\n\t\t\t\t\tmax = val.length - 1;\n\t\t\t\t\tfor(i = 0; i < max; i++) {\n\t\t\t\t\t\tstr += stringify(val[i], true) + ',';\n\t\t\t\t\t}\n\t\t\t\t\tif (max > -1) {\n\t\t\t\t\t\tstr += stringify(val[i], true);\n\t\t\t\t\t}\n\t\t\t\t\treturn str + ']';\n\t\t\t\t} else if (toStr === \"[object Object]\") {\n\t\t\t\t\t// only object is left\n\t\t\t\t\tkeys = objKeys(val).sort();\n\t\t\t\t\tmax = keys.length;\n\t\t\t\t\tstr = \"\";\n\t\t\t\t\ti = 0;\n\t\t\t\t\twhile (i < max) {\n\t\t\t\t\t\tkey = keys[i];\n\t\t\t\t\t\tpropVal = stringify(val[key], false);\n\t\t\t\t\t\tif (propVal !== undefined) {\n\t\t\t\t\t\t\tif (str) {\n\t\t\t\t\t\t\t\tstr += ',';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstr += JSON.stringify(key) + ':' + propVal;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\treturn '{' + str + '}';\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON.stringify(val);\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"function\":\n\t\tcase \"undefined\":\n\t\t\treturn isArrayProp ? null : undefined;\n\t\tcase \"string\":\n\t\t\treturn JSON.stringify(val);\n\t\tdefault:\n\t\t\treturn isFinite(val) ? val : null;\n\t}\n}\n\nmodule.exports = function(val) {\n\tvar returnVal = stringify(val, false);\n\tif (returnVal !== undefined) {\n\t\treturn ''+ returnVal;\n\t}\n};\n","export * from '@solana/addresses';\nexport * from '@solana/instructions';\nexport * from '@solana/keys';\nexport * from '@solana/transactions';\nexport * from './rpc';\nexport * from './rpc-transport';\n","import { base58, string } from '@metaplex-foundation/umi-serializers';\nimport { assertKeyExporterIsAvailable, assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\n// ../build-scripts/env-shim.ts\nvar __DEV__ = /* @__PURE__ */ (() => process[\"env\"].NODE_ENV === \"development\")();\nfunction assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {\n try {\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 || // 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 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}\nfunction getBase58EncodedAddressCodec(config) {\n return string({\n description: config?.description ?? (__DEV__ ? \"A 32-byte account address\" : \"\"),\n encoding: base58,\n size: 32\n });\n}\nfunction getBase58EncodedAddressComparator() {\n return new Intl.Collator(\"en\", {\n caseFirst: \"lower\",\n ignorePunctuation: false,\n localeMatcher: \"best fit\",\n numeric: false,\n sensitivity: \"variant\",\n usage: \"sort\"\n }).compare;\n}\n\n// src/vendor/noble/ed25519.ts\nvar D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nvar P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;\nvar RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;\nfunction mod(a) {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x, power) {\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x) {\n const x2 = x * x % P;\n const b2 = x2 * x % P;\n const b4 = pow2(b2, 2n) * b2 % P;\n const b5 = pow2(b4, 1n) * x % P;\n const b10 = pow2(b5, 5n) * b5 % P;\n const b20 = pow2(b10, 10n) * b10 % P;\n const b40 = pow2(b20, 20n) * b20 % P;\n const b80 = pow2(b40, 40n) * b40 % P;\n const b160 = pow2(b80, 80n) * b80 % P;\n const b240 = pow2(b160, 80n) * b80 % P;\n const b250 = pow2(b240, 10n) * b10 % P;\n const pow_p_5_8 = pow2(b250, 2n) * x % P;\n return pow_p_5_8;\n}\nfunction uvRatio(u, v) {\n const v3 = mod(v * v * v);\n const v7 = mod(v3 * v3 * v);\n const pow = pow_2_252_3(u * v7);\n let x = mod(u * v3 * pow);\n const vx2 = mod(v * x * x);\n const root1 = x;\n const root2 = mod(x * RM1);\n const useRoot1 = vx2 === u;\n const useRoot2 = vx2 === mod(-u);\n const noRoot = vx2 === mod(-u * RM1);\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2;\n if ((mod(x) & 1n) === 1n)\n x = mod(-x);\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\nfunction pointIsOnCurve(y, lastByte) {\n const y2 = mod(y * y);\n const u = mod(y2 - 1n);\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v);\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 128) !== 0;\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n\n// src/curve.ts\nfunction byteToHex(byte) {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\nfunction decompressPointBytes(bytes) {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, \"\");\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\nasync function compressedPointBytesAreOnCurve(bytes) {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n\n// src/computed-address.ts\nvar MAX_SEED_LENGTH = 32;\nvar MAX_SEEDS = 16;\nvar PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80,\n 114,\n 111,\n 103,\n 114,\n 97,\n 109,\n 68,\n 101,\n 114,\n 105,\n 118,\n 101,\n 100,\n 65,\n 100,\n 100,\n 114,\n 101,\n 115,\n 115\n];\nvar PointOnCurveError = class extends Error {\n};\nasync function createProgramDerivedAddress({ programAddress, seeds }) {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === \"string\" ? (textEncoder || (textEncoder = new TextEncoder())).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, []);\n const base58EncodedAddressCodec = getBase58EncodedAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.serialize(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n \"SHA-256\",\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n throw new PointOnCurveError(\"Invalid seeds; point must fall off the Ed25519 curve\");\n }\n return base58EncodedAddressCodec.deserialize(addressBytes)[0];\n}\nasync function getProgramDerivedAddress({ programAddress, seeds }) {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n return {\n bumpSeed,\n pda: await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])]\n })\n };\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n throw new Error(\"Unable to find a viable program address bump seed\");\n}\nasync function createAddressWithSeed({\n baseAddress,\n programAddress,\n seed\n}) {\n const { serialize, deserialize } = getBase58EncodedAddressCodec();\n const seedBytes = typeof seed === \"string\" ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n const programAddressBytes = serialize(programAddress);\n if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n const addressBytesBuffer = await crypto.subtle.digest(\n \"SHA-256\",\n new Uint8Array([...serialize(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n return deserialize(addressBytes)[0];\n}\nasync function getAddressFromPublicKey(publicKey) {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== \"public\" || publicKey.algorithm.name !== \"Ed25519\") {\n throw new Error(\"The `CryptoKey` must be an `Ed25519` public key\");\n }\n const publicKeyBytes = await crypto.subtle.exportKey(\"raw\", publicKey);\n const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n\nexport { assertIsBase58EncodedAddress, createAddressWithSeed, getAddressFromPublicKey, getBase58EncodedAddressCodec, getBase58EncodedAddressComparator, getProgramDerivedAddress };\n","export * from '@metaplex-foundation/umi-serializers-core';\nexport * from '@metaplex-foundation/umi-serializers-encodings';\nexport * from '@metaplex-foundation/umi-serializers-numbers';\nexport { array } from './array.mjs';\nexport { bitArray } from './bitArray.mjs';\nexport { bool } from './bool.mjs';\nexport { bytes } from './bytes.mjs';\nexport { dataEnum } from './dataEnum.mjs';\nexport { EnumDiscriminatorOutOfRangeError, InvalidArrayLikeRemainderSizeError, InvalidDataEnumVariantError, InvalidNumberOfItemsError, InvalidScalarEnumVariantError, UnrecognizedArrayLikeSerializerSizeError } from './errors.mjs';\nexport { map } from './map.mjs';\nexport { nullable } from './nullable.mjs';\nexport { option } from './option.mjs';\nexport { publicKey } from './publicKey.mjs';\nexport { scalarEnum } from './scalarEnum.mjs';\nexport { set } from './set.mjs';\nexport { string } from './string.mjs';\nexport { struct } from './struct.mjs';\nexport { tuple } from './tuple.mjs';\nexport { unit } from './unit.mjs';\nexport { maxSerializerSizes } from './maxSerializerSizes.mjs';\nexport { sumSerializerSizes } from './sumSerializerSizes.mjs';\n//# sourceMappingURL=index.mjs.map\n","export { fixBytes, mergeBytes, padBytes } from './bytes.mjs';\nexport { DeserializingEmptyBufferError, ExpectedFixedSizeSerializerError, NotEnoughBytesError } from './errors.mjs';\nexport { fixSerializer } from './fixSerializer.mjs';\nexport { mapSerializer } from './mapSerializer.mjs';\nexport { reverseSerializer } from './reverseSerializer.mjs';\n//# sourceMappingURL=index.mjs.map\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * @category Utils\n */\nexport const mergeBytes = (bytesArr: Uint8Array[]): Uint8Array => {\n const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n bytesArr.forEach((arr) => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n * @category Utils\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n * @category Utils\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.slice(0, length), length);\n","/** @category Errors */\nexport class DeserializingEmptyBufferError extends Error {\n readonly name: string = 'DeserializingEmptyBufferError';\n\n constructor(serializer: string) {\n super(`Serializer [${serializer}] cannot deserialize empty buffers.`);\n }\n}\n\n/** @category Errors */\nexport class NotEnoughBytesError extends Error {\n readonly name: string = 'NotEnoughBytesError';\n\n constructor(\n serializer: string,\n expected: bigint | number,\n actual: bigint | number\n ) {\n super(\n `Serializer [${serializer}] expected ${expected} bytes, got ${actual}.`\n );\n }\n}\n\n/** @category Errors */\nexport class ExpectedFixedSizeSerializerError extends Error {\n readonly name: string = 'ExpectedFixedSizeSerializerError';\n\n constructor(message?: string) {\n message ??= 'Expected a fixed-size serializer, got a variable-size one.';\n super(message);\n }\n}\n","import { fixBytes } from './bytes';\nimport { Serializer } from './common';\nimport { NotEnoughBytesError } from './errors';\n\n/**\n * Creates a fixed-size serializer from a given serializer.\n *\n * @param serializer - The serializer to wrap into a fixed-size serializer.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the serializer.\n *\n * @category Serializers\n */\nexport function fixSerializer<T, U extends T = T>(\n serializer: Serializer<T, U>,\n fixedBytes: number,\n description?: string\n): Serializer<T, U> {\n return {\n description:\n description ?? `fixed(${fixedBytes}, ${serializer.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n serialize: (value: T) => fixBytes(serializer.serialize(value), fixedBytes),\n deserialize: (buffer: Uint8Array, offset = 0) => {\n // Slice the buffer to the fixed size.\n buffer = buffer.slice(offset, offset + fixedBytes);\n // Ensure we have enough bytes.\n if (buffer.length < fixedBytes) {\n throw new NotEnoughBytesError(\n 'fixSerializer',\n fixedBytes,\n buffer.length\n );\n }\n // If the nested serializer is fixed-size, pad and truncate the buffer accordingly.\n if (serializer.fixedSize !== null) {\n buffer = fixBytes(buffer, serializer.fixedSize);\n }\n // Deserialize the value using the nested serializer.\n const [value] = serializer.deserialize(buffer, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n","import { Serializer } from './common';\n\n/**\n * Converts a serializer A to a serializer B by mapping their values.\n * @category Serializers\n */\nexport function mapSerializer<NewFrom, OldFrom, To extends NewFrom & OldFrom>(\n serializer: Serializer<OldFrom, To>,\n unmap: (value: NewFrom) => OldFrom\n): Serializer<NewFrom, To>;\nexport function mapSerializer<\n NewFrom,\n OldFrom,\n NewTo extends NewFrom = NewFrom,\n OldTo extends OldFrom = OldFrom\n>(\n serializer: Serializer<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map: (value: OldTo, buffer: Uint8Array, offset: number) => NewTo\n): Serializer<NewFrom, NewTo>;\nexport function mapSerializer<\n NewFrom,\n OldFrom,\n NewTo extends NewFrom = NewFrom,\n OldTo extends OldFrom = OldFrom\n>(\n serializer: Serializer<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map?: (value: OldTo, buffer: Uint8Array, offset: number) => NewTo\n): Serializer<NewFrom, NewTo> {\n return {\n description: serializer.description,\n fixedSize: serializer.fixedSize,\n maxSize: serializer.maxSize,\n serialize: (value: NewFrom) => serializer.serialize(unmap(value)),\n deserialize: (buffer: Uint8Array, offset = 0) => {\n const [value, length] = serializer.deserialize(buffer, offset);\n return map\n ? [map(value, buffer, offset), length]\n : [value as any, length];\n },\n };\n}\n","export { base10 } from './base10.mjs';\nexport { base16 } from './base16.mjs';\nexport { base58 } from './base58.mjs';\nexport { base64 } from './base64.mjs';\nexport { baseX } from './baseX.mjs';\nexport { InvalidBaseStringError } from './errors.mjs';\nexport { padNullCharacters, removeNullCharacters } from './nullCharacters.mjs';\nexport { utf8 } from './utf8.mjs';\n//# sourceMappingURL=index.mjs.map\n","/** @category Errors */\nexport class InvalidBaseStringError extends Error {\n readonly name: string = 'InvalidBaseStringError';\n\n readonly cause?: Error;\n\n constructor(value: string, base: number, cause?: Error) {\n const message = `Expected a string of base ${base}, got [${value}].`;\n super(message);\n this.cause = cause;\n }\n}\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { InvalidBaseStringError } from './errors';\n\n/**\n * A string serializer that uses a custom alphabet.\n * This can be used to create serializers for base58, base64, etc.\n * @category Serializers\n */\nexport const baseX = (alphabet: string): Serializer<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n serialize(value: string): Uint8Array {\n // Check if the value is valid.\n if (!value.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new InvalidBaseStringError(value, base);\n }\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex((c) => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n deserialize(buffer, offset = 0): [string, number] {\n if (buffer.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n const bytes = buffer.slice(offset);\n let trailIndex = bytes.findIndex((n) => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, buffer.length];\n\n // From bytes to base10.\n let base10Number = bytes\n .slice(trailIndex)\n .reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), buffer.length];\n },\n };\n};\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { baseX } from './baseX';\n\n/**\n * A string serializer that uses base58 encoding.\n * @category Serializers\n */\nexport const base58: Serializer<string> = baseX(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n","/**\n * Removes null characters from a string.\n * @category Utils\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters at the end.\n * @category Utils\n */\nexport const padNullCharacters = (value: string, chars: number) =>\n value.padEnd(chars, '\\u0000');\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { removeNullCharacters } from './nullCharacters';\n\n/**\n * A string serializer that uses UTF-8 encoding\n * using the native `TextEncoder` API.\n * @category Serializers\n */\nexport const utf8: Serializer<string> = {\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n serialize(value: string) {\n return new TextEncoder().encode(value);\n },\n deserialize(buffer, offset = 0) {\n const value = new TextDecoder().decode(buffer.slice(offset));\n return [removeNullCharacters(value), buffer.length];\n },\n};\n","export { Endian } from './common.mjs';\nexport { NumberOutOfRangeError } from './errors.mjs';\nexport { f32 } from './f32.mjs';\nexport { f64 } from './f64.mjs';\nexport { i8 } from './i8.mjs';\nexport { i16 } from './i16.mjs';\nexport { i32 } from './i32.mjs';\nexport { i64 } from './i64.mjs';\nexport { i128 } from './i128.mjs';\nexport { u8 } from './u8.mjs';\nexport { u16 } from './u16.mjs';\nexport { u32 } from './u32.mjs';\nexport { u64 } from './u64.mjs';\nexport { u128 } from './u128.mjs';\nexport { shortU16 } from './shortU16.mjs';\n//# sourceMappingURL=index.mjs.map\n","import {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\n\n/**\n * Defines a serializer for numbers and bigints.\n * @category Serializers\n */\nexport type NumberSerializer =\n | Serializer<number>\n | Serializer<number | bigint, bigint>;\n\n/**\n * Defines the options for u8 and i8 serializers.\n * @category Serializers\n */\nexport type SingleByteNumberSerializerOptions = BaseSerializerOptions;\n\n/**\n * Defines the options for number serializers that use more than one byte.\n * @category Serializers\n */\nexport type NumberSerializerOptions = BaseSerializerOptions & {\n /**\n * Whether the serializer should use little-endian or big-endian encoding.\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the endianness of a number serializer.\n * @category Serializers\n */\nexport enum Endian {\n Little = 'le',\n Big = 'be',\n}\n","/** @category Errors */\nexport class NumberOutOfRangeError extends RangeError {\n readonly name: string = 'NumberOutOfRangeError';\n\n constructor(\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n actual: number | bigint\n ) {\n super(\n `Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`\n );\n }\n}\n","import {\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport {\n Endian,\n NumberSerializer,\n NumberSerializerOptions,\n SingleByteNumberSerializerOptions,\n} from './common';\nimport { NumberOutOfRangeError } from './errors';\n\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number | bigint, bigint>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number | bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): NumberSerializer {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian =\n !('endian' in input.options) || input.options.endian === Endian.Little;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n maxSize: input.size,\n serialize(value: number | bigint): Uint8Array {\n if (input.range) {\n assertRange(input.name, input.range[0], input.range[1], value);\n }\n const buffer = new ArrayBuffer(input.size);\n input.set(new DataView(buffer), value, littleEndian);\n return new Uint8Array(buffer);\n },\n deserialize(bytes, offset = 0): [number | bigint, number] {\n const slice = bytes.slice(offset, offset + input.size);\n assertEnoughBytes('i8', slice, input.size);\n const view = toDataView(slice);\n return [input.get(view, littleEndian), offset + input.size];\n },\n } as NumberSerializer;\n}\n\n/**\n * Helper function to ensure that the array buffer is converted properly from a uint8array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n * @param {Uint8Array} array Uint8array that's being converted into an array buffer\n * @returns {ArrayBuffer} An array buffer that's necessary to construct a data view\n */\nexport const toArrayBuffer = (array: Uint8Array): ArrayBuffer =>\n array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);\n\nexport const toDataView = (array: Uint8Array): DataView =>\n new DataView(toArrayBuffer(array));\n\nexport const assertRange = (\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) => {\n if (value < min || value > max) {\n throw new NumberOutOfRangeError(serializer, min, max, value);\n }\n};\n\nexport const assertEnoughBytes = (\n serializer: string,\n bytes: Uint8Array,\n expected: number\n) => {\n if (bytes.length === 0) {\n throw new DeserializingEmptyBufferError(serializer);\n }\n if (bytes.length < expected) {\n throw new NotEnoughBytesError(serializer, expected, bytes.length);\n }\n};\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { SingleByteNumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u8 = (\n options: SingleByteNumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u8',\n size: 1,\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n get: (view) => view.getUint8(0),\n options,\n });\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u32 = (\n options: NumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u32',\n size: 4,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n get: (view, le) => view.getUint32(0, le),\n options,\n });\n","/* eslint-disable no-bitwise */\nimport {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { assertRange } from './utils';\n\n/**\n * Defines the options for the shortU16 serializer.\n * @category Serializers\n */\nexport type ShortU16SerializerOptions = BaseSerializerOptions;\n\n/**\n * Same as u16, but serialized with 1 to 3 bytes.\n *\n * If the value is above 0x7f, the top bit is set and the remaining\n * value is stored in the next bytes. Each byte follows the same\n * pattern until the 3rd byte. The 3rd byte, if needed, uses\n * all 8 bits to store the last byte of the original value.\n *\n * @category Serializers\n */\nexport const shortU16 = (\n options: ShortU16SerializerOptions = {}\n): Serializer<number> => ({\n description: options.description ?? 'shortU16',\n fixedSize: null,\n maxSize: 3,\n serialize: (value: number): Uint8Array => {\n assertRange('shortU16', 0, 65535, value);\n const bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = value >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n bytes[ii - 1] |= 0b10000000;\n }\n }\n return new Uint8Array(bytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0): [number, number] => {\n let value = 0;\n let byteCount = 0;\n while (\n ++byteCount // eslint-disable-line no-plusplus\n ) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n});\n","/** @category Errors */\nexport class InvalidNumberOfItemsError extends Error {\n readonly name = 'InvalidNumberOfItemsError';\n\n constructor(\n serializer: string,\n expected: number | bigint,\n actual: number | bigint\n ) {\n super(`Expected [${serializer}] to have ${expected} items, got ${actual}.`);\n }\n}\n\n/** @category Errors */\nexport class InvalidArrayLikeRemainderSizeError extends Error {\n readonly name = 'InvalidArrayLikeRemainderSizeError';\n\n constructor(remainderSize: number | bigint, itemSize: number | bigint) {\n super(\n `The remainder of the buffer (${remainderSize} bytes) cannot be split into chunks of ${itemSize} bytes. ` +\n `Serializers of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainderSize} modulo ${itemSize} should be equal to zero.`\n );\n }\n}\n\n/** @category Errors */\nexport class UnrecognizedArrayLikeSerializerSizeError extends Error {\n readonly name = 'UnrecognizedArrayLikeSerializerSizeError';\n\n constructor(size: never) {\n super(`Unrecognized array-like serializer size: ${JSON.stringify(size)}`);\n }\n}\n\n/** @category Errors */\nexport class InvalidDataEnumVariantError extends Error {\n readonly name = 'InvalidDataEnumVariantError';\n\n constructor(invalidVariant: string, validVariants: string[]) {\n super(\n `Invalid data enum variant. ` +\n `Expected one of [${validVariants.join(', ')}], ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class InvalidScalarEnumVariantError extends Error {\n readonly name = 'InvalidScalarEnumVariantError';\n\n constructor(\n invalidVariant: string | number | bigint,\n validVariants: string[],\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Invalid scalar enum variant. ` +\n `Expected one of [${validVariants.join(', ')}] ` +\n `or a number between ${min} and ${max}, ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class EnumDiscriminatorOutOfRangeError extends RangeError {\n readonly name = 'EnumDiscriminatorOutOfRangeError';\n\n constructor(\n discriminator: number | bigint,\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Enum discriminator out of range. ` +\n `Expected a number between ${min} and ${max}, got ${discriminator}.`\n );\n }\n}\n","export function sumSerializerSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : all + size),\n 0 as number | null\n );\n}\n","import { ExpectedFixedSizeSerializerError } from '@metaplex-foundation/umi-serializers-core';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport {\n InvalidArrayLikeRemainderSizeError,\n UnrecognizedArrayLikeSerializerSizeError,\n} from './errors';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\nexport function getResolvedSize(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: number\n): [number | bigint, number] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.deserialize(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumSerializerSizes(childrenSizes);\n if (childrenSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n throw new InvalidArrayLikeRemainderSizeError(remainder, childrenSize);\n }\n return [remainder / childrenSize, offset];\n }\n\n throw new UnrecognizedArrayLikeSerializerSizeError(size);\n}\n\nexport function getSizeDescription(\n size: ArrayLikeSerializerSize | string\n): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getSizeFromChildren(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumSerializerSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getSizePrefix(\n size: ArrayLikeSerializerSize,\n realSize: number\n): Uint8Array {\n return typeof size === 'object' ? size.serialize(realSize) : new Uint8Array();\n}\n","import {\n BaseSerializerOptions,\n ExpectedFixedSizeSerializerError,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { u32 } from '@metaplex-foundation/umi-serializers-numbers';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport { InvalidNumberOfItemsError } from './errors';\nimport {\n getResolvedSize,\n getSizeDescription,\n getSizeFromChildren,\n getSizePrefix,\n} from './utils';\n\n/**\n * Defines the options for array serializers.\n * @category Serializers\n */\nexport type ArraySerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the array.\n * @defaultValue `u32()`\n */\n size?: ArrayLikeSerializerSize;\n};\n\n/**\n * Creates a serializer for an array of items.\n *\n * @param item - The serializer to use for the array's items.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function array<T, U extends T = T>(\n item: Serializer<T, U>,\n options: ArraySerializerOptions = {}\n): Serializer<T[], U[]> {\n const size = options.size ?? u32();\n if (size === 'remainder' && item.fixedSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n return {\n description:\n options.description ??\n `array(${item.description}; ${getSizeDescription(size)})`,\n fixedSize: getSizeFromChildren(size, [item.fixedSize]),\n maxSize: getSizeFromChildren(size, [item.maxSize]),\n serialize: (value: T[]) => {\n if (typeof size === 'number' && value.length !== size) {\n throw new InvalidNumberOfItemsError('array', size, value.length);\n }\n return mergeBytes([\n getSizePrefix(size, value.length),\n ...value.map((v) => item.serialize(v)),\n ]);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = getResolvedSize(\n size,\n [item.fixedSize],\n bytes,\n offset\n );\n offset = newOffset;\n const values: U[] = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.deserialize(bytes, offset);\n values.push(value);\n offset = newOffset;\n }\n return [values, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializer } from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for bytes serializers.\n * @category Serializers\n */\nexport type BytesSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the buffer. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the buffer with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `'variable'`\n */\n size?: NumberSerializer | number | 'variable';\n};\n\n/**\n * Creates a serializer that passes the buffer as-is.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function bytes(\n options: BytesSerializerOptions = {}\n): Serializer<Uint8Array> {\n const size = options.size ?? 'variable';\n const description =\n options.description ?? `bytes(${getSizeDescription(size)})`;\n\n const byteSerializer: Serializer<Uint8Array> = {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => new Uint8Array(value),\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n };\n\n if (size === 'variable') {\n return byteSerializer;\n }\n\n if (typeof size === 'number') {\n return fixSerializer(byteSerializer, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => {\n const contentBytes = byteSerializer.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('bytes');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('bytes', length, contentBuffer.length);\n }\n const [value, contentOffset] = byteSerializer.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { utf8 } from '@metaplex-foundation/umi-serializers-encodings';\nimport {\n NumberSerializer,\n u32,\n} from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for string serializers.\n * @category Serializers\n */\nexport type StringSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `u32()`\n */\n size?: NumberSerializer | number | 'variable';\n /**\n * The string serializer to use for encoding and decoding the content.\n * @defaultValue `utf8`\n */\n encoding?: Serializer<string>;\n};\n\n/**\n * Creates a string serializer.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function string(\n options: StringSerializerOptions = {}\n): Serializer<string> {\n const size = options.size ?? u32();\n const encoding = options.encoding ?? utf8;\n const description =\n options.description ??\n `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixSerializer(encoding, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: string) => {\n const contentBytes = encoding.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('string');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('string', length, contentBuffer.length);\n }\n const [value, contentOffset] = encoding.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\n/**\n * Get the name and serializer of each field in a struct.\n * @category Serializers\n */\nexport type StructToSerializerTuple<T extends object, U extends T> = Array<\n {\n [K in keyof T]: [K, Serializer<T[K], U[K]>];\n }[keyof T]\n>;\n\n/**\n * Defines the options for struct serializers.\n * @category Serializers\n */\nexport type StructSerializerOptions = BaseSerializerOptions;\n\n/**\n * Creates a serializer for a custom object.\n *\n * @param fields - The name and serializer of each field.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function struct<T extends object, U extends T = T>(\n fields: StructToSerializerTuple<T, U>,\n options: StructSerializerOptions = {}\n): Serializer<T, U> {\n const fieldDescriptions = fields\n .map(([name, serializer]) => `${String(name)}: ${serializer.description}`)\n .join(', ');\n return {\n description: options.description ?? `struct(${fieldDescriptions})`,\n fixedSize: sumSerializerSizes(fields.map(([, field]) => field.fixedSize)),\n maxSize: sumSerializerSizes(fields.map(([, field]) => field.maxSize)),\n serialize: (struct: T) => {\n const fieldBytes = fields.map(([key, serializer]) =>\n serializer.serialize(struct[key])\n );\n return mergeBytes(fieldBytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const struct: Partial<U> = {};\n fields.forEach(([key, serializer]) => {\n const [value, newOffset] = serializer.deserialize(bytes, offset);\n offset = newOffset;\n struct[key] = value;\n });\n return [struct as U, offset];\n },\n };\n}\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","/**\n * Quick primer on bitwise operations: https://stackoverflow.com/a/1436448/802047\n */\n\nexport enum AccountRole {\n // Bitflag guide: is signer ⌄⌄ is writable\n WRITABLE_SIGNER = /* 3 */ 0b11, // prettier-ignore\n READONLY_SIGNER = /* 2 */ 0b10, // prettier-ignore\n WRITABLE = /* 1 */ 0b01, // prettier-ignore\n READONLY = /* 0 */ 0b00, // prettier-ignore\n}\n\nconst IS_SIGNER_BITMASK = 0b10;\nconst IS_WRITABLE_BITMASK = 0b01;\n\nexport function downgradeRoleToNonSigner(role: AccountRole.READONLY_SIGNER): AccountRole.READONLY;\nexport function downgradeRoleToNonSigner(role: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole {\n return role & ~IS_SIGNER_BITMASK;\n}\n\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE): AccountRole.READONLY;\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE_SIGNER): AccountRole.READONLY_SIGNER;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole {\n return role & ~IS_WRITABLE_BITMASK;\n}\n\nexport function isSignerRole(role: AccountRole): role is AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER {\n return role >= AccountRole.READONLY_SIGNER;\n}\n\nexport function isWritableRole(role: AccountRole): role is AccountRole.WRITABLE | AccountRole.WRITABLE_SIGNER {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\n\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE_SIGNER, roleB: AccountRole): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.READONLY_SIGNER): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY, roleB: AccountRole.READONLY): AccountRole.READONLY; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole {\n return roleA | roleB;\n}\n\nexport function upgradeRoleToSigner(role: AccountRole.READONLY): AccountRole.READONLY_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole {\n return role | IS_SIGNER_BITMASK;\n}\n\nexport function upgradeRoleToWritable(role: AccountRole.READONLY): AccountRole.WRITABLE;\nexport function upgradeRoleToWritable(role: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole {\n return role | IS_WRITABLE_BITMASK;\n}\n","import { assertKeyGenerationIsAvailable } from '@solana/assertions';\n\nexport async function generateKeyPair(): Promise<CryptoKeyPair> {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ 'Ed25519', // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify']\n );\n return keyPair as CryptoKeyPair;\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n","import { ITransactionWithSignatures } from '.';\nimport { BaseTransaction } from './types';\n\nexport function getUnsignedTransaction<TTransaction extends BaseTransaction>(\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction & ITransactionWithSignatures, keyof ITransactionWithSignatures> {\n if ('signatures' in transaction) {\n // The implication of the lifetime constraint changing is that any existing signatures are invalid.\n const {\n signatures: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n","import { base58 } from '@metaplex-foundation/umi-serializers';\n\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport type Blockhash = string & { readonly __brand: unique symbol };\n\ntype BlockhashLifetimeConstraint = Readonly<{\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n}>;\n\nexport interface ITransactionWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 ||\n // Highest value (32 bytes of 255)\n putativeBlockhash.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeBlockhash);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBlockhash}\\` is not a blockhash`, {\n cause: e,\n });\n }\n}\n\nexport function setTransactionLifetimeUsingBlockhash<TTransaction extends BaseTransaction & IDurableNonceTransaction>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures | 'lifetimeConstraint'> & ITransactionWithBlockhashLifetime;\nexport function setTransactionLifetimeUsingBlockhash<\n TTransaction extends BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithBlockhashLifetime;\nexport function setTransactionLifetimeUsingBlockhash(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n) {\n if (\n 'lifetimeConstraint' in transaction &&\n transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n lifetimeConstraint: blockhashLifetimeConstraint,\n };\n Object.freeze(out);\n return out;\n}\n","import { Transaction, TransactionVersion } from './types';\n\ntype TransactionConfig<TVersion extends TransactionVersion> = Readonly<{\n version: TVersion;\n}>;\n\nexport function createTransaction<TVersion extends TransactionVersion>(\n config: TransactionConfig<TVersion>\n): Extract<Transaction, { version: TVersion }>;\nexport function createTransaction<TVersion extends TransactionVersion>({\n version,\n}: TransactionConfig<TVersion>): Transaction {\n const out: Transaction = {\n instructions: [],\n version,\n };\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport { AccountRole, IInstruction, IInstructionWithAccounts, IInstructionWithData } from '@solana/instructions';\nimport { ReadonlyAccount, ReadonlySignerAccount, WritableAccount } from '@solana/instructions/dist/types/accounts';\n\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\ntype AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n> = IInstruction<'11111111111111111111111111111111'> &\n IInstructionWithAccounts<\n readonly [\n WritableAccount<TNonceAccountAddress>,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount<TNonceAuthorityAddress>\n ]\n > &\n IInstructionWithData<AdvanceNonceAccountInstructionData>;\ntype AdvanceNonceAccountInstructionData = Uint8Array & {\n readonly __brand: unique symbol;\n};\ntype DurableNonceConfig<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> = Readonly<{\n readonly nonce: Nonce<TNonceValue>;\n readonly nonceAccountAddress: Base58EncodedAddress<TNonceAccountAddress>;\n readonly nonceAuthorityAddress: Base58EncodedAddress<TNonceAuthorityAddress>;\n}>;\nexport type Nonce<TNonceValue extends string = string> = TNonceValue & { readonly __brand: unique symbol };\ntype NonceLifetimeConstraint<TNonceValue extends string = string> = Readonly<{\n nonce: Nonce<TNonceValue>;\n}>;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Base58EncodedAddress<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS =\n '11111111111111111111111111111111' as Base58EncodedAddress<'11111111111111111111111111111111'>;\n\nexport interface IDurableNonceTransaction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint<TNonceValue>;\n}\n\nexport function assertIsDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): asserts transaction is BaseTransaction & IDurableNonceTransaction {\n if (!isDurableNonceTransaction(transaction)) {\n // TODO: Coded error.\n throw new Error('Transaction is not a durable nonce transaction');\n }\n}\n\nfunction createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n>(\n nonceAccountAddress: Base58EncodedAddress<TNonceAccountAddress>,\n nonceAuthorityAddress: Base58EncodedAddress<TNonceAuthorityAddress>\n): AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\nfunction isAdvanceNonceAccountInstruction(instruction: IInstruction): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.programAddress === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accounts?.length === 3 &&\n // First account is nonce account address\n instruction.accounts[0].address != null &&\n instruction.accounts[0].role === AccountRole.WRITABLE &&\n // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS &&\n instruction.accounts[1].role === AccountRole.READONLY &&\n // Third account is nonce authority account\n instruction.accounts[2].address != null &&\n instruction.accounts[2].role === AccountRole.READONLY_SIGNER\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: Uint8Array): data is AdvanceNonceAccountInstructionData {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n\nfunction isDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): transaction is BaseTransaction & IDurableNonceTransaction {\n return (\n 'lifetimeConstraint' in transaction &&\n typeof transaction.lifetimeConstraint.nonce === 'string' &&\n transaction.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transaction.instructions[0])\n );\n}\n\nexport function setTransactionLifetimeUsingDurableNonce<\n TTransaction extends BaseTransaction,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n>(\n {\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n }: DurableNonceConfig<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>,\n transaction: TTransaction | (TTransaction & IDurableNonceTransaction)\n): TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue> {\n const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction);\n if (\n isAlreadyDurableNonceTransaction &&\n transaction.lifetimeConstraint.nonce === nonce &&\n transaction.instructions[0].accounts[0].address === nonceAccountAddress &&\n transaction.instructions[0].accounts[2].address === nonceAuthorityAddress\n ) {\n return transaction as TTransaction &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...(isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions),\n ],\n lifetimeConstraint: {\n nonce,\n },\n } as TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport interface ITransactionWithFeePayer<TAddress extends string = string> {\n readonly feePayer: Base58EncodedAddress<TAddress>;\n}\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | TTransaction\n | (TTransaction & ITransactionWithFeePayer<TFeePayerAddress>)\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<TFeePayerAddress> & ITransactionWithSignatures)\n):\n | (TTransaction & ITransactionWithFeePayer<TFeePayerAddress>)\n | (Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithFeePayer<TFeePayerAddress>) {\n if ('feePayer' in transaction && feePayer === transaction.feePayer) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n feePayer,\n };\n Object.freeze(out);\n return out;\n}\n","import { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport function appendTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [...transaction.instructions, instruction],\n };\n Object.freeze(out);\n return out;\n}\n\nexport function prependTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [instruction, ...transaction.instructions],\n };\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress, getAddressFromPublicKey } from '@solana/addresses';\nimport { Ed25519Signature, signBytes } from '@solana/keys';\n\nimport { CompiledMessage, compileMessage } from './message';\nimport { getCompiledMessageEncoder } from './serializers/message';\n\nexport interface IFullySignedTransaction extends ITransactionWithSignatures {\n readonly __brand: unique symbol;\n}\nexport interface ITransactionWithSignatures {\n readonly signatures: Readonly<Record<Base58EncodedAddress, Ed25519Signature>>;\n}\n\nasync function getCompiledMessageSignature(message: CompiledMessage, secretKey: CryptoKey) {\n const wireMessageBytes = getCompiledMessageEncoder().serialize(message);\n const signature = await signBytes(secretKey, wireMessageBytes);\n return signature;\n}\n\nexport async function signTransaction<TTransaction extends Parameters<typeof compileMessage>[0]>(\n keyPair: CryptoKeyPair,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Promise<TTransaction & ITransactionWithSignatures> {\n const compiledMessage = compileMessage(transaction);\n const [signerPublicKey, signature] = await Promise.all([\n getAddressFromPublicKey(keyPair.publicKey),\n getCompiledMessageSignature(compiledMessage, keyPair.privateKey),\n ]);\n const nextSignatures = {\n ...('signatures' in transaction ? transaction.signatures : null),\n ...({ [signerPublicKey]: signature } as ITransactionWithSignatures['signatures']),\n };\n const out = {\n ...transaction,\n signatures: nextSignatures,\n };\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress, getBase58EncodedAddressComparator } from '@solana/addresses';\nimport {\n AccountRole,\n IAccountLookupMeta,\n IAccountMeta,\n IInstruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit<WritableSignerAccount, 'address'> & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit<ReadonlyAccountLookup | WritableAccountLookup, 'address'> & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = (IAccountMeta | IAccountLookupMeta)[] & { readonly __brand: unique symbol };\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Base58EncodedAddress,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry | Record<never, never>\n ) => AddressMap[Base58EncodedAddress]\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(\n feePayer: Base58EncodedAddress,\n instructions: readonly IInstruction[]\n): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set<Base58EncodedAddress>();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and set as the fee payer. Program addresses may not pay fees.'\n );\n default:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and marked writable. Program addresses may not be writable.'\n );\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType<typeof getBase58EncodedAddressComparator>;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry as FeePayerAccountEntry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getBase58EncodedAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry as LookupTableAccountEntry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${account.address}\\`) which is both invoked and ` +\n 'marked writable. Program addresses may not be ' +\n 'writable.'\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType<typeof getBase58EncodedAddressComparator>;\n const orderedAccounts: (IAccountMeta | IAccountLookupMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getBase58EncodedAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Base58EncodedAddress<typeof address>,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Base58EncodedAddress, getBase58EncodedAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype AddressTableLookup = Readonly<{\n lookupTableAddress: Base58EncodedAddress;\n readableIndices: readonly number[];\n writableIndices: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Base58EncodedAddress,\n { readonly readableIndices: number[]; readonly writableIndices: number[] }\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readableIndices: [],\n writableIndices: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndices.push(account.addressIndex);\n } else {\n entry.readableIndices.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getBase58EncodedAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Base58EncodedAddress,\n ...index[lookupTableAddress as unknown as Base58EncodedAddress],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype MessageHeader = Readonly<{\n numReadonlyNonSignerAccounts: number;\n numReadonlySignerAccounts: number;\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport { IInstruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n accountIndices?: number[];\n data?: Uint8Array;\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record<Base58EncodedAddress, number> = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly IInstruction[],\n orderedAccounts: OrderedAccounts\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { IDurableNonceTransaction, ITransactionWithBlockhashLifetime } from './index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (ITransactionWithBlockhashLifetime | IDurableNonceTransaction)['lifetimeConstraint']\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Base58EncodedAddress[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { ITransactionWithBlockhashLifetime } from './blockhash';\nimport { getCompiledAddressTableLookups } from './compile-address-table-lookups';\nimport { getCompiledMessageHeader } from './compile-header';\nimport { getCompiledInstructions } from './compile-instructions';\nimport { getCompiledLifetimeToken } from './compile-lifetime-token';\nimport { getCompiledStaticAccounts } from './compile-static-accounts';\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithFeePayer } from './fee-payer';\nimport { BaseTransaction } from './types';\n\ntype BaseCompiledMessage = Readonly<{\n header: ReturnType<typeof getCompiledMessageHeader>;\n instructions: ReturnType<typeof getCompiledInstructions>;\n lifetimeToken: ReturnType<typeof getCompiledLifetimeToken>;\n staticAccounts: ReturnType<typeof getCompiledStaticAccounts>;\n}>;\n\ntype CompilableTransaction = BaseTransaction &\n ITransactionWithFeePayer &\n (ITransactionWithBlockhashLifetime | IDurableNonceTransaction);\n\nexport type CompiledMessage = LegacyCompiledMessage | VersionedCompiledMessage;\n\ntype LegacyCompiledMessage = BaseCompiledMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledMessage = BaseCompiledMessage &\n Readonly<{\n addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups>;\n version: number;\n }>;\n\nexport function compileMessage(\n transaction: CompilableTransaction & Readonly<{ version: 'legacy' }>\n): LegacyCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): VersionedCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): CompiledMessage {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...(transaction.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),\n lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transaction.version,\n };\n}\n","import {\n array,\n base58,\n mapSerializer,\n Serializer,\n shortU16,\n string,\n struct,\n StructToSerializerTuple,\n} from '@metaplex-foundation/umi-serializers';\nimport { getBase58EncodedAddressCodec } from '@solana/addresses';\n\nimport { CompiledMessage } from '../message';\nimport { SerializedMessageBytes } from '../types';\nimport { getAddressTableLookupCodec } from './address-table-lookup';\nimport { getMessageHeaderCodec } from './header';\nimport { getInstructionCodec } from './instruction';\nimport { getTransactionVersionCodec } from './transaction-version';\nimport { getUnimplementedDecoder, getUnimplementedEncoder } from './unimplemented';\n\nconst BASE_CONFIG = {\n description: __DEV__ ? 'The wire format of a Solana transaction message' : '',\n fixedSize: null,\n maxSize: null,\n} as const;\n\nfunction deserialize(bytes: Uint8Array, offset = 0): [CompiledMessage, number] {\n const preludeAndOffset = struct(getPreludeStructSerializerTuple()).deserialize(bytes, offset);\n const [prelude, endOfPreludeOffset] = preludeAndOffset;\n if (prelude.version === 'legacy') {\n return preludeAndOffset;\n }\n const [addressTableLookups, finalOffset] = getAddressTableLookupsSerializer().deserialize(\n bytes,\n endOfPreludeOffset\n );\n return [\n {\n ...prelude,\n ...(addressTableLookups.length ? { addressTableLookups } : null),\n },\n finalOffset,\n ];\n}\n\nfunction serialize(compiledMessage: CompiledMessage): SerializedMessageBytes {\n if (compiledMessage.version === 'legacy') {\n return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage) as SerializedMessageBytes;\n } else {\n return mapSerializer(\n struct([\n ...getPreludeStructSerializerTuple(),\n ['addressTableLookups', getAddressTableLookupsSerializer()],\n ] as StructToSerializerTuple<CompiledMessage, CompiledMessage>),\n (value: CompiledMessage) => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n } as Exclude<CompiledMessage, { readonly version: 'legacy' }>;\n }\n ).serialize(compiledMessage) as SerializedMessageBytes;\n }\n}\n\nfunction getPreludeStructSerializerTuple(): StructToSerializerTuple<CompiledMessage, CompiledMessage> {\n return [\n ['version', getTransactionVersionCodec()],\n ['header', getMessageHeaderCodec()],\n [\n 'staticAccounts',\n array(getBase58EncodedAddressCodec(), {\n description: __DEV__ ? 'A compact-array of static account addresses belonging to this transaction' : '',\n size: shortU16(),\n }),\n ],\n [\n 'lifetimeToken',\n string({\n description: __DEV__\n ? 'A 32-byte token that specifies the lifetime of this transaction (eg. a ' +\n 'recent blockhash, or a durable nonce)'\n : '',\n encoding: base58,\n size: 32,\n }),\n ],\n [\n 'instructions',\n array(getInstructionCodec(), {\n description: __DEV__ ? 'A compact-array of instructions belonging to this transaction' : '',\n size: shortU16(),\n }),\n ],\n ];\n}\n\nfunction getAddressTableLookupsSerializer() {\n return array(getAddressTableLookupCodec(), {\n ...(__DEV__ ? { description: 'A compact array of address table lookups belonging to this transaction' } : null),\n size: shortU16(),\n });\n}\n\nexport function getCompiledMessageEncoder(): Serializer<CompiledMessage> {\n return {\n ...BASE_CONFIG,\n deserialize: getUnimplementedDecoder('CompiledMessage'),\n serialize,\n };\n}\n\nexport function getCompiledMessageDecoder(): Serializer<CompiledMessage> {\n return {\n ...BASE_CONFIG,\n deserialize,\n serialize: getUnimplementedEncoder('CompiledMessage'),\n };\n}\n\nexport function getCompiledMessageCodec(): Serializer<CompiledMessage> {\n return {\n ...BASE_CONFIG,\n deserialize,\n serialize,\n };\n}\n","import { array, Serializer, shortU16, struct, StructToSerializerTuple, u8 } from '@metaplex-foundation/umi-serializers';\nimport { getBase58EncodedAddressCodec } from '@solana/addresses';\n\nimport { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\n\ntype AddressTableLookup = ReturnType<typeof getCompiledAddressTableLookups>[number];\n\nexport function getAddressTableLookupCodec(): Serializer<AddressTableLookup> {\n return struct(\n [\n [\n 'lookupTableAddress',\n getBase58EncodedAddressCodec(\n __DEV__\n ? {\n description:\n 'The address of the address lookup table account from which ' +\n 'instruction addresses should be looked up',\n }\n : undefined\n ),\n ],\n [\n 'writableIndices',\n array(u8(), {\n ...(__DEV__\n ? {\n description:\n 'The indices of the accounts in the lookup table that should ' +\n 'be loaded as writeable',\n }\n : null),\n size: shortU16(),\n }),\n ],\n [\n 'readableIndices',\n array(u8(), {\n ...(__DEV__\n ? {\n description:\n 'The indices of the accounts in the lookup table that should ' +\n 'be loaded as read-only',\n }\n : undefined),\n size: shortU16(),\n }),\n ],\n ] as StructToSerializerTuple<AddressTableLookup, AddressTableLookup>,\n __DEV__\n ? {\n description:\n 'A pointer to the address of an address lookup table, along with the ' +\n 'readonly/writeable indices of the addresses that should be loaded from it',\n }\n : undefined\n );\n}\n","import { Serializer, struct, u8 } from '@metaplex-foundation/umi-serializers';\n\nimport { getCompiledMessageHeader } from '../compile-header';\n\ntype MessageHeader = ReturnType<typeof getCompiledMessageHeader>;\n\nexport function getMessageHeaderCodec(): Serializer<MessageHeader> {\n return struct(\n [\n [\n 'numSignerAccounts',\n u8(\n __DEV__\n ? {\n description:\n 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction',\n }\n : undefined\n ),\n ],\n [\n 'numReadonlySignerAccounts',\n u8(\n __DEV__\n ? {\n description:\n 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable',\n }\n : undefined\n ),\n ],\n [\n 'numReadonlyNonSignerAccounts',\n u8(\n __DEV__\n ? {\n description:\n 'The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable',\n }\n : undefined\n ),\n ],\n ],\n __DEV__\n ? {\n description:\n 'The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses',\n }\n : undefined\n );\n}\n","import { array, bytes, mapSerializer, Serializer, shortU16, struct, u8 } from '@metaplex-foundation/umi-serializers';\n\nimport { getCompiledInstructions } from '../compile-instructions';\n\ntype Instruction = ReturnType<typeof getCompiledInstructions>[number];\n\nexport function getInstructionCodec(): Serializer<Instruction> {\n return mapSerializer<Instruction, Required<Instruction>>(\n struct([\n [\n 'programAddressIndex',\n u8(\n __DEV__\n ? {\n description:\n 'The index of the program being called, according to the ' +\n 'well-ordered accounts list for this transaction',\n }\n : undefined\n ),\n ],\n [\n 'accountIndices',\n array(\n u8({\n description: __DEV__\n ? 'The index of an account, according to the well-ordered accounts ' +\n 'list for this transaction'\n : '',\n }),\n {\n description: __DEV__\n ? 'An optional list of account indices, according to the ' +\n 'well-ordered accounts list for this transaction, in the order in ' +\n 'which the program being called expects them'\n : '',\n size: shortU16(),\n }\n ),\n ],\n [\n 'data',\n bytes({\n description: __DEV__ ? 'An optional buffer of data passed to the instruction' : '',\n size: shortU16(),\n }),\n ],\n ]),\n (value: Instruction) => {\n if (value.accountIndices !== undefined && value.data !== undefined) {\n return value as Required<Instruction>;\n }\n return {\n ...value,\n accountIndices: value.accountIndices ?? [],\n data: value.data ?? new Uint8Array(0),\n } as Required<Instruction>;\n },\n (value: Required<Instruction>) => {\n if (value.accountIndices.length && value.data.byteLength) {\n return value;\n }\n const { accountIndices, data, ...rest } = value;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n }\n );\n}\n","function getError(type: 'decoder' | 'encoder', name: string) {\n const functionSuffix = name + type[0].toUpperCase() + type.slice(1);\n return new Error(\n `No ${type} exists for ${name}. Use \\`get${functionSuffix}()\\` if you need a ${type}, and \\`get${name}Codec()\\` if you need to both encode and decode ${name}`\n );\n}\n\nexport function getUnimplementedDecoder(name: string): () => never {\n return () => {\n throw getError('decoder', name);\n };\n}\n\nexport function getUnimplementedEncoder(name: string): () => never {\n return () => {\n throw getError('encoder', name);\n };\n}\n","import { Serializer } from '@metaplex-foundation/umi-serializers';\n\nimport { TransactionVersion } from '../types';\nimport { getUnimplementedDecoder, getUnimplementedEncoder } from './unimplemented';\n\nconst VERSION_FLAG_MASK = 0x80;\n\nconst BASE_CONFIG = {\n description: __DEV__ ? 'A single byte that encodes the version of the transaction' : '',\n fixedSize: null,\n maxSize: 1,\n} as const;\n\nfunction deserialize(bytes: Uint8Array, offset = 0): [TransactionVersion, number] {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n // No version flag set; it's a legacy (unversioned) transaction.\n return ['legacy', offset];\n } else {\n const version = (firstByte ^ VERSION_FLAG_MASK) as TransactionVersion;\n return [version, offset + 1];\n }\n}\n\nfunction serialize(value: TransactionVersion): Uint8Array {\n if (value === 'legacy') {\n return new Uint8Array();\n }\n if (value < 0 || value > 127) {\n // TODO: Coded error.\n throw new Error(`Transaction version must be in the range [0, 127]. \\`${value}\\` given.`);\n }\n return new Uint8Array([value | VERSION_FLAG_MASK]);\n}\n\nexport function getTransactionVersionDecoder(): Serializer<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n deserialize,\n serialize: getUnimplementedEncoder('TransactionVersion'),\n };\n}\n\nexport function getTransactionVersionEncoder(): Serializer<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n deserialize: getUnimplementedDecoder('TransactionVersion'),\n serialize,\n };\n}\n\nexport function getTransactionVersionCodec(): Serializer<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n deserialize,\n serialize,\n };\n}\n","import { array, bytes, Serializer, shortU16, struct } from '@metaplex-foundation/umi-serializers';\n\nimport { getCompiledTransaction } from '../compile-transaction';\nimport { getCompiledMessageEncoder } from './message';\nimport { getUnimplementedDecoder } from './unimplemented';\n\nconst BASE_CONFIG = {\n description: __DEV__ ? 'The wire format of a Solana transaction' : '',\n fixedSize: null,\n maxSize: null,\n} as const;\n\ntype SerializableTransaction = Parameters<typeof getCompiledTransaction>[0];\n\nfunction serialize(transaction: SerializableTransaction) {\n const compiledTransaction = getCompiledTransaction(transaction);\n return struct([\n [\n 'signatures',\n array(bytes({ size: 64 }), {\n ...(__DEV__ ? { description: 'A compact array of 64-byte, base-64 encoded Ed25519 signatures' } : null),\n size: shortU16(),\n }),\n ],\n ['compiledMessage', getCompiledMessageEncoder()],\n ]).serialize(compiledTransaction);\n}\n\nexport function getTransactionEncoder(): Serializer<SerializableTransaction> {\n return {\n ...BASE_CONFIG,\n deserialize: getUnimplementedDecoder('CompiledMessage'),\n serialize,\n };\n}\n","import { Ed25519Signature } from '@solana/keys';\n\nimport { CompiledMessage, compileMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\n\ntype CompiledTransaction = Readonly<{\n compiledMessage: CompiledMessage;\n signatures: Ed25519Signature[];\n}>;\n\ntype CompilableTransaction = Parameters<typeof compileMessage>[0];\n\nexport function getCompiledTransaction(\n transaction: CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n): CompiledTransaction {\n const compiledMessage = compileMessage(transaction);\n let signatures;\n if ('signatures' in transaction) {\n signatures = [];\n for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {\n signatures[ii] =\n transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));\n }\n } else {\n signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));\n }\n return {\n compiledMessage,\n signatures,\n };\n}\n","import { 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\ntype AllowedNumericKeypaths = Partial<Record<keyof ReturnType<typeof createSolanaRpcApi>, readonly KeyPath[]>>;\n\nlet memoizedKeypaths: AllowedNumericKeypaths;\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 getAllowedNumericKeypaths(): AllowedNumericKeypaths {\n if (!memoizedKeypaths) {\n // Numeric values nested in `jsonParsed` accounts\n const jsonParsedTokenAccountsConfigs = [\n // parsed Token/Token22 token account\n ['data', 'parsed', 'info', 'tokenAmount', 'decimals'],\n ['data', 'parsed', 'info', 'tokenAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'decimals'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'uiAmount'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'decimals'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'uiAmount'],\n [\n 'data',\n 'parsed',\n 'info',\n 'extensions',\n KEYPATH_WILDCARD,\n 'state',\n 'olderTransferFee',\n 'transferFeeBasisPoints',\n ],\n [\n 'data',\n 'parsed',\n 'info',\n 'extensions',\n KEYPATH_WILDCARD,\n 'state',\n 'newerTransferFee',\n 'transferFeeBasisPoints',\n ],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n ];\n const jsonParsedAccountsConfigs = [\n ...jsonParsedTokenAccountsConfigs,\n // parsed AddressTableLookup account\n ['data', 'parsed', 'info', 'lastExtendedSlotStartIndex'],\n // parsed Config account\n ['data', 'parsed', 'info', 'slashPenalty'],\n ['data', 'parsed', 'info', 'warmupCooldownRate'],\n // parsed Token/Token22 mint account\n ['data', 'parsed', 'info', 'decimals'],\n // parsed Token/Token22 multisig account\n ['data', 'parsed', 'info', 'numRequiredSigners'],\n ['data', 'parsed', 'info', 'numValidSigners'],\n // parsed Stake account\n ['data', 'parsed', 'info', 'stake', 'delegation', 'warmupCooldownRate'],\n // parsed Sysvar rent account\n ['data', 'parsed', 'info', 'exemptionThreshold'],\n ['data', 'parsed', 'info', 'burnPercent'],\n // parsed Vote account\n ['data', 'parsed', 'info', 'commission'],\n ['data', 'parsed', 'info', 'votes', KEYPATH_WILDCARD, 'confirmationCount'],\n ];\n memoizedKeypaths = {\n getAccountInfo: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\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 memoizedKeypaths;\n}\n","import { getAllowedNumericKeypaths } 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 ? getAllowedNumericKeypaths()[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 { 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 GetBlockCommitmentApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlocksWithLimitApi &\n GetBlockTimeApi &\n GetClusterNodesApi &\n GetEpochInfoApi &\n GetEpochScheduleApi &\n GetFeeForMessageApi &\n GetFirstAvailableBlockApi &\n GetGenesisHashApi &\n GetHealthApi &\n GetHighestSnapshotSlotApi &\n GetIdentityApi &\n GetInflationGovernorApi &\n GetInflationRateApi &\n GetInflationRewardApi &\n GetLargestAccountsApi &\n GetLatestBlockhashApi &\n GetLeaderScheduleApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetMinimumBalanceForRentExemptionApi &\n GetMultipleAccountsApi &\n GetProgramAccountsApi &\n GetRecentPerformanceSamplesApi &\n GetRecentPrioritizationFeesApi &\n GetSignaturesForAddressApi &\n GetSignatureStatusesApi &\n GetSlotApi &\n GetSlotLeaderApi &\n GetSlotLeadersApi &\n GetStakeActivationApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTokenAccountBalanceApi &\n GetTokenAccountsByDelegateApi &\n GetTokenAccountsByOwnerApi &\n GetTokenLargestAccountsApi &\n GetTokenSupplyApi &\n GetTransactionApi &\n GetTransactionCountApi &\n GetVersionApi &\n GetVoteAccountsApi &\n IsBlockhashValidApi &\n MinimumLedgerSlotApi &\n RequestAirdropApi &\n SendTransactionApi &\n SimulateTransactionApi;\n\nexport type { Commitment } from './common';\n\nexport function createSolanaRpcApi(config?: Config): IRpcApi<SolanaRpcMethods> {\n return new Proxy({} as IRpcApi<SolanaRpcMethods>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<TMethodName extends keyof IRpcApi<SolanaRpcMethods>>(\n ...args: Parameters<NonNullable<ProxyHandler<IRpcApi<SolanaRpcMethods>>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof SolanaRpcMethods;\n return function (\n ...rawParams: Parameters<\n SolanaRpcMethods[TMethodName] extends CallableFunction ? SolanaRpcMethods[TMethodName] : never\n >\n ): RpcRequest<ReturnType<SolanaRpcMethods[TMethodName]>> {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n const params = patchParamsForSolanaLabsRpc(\n rawParams,\n handleIntegerOverflow\n ? (keyPath, value) => handleIntegerOverflow(methodName, keyPath, value)\n : undefined\n );\n return {\n methodName,\n params,\n responseProcessor: rawResponse => patchResponseForSolanaLabsRpc(rawResponse, methodName),\n };\n };\n },\n });\n}\n","// 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","export default globalThis.WebSocket;\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","../../addresses/dist/index.browser.js","../../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-strings/dist/index.browser.js","../../codecs-numbers/dist/index.browser.js","../../assertions/src/subtle-crypto.ts","../../instructions/src/roles.ts","../../keys/src/key-pair.ts","../../keys/src/signatures.ts","../../rpc-types/src/commitment.ts","../../rpc-types/src/lamports.ts","../../rpc-types/src/stringified-bigint.ts","../../rpc-types/src/stringified-number.ts","../../rpc-types/src/unix-timestamp.ts","../../codecs-data-structures/src/utils.ts","../../codecs-data-structures/src/array-like-codec-size.ts","../../codecs-data-structures/src/assertions.ts","../../codecs-data-structures/src/array.ts","../../codecs-data-structures/src/boolean.ts","../../codecs-data-structures/src/bytes.ts","../../codecs-data-structures/src/scalar-enum.ts","../../codecs-data-structures/src/set.ts","../../functional/dist/index.browser.js","../../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","../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":["e2","base58Encoder","e","encode","decode","AccountRole","signature","newOffset","combineCodec","mergeBytes","getU32Decoder","getU32Encoder","__DEV__","AccountRole2","IS_WRITABLE_BITMASK","isSignerRole","isWritableRole","mergeRoles","getArrayEncoder","address","getBytesDecoder","getStructDecoder","getStructEncoder","getShortU16Decoder","getShortU16Encoder","getAddressComparator","getAddressDecoder","getU8Encoder","getU8Decoder","getArrayDecoder","getAddressEncoder","getBase58Encoder","mapDecoder","getBytesEncoder","mapEncoder","getTimeoutPromise","lamports","visitNode","makeProxy","index_browser_default","resolve","reject","registerIterableCleanup","EXPLICIT_ABORT_TOKEN","deduplicationKey","pendingSubscription","fastStableStringify","import_fast_stable_stringify","normalizeHeaders","args","base58Decoder"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA,QAAI,cAAc,OAAO,UAAU;AACnC,QAAI,UAAU,OAAO,QAAQ,SAAS,KAAK;AACzC,UAAI,OAAO,CAAC;AACZ,eAAS,QAAQ,KAAK;AACrB,aAAK,KAAK,IAAI;AAAA,MACf;AACA,aAAO;AAAA,IACR;AAED,aAAS,UAAU,KAAK,aAAa;AACpC,UAAI,GAAG,KAAK,KAAK,MAAM,KAAK,SAAS;AACrC,UAAI,QAAQ,MAAM;AACjB,eAAO;AAAA,MACR;AACA,UAAI,QAAQ,OAAO;AAClB,eAAO;AAAA,MACR;AACA,cAAQ,OAAO,KAAK;AAAA,QACnB,KAAK;AACJ,cAAI,QAAQ,MAAM;AACjB,mBAAO;AAAA,UACR,WAAW,IAAI,UAAU,OAAO,IAAI,WAAW,YAAY;AAC1D,mBAAO,UAAU,IAAI,OAAO,GAAG,WAAW;AAAA,UAC3C,OAAO;AACN,oBAAQ,YAAY,KAAK,GAAG;AAC5B,gBAAI,UAAU,kBAAkB;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UAAU,QAAQ,SAAS,cAAc,oBAAoB;;EAEtE,CAAC,QAAQ,UAAU,QAAQ,oBAAoB;EAC/C,CAAC,QAAQ,UAAU,QAAQ,aAAa;;EAExC,CAAC,QAAQ,UAAU,QAAQ,YAAY;EACvC,CAAC,QAAQ,UAAU,QAAQ,SAAS,kBAAkB,mBAAmB;AAC7E;AAIA,IAAI;AAGJ,IAAI;AAMG,SAAS,2CAEd;AACE,MAAI,CAAC,8BAA8B;AAC/B,mCAA+B;MAC3B,sBAAsB,0BAA0B,IAAI,CAAA,MAAK,CAAC,SAAS,GAAG,CAAC,CAAC;MACxE,oBAAoB;QAChB,CAAC,SAAS,SAAS,WAAW;QAC9B;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA,CAAC,SAAS,SAAS,gBAAgB,kBAAkB,QAAQ,WAAW,kBAAkB,YAAY;QACtG;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACJ;QACA;UACI;UACA;UACA;UACA;UACA;UAC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;AAAA,EACJ,CAAC;AACD,QAAM,+BAA+B;AAAA,IACjC;AAAA,IACA;AAAA,IACA;AAAA,EACJ,CAAC;AACD,SAAO;AACX;AAEA,eAAsB,0BAA0B;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACP,GAA6E;AACzE,QAAM,uBAAuB,MAAM,yBAAyB;AAAA,IACxD,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ,CAAC;AACD,QAAM,yBAAyB;AAAA,IAC3B;AAAA,IACA;AAAA,IACA;AAAA,EACJ,CAAC;AACD,SAAO;AACX","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","var objToString = Object.prototype.toString;\nvar objKeys = Object.keys || function(obj) {\n\t\tvar keys = [];\n\t\tfor (var name in obj) {\n\t\t\tkeys.push(name);\n\t\t}\n\t\treturn keys;\n\t};\n\nfunction stringify(val, isArrayProp) {\n\tvar i, max, str, keys, key, propVal, toStr;\n\tif (val === true) {\n\t\treturn \"true\";\n\t}\n\tif (val === false) {\n\t\treturn \"false\";\n\t}\n\tswitch (typeof val) {\n\t\tcase \"object\":\n\t\t\tif (val === null) {\n\t\t\t\treturn null;\n\t\t\t} else if (val.toJSON && typeof val.toJSON === \"function\") {\n\t\t\t\treturn stringify(val.toJSON(), isArrayProp);\n\t\t\t} else {\n\t\t\t\ttoStr = objToString.call(val);\n\t\t\t\tif (toStr === \"[object Array]\") {\n\t\t\t\t\tstr = '[';\n\t\t\t\t\tmax = val.length - 1;\n\t\t\t\t\tfor(i = 0; i < max; i++) {\n\t\t\t\t\t\tstr += stringify(val[i], true) + ',';\n\t\t\t\t\t}\n\t\t\t\t\tif (max > -1) {\n\t\t\t\t\t\tstr += stringify(val[i], true);\n\t\t\t\t\t}\n\t\t\t\t\treturn str + ']';\n\t\t\t\t} else if (toStr === \"[object Object]\") {\n\t\t\t\t\t// only object is left\n\t\t\t\t\tkeys = objKeys(val).sort();\n\t\t\t\t\tmax = keys.length;\n\t\t\t\t\tstr = \"\";\n\t\t\t\t\ti = 0;\n\t\t\t\t\twhile (i < max) {\n\t\t\t\t\t\tkey = keys[i];\n\t\t\t\t\t\tpropVal = stringify(val[key], false);\n\t\t\t\t\t\tif (propVal !== undefined) {\n\t\t\t\t\t\t\tif (str) {\n\t\t\t\t\t\t\t\tstr += ',';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstr += JSON.stringify(key) + ':' + propVal;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\treturn '{' + str + '}';\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON.stringify(val);\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"function\":\n\t\tcase \"undefined\":\n\t\t\treturn isArrayProp ? null : undefined;\n\t\tcase \"string\":\n\t\t\treturn JSON.stringify(val);\n\t\tdefault:\n\t\t\treturn isFinite(val) ? val : null;\n\t}\n}\n\nmodule.exports = function(val) {\n\tvar returnVal = stringify(val, false);\n\tif (returnVal !== undefined) {\n\t\treturn ''+ returnVal;\n\t}\n};\n","export * from '@solana/addresses';\nexport * from '@solana/instructions';\nexport * from '@solana/keys';\nexport * from '@solana/rpc-types';\nexport * from '@solana/transactions';\nexport * from './airdrop';\nexport * from './rpc';\nexport * from './rpc-transport';\nexport * from './rpc-websocket-transport';\nexport * from './send-transaction';\nexport * from './transaction-confirmation';\nexport * from './transaction-confirmation-strategy-blockheight';\nexport * from './transaction-confirmation-strategy-nonce';\nexport * from './transaction-confirmation-strategy-recent-signature';\n","import { mapEncoder, combineCodec } from '@solana/codecs-core';\nimport { getStringEncoder, getStringDecoder, getBase58Encoder, getBase58Decoder } from '@solana/codecs-strings';\nimport { assertKeyExporterIsAvailable, assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\n// src/address.ts\nvar memoizedBase58Encoder;\nvar memoizedBase58Decoder;\nfunction getMemoizedBase58Encoder() {\n if (!memoizedBase58Encoder)\n memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\nfunction getMemoizedBase58Decoder() {\n if (!memoizedBase58Decoder)\n memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\nfunction isAddress(putativeAddress) {\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 || // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\nfunction assertIsAddress(putativeAddress) {\n try {\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 || // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new Error(\"Expected input string to decode to a byte array of length 32.\");\n }\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeAddress}\\` is not a base-58 encoded address`, {\n cause: e\n });\n }\n}\nfunction address(putativeAddress) {\n assertIsAddress(putativeAddress);\n return putativeAddress;\n}\nfunction getAddressEncoder(config) {\n return mapEncoder(\n getStringEncoder({\n description: config?.description ?? \"Address\",\n encoding: getMemoizedBase58Encoder(),\n size: 32\n }),\n (putativeAddress) => address(putativeAddress)\n );\n}\nfunction getAddressDecoder(config) {\n return getStringDecoder({\n description: config?.description ?? \"Address\",\n encoding: getMemoizedBase58Decoder(),\n size: 32\n });\n}\nfunction getAddressCodec(config) {\n return combineCodec(getAddressEncoder(config), getAddressDecoder(config));\n}\nfunction getAddressComparator() {\n return new Intl.Collator(\"en\", {\n caseFirst: \"lower\",\n ignorePunctuation: false,\n localeMatcher: \"best fit\",\n numeric: false,\n sensitivity: \"variant\",\n usage: \"sort\"\n }).compare;\n}\n\n// src/vendor/noble/ed25519.ts\nvar D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nvar P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;\nvar RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;\nfunction mod(a) {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x, power) {\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x) {\n const x2 = x * x % P;\n const b2 = x2 * x % P;\n const b4 = pow2(b2, 2n) * b2 % P;\n const b5 = pow2(b4, 1n) * x % P;\n const b10 = pow2(b5, 5n) * b5 % P;\n const b20 = pow2(b10, 10n) * b10 % P;\n const b40 = pow2(b20, 20n) * b20 % P;\n const b80 = pow2(b40, 40n) * b40 % P;\n const b160 = pow2(b80, 80n) * b80 % P;\n const b240 = pow2(b160, 80n) * b80 % P;\n const b250 = pow2(b240, 10n) * b10 % P;\n const pow_p_5_8 = pow2(b250, 2n) * x % P;\n return pow_p_5_8;\n}\nfunction uvRatio(u, v) {\n const v3 = mod(v * v * v);\n const v7 = mod(v3 * v3 * v);\n const pow = pow_2_252_3(u * v7);\n let x = mod(u * v3 * pow);\n const vx2 = mod(v * x * x);\n const root1 = x;\n const root2 = mod(x * RM1);\n const useRoot1 = vx2 === u;\n const useRoot2 = vx2 === mod(-u);\n const noRoot = vx2 === mod(-u * RM1);\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2;\n if ((mod(x) & 1n) === 1n)\n x = mod(-x);\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\nfunction pointIsOnCurve(y, lastByte) {\n const y2 = mod(y * y);\n const u = mod(y2 - 1n);\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v);\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 128) !== 0;\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n\n// src/curve.ts\nfunction byteToHex(byte) {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\nfunction decompressPointBytes(bytes) {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, \"\");\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\nasync function compressedPointBytesAreOnCurve(bytes) {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n\n// src/program-derived-address.ts\nfunction isProgramDerivedAddress(value) {\n return Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\" && typeof value[1] === \"number\" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);\n}\nfunction assertIsProgramDerivedAddress(value) {\n const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\" && typeof value[1] === \"number\";\n if (!validFormat) {\n throw new Error(\n `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\nvar MAX_SEED_LENGTH = 32;\nvar MAX_SEEDS = 16;\nvar PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80,\n 114,\n 111,\n 103,\n 114,\n 97,\n 109,\n 68,\n 101,\n 114,\n 105,\n 118,\n 101,\n 100,\n 65,\n 100,\n 100,\n 114,\n 101,\n 115,\n 115\n];\nvar PointOnCurveError = class extends Error {\n};\nasync function createProgramDerivedAddress({ programAddress, seeds }) {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === \"string\" ? (textEncoder || (textEncoder = new TextEncoder())).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, []);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n \"SHA-256\",\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n throw new PointOnCurveError(\"Invalid seeds; point must fall off the Ed25519 curve\");\n }\n return base58EncodedAddressCodec.decode(addressBytes)[0];\n}\nasync function getProgramDerivedAddress({\n programAddress,\n seeds\n}) {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address2 = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])]\n });\n return [address2, bumpSeed];\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n throw new Error(\"Unable to find a viable program address bump seed\");\n}\nasync function createAddressWithSeed({ baseAddress, programAddress, seed }) {\n const { encode, decode } = getAddressCodec();\n const seedBytes = typeof seed === \"string\" ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n const programAddressBytes = encode(programAddress);\n if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n const addressBytesBuffer = await crypto.subtle.digest(\n \"SHA-256\",\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n return decode(addressBytes)[0];\n}\nasync function getAddressFromPublicKey(publicKey) {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== \"public\" || publicKey.algorithm.name !== \"Ed25519\") {\n throw new Error(\"The `CryptoKey` must be an `Ed25519` public key\");\n }\n const publicKeyBytes = await crypto.subtle.exportKey(\"raw\", publicKey);\n const [base58EncodedAddress] = getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n\nexport { address, assertIsAddress, assertIsProgramDerivedAddress, createAddressWithSeed, getAddressCodec, getAddressComparator, getAddressDecoder, getAddressEncoder, getAddressFromPublicKey, getProgramDerivedAddress, isAddress, isProgramDerivedAddress };\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","import { combineCodec, fixEncoder, mergeBytes, fixDecoder, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';\nimport { getU32Encoder, getU32Decoder } from '@solana/codecs-numbers';\n\n// src/assertions.ts\nfunction assertValidBaseString(alphabet4, testValue, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {\n throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);\n }\n}\nvar getBaseXEncoder = (alphabet4) => {\n const base = alphabet4.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n encode(value) {\n assertValidBaseString(alphabet4, value);\n if (value === \"\")\n return new Uint8Array();\n const chars = [...value];\n let trailIndex = chars.findIndex((c) => c !== alphabet4[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length)\n return Uint8Array.from(leadingZeroes);\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(alphabet4.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\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};\nvar getBaseXDecoder = (alphabet4) => {\n const base = alphabet4.length;\n const baseBigInt = BigInt(base);\n return {\n decode(rawBytes, offset = 0) {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0)\n return [\"\", 0];\n let trailIndex = bytes.findIndex((n) => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet4[0].repeat(trailIndex);\n if (trailIndex === bytes.length)\n return [leadingZeroes, rawBytes.length];\n let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet4[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n return [leadingZeroes + tailChars.join(\"\"), rawBytes.length];\n },\n description: `base${base}`,\n fixedSize: null,\n maxSize: null\n };\n};\nvar getBaseXCodec = (alphabet4) => combineCodec(getBaseXEncoder(alphabet4), getBaseXDecoder(alphabet4));\n\n// src/base10.ts\nvar alphabet = \"0123456789\";\nvar getBase10Encoder = () => getBaseXEncoder(alphabet);\nvar getBase10Decoder = () => getBaseXDecoder(alphabet);\nvar getBase10Codec = () => getBaseXCodec(alphabet);\nvar getBase16Encoder = () => ({\n description: \"base16\",\n encode(value) {\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) => parseInt(byte, 16)) : []);\n },\n fixedSize: null,\n maxSize: null\n});\nvar getBase16Decoder = () => ({\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});\nvar getBase16Codec = () => combineCodec(getBase16Encoder(), getBase16Decoder());\n\n// src/base58.ts\nvar alphabet2 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nvar getBase58Encoder = () => getBaseXEncoder(alphabet2);\nvar getBase58Decoder = () => getBaseXDecoder(alphabet2);\nvar getBase58Codec = () => getBaseXCodec(alphabet2);\nvar getBaseXResliceEncoder = (alphabet4, bits) => ({\n description: `base${alphabet4.length}`,\n encode(value) {\n assertValidBaseString(alphabet4, value);\n if (value === \"\")\n return new Uint8Array();\n const charIndices = [...value].map((c) => alphabet4.indexOf(c));\n return new Uint8Array(reslice(charIndices, bits, 8, false));\n },\n fixedSize: null,\n maxSize: null\n});\nvar getBaseXResliceDecoder = (alphabet4, bits) => ({\n decode(rawBytes, offset = 0) {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0)\n return [\"\", rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map((i) => alphabet4[i]).join(\"\"), rawBytes.length];\n },\n description: `base${alphabet4.length}`,\n fixedSize: null,\n maxSize: null\n});\nvar getBaseXResliceCodec = (alphabet4, bits) => combineCodec(getBaseXResliceEncoder(alphabet4, bits), getBaseXResliceDecoder(alphabet4, bits));\nfunction reslice(input, inputBits, outputBits, useRemainder) {\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}\nvar getBase64Encoder = () => {\n {\n return {\n description: `base64`,\n encode(value) {\n try {\n const bytes = atob(value).split(\"\").map((c) => c.charCodeAt(0));\n return new Uint8Array(bytes);\n } catch (e2) {\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n fixedSize: null,\n maxSize: null\n };\n }\n};\nvar getBase64Decoder = () => {\n {\n return {\n decode(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = btoa(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n description: `base64`,\n fixedSize: null,\n maxSize: null\n };\n }\n};\nvar getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());\n\n// src/null-characters.ts\nvar removeNullCharacters = (value) => (\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, \"\")\n);\nvar padNullCharacters = (value, chars) => value.padEnd(chars, \"\\0\");\n\n// ../text-encoding-impl/dist/index.browser.js\nvar e = globalThis.TextDecoder;\nvar o = globalThis.TextEncoder;\n\n// src/utf8.ts\nvar getUtf8Encoder = () => {\n let textEncoder;\n return {\n description: \"utf8\",\n encode: (value) => new Uint8Array((textEncoder || (textEncoder = new o())).encode(value)),\n fixedSize: null,\n maxSize: null\n };\n};\nvar getUtf8Decoder = () => {\n let textDecoder;\n return {\n decode(bytes, offset = 0) {\n const value = (textDecoder || (textDecoder = new e())).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n description: \"utf8\",\n fixedSize: null,\n maxSize: null\n };\n};\nvar getUtf8Codec = () => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n\n// src/string.ts\nvar getStringEncoder = (options = {}) => {\n const size = options.size ?? getU32Encoder();\n const encoding = options.encoding ?? getUtf8Encoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n if (size === \"variable\") {\n return { ...encoding, description };\n }\n if (typeof size === \"number\") {\n return fixEncoder(encoding, size, description);\n }\n return {\n description,\n encode: (value) => {\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};\nvar getStringDecoder = (options = {}) => {\n const size = options.size ?? getU32Decoder();\n const encoding = options.encoding ?? getUtf8Decoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n if (size === \"variable\") {\n return { ...encoding, description };\n }\n if (typeof size === \"number\") {\n return fixDecoder(encoding, size, description);\n }\n return {\n decode: (bytes, 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};\nvar getStringCodec = (options = {}) => combineCodec(getStringEncoder(options), getStringDecoder(options));\nfunction getSizeDescription(size) {\n return typeof size === \"object\" ? size.description : `${size}`;\n}\n\nexport { assertValidBaseString, getBase10Codec, getBase10Decoder, getBase10Encoder, getBase16Codec, getBase16Decoder, getBase16Encoder, getBase58Codec, getBase58Decoder, getBase58Encoder, getBase64Codec, getBase64Decoder, getBase64Encoder, getBaseXCodec, getBaseXDecoder, getBaseXEncoder, getBaseXResliceCodec, getBaseXResliceDecoder, getBaseXResliceEncoder, getStringCodec, getStringDecoder, getStringEncoder, getUtf8Codec, getUtf8Decoder, getUtf8Encoder, padNullCharacters, removeNullCharacters };\n","import { combineCodec, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';\n\n// src/assertions.ts\nfunction assertNumberIsBetweenForCodec(codecDescription, min, max, value) {\n if (value < min || value > max) {\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`\n );\n }\n}\n\n// src/common.ts\nvar Endian = /* @__PURE__ */ ((Endian2) => {\n Endian2[Endian2[\"LITTLE\"] = 0] = \"LITTLE\";\n Endian2[Endian2[\"BIG\"] = 1] = \"BIG\";\n return Endian2;\n})(Endian || {});\nfunction sharedNumberFactory(input) {\n let littleEndian;\n let defaultDescription = input.name;\n if (input.size > 1) {\n littleEndian = !(\"endian\" in input.options) || input.options.endian === 0 /* LITTLE */;\n defaultDescription += littleEndian ? \"(le)\" : \"(be)\";\n }\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n littleEndian,\n maxSize: input.size\n };\n}\nfunction numberEncoderFactory(input) {\n const codecData = sharedNumberFactory(input);\n return {\n description: codecData.description,\n encode(value) {\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}\nfunction numberDecoderFactory(input) {\n const codecData = sharedNumberFactory(input);\n return {\n decode(bytes, offset = 0) {\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}\nfunction toArrayBuffer(bytes, offset, length) {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n\n// src/f32.ts\nvar getF32Encoder = (options = {}) => numberEncoderFactory({\n name: \"f32\",\n options,\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4\n});\nvar getF32Decoder = (options = {}) => numberDecoderFactory({\n get: (view, le) => view.getFloat32(0, le),\n name: \"f32\",\n options,\n size: 4\n});\nvar getF32Codec = (options = {}) => combineCodec(getF32Encoder(options), getF32Decoder(options));\nvar getF64Encoder = (options = {}) => numberEncoderFactory({\n name: \"f64\",\n options,\n set: (view, value, le) => view.setFloat64(0, value, le),\n size: 8\n});\nvar getF64Decoder = (options = {}) => numberDecoderFactory({\n get: (view, le) => view.getFloat64(0, le),\n name: \"f64\",\n options,\n size: 8\n});\nvar getF64Codec = (options = {}) => combineCodec(getF64Encoder(options), getF64Decoder(options));\nvar getI128Encoder = (options = {}) => numberEncoderFactory({\n name: \"i128\",\n options,\n range: [-BigInt(\"0x7fffffffffffffffffffffffffffffff\") - 1n, BigInt(\"0x7fffffffffffffffffffffffffffffff\")],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16\n});\nvar getI128Decoder = (options = {}) => numberDecoderFactory({\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigInt64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: \"i128\",\n options,\n size: 16\n});\nvar getI128Codec = (options = {}) => combineCodec(getI128Encoder(options), getI128Decoder(options));\nvar getI16Encoder = (options = {}) => numberEncoderFactory({\n name: \"i16\",\n options,\n range: [-Number(\"0x7fff\") - 1, Number(\"0x7fff\")],\n set: (view, value, le) => view.setInt16(0, value, le),\n size: 2\n});\nvar getI16Decoder = (options = {}) => numberDecoderFactory({\n get: (view, le) => view.getInt16(0, le),\n name: \"i16\",\n options,\n size: 2\n});\nvar getI16Codec = (options = {}) => combineCodec(getI16Encoder(options), getI16Decoder(options));\nvar getI32Encoder = (options = {}) => numberEncoderFactory({\n name: \"i32\",\n options,\n range: [-Number(\"0x7fffffff\") - 1, Number(\"0x7fffffff\")],\n set: (view, value, le) => view.setInt32(0, value, le),\n size: 4\n});\nvar getI32Decoder = (options = {}) => numberDecoderFactory({\n get: (view, le) => view.getInt32(0, le),\n name: \"i32\",\n options,\n size: 4\n});\nvar getI32Codec = (options = {}) => combineCodec(getI32Encoder(options), getI32Decoder(options));\nvar getI64Encoder = (options = {}) => 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});\nvar getI64Decoder = (options = {}) => numberDecoderFactory({\n get: (view, le) => view.getBigInt64(0, le),\n name: \"i64\",\n options,\n size: 8\n});\nvar getI64Codec = (options = {}) => combineCodec(getI64Encoder(options), getI64Decoder(options));\nvar getI8Encoder = (options = {}) => 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});\nvar getI8Decoder = (options = {}) => numberDecoderFactory({\n get: (view) => view.getInt8(0),\n name: \"i8\",\n options,\n size: 1\n});\nvar getI8Codec = (options = {}) => combineCodec(getI8Encoder(options), getI8Decoder(options));\nvar getShortU16Encoder = (options = {}) => ({\n description: options.description ?? \"shortU16\",\n encode: (value) => {\n assertNumberIsBetweenForCodec(\"shortU16\", 0, 65535, value);\n const bytes = [0];\n for (let ii = 0; ; ii += 1) {\n const alignedValue = value >> ii * 7;\n if (alignedValue === 0) {\n break;\n }\n const nextSevenBits = 127 & alignedValue;\n bytes[ii] = nextSevenBits;\n if (ii > 0) {\n bytes[ii - 1] |= 128;\n }\n }\n return new Uint8Array(bytes);\n },\n fixedSize: null,\n maxSize: 3\n});\nvar getShortU16Decoder = (options = {}) => ({\n decode: (bytes, offset = 0) => {\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 = 127 & currentByte;\n value |= nextSevenBits << byteIndex * 7;\n if ((currentByte & 128) === 0) {\n break;\n }\n }\n return [value, offset + byteCount];\n },\n description: options.description ?? \"shortU16\",\n fixedSize: null,\n maxSize: 3\n});\nvar getShortU16Codec = (options = {}) => combineCodec(getShortU16Encoder(options), getShortU16Decoder(options));\nvar getU128Encoder = (options = {}) => 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});\nvar getU128Decoder = (options = {}) => 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});\nvar getU128Codec = (options = {}) => combineCodec(getU128Encoder(options), getU128Decoder(options));\nvar getU16Encoder = (options = {}) => 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});\nvar getU16Decoder = (options = {}) => numberDecoderFactory({\n get: (view, le) => view.getUint16(0, le),\n name: \"u16\",\n options,\n size: 2\n});\nvar getU16Codec = (options = {}) => combineCodec(getU16Encoder(options), getU16Decoder(options));\nvar getU32Encoder = (options = {}) => 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});\nvar getU32Decoder = (options = {}) => numberDecoderFactory({\n get: (view, le) => view.getUint32(0, le),\n name: \"u32\",\n options,\n size: 4\n});\nvar getU32Codec = (options = {}) => combineCodec(getU32Encoder(options), getU32Decoder(options));\nvar getU64Encoder = (options = {}) => numberEncoderFactory({\n name: \"u64\",\n options,\n range: [0, BigInt(\"0xffffffffffffffff\")],\n set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),\n size: 8\n});\nvar getU64Decoder = (options = {}) => numberDecoderFactory({\n get: (view, le) => view.getBigUint64(0, le),\n name: \"u64\",\n options,\n size: 8\n});\nvar getU64Codec = (options = {}) => combineCodec(getU64Encoder(options), getU64Decoder(options));\nvar getU8Encoder = (options = {}) => numberEncoderFactory({\n name: \"u8\",\n options,\n range: [0, Number(\"0xff\")],\n set: (view, value) => view.setUint8(0, value),\n size: 1\n});\nvar getU8Decoder = (options = {}) => numberDecoderFactory({\n get: (view) => view.getUint8(0),\n name: \"u8\",\n options,\n size: 1\n});\nvar getU8Codec = (options = {}) => combineCodec(getU8Encoder(options), getU8Decoder(options));\n\nexport { Endian, assertNumberIsBetweenForCodec, getF32Codec, getF32Decoder, getF32Encoder, getF64Codec, getF64Decoder, getF64Encoder, getI128Codec, getI128Decoder, getI128Encoder, getI16Codec, getI16Decoder, getI16Encoder, getI32Codec, getI32Decoder, getI32Encoder, getI64Codec, getI64Decoder, getI64Encoder, getI8Codec, getI8Decoder, getI8Encoder, getShortU16Codec, getShortU16Decoder, getShortU16Encoder, getU128Codec, getU128Decoder, getU128Encoder, getU16Codec, getU16Decoder, getU16Encoder, getU32Codec, getU32Decoder, getU32Encoder, getU64Codec, getU64Decoder, getU64Encoder, getU8Codec, getU8Decoder, getU8Encoder };\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","/**\n * Quick primer on bitwise operations: https://stackoverflow.com/a/1436448/802047\n */\n\nexport enum AccountRole {\n // Bitflag guide: is signer ⌄⌄ is writable\n WRITABLE_SIGNER = /* 3 */ 0b11, // prettier-ignore\n READONLY_SIGNER = /* 2 */ 0b10, // prettier-ignore\n WRITABLE = /* 1 */ 0b01, // prettier-ignore\n READONLY = /* 0 */ 0b00, // prettier-ignore\n}\n\nconst IS_SIGNER_BITMASK = 0b10;\nconst IS_WRITABLE_BITMASK = 0b01;\n\nexport function downgradeRoleToNonSigner(role: AccountRole.READONLY_SIGNER): AccountRole.READONLY;\nexport function downgradeRoleToNonSigner(role: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole {\n return role & ~IS_SIGNER_BITMASK;\n}\n\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE): AccountRole.READONLY;\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE_SIGNER): AccountRole.READONLY_SIGNER;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole {\n return role & ~IS_WRITABLE_BITMASK;\n}\n\nexport function isSignerRole(role: AccountRole): role is AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER {\n return role >= AccountRole.READONLY_SIGNER;\n}\n\nexport function isWritableRole(role: AccountRole): role is AccountRole.WRITABLE | AccountRole.WRITABLE_SIGNER {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\n\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE_SIGNER, roleB: AccountRole): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.READONLY_SIGNER): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY, roleB: AccountRole.READONLY): AccountRole.READONLY; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole {\n return roleA | roleB;\n}\n\nexport function upgradeRoleToSigner(role: AccountRole.READONLY): AccountRole.READONLY_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole {\n return role | IS_SIGNER_BITMASK;\n}\n\nexport function upgradeRoleToWritable(role: AccountRole.READONLY): AccountRole.WRITABLE;\nexport function upgradeRoleToWritable(role: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole {\n return role | IS_WRITABLE_BITMASK;\n}\n","import { assertKeyGenerationIsAvailable } from '@solana/assertions';\n\nexport async function generateKeyPair(): Promise<CryptoKeyPair> {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ 'Ed25519', // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify']\n );\n return keyPair as CryptoKeyPair;\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n","export type Commitment = 'confirmed' | 'finalized' | 'processed';\n\nfunction getCommitmentScore(commitment: Commitment): number {\n switch (commitment) {\n case 'finalized':\n return 2;\n case 'confirmed':\n return 1;\n case 'processed':\n return 0;\n default:\n return ((_: never) => {\n throw new Error(`Unrecognized commitment \\`${commitment}\\`.`);\n })(commitment);\n }\n}\n\nexport function commitmentComparator(a: Commitment, b: Commitment): -1 | 0 | 1 {\n if (a === b) {\n return 0;\n }\n return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;\n}\n","// FIXME(solana-labs/solana/issues/30341) Beware that any value above 9007199254740991 may be\n// truncated or rounded because of a downcast to JavaScript `number` between your calling code and\n// the JSON-RPC transport.\nexport type LamportsUnsafeBeyond2Pow53Minus1 = bigint & { readonly __brand: unique symbol };\n\n// Largest possible value to be represented by a u64\nconst maxU64Value = 18446744073709551615n; // 2n ** 64n - 1n\n\nexport function isLamports(putativeLamports: bigint): putativeLamports is LamportsUnsafeBeyond2Pow53Minus1 {\n return putativeLamports >= 0 && putativeLamports <= maxU64Value;\n}\n\nexport function assertIsLamports(\n putativeLamports: bigint\n): asserts putativeLamports is LamportsUnsafeBeyond2Pow53Minus1 {\n if (putativeLamports < 0) {\n // TODO: Coded error.\n throw new Error('Input for 64-bit unsigned integer cannot be negative');\n }\n\n if (putativeLamports > maxU64Value) {\n // TODO: Coded error.\n throw new Error('Input number is too large to be represented as a 64-bit unsigned integer');\n }\n}\n\nexport function lamports(putativeLamports: bigint): LamportsUnsafeBeyond2Pow53Minus1 {\n assertIsLamports(putativeLamports);\n return putativeLamports;\n}\n","export type StringifiedBigInt = string & { readonly __brand: unique symbol };\n\nexport function isStringifiedBigInt(putativeBigInt: string): putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n return true;\n } catch (_) {\n return false;\n }\n}\n\nexport function assertIsStringifiedBigInt(putativeBigInt: string): asserts putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n } catch (e) {\n throw new Error(`\\`${putativeBigInt}\\` cannot be parsed as a BigInt`, {\n cause: e,\n });\n }\n}\n\nexport function stringifiedBigInt(putativeBigInt: string): StringifiedBigInt {\n assertIsStringifiedBigInt(putativeBigInt);\n return putativeBigInt;\n}\n","export type StringifiedNumber = string & { readonly __brand: unique symbol };\n\nexport function isStringifiedNumber(putativeNumber: string): putativeNumber is StringifiedNumber {\n return !Number.isNaN(Number(putativeNumber));\n}\n\nexport function assertIsStringifiedNumber(putativeNumber: string): asserts putativeNumber is StringifiedNumber {\n if (Number.isNaN(Number(putativeNumber))) {\n throw new Error(`\\`${putativeNumber}\\` cannot be parsed as a Number`);\n }\n}\n\nexport function stringifiedNumber(putativeNumber: string): StringifiedNumber {\n assertIsStringifiedNumber(putativeNumber);\n return putativeNumber;\n}\n","export type UnixTimestamp = number & { readonly __brand: unique symbol };\n\nexport function isUnixTimestamp(putativeTimestamp: number): putativeTimestamp is UnixTimestamp {\n // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date\n if (putativeTimestamp > 8.64e15 || putativeTimestamp < -8.64e15) {\n return false;\n }\n return true;\n}\n\nexport function assertIsUnixTimestamp(putativeTimestamp: number): asserts putativeTimestamp is UnixTimestamp {\n // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date\n try {\n if (putativeTimestamp > 8.64e15 || putativeTimestamp < -8.64e15) {\n throw new Error('Expected input number to be in the range [-8.64e15, 8.64e15]');\n }\n } catch (e) {\n throw new Error(`\\`${putativeTimestamp}\\` is not a timestamp`, {\n cause: e,\n });\n }\n}\n\nexport function unixTimestamp(putativeTimestamp: number): UnixTimestamp {\n assertIsUnixTimestamp(putativeTimestamp);\n return putativeTimestamp;\n}\n","/** Returns the max size or null if at least one size is null. */\nexport function maxCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : Math.max(all, size)),\n 0 as number | null\n );\n}\n\n/** Returns the sum of all sizes or null if at least one size is null. */\nexport function sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n","import { CodecData, Offset } from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { sumCodecSizes } from './utils';\n\n/**\n * Represents all the size options for array-like codecs\n * — i.e. `array`, `map` and `set`.\n *\n * It can be one of the following:\n * - a {@link NumberCodec} that prefixes its content with its size.\n * - a fixed number of items.\n * - or `'remainder'` to infer the number of items by dividing\n * the rest of the byte array by the fixed size of its item.\n * Note that this option is only available for fixed-size items.\n */\nexport type ArrayLikeCodecSize<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder | CodecData> =\n | TPrefix\n | number\n | 'remainder';\n\n/** Resolves the size of an array-like codec. */\nexport function decodeArrayLikeCodecSize(\n size: ArrayLikeCodecSize<NumberDecoder>,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: Offset\n): [number | bigint, Offset] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.decode(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumCodecSizes(childrenSizes);\n if (childrenSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n // TODO: Coded error.\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${childrenSize} bytes. ` +\n `Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainder} modulo ${childrenSize} should be equal to zero.`\n );\n }\n return [remainder / childrenSize, offset];\n }\n\n // TODO: Coded error.\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\n\nexport function getArrayLikeCodecSizeDescription(size: ArrayLikeCodecSize<CodecData>): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getArrayLikeCodecSizeFromChildren(\n size: ArrayLikeCodecSize<CodecData>,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumCodecSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getArrayLikeCodecSizePrefix(size: ArrayLikeCodecSize<NumberEncoder>, realSize: number): Uint8Array {\n return typeof size === 'object' ? size.encode(realSize) : new Uint8Array();\n}\n","/** Checks the number of items in an array-like structure is expected. */\nexport function assertValidNumberOfItemsForCodec(\n codecDescription: string,\n expected: number | bigint,\n actual: number | bigint\n) {\n if (expected !== actual) {\n // TODO: Coded error.\n throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);\n }\n}\n","import { BaseCodecOptions, Codec, CodecData, combineCodec, Decoder, Encoder, mergeBytes } from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport {\n ArrayLikeCodecSize,\n decodeArrayLikeCodecSize,\n getArrayLikeCodecSizeDescription,\n getArrayLikeCodecSizeFromChildren,\n getArrayLikeCodecSizePrefix,\n} from './array-like-codec-size';\nimport { assertValidNumberOfItemsForCodec } from './assertions';\n\n/** Defines the options for array codecs. */\nexport type ArrayCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The size of the array.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\n};\n\nfunction arrayCodecHelper(item: CodecData, size: ArrayLikeCodecSize<CodecData>, description?: string): CodecData {\n if (size === 'remainder' && item.fixedSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n return {\n description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize]),\n };\n}\n\n/**\n * Encodes an array of items.\n *\n * @param item - The encoder to use for the array's items.\n * @param options - A set of options for the encoder.\n */\nexport function getArrayEncoder<T>(item: Encoder<T>, options: ArrayCodecOptions<NumberEncoder> = {}): Encoder<T[]> {\n const size = options.size ?? getU32Encoder();\n return {\n ...arrayCodecHelper(item, size, options.description),\n encode: (value: T[]) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, value.length);\n }\n return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map(v => item.encode(v))]);\n },\n };\n}\n\n/**\n * Decodes an array of items.\n *\n * @param item - The encoder to use for the array's items.\n * @param options - A set of options for the encoder.\n */\nexport function getArrayDecoder<T>(item: Decoder<T>, options: ArrayCodecOptions<NumberDecoder> = {}): Decoder<T[]> {\n const size = options.size ?? getU32Decoder();\n return {\n ...arrayCodecHelper(item, size, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n const values: T[] = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.decode(bytes, offset);\n values.push(value);\n offset = newOffset;\n }\n return [values, offset];\n },\n };\n}\n\n/**\n * Creates a codec for an array of items.\n *\n * @param item - The codec to use for the array's items.\n * @param options - A set of options for the codec.\n */\nexport function getArrayCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: ArrayCodecOptions<NumberCodec> = {}\n): Codec<T[], U[]> {\n return combineCodec(getArrayEncoder(item, options), getArrayDecoder(item, options));\n}\n","import {\n assertByteArrayIsNotEmptyForCodec,\n assertFixedSizeCodec,\n BaseCodecOptions,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/** Defines the options for boolean codecs. */\nexport type BooleanCodecOptions<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The number codec to delegate to.\n * @defaultValue u8 size.\n */\n size?: TSize;\n};\n\n/**\n * Encodes booleans.\n *\n * @param options - A set of options for the encoder.\n */\nexport function getBooleanEncoder(options: BooleanCodecOptions<NumberEncoder> = {}): Encoder<boolean> {\n const size = options.size ?? getU8Encoder();\n assertFixedSizeCodec(size, 'Codec [bool] requires a fixed size.');\n\n return {\n description: options.description ?? `bool(${size.description})`,\n encode: (value: boolean) => size.encode(value ? 1 : 0),\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize,\n };\n}\n\n/**\n * Decodes booleans.\n *\n * @param options - A set of options for the decoder.\n */\nexport function getBooleanDecoder(options: BooleanCodecOptions<NumberDecoder> = {}): Decoder<boolean> {\n const size = options.size ?? getU8Decoder();\n assertFixedSizeCodec(size, 'Codec [bool] requires a fixed size.');\n\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('bool', bytes, offset);\n const [value, vOffset] = size.decode(bytes, offset);\n return [value === 1, vOffset];\n },\n description: options.description ?? `bool(${size.description})`,\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize,\n };\n}\n\n/**\n * Creates a boolean codec.\n *\n * @param options - A set of options for the codec.\n */\nexport function getBooleanCodec(options: BooleanCodecOptions<NumberCodec> = {}): Codec<boolean> {\n return combineCodec(getBooleanEncoder(options), getBooleanDecoder(options));\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecOptions,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n fixDecoder,\n fixEncoder,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/** Defines the options for bytes codecs. */\nexport type BytesCodecOptions<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The size of the byte array. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the byte array with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the byte array.\n * @defaultValue `'variable'`\n */\n size?: TSize | number | 'variable';\n};\n\n/**\n * Encodes sized bytes.\n *\n * @param options - A set of options for the encoder.\n */\nexport function getBytesEncoder(options: BytesCodecOptions<NumberEncoder> = {}): Encoder<Uint8Array> {\n const size = options.size ?? 'variable';\n const sizeDescription = typeof size === 'object' ? size.description : `${size}`;\n const description = options.description ?? `bytes(${sizeDescription})`;\n\n const byteEncoder: Encoder<Uint8Array> = {\n description,\n encode: (value: Uint8Array) => value,\n fixedSize: null,\n maxSize: null,\n };\n\n if (size === 'variable') {\n return byteEncoder;\n }\n\n if (typeof size === 'number') {\n return fixEncoder(byteEncoder, size, description);\n }\n\n return {\n ...byteEncoder,\n encode: (value: Uint8Array) => {\n const contentBytes = byteEncoder.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n };\n}\n\n/**\n * Decodes sized bytes.\n *\n * @param options - A set of options for the decoder.\n */\nexport function getBytesDecoder(options: BytesCodecOptions<NumberDecoder> = {}): Decoder<Uint8Array> {\n const size = options.size ?? 'variable';\n const sizeDescription = typeof size === 'object' ? size.description : `${size}`;\n const description = options.description ?? `bytes(${sizeDescription})`;\n\n const byteDecoder: Decoder<Uint8Array> = {\n decode: (bytes: Uint8Array, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n description,\n fixedSize: null,\n maxSize: null,\n };\n\n if (size === 'variable') {\n return byteDecoder;\n }\n\n if (typeof size === 'number') {\n return fixDecoder(byteDecoder, size, description);\n }\n\n return {\n ...byteDecoder,\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('bytes', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec('bytes', length, contentBytes);\n const [value, contentOffset] = byteDecoder.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n\n/**\n * Creates a sized bytes codec.\n *\n * @param options - A set of options for the codec.\n */\nexport function getBytesCodec(options: BytesCodecOptions<NumberCodec> = {}): Codec<Uint8Array> {\n return combineCodec(getBytesEncoder(options), getBytesDecoder(options));\n}\n","import {\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/**\n * Defines a scalar enum as a type from its constructor.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionType = ScalarEnum<Direction>;\n * ```\n */\nexport type ScalarEnum<T> = ({ [key: number | string]: string | number | T } | number | T) & NonNullable<unknown>;\n\n/** Defines the options for scalar enum codecs. */\nexport type ScalarEnumCodecOptions<TDiscriminator extends NumberCodec | NumberEncoder | NumberDecoder> =\n BaseCodecOptions & {\n /**\n * The codec to use for the enum discriminator.\n * @defaultValue u8 discriminator.\n */\n size?: TDiscriminator;\n };\n\nfunction scalarEnumCoderHelper<T>(\n constructor: ScalarEnum<T>,\n prefix: CodecData,\n description?: string\n): CodecData & {\n enumKeys: string[];\n enumValues: T[];\n isNumericEnum: boolean;\n minRange: number;\n maxRange: number;\n stringValues: string[];\n} {\n const enumKeys = Object.keys(constructor);\n const enumValues = Object.values(constructor);\n const isNumericEnum = enumValues.some(v => typeof v === 'number');\n const valueDescriptions = enumValues.filter(v => typeof v === 'string').join(', ');\n const minRange = 0;\n const maxRange = isNumericEnum ? enumValues.length / 2 - 1 : enumValues.length - 1;\n const stringValues: string[] = isNumericEnum ? [...enumKeys] : [...new Set([...enumKeys, ...enumValues])];\n\n return {\n description: description ?? `enum(${valueDescriptions}; ${prefix.description})`,\n enumKeys,\n enumValues,\n fixedSize: prefix.fixedSize,\n isNumericEnum,\n maxRange,\n maxSize: prefix.maxSize,\n minRange,\n stringValues,\n };\n}\n\n/**\n * Creates a scalar enum encoder.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param options - A set of options for the encoder.\n */\nexport function getScalarEnumEncoder<T>(\n constructor: ScalarEnum<T>,\n options: ScalarEnumCodecOptions<NumberEncoder> = {}\n): Encoder<T> {\n const prefix = options.size ?? getU8Encoder();\n const { description, fixedSize, maxSize, minRange, maxRange, stringValues, enumKeys, enumValues } =\n scalarEnumCoderHelper(constructor, prefix, options.description);\n return {\n description,\n encode: (value: T) => {\n const isInvalidNumber = typeof value === 'number' && (value < minRange || value > maxRange);\n const isInvalidString = typeof value === 'string' && !stringValues.includes(value);\n if (isInvalidNumber || isInvalidString) {\n // TODO: Coded error.\n throw new Error(\n `Invalid scalar enum variant. ` +\n `Expected one of [${stringValues.join(', ')}] ` +\n `or a number between ${minRange} and ${maxRange}, ` +\n `got \"${value}\".`\n );\n }\n if (typeof value === 'number') return prefix.encode(value);\n const valueIndex = enumValues.indexOf(value);\n if (valueIndex >= 0) return prefix.encode(valueIndex);\n return prefix.encode(enumKeys.indexOf(value as string));\n },\n fixedSize,\n maxSize,\n };\n}\n\n/**\n * Creates a scalar enum decoder.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param options - A set of options for the decoder.\n */\nexport function getScalarEnumDecoder<T>(\n constructor: ScalarEnum<T>,\n options: ScalarEnumCodecOptions<NumberDecoder> = {}\n): Decoder<T> {\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: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('enum', bytes, offset);\n const [value, newOffset] = prefix.decode(bytes, offset);\n const valueAsNumber = Number(value);\n offset = newOffset;\n if (valueAsNumber < minRange || valueAsNumber > maxRange) {\n // TODO: Coded error.\n throw new Error(\n `Enum discriminator out of range. ` +\n `Expected a number between ${minRange} and ${maxRange}, got ${valueAsNumber}.`\n );\n }\n return [(isNumericEnum ? valueAsNumber : enumValues[valueAsNumber]) as T, offset];\n },\n description,\n fixedSize,\n maxSize,\n };\n}\n\n/**\n * Creates a scalar enum codec.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param options - A set of options for the codec.\n */\nexport function getScalarEnumCodec<T>(\n constructor: ScalarEnum<T>,\n options: ScalarEnumCodecOptions<NumberCodec> = {}\n): Codec<T> {\n return combineCodec(getScalarEnumEncoder(constructor, options), getScalarEnumDecoder(constructor, options));\n}\n","import { BaseCodecOptions, Codec, CodecData, combineCodec, Decoder, Encoder, mergeBytes } from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport {\n ArrayLikeCodecSize,\n decodeArrayLikeCodecSize,\n getArrayLikeCodecSizeDescription,\n getArrayLikeCodecSizeFromChildren,\n getArrayLikeCodecSizePrefix,\n} from './array-like-codec-size';\nimport { assertValidNumberOfItemsForCodec } from './assertions';\n\n/** Defines the options for set codecs. */\nexport type SetCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The size of the set.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\n};\n\nfunction setCodecHelper(item: CodecData, size: ArrayLikeCodecSize<CodecData>, description?: string): CodecData {\n if (size === 'remainder' && item.fixedSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n return {\n description: description ?? `set(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize]),\n };\n}\n\n/**\n * Encodes an set of items.\n *\n * @param item - The encoder to use for the set's items.\n * @param options - A set of options for the encoder.\n */\nexport function getSetEncoder<T>(item: Encoder<T>, options: SetCodecOptions<NumberEncoder> = {}): Encoder<Set<T>> {\n const size = options.size ?? getU32Encoder();\n return {\n ...setCodecHelper(item, size, options.description),\n encode: (set: Set<T>) => {\n if (typeof size === 'number' && set.size !== size) {\n assertValidNumberOfItemsForCodec('set', size, set.size);\n }\n const itemBytes = Array.from(set, value => item.encode(value));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, set.size), ...itemBytes]);\n },\n };\n}\n\n/**\n * Decodes an set of items.\n *\n * @param item - The encoder to use for the set's items.\n * @param options - A set of options for the encoder.\n */\nexport function getSetDecoder<T>(item: Decoder<T>, options: SetCodecOptions<NumberDecoder> = {}): Decoder<Set<T>> {\n const size = options.size ?? getU32Decoder();\n return {\n ...setCodecHelper(item, size, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n const set: Set<T> = new Set();\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [set, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n set.add(value);\n }\n return [set, offset];\n },\n };\n}\n\n/**\n * Creates a codec for an set of items.\n *\n * @param item - The codec to use for the set's items.\n * @param options - A set of options for the codec.\n */\nexport function getSetCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: SetCodecOptions<NumberCodec> = {}\n): Codec<Set<T>, Set<U>> {\n return combineCodec(getSetEncoder(item, options), getSetDecoder(item, options));\n}\n","// src/pipe.ts\nfunction pipe(init, ...fns) {\n return fns.reduce((acc, fn) => fn(acc), init);\n}\n\nexport { pipe };\n","import { ITransactionWithSignatures } from '.';\nimport { BaseTransaction } from './types';\n\nexport function getUnsignedTransaction<TTransaction extends BaseTransaction>(\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction & ITransactionWithSignatures, keyof ITransactionWithSignatures> {\n if ('signatures' in transaction) {\n // The implication of the lifetime constraint changing is that any existing signatures are invalid.\n const {\n signatures: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n","import { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport type Blockhash = string & { readonly __brand: unique symbol };\n\ntype BlockhashLifetimeConstraint = Readonly<{\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n}>;\n\nexport interface ITransactionWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 ||\n // Highest value (32 bytes of 255)\n putativeBlockhash.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeBlockhash);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBlockhash}\\` is not a blockhash`, {\n cause: e,\n });\n }\n}\n\nexport function setTransactionLifetimeUsingBlockhash<TTransaction extends BaseTransaction & IDurableNonceTransaction>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures | 'lifetimeConstraint'> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash<\n TTransaction extends BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n) {\n if (\n 'lifetimeConstraint' in transaction &&\n transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n lifetimeConstraint: blockhashLifetimeConstraint,\n };\n Object.freeze(out);\n return out;\n}\n","import { Transaction, TransactionVersion } from './types';\n\ntype TransactionConfig<TVersion extends TransactionVersion> = Readonly<{\n version: TVersion;\n}>;\n\nexport function createTransaction<TVersion extends TransactionVersion>(\n config: TransactionConfig<TVersion>\n): Extract<Transaction, { version: TVersion }>;\nexport function createTransaction<TVersion extends TransactionVersion>({\n version,\n}: TransactionConfig<TVersion>): Transaction {\n const out: Transaction = {\n instructions: [],\n version,\n };\n Object.freeze(out);\n return out;\n}\n","import { Address } from '@solana/addresses';\nimport {\n AccountRole,\n IInstruction,\n IInstructionWithAccounts,\n IInstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\ntype AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n> = IInstruction<'11111111111111111111111111111111'> &\n IInstructionWithAccounts<\n readonly [\n WritableAccount<TNonceAccountAddress>,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount<TNonceAuthorityAddress> | WritableSignerAccount<TNonceAuthorityAddress>\n ]\n > &\n IInstructionWithData<AdvanceNonceAccountInstructionData>;\ntype AdvanceNonceAccountInstructionData = Uint8Array & {\n readonly __brand: unique symbol;\n};\ntype DurableNonceConfig<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> = Readonly<{\n readonly nonce: Nonce<TNonceValue>;\n readonly nonceAccountAddress: Address<TNonceAccountAddress>;\n readonly nonceAuthorityAddress: Address<TNonceAuthorityAddress>;\n}>;\nexport type Nonce<TNonceValue extends string = string> = TNonceValue & { readonly __brand: unique symbol };\ntype NonceLifetimeConstraint<TNonceValue extends string = string> = Readonly<{\n nonce: Nonce<TNonceValue>;\n}>;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Address<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\nexport interface IDurableNonceTransaction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint<TNonceValue>;\n}\n\nexport function assertIsDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): asserts transaction is BaseTransaction & IDurableNonceTransaction {\n if (!isDurableNonceTransaction(transaction)) {\n // TODO: Coded error.\n throw new Error('Transaction is not a durable nonce transaction');\n }\n}\n\nfunction createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n>(\n nonceAccountAddress: Address<TNonceAccountAddress>,\n nonceAuthorityAddress: Address<TNonceAuthorityAddress>\n): AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\nexport function isAdvanceNonceAccountInstruction(\n instruction: IInstruction\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.programAddress === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accounts?.length === 3 &&\n // First account is nonce account address\n instruction.accounts[0].address != null &&\n instruction.accounts[0].role === AccountRole.WRITABLE &&\n // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS &&\n instruction.accounts[1].role === AccountRole.READONLY &&\n // Third account is nonce authority account\n instruction.accounts[2].address != null &&\n isSignerRole(instruction.accounts[2].role)\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: Uint8Array): data is AdvanceNonceAccountInstructionData {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n\nfunction isDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): transaction is BaseTransaction & IDurableNonceTransaction {\n return (\n 'lifetimeConstraint' in transaction &&\n typeof transaction.lifetimeConstraint.nonce === 'string' &&\n transaction.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transaction.instructions[0])\n );\n}\n\nfunction isAdvanceNonceAccountInstructionForNonce<\n TNonceAccountAddress extends Address = Address,\n TNonceAuthorityAddress extends Address = Address\n>(\n instruction: AdvanceNonceAccountInstruction,\n nonceAccountAddress: TNonceAccountAddress,\n nonceAuthorityAddress: TNonceAuthorityAddress\n): instruction is AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return (\n instruction.accounts[0].address === nonceAccountAddress &&\n instruction.accounts[2].address === nonceAuthorityAddress\n );\n}\n\nexport function setTransactionLifetimeUsingDurableNonce<\n TTransaction extends BaseTransaction,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n>(\n {\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n }: DurableNonceConfig<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>,\n transaction: TTransaction | (TTransaction & IDurableNonceTransaction)\n): Omit<TTransaction, keyof ITransactionWithSignatures> &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue> {\n let newInstructions: [\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n\n const firstInstruction = transaction.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {\n return transaction as TTransaction &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions.slice(1),\n ];\n }\n } else {\n // we don't have an existing advance nonce instruction as the first instruction, prepend one\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions,\n ];\n }\n\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: newInstructions,\n lifetimeConstraint: {\n nonce,\n },\n } as TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n Object.freeze(out);\n return out;\n}\n","import { Address } from '@solana/addresses';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport interface ITransactionWithFeePayer<TAddress extends string = string> {\n readonly feePayer: Address<TAddress>;\n}\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Address<TFeePayerAddress>,\n transaction:\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Address<TFeePayerAddress>,\n transaction: TTransaction | (TTransaction & ITransactionWithFeePayer<string>)\n): TTransaction & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Address<TFeePayerAddress>,\n transaction:\n | TTransaction\n | (TTransaction & ITransactionWithFeePayer<string>)\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n) {\n if ('feePayer' in transaction && feePayer === transaction.feePayer) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n feePayer,\n };\n Object.freeze(out);\n return out;\n}\n","import { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport function appendTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [...transaction.instructions, instruction],\n };\n Object.freeze(out);\n return out;\n}\n\nexport function prependTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [instruction, ...transaction.instructions],\n };\n Object.freeze(out);\n return out;\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { CompilableTransaction } from '../compilable-transaction';\nimport { CompiledTransaction, getCompiledTransaction } from '../compile-transaction';\nimport { decompileTransaction } from '../decompile-transaction';\nimport { ITransactionWithSignatures } from '../signatures';\nimport { getCompiledMessageDecoder, getCompiledMessageEncoder } from './message';\n\nconst signaturesDescription = __DEV__ ? 'A compact array of 64-byte, base-64 encoded Ed25519 signatures' : 'signatures';\nconst transactionDescription = __DEV__ ? 'The wire format of a Solana transaction' : 'transaction';\n\nfunction getCompiledTransactionEncoder(): Encoder<CompiledTransaction> {\n return getStructEncoder(\n [\n [\n 'signatures',\n getArrayEncoder(getBytesEncoder({ size: 64 }), {\n description: signaturesDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageEncoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nfunction getSignatureDecoder(): Decoder<SignatureBytes> {\n return mapDecoder(getBytesDecoder({ size: 64 }), bytes => bytes as SignatureBytes);\n}\n\nfunction getCompiledTransactionDecoder(): Decoder<CompiledTransaction> {\n return getStructDecoder(\n [\n [\n 'signatures',\n getArrayDecoder(getSignatureDecoder(), {\n description: signaturesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageDecoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nexport function getTransactionEncoder(): Encoder<\n CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n> {\n return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);\n}\n\nexport function getTransactionDecoder(\n lastValidBlockHeight?: bigint\n): Decoder<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return mapDecoder(getCompiledTransactionDecoder(), compiledTransaction =>\n decompileTransaction(compiledTransaction, lastValidBlockHeight)\n );\n}\n\nexport function getTransactionCodec(\n lastValidBlockHeight?: bigint\n): Codec<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport {\n AccountRole,\n IAccountLookupMeta,\n IAccountMeta,\n IInstruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit<WritableSignerAccount, 'address'> & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit<ReadonlyAccountLookup | WritableAccountLookup, 'address'> & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = (IAccountMeta | IAccountLookupMeta)[] & { readonly __brand: unique symbol };\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Address,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry | Record<never, never>\n ) => AddressMap[Address]\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(feePayer: Address, instructions: readonly IInstruction[]): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set<Address>();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and set as the fee payer. Program addresses may not pay fees.'\n );\n default:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and marked writable. Program addresses may not be writable.'\n );\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType<typeof getAddressComparator>;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry as FeePayerAccountEntry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry as LookupTableAccountEntry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${account.address}\\`) which is both invoked and ` +\n 'marked writable. Program addresses may not be ' +\n 'writable.'\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType<typeof getAddressComparator>;\n const orderedAccounts: (IAccountMeta | IAccountLookupMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Address<typeof address>,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype AddressTableLookup = Readonly<{\n lookupTableAddress: Address;\n readableIndices: readonly number[];\n writableIndices: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<Address, { readonly readableIndices: number[]; readonly writableIndices: number[] }> = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readableIndices: [],\n writableIndices: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndices.push(account.addressIndex);\n } else {\n entry.readableIndices.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Address,\n ...index[lookupTableAddress as unknown as Address],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype MessageHeader = Readonly<{\n numReadonlyNonSignerAccounts: number;\n numReadonlySignerAccounts: number;\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Address } from '@solana/addresses';\nimport { IInstruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n accountIndices?: number[];\n data?: Uint8Array;\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record<Address, number> = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly IInstruction[],\n orderedAccounts: OrderedAccounts\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { IDurableNonceTransaction, ITransactionWithBlockhashLifetime } from './index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (ITransactionWithBlockhashLifetime | IDurableNonceTransaction)['lifetimeConstraint']\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Address } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Address[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { CompilableTransaction } from './compilable-transaction';\nimport { getCompiledAddressTableLookups } from './compile-address-table-lookups';\nimport { getCompiledMessageHeader } from './compile-header';\nimport { getCompiledInstructions } from './compile-instructions';\nimport { getCompiledLifetimeToken } from './compile-lifetime-token';\nimport { getCompiledStaticAccounts } from './compile-static-accounts';\n\ntype BaseCompiledMessage = Readonly<{\n header: ReturnType<typeof getCompiledMessageHeader>;\n instructions: ReturnType<typeof getCompiledInstructions>;\n lifetimeToken: ReturnType<typeof getCompiledLifetimeToken>;\n staticAccounts: ReturnType<typeof getCompiledStaticAccounts>;\n}>;\n\nexport type CompiledMessage = LegacyCompiledMessage | VersionedCompiledMessage;\n\ntype LegacyCompiledMessage = BaseCompiledMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledMessage = BaseCompiledMessage &\n Readonly<{\n addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups>;\n version: number;\n }>;\n\nexport function compileMessage(\n transaction: CompilableTransaction & Readonly<{ version: 'legacy' }>\n): LegacyCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): VersionedCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): CompiledMessage {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...(transaction.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),\n lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transaction.version,\n };\n}\n","import { SignatureBytes } from '@solana/keys';\n\nimport { CompilableTransaction } from './compilable-transaction';\nimport { CompiledMessage, compileMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\n\nexport type CompiledTransaction = Readonly<{\n compiledMessage: CompiledMessage;\n signatures: SignatureBytes[];\n}>;\n\nexport function getCompiledTransaction(\n transaction: CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n): CompiledTransaction {\n const compiledMessage = compileMessage(transaction);\n let signatures;\n if ('signatures' in transaction) {\n signatures = [];\n for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {\n signatures[ii] =\n transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));\n }\n } else {\n signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));\n }\n return {\n compiledMessage,\n signatures,\n };\n}\n","import { Address, assertIsAddress } from '@solana/addresses';\nimport { pipe } from '@solana/functional';\nimport { AccountRole, IAccountMeta, IInstruction } from '@solana/instructions';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { Blockhash, setTransactionLifetimeUsingBlockhash } from './blockhash';\nimport { CompilableTransaction } from './compilable-transaction';\nimport { CompiledTransaction } from './compile-transaction';\nimport { createTransaction } from './create-transaction';\nimport { isAdvanceNonceAccountInstruction, Nonce, setTransactionLifetimeUsingDurableNonce } from './durable-nonce';\nimport { setTransactionFeePayer } from './fee-payer';\nimport { appendTransactionInstruction } from './instructions';\nimport { CompiledMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\nimport { TransactionVersion } from './types';\n\nfunction getAccountMetas(message: CompiledMessage): IAccountMeta[] {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts =\n message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n\n const accountMetas: IAccountMeta[] = [];\n\n let accountIndex = 0;\n for (let i = 0; i < numWritableSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlySignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY,\n });\n accountIndex++;\n }\n\n return accountMetas;\n}\n\nfunction convertInstruction(\n instruction: CompiledMessage['instructions'][0],\n accountMetas: IAccountMeta[]\n): IInstruction {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n // TODO coded error\n throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);\n }\n\n const accounts = instruction.accountIndices?.map(accountIndex => accountMetas[accountIndex]);\n const { data } = instruction;\n\n return {\n programAddress,\n ...(accounts && accounts.length ? { accounts } : {}),\n ...(data && data.length ? { data } : {}),\n };\n}\n\ntype LifetimeConstraint =\n | {\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n }\n | {\n nonce: Nonce;\n nonceAccountAddress: Address;\n nonceAuthorityAddress: Address;\n };\n\nfunction getLifetimeConstraint(\n messageLifetimeToken: string,\n firstInstruction?: IInstruction,\n lastValidBlockHeight?: bigint\n): LifetimeConstraint {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n // first instruction is not advance durable nonce, so use blockhash lifetime constraint\n return {\n blockhash: messageLifetimeToken as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n } else {\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = firstInstruction.accounts![0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = firstInstruction.accounts![2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n return {\n nonce: messageLifetimeToken as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n }\n}\n\nfunction convertSignatures(compiledTransaction: CompiledTransaction): ITransactionWithSignatures['signatures'] {\n const {\n compiledMessage: { staticAccounts },\n signatures,\n } = compiledTransaction;\n return signatures.reduce((acc, sig, index) => {\n // compiled transaction includes a fake all 0 signature if it hasn't been signed\n // we don't store those for the new tx model. So just skip if it's all 0s\n const allZeros = sig.every(byte => byte === 0);\n if (allZeros) return acc;\n\n const address = staticAccounts[index];\n return { ...acc, [address]: sig as SignatureBytes };\n }, {});\n}\n\nexport function decompileTransaction(\n compiledTransaction: CompiledTransaction,\n lastValidBlockHeight?: bigint\n): CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures) {\n const { compiledMessage } = compiledTransaction;\n\n // TODO: add support for address lookup tables\n if ('addressTableLookups' in compiledMessage && compiledMessage.addressTableLookups!.length > 0) {\n // TODO: coded error\n throw new Error('Cannot convert transaction with addressTableLookups');\n }\n\n const feePayer = compiledMessage.staticAccounts[0];\n // TODO: coded error\n if (!feePayer) throw new Error('No fee payer set in CompiledTransaction');\n\n const accountMetas = getAccountMetas(compiledMessage);\n\n const instructions: IInstruction[] = compiledMessage.instructions.map(compiledInstruction =>\n convertInstruction(compiledInstruction, accountMetas)\n );\n\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledMessage.lifetimeToken,\n firstInstruction,\n lastValidBlockHeight\n );\n\n const signatures = convertSignatures(compiledTransaction);\n\n return pipe(\n createTransaction({ version: compiledMessage.version as TransactionVersion }),\n tx => setTransactionFeePayer(feePayer, tx),\n tx =>\n instructions.reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n tx =>\n 'blockhash' in lifetimeConstraint\n ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx)\n : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),\n tx => (compiledTransaction.signatures.length ? { ...tx, signatures } : tx)\n );\n}\n","import { 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 { Address } from '@solana/addresses';\nimport { Signature } from '@solana/keys';\nimport { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport { RequestAirdropApi } from '@solana/rpc-core/dist/types/rpc-methods/requestAirdrop';\nimport { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment, LamportsUnsafeBeyond2Pow53Minus1 } from '@solana/rpc-types';\n\nimport { createDefaultSignatureOnlyRecentTransactionConfirmer } from './airdrop-confirmer';\n\ntype AirdropRequesterConfig = Readonly<{\n rpc: Rpc<RequestAirdropApi & GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>;\n}>;\n\nexport function createDefaultAirdropRequester({ rpc, rpcSubscriptions }: AirdropRequesterConfig) {\n const confirmSignatureOnlyTransaction = createDefaultSignatureOnlyRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n });\n return async function requestAirdrop(\n config: Omit<Parameters<typeof requestAndConfirmAirdrop>[0], 'confirmSignatureOnlyTransaction' | 'rpc'>\n ) {\n return await requestAndConfirmAirdrop({\n ...config,\n confirmSignatureOnlyTransaction,\n rpc,\n });\n };\n}\n\nexport async function requestAndConfirmAirdrop({\n abortSignal,\n commitment,\n confirmSignatureOnlyTransaction,\n lamports,\n recipientAddress,\n rpc,\n}: Readonly<{\n abortSignal?: AbortSignal;\n commitment: Commitment;\n confirmSignatureOnlyTransaction: ReturnType<typeof createDefaultSignatureOnlyRecentTransactionConfirmer>;\n lamports: LamportsUnsafeBeyond2Pow53Minus1;\n recipientAddress: Address;\n rpc: Rpc<RequestAirdropApi>;\n}>): Promise<Signature> {\n const airdropTransactionSignature = await rpc\n .requestAirdrop(recipientAddress, lamports, { commitment })\n .send({ abortSignal });\n await confirmSignatureOnlyTransaction({\n abortSignal,\n commitment,\n signature: airdropTransactionSignature,\n });\n return airdropTransactionSignature;\n}\n","import { Signature } from '@solana/keys';\nimport { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './transaction-confirmation-strategy-racer';\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\nimport { getTimeoutPromise } from './transaction-confirmation-strategy-timeout';\n\ninterface DefaultSignatureOnlyRecentTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>;\n}\n\ninterface WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig\n extends BaseTransactionConfirmationStrategyConfig {\n getTimeoutPromise: typeof getTimeoutPromise;\n signature: Signature;\n}\n\n/** @deprecated */\nexport function createDefaultSignatureOnlyRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultSignatureOnlyRecentTransactionConfirmerConfig) {\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions\n );\n return async function confirmSignatureOnlyRecentTransaction(\n config: Omit<\n Parameters<typeof waitForRecentTransactionConfirmationUntilTimeout>[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >\n ) {\n await waitForRecentTransactionConfirmationUntilTimeout({\n ...config,\n getRecentSignatureConfirmationPromise,\n getTimeoutPromise,\n });\n };\n}\n\n/** @deprecated */\nexport async function waitForRecentTransactionConfirmationUntilTimeout(\n config: WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig\n): Promise<void> {\n await raceStrategies(\n config.signature,\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise }) {\n return [\n getTimeoutPromise({\n abortSignal,\n commitment,\n }),\n ];\n }\n );\n}\n","import { Signature } from '@solana/keys';\nimport { Commitment } from '@solana/rpc-types';\n\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\n\nexport interface BaseTransactionConfirmationStrategyConfig {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n getRecentSignatureConfirmationPromise: ReturnType<typeof createRecentSignatureConfirmationPromiseFactory>;\n}\n\ntype WithNonNullableAbortSignal<T> = Omit<T, 'abortSignal'> & Readonly<{ abortSignal: AbortSignal }>;\n\nexport async function raceStrategies<TConfig extends BaseTransactionConfirmationStrategyConfig>(\n signature: Signature,\n config: TConfig,\n getSpecificStrategiesForRace: (config: WithNonNullableAbortSignal<TConfig>) => readonly Promise<unknown>[]\n) {\n const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;\n callerAbortSignal?.throwIfAborted();\n const abortController = new AbortController();\n if (callerAbortSignal) {\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n }\n try {\n const specificStrategies = getSpecificStrategiesForRace({\n ...config,\n abortSignal: abortController.signal,\n });\n return await Promise.race([\n getRecentSignatureConfirmationPromise({\n abortSignal: abortController.signal,\n commitment,\n signature,\n }),\n ...specificStrategies,\n ]);\n } finally {\n abortController.abort();\n }\n}\n","import { Signature } from '@solana/keys';\nimport { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\n\ntype GetRecentSignatureConfirmationPromiseFn = (config: {\n abortSignal: AbortSignal;\n commitment: Commitment;\n signature: Signature;\n}) => Promise<void>;\n\nexport function createRecentSignatureConfirmationPromiseFactory(\n rpc: Rpc<GetSignatureStatusesApi>,\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>\n): GetRecentSignatureConfirmationPromiseFn {\n return async function getRecentSignatureConfirmationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n signature,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for status changes to a signature.\n */\n const signatureStatusNotifications = await rpcSubscriptions\n .signatureNotifications(signature, { commitment })\n .subscribe({ abortSignal: abortController.signal });\n const signatureDidCommitPromise = (async () => {\n for await (const signatureStatusNotification of signatureStatusNotifications) {\n if (signatureStatusNotification.value.err) {\n // TODO: Coded error.\n throw new Error(`The transaction with signature \\`${signature}\\` failed.`, {\n cause: signatureStatusNotification.value.err,\n });\n } else {\n return;\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current status.\n * This will only yield a result if the signature is still in the status cache.\n */\n const signatureStatusLookupPromise = (async () => {\n const { value: signatureStatusResults } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: abortController.signal });\n const signatureStatus = signatureStatusResults[0];\n if (\n signatureStatus &&\n signatureStatus.confirmationStatus &&\n commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0\n ) {\n return;\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await Promise.race([signatureDidCommitPromise, signatureStatusLookupPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import { Commitment } from '@solana/rpc-types';\n\ntype Config = Readonly<{\n abortSignal: AbortSignal;\n commitment: Commitment;\n}>;\n\nexport async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }: Config) {\n return await new Promise((_, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n clearTimeout(timeoutId);\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n callerAbortSignal.addEventListener('abort', handleAbort);\n const timeoutMs = commitment === 'processed' ? 30_000 : 60_000;\n const startMs = performance.now();\n const timeoutId =\n // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure\n // elapsed time instead of active time.\n // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static\n setTimeout(() => {\n const elapsedMs = performance.now() - startMs;\n reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, 'TimeoutError'));\n }, timeoutMs);\n });\n}\n","import { pipe } from '@solana/functional';\nimport {\n createSolanaRpcApi,\n createSolanaRpcSubscriptionsApi,\n createSolanaRpcSubscriptionsApi_UNSTABLE,\n SolanaRpcMethods,\n SolanaRpcSubscriptions,\n SolanaRpcSubscriptionsUnstable,\n} from '@solana/rpc-core';\nimport { createJsonRpc, createJsonSubscriptionRpc } from '@solana/rpc-transport';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\n\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\nimport { getRpcSubscriptionsWithSubscriptionCoalescing } from './rpc-subscription-coalescer';\n\nexport function createSolanaRpc(config: Omit<Parameters<typeof createJsonRpc>[0], 'api'>): Rpc<SolanaRpcMethods> {\n return createJsonRpc({\n ...config,\n api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n });\n}\n\nexport function createSolanaRpcSubscriptions(\n config: Omit<Parameters<typeof createJsonSubscriptionRpc>[0], 'api'>\n): RpcSubscriptions<SolanaRpcSubscriptions> {\n return pipe(\n createJsonSubscriptionRpc({\n ...config,\n api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG),\n }),\n rpcSubscriptions =>\n getRpcSubscriptionsWithSubscriptionCoalescing({\n getDeduplicationKey: (...args) => fastStableStringify(args),\n rpcSubscriptions,\n })\n );\n}\n\nexport function createSolanaRpcSubscriptions_UNSTABLE(\n config: Omit<Parameters<typeof createJsonSubscriptionRpc>[0], 'api'>\n): RpcSubscriptions<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return createJsonSubscriptionRpc({\n ...config,\n api: createSolanaRpcSubscriptionsApi_UNSTABLE(DEFAULT_RPC_CONFIG),\n });\n}\n","type IntegerOverflowHandler = (keyPath: (number | string)[], value: bigint) => void;\ntype Patched<T> = T extends object ? { [Property in keyof T]: Patched<T[Property]> } : T extends bigint ? number : T;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction visitNode<T>(value: T, keyPath: (number | string)[], onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n if (Array.isArray(value)) {\n return value.map((element, ii) =>\n visitNode(element, [...keyPath, ii], onIntegerOverflow)\n ) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const propName in value) {\n if (Object.prototype.hasOwnProperty.call(value, propName)) {\n out[propName] = visitNode(value[propName], [...keyPath, propName], onIntegerOverflow);\n }\n }\n return out as TypescriptBug33014;\n } else if (typeof value === 'bigint') {\n // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // downcasting `bigints` to `numbers`.\n if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {\n onIntegerOverflow(keyPath, value);\n }\n return Number(value) as TypescriptBug33014;\n } else {\n return value as TypescriptBug33014;\n }\n}\n\nexport function patchParamsForSolanaLabsRpc<T>(params: T, onIntegerOverflow?: IntegerOverflowHandler): Patched<T> {\n return visitNode(params, [], onIntegerOverflow);\n}\n","export type KeyPathWildcard = { readonly __brand: unique symbol };\n\nexport const KEYPATH_WILDCARD = {} as KeyPathWildcard;\n","import { IRpcSubscriptionsApi } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { KeyPath } from './response-patcher';\nimport { KEYPATH_WILDCARD } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\nimport { SolanaRpcSubscriptions, SolanaRpcSubscriptionsUnstable } from './rpc-subscriptions';\n\n// Numeric values nested in `jsonParsed` accounts\nconst jsonParsedTokenAccountsConfigs = [\n // parsed Token/Token22 token account\n ['data', 'parsed', 'info', 'tokenAmount', 'decimals'],\n ['data', 'parsed', 'info', 'tokenAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'decimals'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'uiAmount'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'decimals'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'olderTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'newerTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n];\nconst jsonParsedAccountsConfigs = [\n ...jsonParsedTokenAccountsConfigs,\n // parsed AddressTableLookup account\n ['data', 'parsed', 'info', 'lastExtendedSlotStartIndex'],\n // parsed Config account\n ['data', 'parsed', 'info', 'slashPenalty'],\n ['data', 'parsed', 'info', 'warmupCooldownRate'],\n // parsed Token/Token22 mint account\n ['data', 'parsed', 'info', 'decimals'],\n // parsed Token/Token22 multisig account\n ['data', 'parsed', 'info', 'numRequiredSigners'],\n ['data', 'parsed', 'info', 'numValidSigners'],\n // parsed Stake account\n ['data', 'parsed', 'info', 'stake', 'delegation', 'warmupCooldownRate'],\n // parsed Sysvar rent account\n ['data', 'parsed', 'info', 'exemptionThreshold'],\n ['data', 'parsed', 'info', 'burnPercent'],\n // parsed Vote account\n ['data', 'parsed', 'info', 'commission'],\n ['data', 'parsed', 'info', 'votes', KEYPATH_WILDCARD, 'confirmationCount'],\n];\n\ntype AllowedNumericKeypaths<TApi> = Partial<Record<keyof TApi, readonly KeyPath[]>>;\n\nlet memoizedNotificationKeypaths: AllowedNumericKeypaths<\n IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>\n>;\nlet memoizedResponseKeypaths: AllowedNumericKeypaths<ReturnType<typeof createSolanaRpcApi>>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nexport function getAllowedNumericKeypathsForNotification(): AllowedNumericKeypaths<\n IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>\n> {\n if (!memoizedNotificationKeypaths) {\n memoizedNotificationKeypaths = {\n accountNotifications: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n blockNotifications: [\n ['value', 'block', 'blockTime'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['value', 'block', 'transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'index',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlySignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlyUnsignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numRequiredSignatures',\n ],\n ['value', 'block', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n programNotifications: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n };\n }\n return memoizedNotificationKeypaths;\n}\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nexport function getAllowedNumericKeypathsForResponse(): AllowedNumericKeypaths<ReturnType<typeof createSolanaRpcApi>> {\n if (!memoizedResponseKeypaths) {\n memoizedResponseKeypaths = {\n getAccountInfo: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n getBlock: [\n ['blockTime'],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'innerInstructions', KEYPATH_WILDCARD, 'index'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', 'header', 'numReadonlySignedAccounts'],\n ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', 'header', 'numReadonlyUnsignedAccounts'],\n ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', 'header', 'numRequiredSignatures'],\n ['rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n getBlockTime: [[]],\n getClusterNodes: [\n [KEYPATH_WILDCARD, 'featureSet'],\n [KEYPATH_WILDCARD, 'shredVersion'],\n ],\n getInflationGovernor: [['initial'], ['foundation'], ['foundationTerm'], ['taper'], ['terminal']],\n getInflationRate: [['foundation'], ['total'], ['validator']],\n getInflationReward: [[KEYPATH_WILDCARD, 'commission']],\n getMultipleAccounts: jsonParsedAccountsConfigs.map(c => ['value', KEYPATH_WILDCARD, ...c]),\n getProgramAccounts: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n getRecentPerformanceSamples: [[KEYPATH_WILDCARD, 'samplePeriodSecs']],\n getTokenAccountBalance: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenLargestAccounts: [\n ['value', KEYPATH_WILDCARD, 'decimals'],\n ['value', KEYPATH_WILDCARD, 'uiAmount'],\n ],\n getTokenSupply: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTransaction: [\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ['meta', 'innerInstructions', KEYPATH_WILDCARD, 'index'],\n ['meta', 'innerInstructions', KEYPATH_WILDCARD, 'instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n [\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n ['transaction', 'message', 'instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['transaction', 'message', 'instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['transaction', 'message', 'header', 'numReadonlySignedAccounts'],\n ['transaction', 'message', 'header', 'numReadonlyUnsignedAccounts'],\n ['transaction', 'message', 'header', 'numRequiredSignatures'],\n ],\n getVersion: [['feature-set']],\n getVoteAccounts: [\n ['current', KEYPATH_WILDCARD, 'commission'],\n ['delinquent', KEYPATH_WILDCARD, 'commission'],\n ],\n simulateTransaction: jsonParsedAccountsConfigs.map(c => ['value', 'accounts', KEYPATH_WILDCARD, ...c]),\n };\n }\n return memoizedResponseKeypaths;\n}\n","import {\n getAllowedNumericKeypathsForNotification,\n getAllowedNumericKeypathsForResponse,\n} from './response-patcher-allowed-numeric-values';\nimport { KEYPATH_WILDCARD, KeyPathWildcard } from './response-patcher-types';\nimport { createSolanaRpcApi } from './rpc-methods';\nimport { createSolanaRpcSubscriptionsApi } from './rpc-subscriptions';\n\nexport type KeyPath = ReadonlyArray<KeyPathWildcard | number | string | KeyPath>;\n// FIXME(https://github.com/microsoft/TypeScript/issues/33014)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TypescriptBug33014 = any;\n\nfunction getNextAllowedKeypaths(keyPaths: readonly KeyPath[], property: number | string) {\n return keyPaths\n .filter(keyPath => (keyPath[0] === KEYPATH_WILDCARD && typeof property === 'number') || keyPath[0] === property)\n .map(keyPath => keyPath.slice(1));\n}\n\nfunction visitNode<T>(value: unknown, allowedKeypaths: readonly KeyPath[]): T {\n if (Array.isArray(value)) {\n return value.map((element, ii) => {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, ii);\n return visitNode(element, nextAllowedKeypaths);\n }) as TypescriptBug33014;\n } else if (typeof value === 'object' && value !== null) {\n const out = {} as TypescriptBug33014;\n for (const [propName, innerValue] of Object.entries(value)) {\n const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, propName);\n out[propName] = visitNode(innerValue, nextAllowedKeypaths);\n }\n return out as TypescriptBug33014;\n } else if (\n typeof value === 'number' &&\n // The presence of an allowed keypath on the route to this value implies it's allowlisted;\n // Upcast the value to `bigint` unless an allowed keypath is present.\n allowedKeypaths.length === 0 &&\n // Only try to upcast an Integer to `bigint`\n Number.isInteger(value)\n ) {\n // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // upcasting `numbers` to `bigints`.\n return BigInt(value) as TypescriptBug33014;\n } else {\n return value as TypescriptBug33014;\n }\n}\n\nexport function patchResponseForSolanaLabsRpc<T>(\n rawResponse: unknown,\n methodName?: keyof ReturnType<typeof createSolanaRpcApi>\n): T {\n const allowedKeypaths = methodName ? getAllowedNumericKeypathsForResponse()[methodName] : undefined;\n return visitNode(rawResponse, allowedKeypaths ?? []);\n}\n\nexport function patchResponseForSolanaLabsRpcSubscriptions<T>(\n rawResponse: unknown,\n methodName?: keyof ReturnType<typeof createSolanaRpcSubscriptionsApi>\n): T {\n const allowedKeypaths = methodName ? getAllowedNumericKeypathsForNotification()[methodName] : undefined;\n return visitNode(rawResponse, allowedKeypaths ?? []);\n}\n","import { IRpcApi, RpcRequest } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { patchParamsForSolanaLabsRpc } from '../params-patcher';\nimport { patchResponseForSolanaLabsRpc } from '../response-patcher';\nimport { GetAccountInfoApi } from './getAccountInfo';\nimport { GetBalanceApi } from './getBalance';\nimport { GetBlockApi } from './getBlock';\nimport { GetBlockCommitmentApi } from './getBlockCommitment';\nimport { GetBlockHeightApi } from './getBlockHeight';\nimport { GetBlockProductionApi } from './getBlockProduction';\nimport { GetBlocksApi } from './getBlocks';\nimport { GetBlocksWithLimitApi } from './getBlocksWithLimit';\nimport { GetBlockTimeApi } from './getBlockTime';\nimport { GetClusterNodesApi } from './getClusterNodes';\nimport { GetEpochInfoApi } from './getEpochInfo';\nimport { GetEpochScheduleApi } from './getEpochSchedule';\nimport { GetFeeForMessageApi } from './getFeeForMessage';\nimport { GetFirstAvailableBlockApi } from './getFirstAvailableBlock';\nimport { GetGenesisHashApi } from './getGenesisHash';\nimport { GetHealthApi } from './getHealth';\nimport { GetHighestSnapshotSlotApi } from './getHighestSnapshotSlot';\nimport { GetIdentityApi } from './getIdentity';\nimport { GetInflationGovernorApi } from './getInflationGovernor';\nimport { GetInflationRateApi } from './getInflationRate';\nimport { GetInflationRewardApi } from './getInflationReward';\nimport { GetLargestAccountsApi } from './getLargestAccounts';\nimport { GetLatestBlockhashApi } from './getLatestBlockhash';\nimport { GetLeaderScheduleApi } from './getLeaderSchedule';\nimport { GetMaxRetransmitSlotApi } from './getMaxRetransmitSlot';\nimport { GetMaxShredInsertSlotApi } from './getMaxShredInsertSlot';\nimport { GetMinimumBalanceForRentExemptionApi } from './getMinimumBalanceForRentExemption';\nimport { GetMultipleAccountsApi } from './getMultipleAccounts';\nimport { GetProgramAccountsApi } from './getProgramAccounts';\nimport { GetRecentPerformanceSamplesApi } from './getRecentPerformanceSamples';\nimport { GetRecentPrioritizationFeesApi } from './getRecentPrioritizationFees';\nimport { GetSignaturesForAddressApi } from './getSignaturesForAddress';\nimport { GetSignatureStatusesApi } from './getSignatureStatuses';\nimport { GetSlotApi } from './getSlot';\nimport { GetSlotLeaderApi } from './getSlotLeader';\nimport { GetSlotLeadersApi } from './getSlotLeaders';\nimport { GetStakeActivationApi } from './getStakeActivation';\nimport { GetStakeMinimumDelegationApi } from './getStakeMinimumDelegation';\nimport { GetSupplyApi } from './getSupply';\nimport { GetTokenAccountBalanceApi } from './getTokenAccountBalance';\nimport { GetTokenAccountsByDelegateApi } from './getTokenAccountsByDelegate';\nimport { GetTokenAccountsByOwnerApi } from './getTokenAccountsByOwner';\nimport { GetTokenLargestAccountsApi } from './getTokenLargestAccounts';\nimport { GetTokenSupplyApi } from './getTokenSupply';\nimport { GetTransactionApi } from './getTransaction';\nimport { GetTransactionCountApi } from './getTransactionCount';\nimport { GetVersionApi } from './getVersion';\nimport { GetVoteAccountsApi } from './getVoteAccounts';\nimport { IsBlockhashValidApi } from './isBlockhashValid';\nimport { MinimumLedgerSlotApi } from './minimumLedgerSlot';\nimport { RequestAirdropApi } from './requestAirdrop';\nimport { SendTransactionApi } from './sendTransaction';\nimport { SimulateTransactionApi } from './simulateTransaction';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcMethods = GetAccountInfoApi &\n GetBalanceApi &\n GetBlockApi &\n GetBlockCommitmentApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlocksWithLimitApi &\n GetBlockTimeApi &\n GetClusterNodesApi &\n GetEpochInfoApi &\n GetEpochScheduleApi &\n GetFeeForMessageApi &\n GetFirstAvailableBlockApi &\n GetGenesisHashApi &\n GetHealthApi &\n GetHighestSnapshotSlotApi &\n GetIdentityApi &\n GetInflationGovernorApi &\n GetInflationRateApi &\n GetInflationRewardApi &\n GetLargestAccountsApi &\n GetLatestBlockhashApi &\n GetLeaderScheduleApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetMinimumBalanceForRentExemptionApi &\n GetMultipleAccountsApi &\n GetProgramAccountsApi &\n GetRecentPerformanceSamplesApi &\n GetRecentPrioritizationFeesApi &\n GetSignaturesForAddressApi &\n GetSignatureStatusesApi &\n GetSlotApi &\n GetSlotLeaderApi &\n GetSlotLeadersApi &\n GetStakeActivationApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTokenAccountBalanceApi &\n GetTokenAccountsByDelegateApi &\n GetTokenAccountsByOwnerApi &\n GetTokenLargestAccountsApi &\n GetTokenSupplyApi &\n GetTransactionApi &\n GetTransactionCountApi &\n GetVersionApi &\n GetVoteAccountsApi &\n IsBlockhashValidApi &\n MinimumLedgerSlotApi &\n RequestAirdropApi &\n SendTransactionApi &\n SimulateTransactionApi;\n\nexport function createSolanaRpcApi(config?: Config): IRpcApi<SolanaRpcMethods> {\n return new Proxy({} as IRpcApi<SolanaRpcMethods>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<TMethodName extends keyof IRpcApi<SolanaRpcMethods>>(\n ...args: Parameters<NonNullable<ProxyHandler<IRpcApi<SolanaRpcMethods>>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof SolanaRpcMethods;\n return function (\n ...rawParams: Parameters<\n SolanaRpcMethods[TMethodName] extends CallableFunction ? SolanaRpcMethods[TMethodName] : never\n >\n ): RpcRequest<ReturnType<SolanaRpcMethods[TMethodName]>> {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n const params = patchParamsForSolanaLabsRpc(\n rawParams,\n handleIntegerOverflow\n ? (keyPath, value) => handleIntegerOverflow(methodName, keyPath, value)\n : undefined\n );\n return {\n methodName,\n params,\n responseProcessor: rawResponse => patchResponseForSolanaLabsRpc(rawResponse, methodName),\n };\n };\n },\n });\n}\n","import { IRpcSubscriptionsApi, RpcSubscription } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { patchParamsForSolanaLabsRpc } from '../params-patcher';\nimport { patchResponseForSolanaLabsRpcSubscriptions } from '../response-patcher';\nimport { AccountNotificationsApi } from './account-notifications';\nimport { BlockNotificationsApi } from './block-notifications';\nimport { LogsNotificationsApi } from './logs-notifications';\nimport { ProgramNotificationsApi } from './program-notifications';\nimport { RootNotificationsApi } from './root-notifications';\nimport { SignatureNotificationsApi } from './signature-notifications';\nimport { SlotNotificationsApi } from './slot-notifications';\nimport { SlotsUpdatesNotificationsApi } from './slots-updates-notifications';\nimport { VoteNotificationsApi } from './vote-notifications';\n\ntype Config = Readonly<{\n onIntegerOverflow?: (methodName: string, keyPath: (number | string)[], value: bigint) => void;\n}>;\n\nexport type SolanaRpcSubscriptions = AccountNotificationsApi &\n BlockNotificationsApi &\n LogsNotificationsApi &\n ProgramNotificationsApi &\n RootNotificationsApi &\n SignatureNotificationsApi &\n SlotNotificationsApi;\nexport type SolanaRpcSubscriptionsUnstable = SlotsUpdatesNotificationsApi & VoteNotificationsApi;\n\nexport function createSolanaRpcSubscriptionsApi(\n config?: Config\n): IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return new Proxy({} as IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<\n TNotificationName extends keyof IRpcSubscriptionsApi<\n SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable\n >\n >(\n ...args: Parameters<\n NonNullable<\n ProxyHandler<IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>>['get']\n >\n >\n ) {\n const [_, p] = args;\n const notificationName = p.toString() as keyof (SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable);\n return function (\n ...rawParams: Parameters<\n (SolanaRpcSubscriptions &\n SolanaRpcSubscriptionsUnstable)[TNotificationName] extends CallableFunction\n ? (SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable)[TNotificationName]\n : never\n >\n ): RpcSubscription<\n ReturnType<(SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable)[TNotificationName]>\n > {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n const params = patchParamsForSolanaLabsRpc(\n rawParams,\n handleIntegerOverflow\n ? (keyPath, value) => handleIntegerOverflow(notificationName, keyPath, value)\n : undefined\n );\n return {\n params,\n responseProcessor: rawResponse =>\n patchResponseForSolanaLabsRpcSubscriptions(rawResponse, notificationName),\n subscribeMethodName: notificationName.replace(/Notifications$/, 'Subscribe'),\n unsubscribeMethodName: notificationName.replace(/Notifications$/, 'Unsubscribe'),\n };\n };\n },\n });\n}\n\nexport function createSolanaRpcSubscriptionsApi_UNSTABLE(\n config?: Config\n): IRpcSubscriptionsApi<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable> {\n return createSolanaRpcSubscriptionsApi(config) as IRpcSubscriptionsApi<\n SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable\n >;\n}\n","// Keep in sync with https://github.com/solana-labs/solana/blob/master/rpc-client-api/src/custom_error.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nexport const SolanaJsonRpcErrorCode = {\n JSON_RPC_INVALID_PARAMS: -32602,\n JSON_RPC_SCAN_ERROR: -32012,\n JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016,\n JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n} as const;\ntype SolanaJsonRpcErrorCodeEnum = (typeof SolanaJsonRpcErrorCode)[keyof typeof SolanaJsonRpcErrorCode];\n\ntype SolanaJsonRpcErrorDetails = Readonly<{\n code: number;\n data?: unknown;\n message: string;\n}>;\n\nexport class SolanaJsonRpcError extends Error {\n readonly code: SolanaJsonRpcErrorCodeEnum;\n readonly data: unknown;\n constructor(details: SolanaJsonRpcErrorDetails) {\n super(`JSON-RPC 2.0 error (${details.code}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.code = details.code as SolanaJsonRpcErrorCodeEnum;\n this.data = details.data;\n }\n get name() {\n return 'SolanaJsonRpcError';\n }\n}\n","let _nextMessageId = 0;\nexport function getNextMessageId() {\n const id = _nextMessageId;\n _nextMessageId = (_nextMessageId + 1) % Number.MAX_SAFE_INTEGER;\n return id;\n}\n","import { getNextMessageId } from './json-rpc-message-id';\n\nexport function createJsonRpcMessage<TParams>(method: string, params: TParams) {\n return {\n id: getNextMessageId(),\n jsonrpc: '2.0',\n method,\n params,\n };\n}\n","import { SolanaJsonRpcError } from './json-rpc-errors';\nimport { createJsonRpcMessage } from './json-rpc-message';\nimport { PendingRpcRequest, Rpc, RpcConfig, RpcRequest, SendOptions } from './json-rpc-types';\n\ninterface IHasIdentifier {\n readonly id: number;\n}\nexport type JsonRpcResponse<TResponse> = IHasIdentifier &\n Readonly<{ result: TResponse } | { error: { code: number; message: string; data?: unknown } }>;\n\nfunction createPendingRpcRequest<TRpcMethods, TResponse>(\n rpcConfig: RpcConfig<TRpcMethods>,\n pendingRequest: RpcRequest<TResponse>\n): PendingRpcRequest<TResponse> {\n return {\n async send(options?: SendOptions): Promise<TResponse> {\n const { methodName, params, responseProcessor } = pendingRequest;\n const payload = createJsonRpcMessage(methodName, params);\n const response = await rpcConfig.transport<JsonRpcResponse<unknown>>({\n payload,\n signal: options?.abortSignal,\n });\n if ('error' in response) {\n throw new SolanaJsonRpcError(response.error);\n } else {\n return (responseProcessor ? responseProcessor(response.result) : response.result) as TResponse;\n }\n },\n };\n}\n\nfunction makeProxy<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const createRpcRequest = Reflect.get(target, methodName, receiver);\n const newRequest = createRpcRequest\n ? createRpcRequest(...rawParams)\n : { methodName, params: rawParams };\n return createPendingRpcRequest(rpcConfig, newRequest);\n };\n },\n }) as Rpc<TRpcMethods>;\n}\n\nexport function createJsonRpc<TRpcMethods>(rpcConfig: RpcConfig<TRpcMethods>): Rpc<TRpcMethods> {\n return makeProxy(rpcConfig);\n}\n","import { JsonRpcResponse } from './json-rpc';\nimport { SolanaJsonRpcError } from './json-rpc-errors';\nimport { createJsonRpcMessage } from './json-rpc-message';\nimport {\n PendingRpcSubscription,\n RpcSubscription,\n RpcSubscriptionConfig,\n RpcSubscriptions,\n SubscribeOptions,\n} from './json-rpc-types';\n\ntype JsonRpcNotification<TNotification> = Readonly<{\n params: Readonly<{\n result: TNotification;\n subscription: number;\n }>;\n}>;\ntype SubscriptionId = number;\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nfunction createPendingRpcSubscription<TRpcSubscriptionMethods, TNotification>(\n rpcConfig: RpcSubscriptionConfig<TRpcSubscriptionMethods>,\n { params, subscribeMethodName, unsubscribeMethodName, responseProcessor }: RpcSubscription<TNotification>\n): PendingRpcSubscription<TNotification> {\n return {\n async subscribe({ abortSignal }: SubscribeOptions): Promise<AsyncIterable<TNotification>> {\n abortSignal.throwIfAborted();\n let subscriptionId: number | undefined;\n function handleCleanup() {\n if (subscriptionId !== undefined) {\n const payload = createJsonRpcMessage(unsubscribeMethodName, [subscriptionId]);\n connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload).finally(() => {\n connectionAbortController.abort();\n });\n } else {\n connectionAbortController.abort();\n }\n }\n abortSignal.addEventListener('abort', handleCleanup);\n /**\n * STEP 1: Send the subscribe message.\n */\n const connectionAbortController = new AbortController();\n const subscribeMessage = createJsonRpcMessage(subscribeMethodName, params);\n const connection = await rpcConfig.transport({\n payload: subscribeMessage,\n signal: connectionAbortController.signal,\n });\n function handleConnectionCleanup() {\n abortSignal.removeEventListener('abort', handleCleanup);\n }\n registerIterableCleanup(connection, handleConnectionCleanup);\n /**\n * STEP 2: Wait for the acknowledgement from the server with the subscription id.\n */\n for await (const message of connection as AsyncIterable<\n JsonRpcNotification<unknown> | JsonRpcResponse<SubscriptionId>\n >) {\n if ('id' in message && message.id === subscribeMessage.id) {\n if ('error' in message) {\n throw new SolanaJsonRpcError(message.error);\n } else {\n subscriptionId = message.result as SubscriptionId;\n break;\n }\n }\n }\n if (subscriptionId == null) {\n // TODO: Coded error.\n throw new Error('Failed to obtain a subscription id from the server');\n }\n /**\n * STEP 3: Return an iterable that yields notifications for this subscription id.\n */\n return {\n async *[Symbol.asyncIterator]() {\n for await (const message of connection as AsyncIterable<\n JsonRpcNotification<unknown> | JsonRpcResponse<SubscriptionId>\n >) {\n if (!('params' in message) || message.params.subscription !== subscriptionId) {\n continue;\n }\n const notification = message.params.result as TNotification;\n yield responseProcessor ? responseProcessor(notification) : notification;\n }\n },\n };\n },\n };\n}\n\nfunction makeProxy<TRpcSubscriptionMethods>(\n rpcConfig: RpcSubscriptionConfig<TRpcSubscriptionMethods>\n): RpcSubscriptions<TRpcSubscriptionMethods> {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const createRpcSubscription = Reflect.get(target, methodName, receiver);\n if (p.toString().endsWith('Notifications') === false && !createRpcSubscription) {\n // TODO: Coded error.\n throw new Error(\n \"Either the notification name must end in 'Notifications' or the API \" +\n 'must supply a subscription creator function to map between the ' +\n 'notification name and the subscribe/unsubscribe method names.'\n );\n }\n const newRequest = createRpcSubscription\n ? createRpcSubscription(...rawParams)\n : {\n params: rawParams,\n subscribeMethodName: methodName.replace(/Notifications$/, 'Subscribe'),\n unsubscribeMethodName: methodName.replace(/Notifications$/, 'Unsubscribe'),\n };\n return createPendingRpcSubscription(rpcConfig, newRequest);\n };\n },\n }) as RpcSubscriptions<TRpcSubscriptionMethods>;\n}\n\nexport function createJsonSubscriptionRpc<TRpcSubscriptionMethods>(\n rpcConfig: RpcSubscriptionConfig<TRpcSubscriptionMethods>\n): RpcSubscriptions<TRpcSubscriptionMethods> {\n return makeProxy(rpcConfig);\n}\n","export default globalThis.fetch;\n","type SolanaHttpErrorDetails = Readonly<{\n statusCode: number;\n message: string;\n}>;\n\nexport class SolanaHttpError extends Error {\n readonly statusCode: number;\n constructor(details: SolanaHttpErrorDetails) {\n super(`HTTP error (${details.statusCode}): ${details.message}`);\n Error.captureStackTrace(this, this.constructor);\n this.statusCode = details.statusCode;\n }\n get name() {\n return 'SolanaHttpError';\n }\n}\n","export type AllowedHttpRequestHeaders = Readonly<\n { [headerName: string]: string } & {\n // Someone can still sneak a forbidden header past Typescript if they do something like\n // fOo-BaR, but at that point they deserve the runtime failure.\n [K in DisallowedHeaders | ForbiddenHeaders as\n | K // `Foo-Bar`\n | Capitalize<Lowercase<K>> // `Foo-bar`\n | Lowercase<K> // `foo-bar`\n | Uncapitalize<K> // `foo-Bar`\n // `FOO-BAR`\n | Uppercase<K>]?: never;\n }\n>;\n// These are headers that we simply don't allow the developer to override because they're\n// fundamental to the operation of the JSON-RPC transport.\ntype DisallowedHeaders = 'Accept' | 'Content-Length' | 'Content-Type' | 'Solana-Client';\ntype ForbiddenHeaders =\n | 'Accept-Charset'\n | 'Accept-Encoding'\n | 'Access-Control-Request-Headers'\n | 'Access-Control-Request-Method'\n | 'Connection'\n | 'Content-Length'\n | 'Cookie'\n | 'Date'\n | 'DNT'\n | 'Expect'\n | 'Host'\n | 'Keep-Alive'\n | 'Origin'\n | 'Permissions-Policy'\n // No currently available Typescript technique allows you to match on a prefix.\n // | 'Proxy-'\n // | 'Sec-'\n | 'Referer'\n | 'TE'\n | 'Trailer'\n | 'Transfer-Encoding'\n | 'Upgrade'\n | 'Via';\n\n// These are headers which are fundamental to the JSON-RPC transport, and must not be modified.\nconst DISALLOWED_HEADERS: Record<string, boolean> = {\n accept: true,\n 'content-length': true,\n 'content-type': true,\n};\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS: Record<string, boolean> = {\n 'accept-charset': true,\n 'accept-encoding': true,\n 'access-control-request-headers': true,\n 'access-control-request-method': true,\n connection: true,\n 'content-length': true,\n cookie: true,\n date: true,\n dnt: true,\n expect: true,\n host: true,\n 'keep-alive': true,\n origin: true,\n 'permissions-policy': true,\n // No currently available Typescript technique allows you to match on a prefix.\n // 'proxy-':true,\n // 'sec-':true,\n referer: true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n via: true,\n};\n\nexport function assertIsAllowedHttpRequestHeaders(\n headers: Record<string, string>\n): asserts headers is AllowedHttpRequestHeaders {\n const badHeaders = Object.keys(headers).filter(headerName => {\n const lowercaseHeaderName = headerName.toLowerCase();\n return (\n DISALLOWED_HEADERS[headerName.toLowerCase()] === true ||\n FORBIDDEN_HEADERS[headerName.toLowerCase()] === true ||\n lowercaseHeaderName.startsWith('proxy-') ||\n lowercaseHeaderName.startsWith('sec-')\n );\n });\n if (badHeaders.length > 0) {\n throw new Error(\n `${badHeaders.length > 1 ? 'These headers are' : 'This header is'} forbidden: ` +\n `\\`${badHeaders.join('`, `')}\\`. Learn more at ` +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.'\n );\n }\n}\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers, such as those defined\n * in the `DisallowedHeaders` type.\n */\nexport function normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n","import fetchImpl from 'fetch-impl';\n\nimport { IRpcTransport } from '../transport-types';\nimport { SolanaHttpError } from './http-transport-errors';\nimport {\n AllowedHttpRequestHeaders,\n assertIsAllowedHttpRequestHeaders,\n normalizeHeaders,\n} from './http-transport-headers';\n\ntype Config = Readonly<{\n headers?: AllowedHttpRequestHeaders;\n url: string;\n}>;\n\nexport function createHttpTransport({ headers, url }: Config): IRpcTransport {\n if (__DEV__ && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\n }\n const customHeaders = headers && normalizeHeaders(headers);\n return async function makeHttpRequest<TResponse>({\n payload,\n signal,\n }: Parameters<IRpcTransport>[0]): Promise<TResponse> {\n const body = JSON.stringify(payload);\n const requestInfo = {\n body,\n headers: {\n ...customHeaders,\n // Keep these headers lowercase so they will override any user-supplied headers above.\n accept: 'application/json',\n 'content-length': body.length.toString(),\n 'content-type': 'application/json; charset=utf-8',\n },\n method: 'POST',\n signal,\n };\n const response = await fetchImpl(url, requestInfo);\n if (!response.ok) {\n throw new SolanaHttpError({\n message: response.statusText,\n statusCode: response.status,\n });\n }\n return (await response.json()) as TResponse;\n };\n}\n","export default globalThis.WebSocket;\n","import WebSocket from 'ws-impl';\n\ntype Config = Readonly<{\n sendBufferHighWatermark: number;\n signal: AbortSignal;\n url: string;\n}>;\ntype IteratorKey = symbol;\ntype IteratorState =\n | {\n __hasPolled: true;\n onMessage: Parameters<ConstructorParameters<typeof Promise>[0]>[0];\n onError: Parameters<ConstructorParameters<typeof Promise>[0]>[1];\n }\n | {\n __hasPolled: false;\n queuedMessages: unknown[];\n };\nexport type RpcWebSocketConnection = Readonly<{\n send(payload: unknown): Promise<void>;\n [Symbol.asyncIterator](): AsyncGenerator<unknown>;\n}>;\n\nconst EXPLICIT_ABORT_TOKEN = Symbol(\n __DEV__\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly aborted by the user\"\n : undefined\n);\n\nexport async function createWebSocketConnection({\n sendBufferHighWatermark,\n signal,\n url,\n}: Config): Promise<RpcWebSocketConnection> {\n return new Promise((resolve, reject) => {\n signal.addEventListener('abort', handleAbort, { once: true });\n const iteratorState: Map<IteratorKey, IteratorState> = new Map();\n function errorAndClearAllIteratorStates(reason: unknown) {\n const errorCallbacks = [...iteratorState.values()]\n .filter((state): state is Extract<IteratorState, { __hasPolled: true }> => state.__hasPolled)\n .map(({ onError }) => onError);\n iteratorState.clear();\n errorCallbacks.forEach(cb => {\n try {\n cb(reason);\n } catch {\n /* empty */\n }\n });\n }\n function handleAbort() {\n errorAndClearAllIteratorStates(EXPLICIT_ABORT_TOKEN);\n if (webSocket.readyState !== WebSocket.CLOSED && webSocket.readyState !== WebSocket.CLOSING) {\n webSocket.close(1000);\n }\n }\n function handleClose(ev: CloseEvent) {\n bufferDrainWatcher?.onCancel();\n signal.removeEventListener('abort', handleAbort);\n webSocket.removeEventListener('close', handleClose);\n webSocket.removeEventListener('error', handleError);\n webSocket.removeEventListener('open', handleOpen);\n webSocket.removeEventListener('message', handleMessage);\n errorAndClearAllIteratorStates(ev);\n }\n function handleError(ev: Event) {\n if (!hasConnected) {\n reject(\n // TODO: Coded error\n new Error('WebSocket failed to connect', { cause: ev })\n );\n }\n }\n let hasConnected = false;\n let bufferDrainWatcher: Readonly<{ onCancel(): void; promise: Promise<void> }> | undefined;\n function handleOpen() {\n hasConnected = true;\n resolve({\n async send(payload: unknown) {\n const message = JSON.stringify(payload);\n if (\n !bufferDrainWatcher &&\n webSocket.readyState === WebSocket.OPEN &&\n webSocket.bufferedAmount > sendBufferHighWatermark\n ) {\n let onCancel: () => void;\n const promise = new Promise<void>((resolve, reject) => {\n const intervalId = setInterval(() => {\n if (\n webSocket.readyState !== WebSocket.OPEN ||\n !(webSocket.bufferedAmount > sendBufferHighWatermark)\n ) {\n clearInterval(intervalId);\n bufferDrainWatcher = undefined;\n resolve();\n }\n }, 16);\n onCancel = () => {\n bufferDrainWatcher = undefined;\n clearInterval(intervalId);\n reject(\n // TODO: Coded error\n new Error('WebSocket was closed before payload could be sent')\n );\n };\n });\n bufferDrainWatcher = {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n onCancel,\n promise,\n };\n }\n if (bufferDrainWatcher) {\n await bufferDrainWatcher.promise;\n }\n webSocket.send(message);\n },\n async *[Symbol.asyncIterator]() {\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new Error('Invariant: WebSocket message iterator is missing state storage');\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new Error(\n 'Invariant: WebSocket message iterator state is corrupt; ' +\n 'iterated without first resolving existing message promise'\n );\n }\n const queuedMessages = state.queuedMessages;\n if (queuedMessages.length) {\n state.queuedMessages = [];\n yield* queuedMessages;\n } else {\n try {\n yield await new Promise((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onError: reject,\n onMessage: resolve,\n });\n });\n } catch (e) {\n if (e === EXPLICIT_ABORT_TOKEN) {\n return;\n } else {\n // TODO: Coded error.\n throw new Error('WebSocket connection closed', { cause: e });\n }\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n });\n }\n function handleMessage({ data }: MessageEvent) {\n const message = JSON.parse(data);\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onMessage } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });\n onMessage(message);\n } else {\n state.queuedMessages.push(message);\n }\n });\n }\n const webSocket = new WebSocket(url);\n webSocket.addEventListener('close', handleClose);\n webSocket.addEventListener('error', handleError);\n webSocket.addEventListener('open', handleOpen);\n webSocket.addEventListener('message', handleMessage);\n });\n}\n","import { IRpcWebSocketTransport } from '../transport-types';\nimport { createWebSocketConnection } from './websocket-connection';\n\ntype Config = Readonly<{\n sendBufferHighWatermark: number;\n url: string;\n}>;\n\nexport function createWebSocketTransport({ sendBufferHighWatermark, url }: Config): IRpcWebSocketTransport {\n if (/^wss?:/i.test(url) === false) {\n const protocolMatch = url.match(/^([^:]+):/);\n throw new DOMException(\n protocolMatch\n ? `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${protocolMatch[1]}:' is not allowed.`\n : `Failed to construct 'WebSocket': The URL '${url}' is invalid.`\n );\n }\n return async function sendWebSocketMessage({ payload, signal }: Parameters<IRpcWebSocketTransport>[0]) {\n signal?.throwIfAborted();\n const connection = await createWebSocketConnection({\n sendBufferHighWatermark,\n signal,\n url,\n });\n signal?.throwIfAborted();\n await connection.send(payload);\n return {\n [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),\n send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: connection.send.bind(connection),\n };\n };\n}\n","import { createSolanaRpcApi } from '@solana/rpc-core';\n\nimport { SolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\nexport const DEFAULT_RPC_CONFIG: Partial<Parameters<typeof createSolanaRpcApi>[0]> = {\n onIntegerOverflow(methodName, keyPath, value) {\n throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);\n },\n};\n","export class SolanaJsonRpcIntegerOverflowError extends Error {\n readonly methodName: string;\n readonly keyPath: (number | string)[];\n readonly value: bigint;\n constructor(methodName: string, keyPath: (number | string)[], value: bigint) {\n const argPosition = (typeof keyPath[0] === 'number' ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;\n let ordinal = '';\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n ordinal = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n ordinal = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n ordinal = argPosition + 'rd';\n } else {\n ordinal = argPosition + 'th';\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : null;\n super(\n `The ${ordinal} argument to the \\`${methodName}\\` RPC method` +\n `${path ? ` at path \\`${path}\\`` : ''} was \\`${value}\\`. This number is ` +\n 'unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.'\n );\n this.keyPath = keyPath;\n this.methodName = methodName;\n this.value = value;\n }\n get name() {\n return 'SolanaJsonRpcIntegerOverflowError';\n }\n}\n","import { PendingRpcSubscription, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\nimport { getCachedAbortableIterableFactory } from './cached-abortable-iterable';\n\ntype CacheKey = string | undefined;\ntype Config<TRpcSubscriptionsMethods> = Readonly<{\n getDeduplicationKey: GetDeduplicationKeyFn;\n rpcSubscriptions: RpcSubscriptions<TRpcSubscriptionsMethods>;\n}>;\ntype GetDeduplicationKeyFn = (subscriptionMethod: string | symbol, payload: unknown) => CacheKey;\n\nconst EXPLICIT_ABORT_TOKEN = Symbol(\n __DEV__\n ? \"This symbol is thrown from a subscription's iterator when the subscription is \" +\n 'explicitly aborted by the user'\n : undefined\n);\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nexport function getRpcSubscriptionsWithSubscriptionCoalescing<TRpcSubscriptionsMethods>({\n getDeduplicationKey,\n rpcSubscriptions,\n}: Config<TRpcSubscriptionsMethods>): RpcSubscriptions<TRpcSubscriptionsMethods> {\n const cache = new Map<CacheKey, PendingRpcSubscription<unknown>>();\n return new Proxy(rpcSubscriptions, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n const subscriptionMethod = Reflect.get(target, p, receiver);\n if (typeof subscriptionMethod !== 'function') {\n return subscriptionMethod;\n }\n return function (...rawParams: unknown[]) {\n const deduplicationKey = getDeduplicationKey(p, rawParams);\n if (deduplicationKey === undefined) {\n return (subscriptionMethod as CallableFunction)(...rawParams);\n }\n if (cache.has(deduplicationKey)) {\n return cache.get(deduplicationKey)!;\n }\n const iterableFactory = getCachedAbortableIterableFactory<\n Parameters<PendingRpcSubscription<unknown>['subscribe']>,\n AsyncIterable<unknown>\n >({\n getAbortSignalFromInputArgs: ({ abortSignal }) => abortSignal,\n getCacheEntryMissingError(deduplicationKey) {\n // TODO: Coded error.\n return new Error(\n `Found no cache entry for subscription with deduplication key \\`${deduplicationKey?.toString()}\\``\n );\n },\n getCacheKeyFromInputArgs: () => deduplicationKey,\n async onCacheHit(_iterable, _config) {\n /**\n * This transport's goal is to prevent duplicate subscriptions from\n * being made. If a cached iterable] is found, do not send the subscribe\n * message again.\n */\n },\n async onCreateIterable(abortSignal, config) {\n const pendingSubscription = (subscriptionMethod as CallableFunction)(\n ...rawParams\n ) as PendingRpcSubscription<unknown>;\n const iterable = await pendingSubscription.subscribe({\n ...config,\n abortSignal,\n });\n registerIterableCleanup(iterable, () => {\n cache.delete(deduplicationKey);\n });\n return iterable;\n },\n });\n const pendingSubscription: PendingRpcSubscription<unknown> = {\n async subscribe(...args) {\n const iterable = await iterableFactory(...args);\n const { abortSignal } = args[0];\n let abortPromise;\n return {\n ...iterable,\n async *[Symbol.asyncIterator]() {\n abortPromise ||= abortSignal.aborted\n ? Promise.reject(EXPLICIT_ABORT_TOKEN)\n : new Promise<never>((_, reject) => {\n abortSignal.addEventListener('abort', () => {\n reject(EXPLICIT_ABORT_TOKEN);\n });\n });\n try {\n const iterator = iterable[Symbol.asyncIterator]();\n while (true) {\n const iteratorResult = await Promise.race([iterator.next(), abortPromise]);\n if (iteratorResult.done) {\n return;\n } else {\n yield iteratorResult.value;\n }\n }\n } catch (e) {\n if (e === EXPLICIT_ABORT_TOKEN) {\n return;\n }\n cache.delete(deduplicationKey);\n throw e;\n }\n },\n };\n },\n };\n cache.set(deduplicationKey, pendingSubscription);\n return pendingSubscription;\n };\n },\n });\n}\n","type CacheEntry<TIterable extends AsyncIterable<unknown>> = {\n abortController: AbortController;\n iterable: Promise<TIterable> | TIterable;\n purgeScheduled: boolean;\n referenceCount: number;\n};\ntype CacheKey = string | symbol;\ntype Config<TInput extends unknown[], TIterable extends AsyncIterable<unknown>> = Readonly<{\n getAbortSignalFromInputArgs: (...args: TInput) => AbortSignal;\n getCacheEntryMissingError: (cacheKey: CacheKey) => Error;\n getCacheKeyFromInputArgs: (...args: TInput) =>\n | CacheKey\n // `undefined` implies 'do not cache'\n | undefined;\n onCacheHit: (iterable: TIterable, ...args: TInput) => Promise<void>;\n onCreateIterable: (abortSignal: AbortSignal, ...args: TInput) => Promise<TIterable>;\n}>;\n\nfunction registerIterableCleanup(iterable: AsyncIterable<unknown>, cleanupFn: CallableFunction) {\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of iterable);\n } catch {\n /* empty */\n } finally {\n // Run the cleanup function.\n cleanupFn();\n }\n })();\n}\n\nexport function getCachedAbortableIterableFactory<TInput extends unknown[], TIterable extends AsyncIterable<unknown>>({\n getAbortSignalFromInputArgs,\n getCacheEntryMissingError,\n getCacheKeyFromInputArgs,\n onCacheHit,\n onCreateIterable,\n}: Config<TInput, TIterable>): (...args: TInput) => Promise<TIterable> {\n const cache = new Map<CacheKey, CacheEntry<TIterable>>();\n function getCacheEntryOrThrow(cacheKey: CacheKey) {\n const currentCacheEntry = cache.get(cacheKey);\n if (!currentCacheEntry) {\n throw getCacheEntryMissingError(cacheKey);\n }\n return currentCacheEntry;\n }\n return async (...args: TInput) => {\n const cacheKey = getCacheKeyFromInputArgs(...args);\n const signal = getAbortSignalFromInputArgs(...args);\n if (cacheKey === undefined) {\n return await onCreateIterable(signal, ...args);\n }\n const cleanup = () => {\n cache.delete(cacheKey);\n signal.removeEventListener('abort', handleAbort);\n };\n const handleAbort = () => {\n const cacheEntry = getCacheEntryOrThrow(cacheKey);\n if (cacheEntry.purgeScheduled !== true) {\n cacheEntry.purgeScheduled = true;\n globalThis.queueMicrotask(() => {\n cacheEntry.purgeScheduled = false;\n if (cacheEntry.referenceCount === 0) {\n cacheEntry.abortController.abort();\n cleanup();\n }\n });\n }\n cacheEntry.referenceCount--;\n };\n signal.addEventListener('abort', handleAbort);\n try {\n const cacheEntry = cache.get(cacheKey);\n if (!cacheEntry) {\n const singletonAbortController = new AbortController();\n const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);\n const newCacheEntry: CacheEntry<TIterable> = {\n abortController: singletonAbortController,\n iterable: newIterablePromise,\n purgeScheduled: false,\n referenceCount: 1,\n };\n cache.set(cacheKey, newCacheEntry);\n const newIterable = await newIterablePromise;\n registerIterableCleanup(newIterable, cleanup);\n newCacheEntry.iterable = newIterable;\n return newIterable;\n } else {\n cacheEntry.referenceCount++;\n const iterableOrIterablePromise = cacheEntry.iterable;\n const cachedIterable =\n 'then' in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;\n await onCacheHit(cachedIterable, ...args);\n return cachedIterable;\n }\n } catch (e) {\n cleanup();\n throw e;\n }\n };\n}\n","import { pipe } from '@solana/functional';\nimport { createHttpTransport } from '@solana/rpc-transport';\nimport { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getRpcTransportWithRequestCoalescing } from './rpc-request-coalescer';\nimport { getSolanaRpcPayloadDeduplicationKey } from './rpc-request-deduplication';\n\n/**\n * Lowercasing header names makes it easier to override user-supplied headers.\n */\nfunction normalizeHeaders<T extends Record<string, string>>(\n headers: T\n): { [K in keyof T & string as Lowercase<K>]: T[K] } {\n const out: Record<string, string> = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in keyof T & string as Lowercase<K>]: T[K] };\n}\n\nexport function createDefaultRpcTransport(config: Parameters<typeof createHttpTransport>[0]): IRpcTransport {\n return pipe(\n createHttpTransport({\n ...config,\n headers: {\n ...(config.headers ? normalizeHeaders(config.headers) : undefined),\n ...({\n // Keep these headers lowercase so they will override any user-supplied headers above.\n 'solana-client': `js/${__VERSION__}` ?? 'UNKNOWN',\n } as { [overrideHeader: string]: string }),\n },\n }),\n transport => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)\n );\n}\n","import { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\ntype CoalescedRequest = {\n readonly abortController: AbortController;\n numConsumers: number;\n readonly responsePromise: Promise<unknown>;\n};\n\ntype GetDeduplicationKeyFn = (payload: unknown) => string | undefined;\n\nexport function getRpcTransportWithRequestCoalescing(\n transport: IRpcTransport,\n getDeduplicationKey: GetDeduplicationKeyFn\n): IRpcTransport {\n let coalescedRequestsByDeduplicationKey: Record<string, CoalescedRequest> | undefined;\n return async function makeCoalescedHttpRequest<TResponse>(\n config: Parameters<IRpcTransport>[0]\n ): Promise<TResponse> {\n const { payload, signal } = config;\n const deduplicationKey = getDeduplicationKey(payload);\n if (deduplicationKey === undefined) {\n return await transport(config);\n }\n if (!coalescedRequestsByDeduplicationKey) {\n Promise.resolve().then(() => {\n coalescedRequestsByDeduplicationKey = undefined;\n });\n coalescedRequestsByDeduplicationKey = {};\n }\n if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {\n const abortController = new AbortController();\n coalescedRequestsByDeduplicationKey[deduplicationKey] = {\n abortController,\n numConsumers: 0,\n responsePromise: transport<TResponse>({\n ...config,\n signal: abortController.signal,\n }),\n };\n }\n const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];\n coalescedRequest.numConsumers++;\n if (signal) {\n const responsePromise = coalescedRequest.responsePromise as Promise<TResponse>;\n return await new Promise<TResponse>((resolve, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n signal.removeEventListener('abort', handleAbort);\n coalescedRequest.numConsumers -= 1;\n if (coalescedRequest.numConsumers === 0) {\n const abortController = coalescedRequest.abortController;\n abortController.abort();\n }\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n signal.addEventListener('abort', handleAbort);\n responsePromise.then(resolve).finally(() => {\n signal.removeEventListener('abort', handleAbort);\n });\n });\n } else {\n return (await coalescedRequest.responsePromise) as TResponse;\n }\n };\n}\n","// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\n\nfunction isJsonRpcPayload(payload: unknown): payload is Readonly<{ method: string; params: unknown }> {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n return (\n 'jsonrpc' in payload &&\n payload.jsonrpc === '2.0' &&\n 'method' in payload &&\n typeof payload.method === 'string' &&\n 'params' in payload\n );\n}\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n return isJsonRpcPayload(payload) ? fastStableStringify([payload.method, payload.params]) : undefined;\n}\n","import { pipe } from '@solana/functional';\nimport { createWebSocketTransport } from '@solana/rpc-transport';\nimport { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getWebSocketTransportWithAutoping } from './rpc-websocket-autopinger';\nimport { getWebSocketTransportWithConnectionSharding } from './rpc-websocket-connection-sharding';\n\nexport function createDefaultRpcSubscriptionsTransport(\n config: Omit<Parameters<typeof createWebSocketTransport>[0], 'sendBufferHighWatermark'> & {\n /**\n * You might like to open more subscriptions per connection than your RPC provider allows\n * for. Using the initial payload as input, return a shard key from this method to assign\n * subscriptions to separate connections. One socket will be opened per shard key.\n */\n getShard?: (payload: unknown) => string;\n intervalMs?: number;\n sendBufferHighWatermark?: number;\n }\n): IRpcWebSocketTransport {\n const { getShard, intervalMs, ...rest } = config;\n return pipe(\n createWebSocketTransport({\n ...rest,\n sendBufferHighWatermark:\n config.sendBufferHighWatermark ??\n // Let 128KB of data into the WebSocket buffer before buffering it in the app.\n 131_072,\n }),\n transport =>\n getWebSocketTransportWithAutoping({\n intervalMs: intervalMs ?? 5_000,\n transport,\n }),\n transport =>\n getWebSocketTransportWithConnectionSharding({\n getShard,\n transport,\n })\n );\n}\n","import { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\ntype Config = Readonly<{\n intervalMs: number;\n transport: IRpcWebSocketTransport;\n}>;\n\nconst PING_PAYLOAD = {\n jsonrpc: '2.0',\n method: 'ping',\n} as const;\n\nexport function getWebSocketTransportWithAutoping({ intervalMs, transport }: Config): IRpcWebSocketTransport {\n const pingableConnections = new Map<\n Awaited<ReturnType<IRpcWebSocketTransport>>,\n Awaited<ReturnType<IRpcWebSocketTransport>>\n >();\n return async (...args) => {\n const connection = await transport(...args);\n let intervalId: string | number | NodeJS.Timeout | undefined;\n function sendPing() {\n connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);\n }\n function restartPingTimer() {\n clearInterval(intervalId);\n intervalId = setInterval(sendPing, intervalMs);\n }\n if (pingableConnections.has(connection) === false) {\n pingableConnections.set(connection, {\n [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),\n send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: (\n ...args: Parameters<typeof connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED>\n ) => {\n restartPingTimer();\n return connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(...args);\n },\n });\n (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of connection) {\n restartPingTimer();\n }\n } catch {\n /* empty */\n } finally {\n pingableConnections.delete(connection);\n clearInterval(intervalId);\n if (handleOffline) {\n globalThis.window.removeEventListener('offline', handleOffline);\n }\n if (handleOnline) {\n globalThis.window.removeEventListener('online', handleOnline);\n }\n }\n })();\n if (!__BROWSER__ || globalThis.navigator.onLine) {\n restartPingTimer();\n }\n let handleOffline;\n let handleOnline;\n if (__BROWSER__) {\n handleOffline = () => {\n clearInterval(intervalId);\n };\n handleOnline = () => {\n sendPing();\n restartPingTimer();\n };\n globalThis.window.addEventListener('offline', handleOffline);\n globalThis.window.addEventListener('online', handleOnline);\n }\n }\n return pingableConnections.get(connection)!;\n };\n}\n","import { IRpcWebSocketTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';\n\nimport { getCachedAbortableIterableFactory } from './cached-abortable-iterable';\n\ntype Config = Readonly<{\n /**\n * You might like to open more subscriptions per connection than your RPC provider allows for.\n * Using the initial payload as input, return a shard key from this method to assign\n * subscriptions to separate connections. One socket will be opened per shard key.\n */\n getShard?: (payload: unknown) => string | symbol;\n transport: IRpcWebSocketTransport;\n}>;\n\nconst NULL_SHARD_CACHE_KEY = Symbol(\n __DEV__ ? 'Cache key to use when there is no connection sharding strategy' : undefined\n);\n\nexport function getWebSocketTransportWithConnectionSharding({ getShard, transport }: Config): IRpcWebSocketTransport {\n return getCachedAbortableIterableFactory({\n getAbortSignalFromInputArgs: ({ signal }) => signal,\n getCacheEntryMissingError(shardKey) {\n // TODO: Coded error.\n return new Error(`Found no cache entry for connection with shard key \\`${shardKey?.toString()}\\``);\n },\n getCacheKeyFromInputArgs: ({ payload }) => (getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY),\n onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),\n onCreateIterable: (abortSignal, config) =>\n transport({\n ...config,\n signal: abortSignal,\n }),\n });\n}\n","import { Signature } from '@solana/keys';\nimport { SendTransactionApi } from '@solana/rpc-core/dist/types/rpc-methods/sendTransaction';\nimport { Rpc } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\nimport {\n BaseTransaction,\n getBase64EncodedWireTransaction,\n IDurableNonceTransaction,\n IFullySignedTransaction,\n ITransactionWithBlockhashLifetime,\n ITransactionWithFeePayer,\n} from '@solana/transactions';\n\nimport {\n createDefaultDurableNonceTransactionConfirmer,\n createDefaultRecentTransactionConfirmer,\n} from './transaction-confirmation';\n\ninterface DurableNonceTransactionSenderFactoryConfig {\n rpc: Rpc<SendTransactionApi> & Parameters<typeof createDefaultDurableNonceTransactionConfirmer>[0]['rpc'];\n rpcSubscriptions: Parameters<typeof createDefaultDurableNonceTransactionConfirmer>[0]['rpcSubscriptions'];\n}\n\ninterface TransactionWithBlockhashLifetimeSenderFactoryConfig {\n rpc: Rpc<SendTransactionApi> & Parameters<typeof createDefaultRecentTransactionConfirmer>[0]['rpc'];\n rpcSubscriptions: Parameters<typeof createDefaultRecentTransactionConfirmer>[0]['rpcSubscriptions'];\n}\n\ninterface SendAndConfirmDurableNonceTransactionConfig\n extends SendTransactionInternalConfig,\n SendTransactionConfigWithoutEncoding {\n confirmDurableNonceTransaction: ReturnType<typeof createDefaultDurableNonceTransactionConfirmer>;\n transaction: SendableTransaction & IDurableNonceTransaction;\n}\n\ninterface SendAndConfirmTransactionWithBlockhashLifetimeConfig\n extends SendTransactionInternalConfig,\n SendTransactionConfigWithoutEncoding {\n confirmRecentTransaction: ReturnType<typeof createDefaultRecentTransactionConfirmer>;\n transaction: SendableTransaction & ITransactionWithBlockhashLifetime;\n}\n\ninterface SendTransactionInternalConfig extends SendTransactionConfigWithoutEncoding {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n rpc: Rpc<SendTransactionApi>;\n transaction: SendableTransaction;\n}\n\ntype SendableTransaction = BaseTransaction &\n (ITransactionWithBlockhashLifetime | IDurableNonceTransaction) &\n ITransactionWithFeePayer &\n IFullySignedTransaction;\ntype SendTransactionConfig = Parameters<SendTransactionApi['sendTransaction']>[1];\ninterface SendTransactionConfigWithoutEncoding extends Omit<NonNullable<SendTransactionConfig>, 'encoding'> {}\n\nfunction getSendTransactionConfigWithAdjustedPreflightCommitment(\n commitment: Commitment,\n config?: SendTransactionConfigWithoutEncoding\n): SendTransactionConfigWithoutEncoding | void {\n if (\n // The developer has supplied no value for `preflightCommitment`.\n !config?.preflightCommitment &&\n // The value of `commitment` is lower than the server default of `preflightCommitment`.\n commitmentComparator(commitment, 'finalized' /* default value of `preflightCommitment` */) < 0\n ) {\n return {\n ...config,\n // In the common case, it is unlikely that you want to simulate a transaction at\n // `finalized` commitment when your standard of commitment for confirming the\n // transaction is lower. Cap the simulation commitment level to the level of the\n // confirmation commitment.\n preflightCommitment: commitment,\n };\n }\n // The commitment at which the developer wishes to confirm the transaction is at least as\n // high as the commitment at which they want to simulate it. Honour the config as-is.\n return config;\n}\n\nasync function sendTransaction_INTERNAL({\n abortSignal,\n commitment,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendTransactionInternalConfig): Promise<Signature> {\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);\n return await rpc\n .sendTransaction(base64EncodedWireTransaction, {\n ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),\n encoding: 'base64',\n })\n .send({ abortSignal });\n}\n\nexport function createDefaultDurableNonceTransactionSender({\n rpc,\n rpcSubscriptions,\n}: DurableNonceTransactionSenderFactoryConfig) {\n const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n });\n return async function sendDurableNonceTransaction(\n transaction: BaseTransaction & ITransactionWithFeePayer & IDurableNonceTransaction & IFullySignedTransaction,\n config: Omit<\n Parameters<typeof sendAndConfirmDurableNonceTransaction>[0],\n 'confirmDurableNonceTransaction' | 'rpc' | 'transaction'\n >\n ): Promise<void> {\n await sendAndConfirmDurableNonceTransaction({\n ...config,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n });\n };\n}\n\nexport function createDefaultTransactionSender({\n rpc,\n rpcSubscriptions,\n}: TransactionWithBlockhashLifetimeSenderFactoryConfig) {\n const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n });\n return async function sendTransaction(\n transaction: SendableTransaction & ITransactionWithBlockhashLifetime,\n config: Omit<\n Parameters<typeof sendAndConfirmTransaction>[0],\n 'confirmRecentTransaction' | 'rpc' | 'transaction'\n >\n ): Promise<void> {\n await sendAndConfirmTransaction({\n ...config,\n confirmRecentTransaction,\n rpc,\n transaction,\n });\n };\n}\n\nexport async function sendAndConfirmDurableNonceTransaction({\n abortSignal,\n commitment,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmDurableNonceTransactionConfig): Promise<Signature> {\n const transactionSignature = await sendTransaction_INTERNAL({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmDurableNonceTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n\nexport async function sendAndConfirmTransaction({\n abortSignal,\n commitment,\n confirmRecentTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmTransactionWithBlockhashLifetimeConfig): Promise<Signature> {\n const transactionSignature = await sendTransaction_INTERNAL({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmRecentTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n","import { Slot } from '@solana/rpc-core/dist/types/rpc-methods/common';\nimport type { GetAccountInfoApi } from '@solana/rpc-core/dist/types/rpc-methods/getAccountInfo';\nimport type { GetSignatureStatusesApi } from '@solana/rpc-core/dist/types/rpc-methods/getSignatureStatuses';\nimport type { AccountNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/account-notifications';\nimport type { SignatureNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/signature-notifications';\nimport type { SlotNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/slot-notifications';\nimport type { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport {\n getSignatureFromTransaction,\n IDurableNonceTransaction,\n ITransactionWithFeePayer,\n ITransactionWithSignatures,\n} from '@solana/transactions';\n\nimport { createBlockHeightExceedencePromiseFactory } from './transaction-confirmation-strategy-blockheight';\nimport { createNonceInvalidationPromiseFactory } from './transaction-confirmation-strategy-nonce';\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './transaction-confirmation-strategy-racer';\nimport { createRecentSignatureConfirmationPromiseFactory } from './transaction-confirmation-strategy-recent-signature';\n\ninterface DefaultDurableNonceTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi & GetAccountInfoApi>;\n rpcSubscriptions: RpcSubscriptions<AccountNotificationsApi & SignatureNotificationsApi>;\n}\n\ninterface DefaultRecentTransactionConfirmerConfig {\n rpc: Rpc<GetSignatureStatusesApi>;\n rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi & SlotNotificationsApi>;\n}\n\ninterface WaitForDurableNonceTransactionConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getNonceInvalidationPromise: ReturnType<typeof createNonceInvalidationPromiseFactory>;\n transaction: ITransactionWithFeePayer & ITransactionWithSignatures & IDurableNonceTransaction;\n}\n\ninterface WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig\n extends BaseTransactionConfirmationStrategyConfig {\n getBlockHeightExceedencePromise: ReturnType<typeof createBlockHeightExceedencePromiseFactory>;\n transaction: ITransactionWithFeePayer &\n ITransactionWithSignatures &\n Readonly<{\n lifetimeConstraint: {\n lastValidBlockHeight: Slot;\n };\n }>;\n}\n\nexport function createDefaultDurableNonceTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultDurableNonceTransactionConfirmerConfig) {\n const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions\n );\n return async function confirmDurableNonceTransaction(\n config: Omit<\n Parameters<typeof waitForDurableNonceTransactionConfirmation>[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >\n ) {\n await waitForDurableNonceTransactionConfirmation({\n ...config,\n getNonceInvalidationPromise,\n getRecentSignatureConfirmationPromise,\n });\n };\n}\n\nexport function createDefaultRecentTransactionConfirmer({\n rpc,\n rpcSubscriptions,\n}: DefaultRecentTransactionConfirmerConfig) {\n const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory(rpcSubscriptions);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(\n rpc,\n rpcSubscriptions\n );\n return async function confirmRecentTransaction(\n config: Omit<\n Parameters<typeof waitForRecentTransactionConfirmation>[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >\n ) {\n await waitForRecentTransactionConfirmation({\n ...config,\n getBlockHeightExceedencePromise,\n getRecentSignatureConfirmationPromise,\n });\n };\n}\n\nexport async function waitForDurableNonceTransactionConfirmation(\n config: WaitForDurableNonceTransactionConfirmationConfig\n): Promise<void> {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {\n return [\n getNonceInvalidationPromise({\n abortSignal,\n commitment,\n currentNonceValue: transaction.lifetimeConstraint.nonce,\n nonceAccountAddress: transaction.instructions[0].accounts[0].address,\n }),\n ];\n }\n );\n}\n\nexport async function waitForRecentTransactionConfirmation(\n config: WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig\n): Promise<void> {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, getBlockHeightExceedencePromise, transaction }) {\n return [\n getBlockHeightExceedencePromise({\n abortSignal,\n lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight,\n }),\n ];\n }\n );\n}\n","import { Slot } from '@solana/rpc-core/dist/types/rpc-methods/common';\nimport type { SlotNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/slot-notifications';\nimport { RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\n\ntype GetBlockHeightExceedencePromiseFn = (config: {\n abortSignal: AbortSignal;\n lastValidBlockHeight: Slot;\n}) => Promise<void>;\n\nexport function createBlockHeightExceedencePromiseFactory(\n rpcSubscriptions: RpcSubscriptions<SlotNotificationsApi>\n): GetBlockHeightExceedencePromiseFn {\n return async function getBlockHeightExceedencePromise({ abortSignal: callerAbortSignal, lastValidBlockHeight }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n const slotNotifications = await rpcSubscriptions\n .slotNotifications()\n .subscribe({ abortSignal: abortController.signal });\n try {\n for await (const slotNotification of slotNotifications) {\n if (slotNotification.slot > lastValidBlockHeight) {\n // TODO: Coded error.\n throw new Error(\n 'The network has progressed past the last block for which this transaction ' +\n 'could have committed.'\n );\n }\n }\n } finally {\n abortController.abort();\n }\n };\n}\n","import { Address } from '@solana/addresses';\nimport { getBase58Decoder, getBase64Encoder } from '@solana/codecs-strings';\nimport { Base64EncodedDataResponse } from '@solana/rpc-core/dist/types/rpc-methods/common';\nimport { GetAccountInfoApi } from '@solana/rpc-core/dist/types/rpc-methods/getAccountInfo';\nimport { AccountNotificationsApi } from '@solana/rpc-core/dist/types/rpc-subscriptions/account-notifications';\nimport { Rpc, RpcSubscriptions } from '@solana/rpc-transport/dist/types/json-rpc-types';\nimport { Commitment } from '@solana/rpc-types';\nimport { Nonce } from '@solana/transactions';\n\ntype GetNonceInvalidationPromiseFn = (config: {\n abortSignal: AbortSignal;\n commitment: Commitment;\n currentNonceValue: Nonce;\n nonceAccountAddress: Address;\n}) => Promise<void>;\n\nconst NONCE_VALUE_OFFSET =\n 4 + // version(u32)\n 4 + // state(u32)\n 32; // nonce authority(pubkey)\n// Then comes the nonce value.\n\nexport function createNonceInvalidationPromiseFactory(\n rpc: Rpc<GetAccountInfoApi>,\n rpcSubscriptions: RpcSubscriptions<AccountNotificationsApi>\n): GetNonceInvalidationPromiseFn {\n return async function getNonceInvalidationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n currentNonceValue,\n nonceAccountAddress,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for nonce account changes.\n */\n const accountNotifications = await rpcSubscriptions\n .accountNotifications(nonceAccountAddress, { commitment, encoding: 'base64' })\n .subscribe({ abortSignal: abortController.signal });\n const base58Decoder = getBase58Decoder();\n const base64Encoder = getBase64Encoder();\n function getNonceFromAccountData([base64EncodedBytes]: Base64EncodedDataResponse): Nonce {\n const data = base64Encoder.encode(base64EncodedBytes);\n const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);\n return base58Decoder.decode(nonceValueBytes)[0] as Nonce;\n }\n const nonceAccountDidAdvancePromise = (async () => {\n for await (const accountNotification of accountNotifications) {\n const nonceValue = getNonceFromAccountData(accountNotification.value.data);\n if (nonceValue !== currentNonceValue) {\n throw new Error(\n `The nonce \\`${currentNonceValue}\\` is no longer valid. It has advanced ` +\n `to \\`${nonceValue}\\`.`\n );\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current nonce\n * value to check if it has already been advanced.\n */\n const nonceIsAlreadyInvalidPromise = (async () => {\n const { value: nonceAccount } = await rpc\n .getAccountInfo(nonceAccountAddress, {\n commitment,\n dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },\n encoding: 'base58',\n })\n .send({ abortSignal: abortController.signal });\n if (!nonceAccount) {\n throw new Error(`No nonce account could be found at address \\`${nonceAccountAddress}\\`.`);\n }\n const nonceValue =\n // This works because we asked for the exact slice of data representing the nonce\n // value, and furthermore asked for it in `base58` encoding.\n nonceAccount.data[0] as unknown as Nonce;\n if (nonceValue !== currentNonceValue) {\n throw new Error(\n `The nonce \\`${currentNonceValue}\\` is no longer valid. It has advanced to \\`${nonceValue}\\`.`\n );\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n"]}