@solana/transactions 2.0.0-experimental.71a42a7 → 2.0.0-experimental.72efece

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/fixSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/mapSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/baseX.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/base58.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/nullCharacters.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/utf8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/common.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u32.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/shortU16.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/sumSerializerSizes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/array.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/string.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/struct.ts","../src/unsigned-transaction.ts","../src/blockhash.ts","../src/create-transaction.ts","../../instructions/src/roles.ts","../src/durable-nonce.ts","../src/fee-payer.ts","../src/instructions.ts","../../codecs-core/src/assertions.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/combine-codec.ts","../../codecs-core/src/fix-codec.ts","../../codecs-core/src/map-codec.ts","../../codecs-numbers/src/assertions.ts","../../codecs-numbers/src/f32.ts","../../codecs-numbers/src/utils.ts","../../codecs-numbers/src/u128.ts","../../codecs-numbers/src/u16.ts","../../codecs-numbers/src/u32.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/base64.ts","../../codecs-strings/src/null-characters.ts","../../codecs-strings/src/string.ts","../../codecs-strings/src/utf8.ts","../../text-encoding-impl/src/index.browser.ts","../../assertions/src/subtle-crypto.ts","../../addresses/src/address.ts","../../addresses/src/program-derived-address.ts","../../addresses/src/public-key.ts","../src/accounts.ts","../src/compile-address-table-lookups.ts","../src/compile-header.ts","../src/compile-instructions.ts","../src/compile-lifetime-token.ts","../src/compile-static-accounts.ts","../src/message.ts","../src/compile-transaction.ts","../src/serializers/address-table-lookup.ts","../../codecs-data-structures/dist/index.browser.js","../src/serializers/header.ts","../src/serializers/instruction.ts","../src/serializers/transaction-version.ts","../src/serializers/unimplemented.ts","../src/serializers/message.ts","../src/serializers/transaction.ts","../../keys/src/signatures.ts","../src/signatures.ts","../src/wire-transaction.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","e","AccountRole","combineCodec","address","BASE_CONFIG"],"mappings":";;;;;;;;AAIaA,IAAAA,aAAcC,cAAuC;AAChE,QAAMC,cAAcD,SAASE,OAAO,CAACC,OAAOC,QAAQD,QAAQC,IAAIC,QAAQ,CAAC;AACzE,QAAMC,SAAS,IAAIC,WAAWN,WAAW;AACzC,MAAIO,SAAS;AACbR,WAASS,QAASL,SAAQ;AACxBE,WAAOI,IAAIN,KAAKI,MAAM;AACtBA,cAAUJ,IAAIC;EAChB,CAAC;AACD,SAAOC;AACT;IAOaK,WAAW,CAACC,QAAmBP,WAA+B;AACzE,MAAIO,OAAMP,UAAUA;AAAQ,WAAOO;AACnC,QAAMC,cAAc,IAAIN,WAAWF,MAAM,EAAES,KAAK,CAAC;AACjDD,cAAYH,IAAIE,MAAK;AACrB,SAAOC;AACT;AAQO,IAAME,WAAW,CAACH,QAAmBP,WAC1CM,SAASC,OAAMI,MAAM,GAAGX,MAAM,GAAGA,MAAM;;;ACjClC,IAAMY,gCAAN,cAA4CC,MAAM;EAGvDC,YAAYC,YAAoB;AAC9B,UAAO,eAAcA,UAAW,qCAAoC;AAH7DC,gCAAe;EAIxB;AACF;AAGO,IAAMC,sBAAN,cAAkCJ,MAAM;EAG7CC,YACEC,YACAG,UACAC,QACA;AACA,UACG,eAAcJ,UAAW,cAAaG,QAAS,eAAcC,MAAO,GAAE;AARlEH,gCAAe;EAUxB;AACF;AAGO,IAAMI,mCAAN,cAA+CP,MAAM;EAG1DC,YAAYO,SAAkB;AAC5BA,0BAAY;AACZ,UAAMA,OAAO;AAJNL,gCAA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BAAuB,sBAAsB,EAAE,UAAU,WAAW;AAC1E,MAAI,OAAY;AACZ,WAAO,OAAO,KAAK,oBAAoB,EAAE,SAAS,QAAQ;AAAA,EAC9D,OAAO;AACH,WAAQ,KAAwB,OAAO,aAAa,GAAG,oBAAoB,CAAC;AAAA,EAChF;AACJ","sourcesContent":["/**\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","/** @category Errors */\nexport class InvalidBaseStringError extends Error {\n readonly name: string = 'InvalidBaseStringError';\n\n readonly cause?: Error;\n\n constructor(value: string, base: number, cause?: Error) {\n const message = `Expected a string of base ${base}, got [${value}].`;\n super(message);\n this.cause = cause;\n }\n}\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { InvalidBaseStringError } from './errors';\n\n/**\n * A string serializer that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create serializers such as base10 or base58.\n *\n * @category Serializers\n */\nexport const baseX = (alphabet: string): Serializer<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n serialize(value: string): Uint8Array {\n // Check if the value is valid.\n if (!value.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new InvalidBaseStringError(value, base);\n }\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex((c) => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n deserialize(buffer, offset = 0): [string, number] {\n if (buffer.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n const bytes = buffer.slice(offset);\n let trailIndex = bytes.findIndex((n) => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, buffer.length];\n\n // From bytes to base10.\n let base10Number = bytes\n .slice(trailIndex)\n .reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), buffer.length];\n },\n };\n};\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { baseX } from './baseX';\n\n/**\n * A string serializer that uses base58 encoding.\n * @category Serializers\n */\nexport const base58: Serializer<string> = baseX(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n","/**\n * Removes null characters from a string.\n * @category Utils\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters at the end.\n * @category Utils\n */\nexport const padNullCharacters = (value: string, chars: number) =>\n value.padEnd(chars, '\\u0000');\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { removeNullCharacters } from './nullCharacters';\n\n/**\n * A string serializer that uses UTF-8 encoding\n * using the native `TextEncoder` API.\n * @category Serializers\n */\nexport const utf8: Serializer<string> = {\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n serialize(value: string) {\n return new TextEncoder().encode(value);\n },\n deserialize(buffer, offset = 0) {\n const value = new TextDecoder().decode(buffer.slice(offset));\n return [removeNullCharacters(value), buffer.length];\n },\n};\n","import {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\n\n/**\n * Defines a serializer for numbers and bigints.\n * @category Serializers\n */\nexport type NumberSerializer =\n | Serializer<number>\n | Serializer<number | bigint, bigint>;\n\n/**\n * Defines the options for u8 and i8 serializers.\n * @category Serializers\n */\nexport type SingleByteNumberSerializerOptions = BaseSerializerOptions;\n\n/**\n * Defines the options for number serializers that use more than one byte.\n * @category Serializers\n */\nexport type NumberSerializerOptions = BaseSerializerOptions & {\n /**\n * Whether the serializer should use little-endian or big-endian encoding.\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the endianness of a number serializer.\n * @category Serializers\n */\nexport enum Endian {\n Little = 'le',\n Big = 'be',\n}\n","/** @category Errors */\nexport class NumberOutOfRangeError extends RangeError {\n readonly name: string = 'NumberOutOfRangeError';\n\n constructor(\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n actual: number | bigint\n ) {\n super(\n `Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`\n );\n }\n}\n","import {\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport {\n Endian,\n NumberSerializer,\n NumberSerializerOptions,\n SingleByteNumberSerializerOptions,\n} from './common';\nimport { NumberOutOfRangeError } from './errors';\n\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number | bigint, bigint>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number | bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): NumberSerializer {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian =\n !('endian' in input.options) || input.options.endian === Endian.Little;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n maxSize: input.size,\n serialize(value: number | bigint): Uint8Array {\n if (input.range) {\n assertRange(input.name, input.range[0], input.range[1], value);\n }\n const buffer = new ArrayBuffer(input.size);\n input.set(new DataView(buffer), value, littleEndian);\n return new Uint8Array(buffer);\n },\n deserialize(bytes, offset = 0): [number | bigint, number] {\n const slice = bytes.slice(offset, offset + input.size);\n assertEnoughBytes('i8', slice, input.size);\n const view = toDataView(slice);\n return [input.get(view, littleEndian), offset + input.size];\n },\n } as NumberSerializer;\n}\n\n/**\n * Helper function to ensure that the array buffer is converted properly from a uint8array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n * @param {Uint8Array} array Uint8array that's being converted into an array buffer\n * @returns {ArrayBuffer} An array buffer that's necessary to construct a data view\n */\nexport const toArrayBuffer = (array: Uint8Array): ArrayBuffer =>\n array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);\n\nexport const toDataView = (array: Uint8Array): DataView =>\n new DataView(toArrayBuffer(array));\n\nexport const assertRange = (\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) => {\n if (value < min || value > max) {\n throw new NumberOutOfRangeError(serializer, min, max, value);\n }\n};\n\nexport const assertEnoughBytes = (\n serializer: string,\n bytes: Uint8Array,\n expected: number\n) => {\n if (bytes.length === 0) {\n throw new DeserializingEmptyBufferError(serializer);\n }\n if (bytes.length < expected) {\n throw new NotEnoughBytesError(serializer, expected, bytes.length);\n }\n};\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { SingleByteNumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u8 = (\n options: SingleByteNumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u8',\n size: 1,\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n get: (view) => view.getUint8(0),\n options,\n });\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u32 = (\n options: NumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u32',\n size: 4,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n get: (view, le) => view.getUint32(0, le),\n options,\n });\n","/* eslint-disable no-bitwise */\nimport {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { assertRange } from './utils';\n\n/**\n * Defines the options for the shortU16 serializer.\n * @category Serializers\n */\nexport type ShortU16SerializerOptions = BaseSerializerOptions;\n\n/**\n * Same as u16, but serialized with 1 to 3 bytes.\n *\n * If the value is above 0x7f, the top bit is set and the remaining\n * value is stored in the next bytes. Each byte follows the same\n * pattern until the 3rd byte. The 3rd byte, if needed, uses\n * all 8 bits to store the last byte of the original value.\n *\n * @category Serializers\n */\nexport const shortU16 = (\n options: ShortU16SerializerOptions = {}\n): Serializer<number> => ({\n description: options.description ?? 'shortU16',\n fixedSize: null,\n maxSize: 3,\n serialize: (value: number): Uint8Array => {\n assertRange('shortU16', 0, 65535, value);\n const bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = value >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n bytes[ii - 1] |= 0b10000000;\n }\n }\n return new Uint8Array(bytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0): [number, number] => {\n let value = 0;\n let byteCount = 0;\n while (\n ++byteCount // eslint-disable-line no-plusplus\n ) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n});\n","/** @category Errors */\nexport class InvalidNumberOfItemsError extends Error {\n readonly name = 'InvalidNumberOfItemsError';\n\n constructor(\n serializer: string,\n expected: number | bigint,\n actual: number | bigint\n ) {\n super(`Expected [${serializer}] to have ${expected} items, got ${actual}.`);\n }\n}\n\n/** @category Errors */\nexport class InvalidArrayLikeRemainderSizeError extends Error {\n readonly name = 'InvalidArrayLikeRemainderSizeError';\n\n constructor(remainderSize: number | bigint, itemSize: number | bigint) {\n super(\n `The remainder of the buffer (${remainderSize} bytes) cannot be split into chunks of ${itemSize} bytes. ` +\n `Serializers of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainderSize} modulo ${itemSize} should be equal to zero.`\n );\n }\n}\n\n/** @category Errors */\nexport class UnrecognizedArrayLikeSerializerSizeError extends Error {\n readonly name = 'UnrecognizedArrayLikeSerializerSizeError';\n\n constructor(size: never) {\n super(`Unrecognized array-like serializer size: ${JSON.stringify(size)}`);\n }\n}\n\n/** @category Errors */\nexport class InvalidDataEnumVariantError extends Error {\n readonly name = 'InvalidDataEnumVariantError';\n\n constructor(invalidVariant: string, validVariants: string[]) {\n super(\n `Invalid data enum variant. ` +\n `Expected one of [${validVariants.join(', ')}], ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class InvalidScalarEnumVariantError extends Error {\n readonly name = 'InvalidScalarEnumVariantError';\n\n constructor(\n invalidVariant: string | number | bigint,\n validVariants: string[],\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Invalid scalar enum variant. ` +\n `Expected one of [${validVariants.join(', ')}] ` +\n `or a number between ${min} and ${max}, ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class EnumDiscriminatorOutOfRangeError extends RangeError {\n readonly name = 'EnumDiscriminatorOutOfRangeError';\n\n constructor(\n discriminator: number | bigint,\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Enum discriminator out of range. ` +\n `Expected a number between ${min} and ${max}, got ${discriminator}.`\n );\n }\n}\n","export function sumSerializerSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : all + size),\n 0 as number | null\n );\n}\n","import { ExpectedFixedSizeSerializerError } from '@metaplex-foundation/umi-serializers-core';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport {\n InvalidArrayLikeRemainderSizeError,\n UnrecognizedArrayLikeSerializerSizeError,\n} from './errors';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\nexport function getResolvedSize(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: number\n): [number | bigint, number] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.deserialize(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumSerializerSizes(childrenSizes);\n if (childrenSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n throw new InvalidArrayLikeRemainderSizeError(remainder, childrenSize);\n }\n return [remainder / childrenSize, offset];\n }\n\n throw new UnrecognizedArrayLikeSerializerSizeError(size);\n}\n\nexport function getSizeDescription(\n size: ArrayLikeSerializerSize | string\n): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getSizeFromChildren(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumSerializerSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getSizePrefix(\n size: ArrayLikeSerializerSize,\n realSize: number\n): Uint8Array {\n return typeof size === 'object' ? size.serialize(realSize) : new Uint8Array();\n}\n","import {\n BaseSerializerOptions,\n ExpectedFixedSizeSerializerError,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { u32 } from '@metaplex-foundation/umi-serializers-numbers';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport { InvalidNumberOfItemsError } from './errors';\nimport {\n getResolvedSize,\n getSizeDescription,\n getSizeFromChildren,\n getSizePrefix,\n} from './utils';\n\n/**\n * Defines the options for array serializers.\n * @category Serializers\n */\nexport type ArraySerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the array.\n * @defaultValue `u32()`\n */\n size?: ArrayLikeSerializerSize;\n};\n\n/**\n * Creates a serializer for an array of items.\n *\n * @param item - The serializer to use for the array's items.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function array<T, U extends T = T>(\n item: Serializer<T, U>,\n options: ArraySerializerOptions = {}\n): Serializer<T[], U[]> {\n const size = options.size ?? u32();\n if (size === 'remainder' && item.fixedSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n return {\n description:\n options.description ??\n `array(${item.description}; ${getSizeDescription(size)})`,\n fixedSize: getSizeFromChildren(size, [item.fixedSize]),\n maxSize: getSizeFromChildren(size, [item.maxSize]),\n serialize: (value: T[]) => {\n if (typeof size === 'number' && value.length !== size) {\n throw new InvalidNumberOfItemsError('array', size, value.length);\n }\n return mergeBytes([\n getSizePrefix(size, value.length),\n ...value.map((v) => item.serialize(v)),\n ]);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = getResolvedSize(\n size,\n [item.fixedSize],\n bytes,\n offset\n );\n offset = newOffset;\n const values: U[] = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.deserialize(bytes, offset);\n values.push(value);\n offset = newOffset;\n }\n return [values, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializer } from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for bytes serializers.\n * @category Serializers\n */\nexport type BytesSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the buffer. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the buffer with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `'variable'`\n */\n size?: NumberSerializer | number | 'variable';\n};\n\n/**\n * Creates a serializer that passes the buffer as-is.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function bytes(\n options: BytesSerializerOptions = {}\n): Serializer<Uint8Array> {\n const size = options.size ?? 'variable';\n const description =\n options.description ?? `bytes(${getSizeDescription(size)})`;\n\n const byteSerializer: Serializer<Uint8Array> = {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => new Uint8Array(value),\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n };\n\n if (size === 'variable') {\n return byteSerializer;\n }\n\n if (typeof size === 'number') {\n return fixSerializer(byteSerializer, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => {\n const contentBytes = byteSerializer.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('bytes');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('bytes', length, contentBuffer.length);\n }\n const [value, contentOffset] = byteSerializer.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { utf8 } from '@metaplex-foundation/umi-serializers-encodings';\nimport {\n NumberSerializer,\n u32,\n} from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for string serializers.\n * @category Serializers\n */\nexport type StringSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `u32()`\n */\n size?: NumberSerializer | number | 'variable';\n /**\n * The string serializer to use for encoding and decoding the content.\n * @defaultValue `utf8`\n */\n encoding?: Serializer<string>;\n};\n\n/**\n * Creates a string serializer.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function string(\n options: StringSerializerOptions = {}\n): Serializer<string> {\n const size = options.size ?? u32();\n const encoding = options.encoding ?? utf8;\n const description =\n options.description ??\n `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixSerializer(encoding, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: string) => {\n const contentBytes = encoding.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('string');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('string', length, contentBuffer.length);\n }\n const [value, contentOffset] = encoding.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\n/**\n * Get the name and serializer of each field in a struct.\n * @category Serializers\n */\nexport type StructToSerializerTuple<T extends object, U extends T> = Array<\n {\n [K in keyof T]: [K, Serializer<T[K], U[K]>];\n }[keyof T]\n>;\n\n/**\n * Defines the options for struct serializers.\n * @category Serializers\n */\nexport type StructSerializerOptions = BaseSerializerOptions;\n\n/**\n * Creates a serializer for a custom object.\n *\n * @param fields - The name and serializer of each field.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function struct<T extends object, U extends T = T>(\n fields: StructToSerializerTuple<T, U>,\n options: StructSerializerOptions = {}\n): Serializer<T, U> {\n const fieldDescriptions = fields\n .map(([name, serializer]) => `${String(name)}: ${serializer.description}`)\n .join(', ');\n return {\n description: options.description ?? `struct(${fieldDescriptions})`,\n fixedSize: sumSerializerSizes(fields.map(([, field]) => field.fixedSize)),\n maxSize: sumSerializerSizes(fields.map(([, field]) => field.maxSize)),\n serialize: (struct: T) => {\n const fieldBytes = fields.map(([key, serializer]) =>\n serializer.serialize(struct[key])\n );\n return mergeBytes(fieldBytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const struct: Partial<U> = {};\n fields.forEach(([key, serializer]) => {\n const [value, newOffset] = serializer.deserialize(bytes, offset);\n offset = newOffset;\n struct[key] = value;\n });\n return [struct as U, offset];\n },\n };\n}\n","import { ITransactionWithSignatures } from '.';\nimport { BaseTransaction } from './types';\n\nexport function getUnsignedTransaction<TTransaction extends BaseTransaction>(\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction & ITransactionWithSignatures, keyof ITransactionWithSignatures> {\n if ('signatures' in transaction) {\n // The implication of the lifetime constraint changing is that any existing signatures are invalid.\n const {\n signatures: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n","import { base58 } from '@metaplex-foundation/umi-serializers';\n\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport type Blockhash = string & { readonly __brand: unique symbol };\n\ntype BlockhashLifetimeConstraint = Readonly<{\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n}>;\n\nexport interface ITransactionWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 ||\n // Highest value (32 bytes of 255)\n putativeBlockhash.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeBlockhash);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBlockhash}\\` is not a blockhash`, {\n cause: e,\n });\n }\n}\n\nexport function setTransactionLifetimeUsingBlockhash<TTransaction extends BaseTransaction & IDurableNonceTransaction>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures | 'lifetimeConstraint'> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash<\n TTransaction extends BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n) {\n if (\n 'lifetimeConstraint' in transaction &&\n transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n lifetimeConstraint: blockhashLifetimeConstraint,\n };\n Object.freeze(out);\n return out;\n}\n","import { Transaction, TransactionVersion } from './types';\n\ntype TransactionConfig<TVersion extends TransactionVersion> = Readonly<{\n version: TVersion;\n}>;\n\nexport function createTransaction<TVersion extends TransactionVersion>(\n config: TransactionConfig<TVersion>\n): Extract<Transaction, { version: TVersion }>;\nexport function createTransaction<TVersion extends TransactionVersion>({\n version,\n}: TransactionConfig<TVersion>): Transaction {\n const out: Transaction = {\n instructions: [],\n version,\n };\n Object.freeze(out);\n return out;\n}\n","/**\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 { Base58EncodedAddress } from '@solana/addresses';\nimport { AccountRole, IInstruction, IInstructionWithAccounts, IInstructionWithData } from '@solana/instructions';\nimport { ReadonlyAccount, ReadonlySignerAccount, WritableAccount } from '@solana/instructions/dist/types/accounts';\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>\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): Omit<TTransaction, keyof ITransactionWithSignatures> &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue> {\n const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction);\n if (\n isAlreadyDurableNonceTransaction &&\n transaction.lifetimeConstraint.nonce === nonce &&\n transaction.instructions[0].accounts[0].address === nonceAccountAddress &&\n transaction.instructions[0].accounts[2].address === nonceAuthorityAddress\n ) {\n return transaction as TTransaction &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...(isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions),\n ],\n lifetimeConstraint: {\n nonce,\n },\n } as TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport interface ITransactionWithFeePayer<TAddress extends string = string> {\n readonly feePayer: Base58EncodedAddress<TAddress>;\n}\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction: TTransaction | (TTransaction & ITransactionWithFeePayer<string>)\n): TTransaction & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | TTransaction\n | (TTransaction & ITransactionWithFeePayer<string>)\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n) {\n if ('feePayer' in transaction && feePayer === transaction.feePayer) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n feePayer,\n };\n Object.freeze(out);\n return out;\n}\n","import { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport function appendTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [...transaction.instructions, instruction],\n };\n Object.freeze(out);\n return out;\n}\n\nexport function prependTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [instruction, ...transaction.instructions],\n };\n Object.freeze(out);\n return out;\n}\n","import { CodecData } from './codec';\n\n/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n\n/**\n * Asserts that a given codec is fixed-size codec.\n */\nexport function assertFixedSizeCodec(\n data: Pick<CodecData, 'fixedSize'>,\n message?: string\n): asserts data is { fixedSize: number } {\n if (data.fixedSize === null) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<From, To extends From = From>(\n encoder: Encoder<From>,\n decoder: Decoder<To>,\n description?: string\n): Codec<From, To> {\n if (encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`\n );\n }\n\n if (encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`\n );\n }\n\n if (description === undefined && encoder.description !== decoder.description) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. ` +\n `Pass a custom description as a third argument if you want to override the description and bypass this error.`\n );\n }\n\n return {\n decode: decoder.decode,\n description: description ?? encoder.description,\n encode: encoder.encode,\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport { Codec, CodecData, Decoder, Encoder } from './codec';\nimport { combineCodec } from './combine-codec';\n\nfunction fixCodecHelper(data: CodecData, fixedBytes: number, description?: string): CodecData {\n return {\n description: description ?? `fixed(${fixedBytes}, ${data.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n };\n}\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @param description - A custom description for the encoder.\n */\nexport function fixEncoder<T>(encoder: Encoder<T>, fixedBytes: number, description?: string): Encoder<T> {\n return {\n ...fixCodecHelper(encoder, fixedBytes, description),\n encode: (value: T) => fixBytes(encoder.encode(value), fixedBytes),\n };\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the decoder.\n */\nexport function fixDecoder<T>(decoder: Decoder<T>, fixedBytes: number, description?: string): Decoder<T> {\n return {\n ...fixCodecHelper(decoder, fixedBytes, description),\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (decoder.fixedSize !== null) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.decode(bytes, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @param description - A custom description for the codec.\n */\nexport function fixCodec<T, U extends T = T>(\n codec: Codec<T, U>,\n fixedBytes: number,\n description?: string\n): Codec<T, U> {\n return combineCodec(fixEncoder(codec, fixedBytes, description), fixDecoder(codec, fixedBytes, description));\n}\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<T, U>(encoder: Encoder<T>, unmap: (value: U) => T): Encoder<U> {\n return {\n description: encoder.description,\n encode: (value: U) => encoder.encode(unmap(value)),\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<T, U>(\n decoder: Decoder<T>,\n map: (value: T, bytes: Uint8Array, offset: number) => U\n): Decoder<U> {\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n const [value, length] = decoder.decode(bytes, offset);\n return [map(value, bytes, offset), length];\n },\n description: decoder.description,\n fixedSize: decoder.fixedSize,\n maxSize: decoder.maxSize,\n };\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<NewFrom, OldFrom, To extends NewFrom & OldFrom>(\n codec: Codec<OldFrom, To>,\n unmap: (value: NewFrom) => OldFrom\n): Codec<NewFrom, To>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map?: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo> {\n return {\n decode: map ? mapDecoder(codec, map).decode : (codec.decode as unknown as Decoder<NewTo>['decode']),\n description: codec.description,\n encode: mapEncoder(codec, unmap).encode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n };\n}\n","/**\n * Asserts that a given number is between a given range.\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) {\n if (value < min || value > max) {\n // TODO: Coded error.\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`\n );\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'f32',\n options,\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n options,\n size: 4,\n });\n\nexport const getF32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getF32Encoder(options), getF32Decoder(options));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n CodecData,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecOptions, SingleByteNumberCodecOptions } from './common';\n\ntype NumberFactorySharedInput = {\n name: string;\n size: number;\n options: SingleByteNumberCodecOptions | NumberCodecOptions;\n};\n\ntype NumberFactoryEncoderInput<T> = NumberFactorySharedInput & {\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: T, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput<T> = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => T;\n};\n\nfunction sharedNumberFactory(input: NumberFactorySharedInput): CodecData & { littleEndian: boolean | undefined } {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian = !('endian' in input.options) || input.options.endian === Endian.LITTLE;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n littleEndian,\n maxSize: input.size,\n };\n}\n\nexport function numberEncoderFactory<T extends number | bigint>(input: NumberFactoryEncoderInput<T>): Encoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n description: codecData.description,\n encode(value: T): Uint8Array {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, codecData.littleEndian);\n return new Uint8Array(arrayBuffer);\n },\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\nexport function numberDecoderFactory<T extends number | bigint>(input: NumberFactoryDecoderInput<T>): Decoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n decode(bytes, offset = 0): [T, number] {\n assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, codecData.littleEndian), offset + input.size];\n },\n description: codecData.description,\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\n/**\n * Helper function to ensure that the ArrayBuffer is converted properly from a Uint8Array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nfunction toArrayBuffer(bytes: Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (options: NumberCodecOptions = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n name: 'u128',\n options,\n range: [0, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\nexport const getU128Decoder = (options: NumberCodecOptions = {}): Decoder<bigint> =>\n numberDecoderFactory({\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n options,\n size: 16,\n });\n\nexport const getU128Codec = (options: NumberCodecOptions = {}): Codec<number | bigint, bigint> =>\n combineCodec(getU128Encoder(options), getU128Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u16',\n options,\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, value, le),\n size: 2,\n });\n\nexport const getU16Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n options,\n size: 2,\n });\n\nexport const getU16Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU16Encoder(options), getU16Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u32',\n options,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, value, le),\n size: 4,\n });\n\nexport const getU32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n options,\n size: 4,\n });\n\nexport const getU32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU32Encoder(options), getU32Decoder(options));\n","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXEncoder = (alphabet: string): Encoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n encode(value: string): Uint8Array {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex(c => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * Decodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXDecoder = (alphabet: string): Decoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n decode(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), rawBytes.length];\n },\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * A string codec that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create codecs such as base10 or base58.\n */\nexport const getBaseXCodec = (alphabet: string): Codec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): Encoder<string> => ({\n description: 'base16',\n encode(value: string) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString('0123456789abcdef', lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n return Uint8Array.from(matches ? matches.map((byte: string) => parseInt(byte, 16)) : []);\n },\n fixedSize: null,\n maxSize: null,\n});\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): Decoder<string> => ({\n decode(bytes, offset = 0) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n description: 'base16',\n fixedSize: null,\n maxSize: null,\n});\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): Codec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Encodes strings in base64. */\nexport const getBase64Encoder = (): Encoder<string> => {\n if (__BROWSER__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n try {\n const bytes = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n return new Uint8Array(bytes);\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n return new Uint8Array(Buffer.from(value, 'base64'));\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/** Decodes strings in base64. */\nexport const getBase64Decoder = (): Decoder<string> => {\n if (__BROWSER__) {\n return {\n decode(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n decode: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString('base64'), bytes.length],\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '=')\n );\n};\n\n/** Encodes and decodes strings in base64. */\nexport const getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());\n","/**Removes null characters from a string. */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/** Pads a string with null characters at the end. */\nexport const padNullCharacters = (value: string, chars: number) => value.padEnd(chars, '\\u0000');\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixDecoder,\n fixEncoder,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { getUtf8Decoder, getUtf8Encoder } from './utf8';\n\n/** Defines the options for string codecs. */\nexport type StringCodecOptions<\n TPrefix extends NumberCodec | NumberEncoder | NumberDecoder,\n TEncoding extends Codec<string> | Encoder<string> | Decoder<string>\n> = BaseCodecOptions & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberCodec} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the byte array.\n * @defaultValue u32 prefix.\n */\n size?: TPrefix | number | 'variable';\n\n /**\n * The codec to use for encoding and decoding the content.\n * @defaultValue UTF-8 encoding.\n */\n encoding?: TEncoding;\n};\n\n/** Encodes strings from a given encoding and size strategy. */\nexport const getStringEncoder = (options: StringCodecOptions<NumberEncoder, Encoder<string>> = {}): Encoder<string> => {\n const size = options.size ?? getU32Encoder();\n const encoding = options.encoding ?? getUtf8Encoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixEncoder(encoding, size, description);\n }\n\n return {\n description,\n encode: (value: string) => {\n const contentBytes = encoding.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes strings from a given encoding and size strategy. */\nexport const getStringDecoder = (options: StringCodecOptions<NumberDecoder, Decoder<string>> = {}): Decoder<string> => {\n const size = options.size ?? getU32Decoder();\n const encoding = options.encoding ?? getUtf8Decoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixDecoder(encoding, size, description);\n }\n\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('string', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec('string', length, contentBytes);\n const [value, contentOffset] = encoding.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n },\n description,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes strings from a given encoding and size strategy. */\nexport const getStringCodec = (options: StringCodecOptions<NumberCodec, Codec<string>> = {}): Codec<string> =>\n combineCodec(getStringEncoder(options), getStringDecoder(options));\n\nfunction getSizeDescription(size: CodecData | number | 'variable'): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from 'text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/** Encodes UTF-8 strings using the native `TextEncoder` API. */\nexport const getUtf8Encoder = (): Encoder<string> => {\n let textEncoder: TextEncoder;\n return {\n description: 'utf8',\n encode: (value: string) => new Uint8Array((textEncoder ||= new TextEncoder()).encode(value)),\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes UTF-8 strings using the native `TextDecoder` API. */\nexport const getUtf8Decoder = (): Decoder<string> => {\n let textDecoder: TextDecoder;\n return {\n decode(bytes, offset = 0) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes UTF-8 strings using the native `TextEncoder` and `TextDecoder` API. */\nexport const getUtf8Codec = (): Codec<string> => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapEncoder } from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\nexport function isAddress(\n putativeBase58EncodedAddress: string\n): putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function address<TAddress extends string = string>(\n putativeBase58EncodedAddress: TAddress\n): Base58EncodedAddress<TAddress> {\n assertIsAddress(putativeBase58EncodedAddress);\n return putativeBase58EncodedAddress as Base58EncodedAddress<TAddress>;\n}\n\nexport function getAddressEncoder(config?: Readonly<{ description: string }>): Encoder<Base58EncodedAddress> {\n return mapEncoder(\n getStringEncoder({\n description: config?.description ?? 'Base58EncodedAddress',\n encoding: getMemoizedBase58Encoder(),\n size: 32,\n }),\n putativeAddress => address(putativeAddress)\n );\n}\n\nexport function getAddressDecoder(config?: Readonly<{ description: string }>): Decoder<Base58EncodedAddress> {\n return getStringDecoder({\n description: config?.description ?? 'Base58EncodedAddress',\n encoding: getMemoizedBase58Decoder(),\n size: 32,\n }) as Decoder<Base58EncodedAddress>;\n}\n\nexport function getAddressCodec(config?: Readonly<{ description: string }>): Codec<Base58EncodedAddress> {\n return combineCodec(getAddressEncoder(config), getAddressDecoder(config));\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\nimport { assertIsAddress, Base58EncodedAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve';\n\n/**\n * An address derived from a program address and a set of seeds.\n * It includes the bump seed used to derive the address and\n * ensure the address is not on the Ed25519 curve.\n */\nexport type ProgramDerivedAddress<TAddress extends string = string> = Readonly<\n [Base58EncodedAddress<TAddress>, ProgramDerivedAddressBump]\n>;\n\n/**\n * A number between 0 and 255, inclusive.\n */\nexport type ProgramDerivedAddressBump = number & {\n readonly __brand: unique symbol;\n};\n\n/**\n * Returns true if the input value is a program derived address.\n */\nexport function isProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): value is ProgramDerivedAddress<TAddress> {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * Fails if the input value is not a program derived address.\n */\nexport function assertIsProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): asserts value is ProgramDerivedAddress<TAddress> {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n // TODO: Coded error.\n throw new Error(\n `Expected given program derived address to have the following format: [Base58EncodedAddress, ProgramDerivedAddressBump].`\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n // TODO: Coded error.\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Base58EncodedAddress;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Base58EncodedAddress;\n programAddress: Base58EncodedAddress;\n seed: Seed;\n}>;\n\ntype Seed = string | Uint8Array;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\n// TODO: Coded error.\nclass PointOnCurveError extends Error {}\n\nasync function createProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<Base58EncodedAddress> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n // TODO: Coded error.\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n // TODO: Coded error.\n throw new PointOnCurveError('Invalid seeds; point must fall off the Ed25519 curve');\n }\n return base58EncodedAddressCodec.decode(addressBytes)[0];\n}\n\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<ProgramDerivedAddress> {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n // TODO: Coded error.\n throw new Error('Unable to find a viable program address bump seed');\n}\n\nexport async function createAddressWithSeed({\n baseAddress,\n programAddress,\n seed,\n}: SeedInput): Promise<Base58EncodedAddress> {\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])\n ) {\n // TODO: Coded error.\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes)[0];\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Base58EncodedAddress, getAddressDecoder } from './address';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n","import { Base58EncodedAddress, getAddressComparator } from '@solana/addresses';\nimport {\n AccountRole,\n IAccountLookupMeta,\n IAccountMeta,\n IInstruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit<WritableSignerAccount, 'address'> & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit<ReadonlyAccountLookup | WritableAccountLookup, 'address'> & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = (IAccountMeta | IAccountLookupMeta)[] & { readonly __brand: unique symbol };\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Base58EncodedAddress,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry | Record<never, never>\n ) => AddressMap[Base58EncodedAddress]\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(\n feePayer: Base58EncodedAddress,\n instructions: readonly IInstruction[]\n): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set<Base58EncodedAddress>();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and set as the fee payer. Program addresses may not pay fees.'\n );\n default:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and marked writable. Program addresses may not be writable.'\n );\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType<typeof getAddressComparator>;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry as FeePayerAccountEntry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry as LookupTableAccountEntry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${account.address}\\`) which is both invoked and ` +\n 'marked writable. Program addresses may not be ' +\n 'writable.'\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType<typeof getAddressComparator>;\n const orderedAccounts: (IAccountMeta | IAccountLookupMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Base58EncodedAddress<typeof address>,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Base58EncodedAddress, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype AddressTableLookup = Readonly<{\n lookupTableAddress: Base58EncodedAddress;\n readableIndices: readonly number[];\n writableIndices: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Base58EncodedAddress,\n { readonly readableIndices: number[]; readonly writableIndices: number[] }\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readableIndices: [],\n writableIndices: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndices.push(account.addressIndex);\n } else {\n entry.readableIndices.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Base58EncodedAddress,\n ...index[lookupTableAddress as unknown as Base58EncodedAddress],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype MessageHeader = Readonly<{\n numReadonlyNonSignerAccounts: number;\n numReadonlySignerAccounts: number;\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport { IInstruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n accountIndices?: number[];\n data?: Uint8Array;\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record<Base58EncodedAddress, number> = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly IInstruction[],\n orderedAccounts: OrderedAccounts\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { IDurableNonceTransaction, ITransactionWithBlockhashLifetime } from './index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (ITransactionWithBlockhashLifetime | IDurableNonceTransaction)['lifetimeConstraint']\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Base58EncodedAddress[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { ITransactionWithBlockhashLifetime } from './blockhash';\nimport { getCompiledAddressTableLookups } from './compile-address-table-lookups';\nimport { getCompiledMessageHeader } from './compile-header';\nimport { getCompiledInstructions } from './compile-instructions';\nimport { getCompiledLifetimeToken } from './compile-lifetime-token';\nimport { getCompiledStaticAccounts } from './compile-static-accounts';\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithFeePayer } from './fee-payer';\nimport { BaseTransaction } from './types';\n\ntype BaseCompiledMessage = Readonly<{\n header: ReturnType<typeof getCompiledMessageHeader>;\n instructions: ReturnType<typeof getCompiledInstructions>;\n lifetimeToken: ReturnType<typeof getCompiledLifetimeToken>;\n staticAccounts: ReturnType<typeof getCompiledStaticAccounts>;\n}>;\n\ntype CompilableTransaction = BaseTransaction &\n ITransactionWithFeePayer &\n (ITransactionWithBlockhashLifetime | IDurableNonceTransaction);\n\nexport type CompiledMessage = LegacyCompiledMessage | VersionedCompiledMessage;\n\ntype LegacyCompiledMessage = BaseCompiledMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledMessage = BaseCompiledMessage &\n Readonly<{\n addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups>;\n version: number;\n }>;\n\nexport function compileMessage(\n transaction: CompilableTransaction & Readonly<{ version: 'legacy' }>\n): LegacyCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): VersionedCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): CompiledMessage {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...(transaction.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),\n lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transaction.version,\n };\n}\n","import { Ed25519Signature } from '@solana/keys';\n\nimport { CompiledMessage, compileMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\n\ntype CompiledTransaction = Readonly<{\n compiledMessage: CompiledMessage;\n signatures: Ed25519Signature[];\n}>;\n\ntype CompilableTransaction = Parameters<typeof compileMessage>[0];\n\nexport function getCompiledTransaction(\n transaction: CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n): CompiledTransaction {\n const compiledMessage = compileMessage(transaction);\n let signatures;\n if ('signatures' in transaction) {\n signatures = [];\n for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {\n signatures[ii] =\n transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));\n }\n } else {\n signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));\n }\n return {\n compiledMessage,\n signatures,\n };\n}\n","import { array, Serializer, shortU16, struct, StructToSerializerTuple, u8 } from '@metaplex-foundation/umi-serializers';\nimport { Base58EncodedAddress, getAddressCodec } from '@solana/addresses';\n\nimport { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\n\ntype AddressTableLookup = ReturnType<typeof getCompiledAddressTableLookups>[number];\n\n// Temporary, will use getAddressCodec directly when everything else is migrated\nfunction addressSerializerCompat(compat?: { description: string }): Serializer<Base58EncodedAddress> {\n const codec = getAddressCodec();\n return {\n description: compat?.description ?? codec.description,\n deserialize: codec.decode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n serialize: codec.encode,\n };\n}\n\nexport function getAddressTableLookupCodec(): Serializer<AddressTableLookup> {\n return struct(\n [\n [\n 'lookupTableAddress',\n addressSerializerCompat(\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 { mergeBytes, combineCodec, assertByteArrayHasEnoughBytesForCodec, assertFixedSizeCodec, assertByteArrayIsNotEmptyForCodec, fixEncoder, fixDecoder, fixBytes } from '@solana/codecs-core';\nimport { getU32Encoder, getU32Decoder, getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';\n\n// src/array.ts\n\n// src/utils.ts\nfunction maxCodecSizes(sizes) {\n return sizes.reduce(\n (all, size) => all === null || size === null ? null : Math.max(all, size),\n 0\n );\n}\nfunction sumCodecSizes(sizes) {\n return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);\n}\n\n// src/array-like-codec-size.ts\nfunction decodeArrayLikeCodecSize(size, childrenSizes, bytes, offset) {\n if (typeof size === \"number\") {\n return [size, offset];\n }\n if (typeof size === \"object\") {\n return size.decode(bytes, offset);\n }\n if (size === \"remainder\") {\n const childrenSize = sumCodecSizes(childrenSizes);\n if (childrenSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${childrenSize} bytes. Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. In other words, ${remainder} modulo ${childrenSize} should be equal to zero.`\n );\n }\n return [remainder / childrenSize, offset];\n }\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\nfunction getArrayLikeCodecSizeDescription(size) {\n return typeof size === \"object\" ? size.description : `${size}`;\n}\nfunction getArrayLikeCodecSizeFromChildren(size, childrenSizes) {\n if (typeof size !== \"number\")\n return null;\n if (size === 0)\n return 0;\n const childrenSize = sumCodecSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\nfunction getArrayLikeCodecSizePrefix(size, realSize) {\n return typeof size === \"object\" ? size.encode(realSize) : new Uint8Array();\n}\n\n// src/assertions.ts\nfunction assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {\n if (expected !== actual) {\n throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);\n }\n}\n\n// src/array.ts\nfunction arrayCodecHelper(item, size, description) {\n if (size === \"remainder\" && item.fixedSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n return {\n description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize])\n };\n}\nfunction getArrayEncoder(item, options = {}) {\n const size = options.size ?? getU32Encoder();\n return {\n ...arrayCodecHelper(item, size, options.description),\n encode: (value) => {\n if (typeof size === \"number\") {\n assertValidNumberOfItemsForCodec(\"array\", size, value.length);\n }\n return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map((v) => item.encode(v))]);\n }\n };\n}\nfunction getArrayDecoder(item, options = {}) {\n const size = options.size ?? getU32Decoder();\n return {\n ...arrayCodecHelper(item, size, options.description),\n decode: (bytes, offset = 0) => {\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n const values = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset2] = item.decode(bytes, offset);\n values.push(value);\n offset = newOffset2;\n }\n return [values, offset];\n }\n };\n}\nfunction getArrayCodec(item, options = {}) {\n return combineCodec(getArrayEncoder(item, options), getArrayDecoder(item, options));\n}\nvar getBitArrayEncoder = (size, options = {}) => {\n const parsedOptions = typeof options === \"boolean\" ? { backward: options } : options;\n const backward = parsedOptions.backward ?? false;\n const backwardSuffix = backward ? \"; backward\" : \"\";\n return {\n description: parsedOptions.description ?? `bitArray(${size}${backwardSuffix})`,\n encode(value) {\n const bytes = [];\n for (let i = 0; i < size; i += 1) {\n let byte = 0;\n for (let j = 0; j < 8; j += 1) {\n const feature = Number(value[i * 8 + j] ?? 0);\n byte |= feature << (backward ? j : 7 - j);\n }\n if (backward) {\n bytes.unshift(byte);\n } else {\n bytes.push(byte);\n }\n }\n return new Uint8Array(bytes);\n },\n fixedSize: size,\n maxSize: size\n };\n};\nvar getBitArrayDecoder = (size, options = {}) => {\n const parsedOptions = typeof options === \"boolean\" ? { backward: options } : options;\n const backward = parsedOptions.backward ?? false;\n const backwardSuffix = backward ? \"; backward\" : \"\";\n return {\n decode(bytes, offset = 0) {\n assertByteArrayHasEnoughBytesForCodec(\"bitArray\", size, bytes, offset);\n const booleans = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n slice.forEach((byte) => {\n for (let i = 0; i < 8; i += 1) {\n if (backward) {\n booleans.push(Boolean(byte & 1));\n byte >>= 1;\n } else {\n booleans.push(Boolean(byte & 128));\n byte <<= 1;\n }\n }\n });\n return [booleans, offset + size];\n },\n description: parsedOptions.description ?? `bitArray(${size}${backwardSuffix})`,\n fixedSize: size,\n maxSize: size\n };\n};\nvar getBitArrayCodec = (size, options = {}) => combineCodec(getBitArrayEncoder(size, options), getBitArrayDecoder(size, options));\nfunction getBooleanEncoder(options = {}) {\n const size = options.size ?? getU8Encoder();\n assertFixedSizeCodec(size, \"Codec [bool] requires a fixed size.\");\n return {\n description: options.description ?? `bool(${size.description})`,\n encode: (value) => size.encode(value ? 1 : 0),\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize\n };\n}\nfunction getBooleanDecoder(options = {}) {\n const size = options.size ?? getU8Decoder();\n assertFixedSizeCodec(size, \"Codec [bool] requires a fixed size.\");\n return {\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"bool\", bytes, offset);\n const [value, vOffset] = size.decode(bytes, offset);\n return [value === 1, vOffset];\n },\n description: options.description ?? `bool(${size.description})`,\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize\n };\n}\nfunction getBooleanCodec(options = {}) {\n return combineCodec(getBooleanEncoder(options), getBooleanDecoder(options));\n}\nfunction getBytesEncoder(options = {}) {\n const size = options.size ?? \"variable\";\n const sizeDescription = typeof size === \"object\" ? size.description : `${size}`;\n const description = options.description ?? `bytes(${sizeDescription})`;\n const byteEncoder = {\n description,\n encode: (value) => value,\n fixedSize: null,\n maxSize: null\n };\n if (size === \"variable\") {\n return byteEncoder;\n }\n if (typeof size === \"number\") {\n return fixEncoder(byteEncoder, size, description);\n }\n return {\n ...byteEncoder,\n encode: (value) => {\n const contentBytes = byteEncoder.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n }\n };\n}\nfunction getBytesDecoder(options = {}) {\n const size = options.size ?? \"variable\";\n const sizeDescription = typeof size === \"object\" ? size.description : `${size}`;\n const description = options.description ?? `bytes(${sizeDescription})`;\n const byteDecoder = {\n decode: (bytes, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n description,\n fixedSize: null,\n maxSize: null\n };\n if (size === \"variable\") {\n return byteDecoder;\n }\n if (typeof size === \"number\") {\n return fixDecoder(byteDecoder, size, description);\n }\n return {\n ...byteDecoder,\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"bytes\", bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec(\"bytes\", length, contentBytes);\n const [value, contentOffset] = byteDecoder.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n }\n };\n}\nfunction getBytesCodec(options = {}) {\n return combineCodec(getBytesEncoder(options), getBytesDecoder(options));\n}\nfunction dataEnumCodecHelper(variants, prefix, description) {\n const fieldDescriptions = variants.map(([name, codec]) => `${String(name)}${codec ? `: ${codec.description}` : \"\"}`).join(\", \");\n const allVariantHaveTheSameFixedSize = variants.every((one, _i, all) => one[1].fixedSize === all[0][1].fixedSize);\n const fixedVariantSize = allVariantHaveTheSameFixedSize ? variants[0][1].fixedSize : null;\n const maxVariantSize = maxCodecSizes(variants.map(([, field]) => field.maxSize));\n return {\n description: description ?? `dataEnum(${fieldDescriptions}; ${prefix.description})`,\n fixedSize: variants.length === 0 ? prefix.fixedSize : sumCodecSizes([prefix.fixedSize, fixedVariantSize]),\n maxSize: variants.length === 0 ? prefix.maxSize : sumCodecSizes([prefix.maxSize, maxVariantSize])\n };\n}\nfunction getDataEnumEncoder(variants, options = {}) {\n const prefix = options.size ?? getU8Encoder();\n return {\n ...dataEnumCodecHelper(variants, prefix, options.description),\n encode: (variant) => {\n const discriminator = variants.findIndex(([key]) => variant.__kind === key);\n if (discriminator < 0) {\n throw new Error(\n `Invalid data enum variant. Expected one of [${variants.map(([key]) => key).join(\", \")}], got \"${variant.__kind}\".`\n );\n }\n const variantPrefix = prefix.encode(discriminator);\n const variantSerializer = variants[discriminator][1];\n const variantBytes = variantSerializer.encode(variant);\n return mergeBytes([variantPrefix, variantBytes]);\n }\n };\n}\nfunction getDataEnumDecoder(variants, options = {}) {\n const prefix = options.size ?? getU8Decoder();\n return {\n ...dataEnumCodecHelper(variants, prefix, options.description),\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"dataEnum\", bytes, offset);\n const [discriminator, dOffset] = prefix.decode(bytes, offset);\n offset = dOffset;\n const variantField = variants[Number(discriminator)] ?? null;\n if (!variantField) {\n throw new Error(\n `Enum discriminator out of range. Expected a number between 0 and ${variants.length - 1}, got ${discriminator}.`\n );\n }\n const [variant, vOffset] = variantField[1].decode(bytes, offset);\n offset = vOffset;\n return [{ __kind: variantField[0], ...variant ?? {} }, offset];\n }\n };\n}\nfunction getDataEnumCodec(variants, options = {}) {\n return combineCodec(getDataEnumEncoder(variants, options), getDataEnumDecoder(variants, options));\n}\nfunction mapCodecHelper(key, value, size, description) {\n if (size === \"remainder\" && (key.fixedSize === null || value.fixedSize === null)) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n return {\n description: description ?? `map(${key.description}, ${value.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [key.fixedSize, value.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [key.maxSize, value.maxSize])\n };\n}\nfunction getMapEncoder(key, value, options = {}) {\n const size = options.size ?? getU32Encoder();\n return {\n ...mapCodecHelper(key, value, size, options.description),\n encode: (map) => {\n if (typeof size === \"number\") {\n assertValidNumberOfItemsForCodec(\"map\", size, map.size);\n }\n const itemBytes = Array.from(map, ([k, v]) => mergeBytes([key.encode(k), value.encode(v)]));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, map.size), ...itemBytes]);\n }\n };\n}\nfunction getMapDecoder(key, value, options = {}) {\n const size = options.size ?? getU32Decoder();\n return {\n ...mapCodecHelper(key, value, size, options.description),\n decode: (bytes, offset = 0) => {\n const map = /* @__PURE__ */ new Map();\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [map, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(\n size,\n [key.fixedSize, value.fixedSize],\n bytes,\n offset\n );\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [decodedKey, kOffset] = key.decode(bytes, offset);\n offset = kOffset;\n const [decodedValue, vOffset] = value.decode(bytes, offset);\n offset = vOffset;\n map.set(decodedKey, decodedValue);\n }\n return [map, offset];\n }\n };\n}\nfunction getMapCodec(key, value, options = {}) {\n return combineCodec(getMapEncoder(key, value, options), getMapDecoder(key, value, options));\n}\nfunction nullableCodecHelper(item, prefix, fixed, description) {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, \"Fixed nullables can only be used with fixed-size codecs.\");\n assertFixedSizeCodec(prefix, \"Fixed nullables can only be used with fixed-size prefix.\");\n descriptionSuffix += \"; fixed\";\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n return {\n description: description ?? `nullable(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize])\n };\n}\nfunction getNullableEncoder(item, options = {}) {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...nullableCodecHelper(item, prefix, fixed, options.description),\n encode: (option) => {\n const prefixByte = prefix.encode(Number(option !== null));\n let itemBytes = option !== null ? item.encode(option) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n }\n };\n}\nfunction getNullableDecoder(item, options = {}) {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...nullableCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [null, offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [null, fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [value, fixed ? fixedOffset : offset];\n }\n };\n}\nfunction getNullableCodec(item, options = {}) {\n return combineCodec(getNullableEncoder(item, options), getNullableDecoder(item, options));\n}\nfunction scalarEnumCoderHelper(constructor, prefix, description) {\n const enumKeys = Object.keys(constructor);\n const enumValues = Object.values(constructor);\n const isNumericEnum = enumValues.some((v) => typeof v === \"number\");\n const valueDescriptions = enumValues.filter((v) => typeof v === \"string\").join(\", \");\n const minRange = 0;\n const maxRange = isNumericEnum ? enumValues.length / 2 - 1 : enumValues.length - 1;\n const stringValues = isNumericEnum ? [...enumKeys] : [.../* @__PURE__ */ new Set([...enumKeys, ...enumValues])];\n return {\n description: description ?? `enum(${valueDescriptions}; ${prefix.description})`,\n enumKeys,\n enumValues,\n fixedSize: prefix.fixedSize,\n isNumericEnum,\n maxRange,\n maxSize: prefix.maxSize,\n minRange,\n stringValues\n };\n}\nfunction getScalarEnumEncoder(constructor, options = {}) {\n const prefix = options.size ?? getU8Encoder();\n const { description, fixedSize, maxSize, minRange, maxRange, stringValues, enumKeys, enumValues } = scalarEnumCoderHelper(constructor, prefix, options.description);\n return {\n description,\n encode: (value) => {\n const isInvalidNumber = typeof value === \"number\" && (value < minRange || value > maxRange);\n const isInvalidString = typeof value === \"string\" && !stringValues.includes(value);\n if (isInvalidNumber || isInvalidString) {\n throw new Error(\n `Invalid scalar enum variant. Expected one of [${stringValues.join(\", \")}] or a number between ${minRange} and ${maxRange}, got \"${value}\".`\n );\n }\n if (typeof value === \"number\")\n return prefix.encode(value);\n const valueIndex = enumValues.indexOf(value);\n if (valueIndex >= 0)\n return prefix.encode(valueIndex);\n return prefix.encode(enumKeys.indexOf(value));\n },\n fixedSize,\n maxSize\n };\n}\nfunction getScalarEnumDecoder(constructor, options = {}) {\n const prefix = options.size ?? getU8Decoder();\n const { description, fixedSize, maxSize, minRange, maxRange, isNumericEnum, enumValues } = scalarEnumCoderHelper(\n constructor,\n prefix,\n options.description\n );\n return {\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"enum\", bytes, offset);\n const [value, newOffset] = prefix.decode(bytes, offset);\n const valueAsNumber = Number(value);\n offset = newOffset;\n if (valueAsNumber < minRange || valueAsNumber > maxRange) {\n throw new Error(\n `Enum discriminator out of range. Expected a number between ${minRange} and ${maxRange}, got ${valueAsNumber}.`\n );\n }\n return [isNumericEnum ? valueAsNumber : enumValues[valueAsNumber], offset];\n },\n description,\n fixedSize,\n maxSize\n };\n}\nfunction getScalarEnumCodec(constructor, options = {}) {\n return combineCodec(getScalarEnumEncoder(constructor, options), getScalarEnumDecoder(constructor, options));\n}\nfunction setCodecHelper(item, size, description) {\n if (size === \"remainder\" && item.fixedSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n return {\n description: description ?? `set(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize])\n };\n}\nfunction getSetEncoder(item, options = {}) {\n const size = options.size ?? getU32Encoder();\n return {\n ...setCodecHelper(item, size, options.description),\n encode: (set) => {\n if (typeof size === \"number\" && set.size !== size) {\n assertValidNumberOfItemsForCodec(\"set\", size, set.size);\n }\n const itemBytes = Array.from(set, (value) => item.encode(value));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, set.size), ...itemBytes]);\n }\n };\n}\nfunction getSetDecoder(item, options = {}) {\n const size = options.size ?? getU32Decoder();\n return {\n ...setCodecHelper(item, size, options.description),\n decode: (bytes, offset = 0) => {\n const set = /* @__PURE__ */ new Set();\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [set, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset2] = item.decode(bytes, offset);\n offset = newOffset2;\n set.add(value);\n }\n return [set, offset];\n }\n };\n}\nfunction getSetCodec(item, options = {}) {\n return combineCodec(getSetEncoder(item, options), getSetDecoder(item, options));\n}\nfunction structCodecHelper(fields, description) {\n const fieldDescriptions = fields.map(([name, codec]) => `${String(name)}: ${codec.description}`).join(\", \");\n return {\n description: description ?? `struct(${fieldDescriptions})`,\n fixedSize: sumCodecSizes(fields.map(([, field]) => field.fixedSize)),\n maxSize: sumCodecSizes(fields.map(([, field]) => field.maxSize))\n };\n}\nfunction getStructEncoder(fields, options = {}) {\n return {\n ...structCodecHelper(fields, options.description),\n encode: (struct) => {\n const fieldBytes = fields.map(([key, codec]) => codec.encode(struct[key]));\n return mergeBytes(fieldBytes);\n }\n };\n}\nfunction getStructDecoder(fields, options = {}) {\n return {\n ...structCodecHelper(fields, options.description),\n decode: (bytes, offset = 0) => {\n const struct = {};\n fields.forEach(([key, codec]) => {\n const [value, newOffset] = codec.decode(bytes, offset);\n offset = newOffset;\n struct[key] = value;\n });\n return [struct, offset];\n }\n };\n}\nfunction getStructCodec(fields, options = {}) {\n return combineCodec(getStructEncoder(fields, options), getStructDecoder(fields, options));\n}\nfunction tupleCodecHelper(items, description) {\n const itemDescriptions = items.map((item) => item.description).join(\", \");\n return {\n description: description ?? `tuple(${itemDescriptions})`,\n fixedSize: sumCodecSizes(items.map((item) => item.fixedSize)),\n maxSize: sumCodecSizes(items.map((item) => item.maxSize))\n };\n}\nfunction getTupleEncoder(items, options = {}) {\n return {\n ...tupleCodecHelper(items, options.description),\n encode: (value) => {\n assertValidNumberOfItemsForCodec(\"tuple\", items.length, value.length);\n return mergeBytes(items.map((item, index) => item.encode(value[index])));\n }\n };\n}\nfunction getTupleDecoder(items, options = {}) {\n return {\n ...tupleCodecHelper(items, options.description),\n decode: (bytes, offset = 0) => {\n const values = [];\n items.forEach((codec) => {\n const [newValue, newOffset] = codec.decode(bytes, offset);\n values.push(newValue);\n offset = newOffset;\n });\n return [values, offset];\n }\n };\n}\nfunction getTupleCodec(items, options = {}) {\n return combineCodec(\n getTupleEncoder(items, options),\n getTupleDecoder(items, options)\n );\n}\nfunction getUnitEncoder(options = {}) {\n return {\n description: options.description ?? \"unit\",\n encode: () => new Uint8Array(),\n fixedSize: 0,\n maxSize: 0\n };\n}\nfunction getUnitDecoder(options = {}) {\n return {\n decode: (_bytes, offset = 0) => [void 0, offset],\n description: options.description ?? \"unit\",\n fixedSize: 0,\n maxSize: 0\n };\n}\nfunction getUnitCodec(options = {}) {\n return combineCodec(getUnitEncoder(options), getUnitDecoder(options));\n}\n\nexport { assertValidNumberOfItemsForCodec, decodeArrayLikeCodecSize, getArrayCodec, getArrayDecoder, getArrayEncoder, getArrayLikeCodecSizeDescription, getArrayLikeCodecSizeFromChildren, getArrayLikeCodecSizePrefix, getBitArrayCodec, getBitArrayDecoder, getBitArrayEncoder, getBooleanCodec, getBooleanDecoder, getBooleanEncoder, getBytesCodec, getBytesDecoder, getBytesEncoder, getDataEnumCodec, getDataEnumDecoder, getDataEnumEncoder, getMapCodec, getMapDecoder, getMapEncoder, getNullableCodec, getNullableDecoder, getNullableEncoder, getScalarEnumCodec, getScalarEnumDecoder, getScalarEnumEncoder, getSetCodec, getSetDecoder, getSetEncoder, getStructCodec, getStructDecoder, getStructEncoder, getTupleCodec, getTupleDecoder, getTupleEncoder, getUnitCodec, getUnitDecoder, getUnitEncoder };\n","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 { 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","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","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 {\n array,\n base58,\n mapSerializer,\n Serializer,\n shortU16,\n string,\n struct,\n StructToSerializerTuple,\n} from '@metaplex-foundation/umi-serializers';\nimport { getAddressCodec } from '@solana/addresses';\nimport { Codec } from '@solana/codecs-core';\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\n// Temporary, convert a codec to a serializer for compatiblity for now\nfunction toSerializer<T>(codec: Codec<T>): Serializer<T> {\n return {\n description: codec.description,\n deserialize: codec.decode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n serialize: codec.encode,\n };\n}\n\nfunction getPreludeStructSerializerTuple(): StructToSerializerTuple<CompiledMessage, CompiledMessage> {\n return [\n ['version', toSerializer(getTransactionVersionCodec())],\n ['header', toSerializer(getMessageHeaderCodec())],\n [\n 'staticAccounts',\n array(toSerializer(getAddressCodec()), {\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, 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 { 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 { base58 } from '@metaplex-foundation/umi-serializers';\nimport { Base58EncodedAddress, getAddressFromPublicKey } from '@solana/addresses';\nimport { Ed25519Signature, signBytes } from '@solana/keys';\n\nimport { ITransactionWithFeePayer } from './fee-payer';\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\nexport type TransactionSignature = string & { readonly __brand: unique symbol };\n\nexport function assertIsTransactionSignature(\n putativeTransactionSignature: string\n): asserts putativeTransactionSignature is TransactionSignature {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeTransactionSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeTransactionSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeTransactionSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeTransactionSignature}\\` is not a transaction signature`, {\n cause: e,\n });\n }\n}\n\nexport function isTransactionSignature(\n putativeTransactionSignature: string\n): putativeTransactionSignature is TransactionSignature {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeTransactionSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeTransactionSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeTransactionSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\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 function getSignatureFromTransaction(\n transaction: ITransactionWithFeePayer & ITransactionWithSignatures\n): TransactionSignature {\n const signature = transaction.signatures[transaction.feePayer];\n if (!signature) {\n // TODO: Coded error.\n throw new Error(\n \"Could not determine this transaction's signature. Make sure that the transaction \" +\n 'has been signed by its fee payer.'\n );\n }\n return signature as unknown as TransactionSignature;\n}\n\nexport async function signTransaction<TTransaction extends Parameters<typeof compileMessage>[0]>(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Promise<TTransaction & ITransactionWithSignatures> {\n const compiledMessage = compileMessage(transaction);\n const nextSignatures: Record<Base58EncodedAddress, Ed25519Signature> =\n 'signatures' in transaction ? { ...transaction.signatures } : {};\n const publicKeySignaturePairs = await Promise.all(\n keyPairs.map(keyPair =>\n Promise.all([\n getAddressFromPublicKey(keyPair.publicKey),\n getCompiledMessageSignature(compiledMessage, keyPair.privateKey),\n ])\n )\n );\n for (const [signerPublicKey, signature] of publicKeySignaturePairs) {\n nextSignatures[signerPublicKey] = signature;\n }\n const out = {\n ...transaction,\n signatures: nextSignatures,\n };\n Object.freeze(out);\n return out;\n}\n\nexport function transactionSignature(putativeTransactionSignature: string): TransactionSignature {\n assertIsTransactionSignature(putativeTransactionSignature);\n return putativeTransactionSignature;\n}\n","import { getTransactionEncoder } from './serializers/transaction';\n\nexport type Base64EncodedWireTransaction = string & {\n readonly __brand: unique symbol;\n};\n\nexport function getBase64EncodedWireTransaction(\n transaction: Parameters<ReturnType<typeof getTransactionEncoder>['serialize']>[0]\n): Base64EncodedWireTransaction {\n const wireTransactionBytes = getTransactionEncoder().serialize(transaction);\n if (__NODEJS__) {\n return Buffer.from(wireTransactionBytes).toString('base64') as Base64EncodedWireTransaction;\n } else {\n return (btoa as Window['btoa'])(String.fromCharCode(...wireTransactionBytes)) as Base64EncodedWireTransaction;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/fixSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/src/mapSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/baseX.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/base58.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/nullCharacters.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/src/utf8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/common.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u32.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/src/shortU16.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/sumSerializerSizes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/array.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/string.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/src/struct.ts","../src/unsigned-transaction.ts","../src/blockhash.ts","../src/create-transaction.ts","../../instructions/src/roles.ts","../src/durable-nonce.ts","../src/fee-payer.ts","../src/instructions.ts","../../codecs-core/src/assertions.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/combine-codec.ts","../../codecs-core/src/fix-codec.ts","../../codecs-core/src/map-codec.ts","../../codecs-numbers/src/assertions.ts","../../codecs-numbers/src/f32.ts","../../codecs-numbers/src/utils.ts","../../codecs-numbers/src/u128.ts","../../codecs-numbers/src/u16.ts","../../codecs-numbers/src/u32.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/base64.ts","../../codecs-strings/src/null-characters.ts","../../codecs-strings/src/string.ts","../../codecs-strings/src/utf8.ts","../../text-encoding-impl/src/index.browser.ts","../../assertions/src/subtle-crypto.ts","../../addresses/src/address.ts","../../addresses/src/program-derived-address.ts","../../addresses/src/public-key.ts","../src/accounts.ts","../src/compile-address-table-lookups.ts","../src/compile-header.ts","../src/compile-instructions.ts","../src/compile-lifetime-token.ts","../src/compile-static-accounts.ts","../src/message.ts","../src/compile-transaction.ts","../src/serializers/address-table-lookup.ts","../../codecs-data-structures/src/utils.ts","../../codecs-data-structures/src/scalar-enum.ts","../../codecs-data-structures/src/set.ts","../src/serializers/header.ts","../src/serializers/instruction.ts","../src/serializers/transaction-version.ts","../src/serializers/unimplemented.ts","../src/serializers/message.ts","../src/serializers/transaction.ts","../../keys/src/signatures.ts","../src/signatures.ts","../src/wire-transaction.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","e","AccountRole","combineCodec","address","getU32Decoder","getU32Encoder","BASE_CONFIG"],"mappings":";;;;;;;;AAIaA,IAAAA,aAAcC,cAAuC;AAChE,QAAMC,cAAcD,SAASE,OAAO,CAACC,OAAOC,QAAQD,QAAQC,IAAIC,QAAQ,CAAC;AACzE,QAAMC,SAAS,IAAIC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;AAEA,eAAsB,gBAClB,UACA,aACkD;AAClD,QAAM,kBAAkB,eAAe,WAAW;AAClD,QAAM,iBACF,gBAAgB,cAAc,EAAE,GAAG,YAAY,WAAW,IAAI,CAAC;AACnE,QAAM,0BAA0B,MAAM,QAAQ;AAAA,IAC1C,SAAS;AAAA,MAAI,aACT,QAAQ,IAAI;AAAA,QACR,wBAAwB,QAAQ,SAAS;AAAA,QACzC,4BAA4B,iBAAiB,QAAQ,UAAU;AAAA,MACnE,CAAC;AAAA,IACL;AAAA,EACJ;AACA,aAAW,CAAC,iBAAiB,SAAS,KAAK,yBAAyB;AAChE,mBAAe,eAAe,IAAI;AAAA,EACtC;AACA,QAAM,MAAM;AAAA,IACR,GAAG;AAAA,IACH,YAAY;AAAA,EAChB;AACA,SAAO,OAAO,GAAG;AACjB,SAAO;AACX;AAEO,SAAS,qBAAqB,8BAA4D;AAC7F,+BAA6B,4BAA4B;AACzD,SAAO;AACX;;;AC3GO,SAAS,gCACZ,aAC4B;AAC5B,QAAM,uBAAuB,sBAAsB,EAAE,UAAU,WAAW;AAC1E,MAAI,OAAY;AACZ,WAAO,OAAO,KAAK,oBAAoB,EAAE,SAAS,QAAQ;AAAA,EAC9D,OAAO;AACH,WAAQ,KAAwB,OAAO,aAAa,GAAG,oBAAoB,CAAC;AAAA,EAChF;AACJ","sourcesContent":["/**\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","/** @category Errors */\nexport class InvalidBaseStringError extends Error {\n readonly name: string = 'InvalidBaseStringError';\n\n readonly cause?: Error;\n\n constructor(value: string, base: number, cause?: Error) {\n const message = `Expected a string of base ${base}, got [${value}].`;\n super(message);\n this.cause = cause;\n }\n}\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { InvalidBaseStringError } from './errors';\n\n/**\n * A string serializer that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create serializers such as base10 or base58.\n *\n * @category Serializers\n */\nexport const baseX = (alphabet: string): Serializer<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n serialize(value: string): Uint8Array {\n // Check if the value is valid.\n if (!value.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new InvalidBaseStringError(value, base);\n }\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex((c) => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n deserialize(buffer, offset = 0): [string, number] {\n if (buffer.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n const bytes = buffer.slice(offset);\n let trailIndex = bytes.findIndex((n) => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, buffer.length];\n\n // From bytes to base10.\n let base10Number = bytes\n .slice(trailIndex)\n .reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), buffer.length];\n },\n };\n};\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { baseX } from './baseX';\n\n/**\n * A string serializer that uses base58 encoding.\n * @category Serializers\n */\nexport const base58: Serializer<string> = baseX(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n","/**\n * Removes null characters from a string.\n * @category Utils\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters at the end.\n * @category Utils\n */\nexport const padNullCharacters = (value: string, chars: number) =>\n value.padEnd(chars, '\\u0000');\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { removeNullCharacters } from './nullCharacters';\n\n/**\n * A string serializer that uses UTF-8 encoding\n * using the native `TextEncoder` API.\n * @category Serializers\n */\nexport const utf8: Serializer<string> = {\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n serialize(value: string) {\n return new TextEncoder().encode(value);\n },\n deserialize(buffer, offset = 0) {\n const value = new TextDecoder().decode(buffer.slice(offset));\n return [removeNullCharacters(value), buffer.length];\n },\n};\n","import {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\n\n/**\n * Defines a serializer for numbers and bigints.\n * @category Serializers\n */\nexport type NumberSerializer =\n | Serializer<number>\n | Serializer<number | bigint, bigint>;\n\n/**\n * Defines the options for u8 and i8 serializers.\n * @category Serializers\n */\nexport type SingleByteNumberSerializerOptions = BaseSerializerOptions;\n\n/**\n * Defines the options for number serializers that use more than one byte.\n * @category Serializers\n */\nexport type NumberSerializerOptions = BaseSerializerOptions & {\n /**\n * Whether the serializer should use little-endian or big-endian encoding.\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the endianness of a number serializer.\n * @category Serializers\n */\nexport enum Endian {\n Little = 'le',\n Big = 'be',\n}\n","/** @category Errors */\nexport class NumberOutOfRangeError extends RangeError {\n readonly name: string = 'NumberOutOfRangeError';\n\n constructor(\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n actual: number | bigint\n ) {\n super(\n `Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`\n );\n }\n}\n","import {\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport {\n Endian,\n NumberSerializer,\n NumberSerializerOptions,\n SingleByteNumberSerializerOptions,\n} from './common';\nimport { NumberOutOfRangeError } from './errors';\n\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number | bigint, bigint>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number | bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): NumberSerializer {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian =\n !('endian' in input.options) || input.options.endian === Endian.Little;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n maxSize: input.size,\n serialize(value: number | bigint): Uint8Array {\n if (input.range) {\n assertRange(input.name, input.range[0], input.range[1], value);\n }\n const buffer = new ArrayBuffer(input.size);\n input.set(new DataView(buffer), value, littleEndian);\n return new Uint8Array(buffer);\n },\n deserialize(bytes, offset = 0): [number | bigint, number] {\n const slice = bytes.slice(offset, offset + input.size);\n assertEnoughBytes('i8', slice, input.size);\n const view = toDataView(slice);\n return [input.get(view, littleEndian), offset + input.size];\n },\n } as NumberSerializer;\n}\n\n/**\n * Helper function to ensure that the array buffer is converted properly from a uint8array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n * @param {Uint8Array} array Uint8array that's being converted into an array buffer\n * @returns {ArrayBuffer} An array buffer that's necessary to construct a data view\n */\nexport const toArrayBuffer = (array: Uint8Array): ArrayBuffer =>\n array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);\n\nexport const toDataView = (array: Uint8Array): DataView =>\n new DataView(toArrayBuffer(array));\n\nexport const assertRange = (\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) => {\n if (value < min || value > max) {\n throw new NumberOutOfRangeError(serializer, min, max, value);\n }\n};\n\nexport const assertEnoughBytes = (\n serializer: string,\n bytes: Uint8Array,\n expected: number\n) => {\n if (bytes.length === 0) {\n throw new DeserializingEmptyBufferError(serializer);\n }\n if (bytes.length < expected) {\n throw new NotEnoughBytesError(serializer, expected, bytes.length);\n }\n};\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { SingleByteNumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u8 = (\n options: SingleByteNumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u8',\n size: 1,\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n get: (view) => view.getUint8(0),\n options,\n });\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u32 = (\n options: NumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u32',\n size: 4,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n get: (view, le) => view.getUint32(0, le),\n options,\n });\n","/* eslint-disable no-bitwise */\nimport {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { assertRange } from './utils';\n\n/**\n * Defines the options for the shortU16 serializer.\n * @category Serializers\n */\nexport type ShortU16SerializerOptions = BaseSerializerOptions;\n\n/**\n * Same as u16, but serialized with 1 to 3 bytes.\n *\n * If the value is above 0x7f, the top bit is set and the remaining\n * value is stored in the next bytes. Each byte follows the same\n * pattern until the 3rd byte. The 3rd byte, if needed, uses\n * all 8 bits to store the last byte of the original value.\n *\n * @category Serializers\n */\nexport const shortU16 = (\n options: ShortU16SerializerOptions = {}\n): Serializer<number> => ({\n description: options.description ?? 'shortU16',\n fixedSize: null,\n maxSize: 3,\n serialize: (value: number): Uint8Array => {\n assertRange('shortU16', 0, 65535, value);\n const bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = value >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n bytes[ii - 1] |= 0b10000000;\n }\n }\n return new Uint8Array(bytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0): [number, number] => {\n let value = 0;\n let byteCount = 0;\n while (\n ++byteCount // eslint-disable-line no-plusplus\n ) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n});\n","/** @category Errors */\nexport class InvalidNumberOfItemsError extends Error {\n readonly name = 'InvalidNumberOfItemsError';\n\n constructor(\n serializer: string,\n expected: number | bigint,\n actual: number | bigint\n ) {\n super(`Expected [${serializer}] to have ${expected} items, got ${actual}.`);\n }\n}\n\n/** @category Errors */\nexport class InvalidArrayLikeRemainderSizeError extends Error {\n readonly name = 'InvalidArrayLikeRemainderSizeError';\n\n constructor(remainderSize: number | bigint, itemSize: number | bigint) {\n super(\n `The remainder of the buffer (${remainderSize} bytes) cannot be split into chunks of ${itemSize} bytes. ` +\n `Serializers of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainderSize} modulo ${itemSize} should be equal to zero.`\n );\n }\n}\n\n/** @category Errors */\nexport class UnrecognizedArrayLikeSerializerSizeError extends Error {\n readonly name = 'UnrecognizedArrayLikeSerializerSizeError';\n\n constructor(size: never) {\n super(`Unrecognized array-like serializer size: ${JSON.stringify(size)}`);\n }\n}\n\n/** @category Errors */\nexport class InvalidDataEnumVariantError extends Error {\n readonly name = 'InvalidDataEnumVariantError';\n\n constructor(invalidVariant: string, validVariants: string[]) {\n super(\n `Invalid data enum variant. ` +\n `Expected one of [${validVariants.join(', ')}], ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class InvalidScalarEnumVariantError extends Error {\n readonly name = 'InvalidScalarEnumVariantError';\n\n constructor(\n invalidVariant: string | number | bigint,\n validVariants: string[],\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Invalid scalar enum variant. ` +\n `Expected one of [${validVariants.join(', ')}] ` +\n `or a number between ${min} and ${max}, ` +\n `got \"${invalidVariant}\".`\n );\n }\n}\n\n/** @category Errors */\nexport class EnumDiscriminatorOutOfRangeError extends RangeError {\n readonly name = 'EnumDiscriminatorOutOfRangeError';\n\n constructor(\n discriminator: number | bigint,\n min: number | bigint,\n max: number | bigint\n ) {\n super(\n `Enum discriminator out of range. ` +\n `Expected a number between ${min} and ${max}, got ${discriminator}.`\n );\n }\n}\n","export function sumSerializerSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : all + size),\n 0 as number | null\n );\n}\n","import { ExpectedFixedSizeSerializerError } from '@metaplex-foundation/umi-serializers-core';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport {\n InvalidArrayLikeRemainderSizeError,\n UnrecognizedArrayLikeSerializerSizeError,\n} from './errors';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\nexport function getResolvedSize(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: number\n): [number | bigint, number] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.deserialize(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumSerializerSizes(childrenSizes);\n if (childrenSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n throw new InvalidArrayLikeRemainderSizeError(remainder, childrenSize);\n }\n return [remainder / childrenSize, offset];\n }\n\n throw new UnrecognizedArrayLikeSerializerSizeError(size);\n}\n\nexport function getSizeDescription(\n size: ArrayLikeSerializerSize | string\n): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getSizeFromChildren(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumSerializerSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getSizePrefix(\n size: ArrayLikeSerializerSize,\n realSize: number\n): Uint8Array {\n return typeof size === 'object' ? size.serialize(realSize) : new Uint8Array();\n}\n","import {\n BaseSerializerOptions,\n ExpectedFixedSizeSerializerError,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { u32 } from '@metaplex-foundation/umi-serializers-numbers';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport { InvalidNumberOfItemsError } from './errors';\nimport {\n getResolvedSize,\n getSizeDescription,\n getSizeFromChildren,\n getSizePrefix,\n} from './utils';\n\n/**\n * Defines the options for array serializers.\n * @category Serializers\n */\nexport type ArraySerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the array.\n * @defaultValue `u32()`\n */\n size?: ArrayLikeSerializerSize;\n};\n\n/**\n * Creates a serializer for an array of items.\n *\n * @param item - The serializer to use for the array's items.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function array<T, U extends T = T>(\n item: Serializer<T, U>,\n options: ArraySerializerOptions = {}\n): Serializer<T[], U[]> {\n const size = options.size ?? u32();\n if (size === 'remainder' && item.fixedSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n return {\n description:\n options.description ??\n `array(${item.description}; ${getSizeDescription(size)})`,\n fixedSize: getSizeFromChildren(size, [item.fixedSize]),\n maxSize: getSizeFromChildren(size, [item.maxSize]),\n serialize: (value: T[]) => {\n if (typeof size === 'number' && value.length !== size) {\n throw new InvalidNumberOfItemsError('array', size, value.length);\n }\n return mergeBytes([\n getSizePrefix(size, value.length),\n ...value.map((v) => item.serialize(v)),\n ]);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = getResolvedSize(\n size,\n [item.fixedSize],\n bytes,\n offset\n );\n offset = newOffset;\n const values: U[] = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.deserialize(bytes, offset);\n values.push(value);\n offset = newOffset;\n }\n return [values, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializer } from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for bytes serializers.\n * @category Serializers\n */\nexport type BytesSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the buffer. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the buffer with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `'variable'`\n */\n size?: NumberSerializer | number | 'variable';\n};\n\n/**\n * Creates a serializer that passes the buffer as-is.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function bytes(\n options: BytesSerializerOptions = {}\n): Serializer<Uint8Array> {\n const size = options.size ?? 'variable';\n const description =\n options.description ?? `bytes(${getSizeDescription(size)})`;\n\n const byteSerializer: Serializer<Uint8Array> = {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => new Uint8Array(value),\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n };\n\n if (size === 'variable') {\n return byteSerializer;\n }\n\n if (typeof size === 'number') {\n return fixSerializer(byteSerializer, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: Uint8Array) => {\n const contentBytes = byteSerializer.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('bytes');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('bytes', length, contentBuffer.length);\n }\n const [value, contentOffset] = byteSerializer.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { utf8 } from '@metaplex-foundation/umi-serializers-encodings';\nimport {\n NumberSerializer,\n u32,\n} from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for string serializers.\n * @category Serializers\n */\nexport type StringSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `u32()`\n */\n size?: NumberSerializer | number | 'variable';\n /**\n * The string serializer to use for encoding and decoding the content.\n * @defaultValue `utf8`\n */\n encoding?: Serializer<string>;\n};\n\n/**\n * Creates a string serializer.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function string(\n options: StringSerializerOptions = {}\n): Serializer<string> {\n const size = options.size ?? u32();\n const encoding = options.encoding ?? utf8;\n const description =\n options.description ??\n `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixSerializer(encoding, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: string) => {\n const contentBytes = encoding.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('string');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('string', length, contentBuffer.length);\n }\n const [value, contentOffset] = encoding.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import {\n BaseSerializerOptions,\n Serializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\n/**\n * Get the name and serializer of each field in a struct.\n * @category Serializers\n */\nexport type StructToSerializerTuple<T extends object, U extends T> = Array<\n {\n [K in keyof T]: [K, Serializer<T[K], U[K]>];\n }[keyof T]\n>;\n\n/**\n * Defines the options for struct serializers.\n * @category Serializers\n */\nexport type StructSerializerOptions = BaseSerializerOptions;\n\n/**\n * Creates a serializer for a custom object.\n *\n * @param fields - The name and serializer of each field.\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function struct<T extends object, U extends T = T>(\n fields: StructToSerializerTuple<T, U>,\n options: StructSerializerOptions = {}\n): Serializer<T, U> {\n const fieldDescriptions = fields\n .map(([name, serializer]) => `${String(name)}: ${serializer.description}`)\n .join(', ');\n return {\n description: options.description ?? `struct(${fieldDescriptions})`,\n fixedSize: sumSerializerSizes(fields.map(([, field]) => field.fixedSize)),\n maxSize: sumSerializerSizes(fields.map(([, field]) => field.maxSize)),\n serialize: (struct: T) => {\n const fieldBytes = fields.map(([key, serializer]) =>\n serializer.serialize(struct[key])\n );\n return mergeBytes(fieldBytes);\n },\n deserialize: (bytes: Uint8Array, offset = 0) => {\n const struct: Partial<U> = {};\n fields.forEach(([key, serializer]) => {\n const [value, newOffset] = serializer.deserialize(bytes, offset);\n offset = newOffset;\n struct[key] = value;\n });\n return [struct as U, offset];\n },\n };\n}\n","import { ITransactionWithSignatures } from '.';\nimport { BaseTransaction } from './types';\n\nexport function getUnsignedTransaction<TTransaction extends BaseTransaction>(\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction & ITransactionWithSignatures, keyof ITransactionWithSignatures> {\n if ('signatures' in transaction) {\n // The implication of the lifetime constraint changing is that any existing signatures are invalid.\n const {\n signatures: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n","import { base58 } from '@metaplex-foundation/umi-serializers';\n\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport type Blockhash = string & { readonly __brand: unique symbol };\n\ntype BlockhashLifetimeConstraint = Readonly<{\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n}>;\n\nexport interface ITransactionWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 ||\n // Highest value (32 bytes of 255)\n putativeBlockhash.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeBlockhash);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBlockhash}\\` is not a blockhash`, {\n cause: e,\n });\n }\n}\n\nexport function setTransactionLifetimeUsingBlockhash<TTransaction extends BaseTransaction & IDurableNonceTransaction>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures | 'lifetimeConstraint'> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash<\n TTransaction extends BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n) {\n if (\n 'lifetimeConstraint' in transaction &&\n transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n lifetimeConstraint: blockhashLifetimeConstraint,\n };\n Object.freeze(out);\n return out;\n}\n","import { Transaction, TransactionVersion } from './types';\n\ntype TransactionConfig<TVersion extends TransactionVersion> = Readonly<{\n version: TVersion;\n}>;\n\nexport function createTransaction<TVersion extends TransactionVersion>(\n config: TransactionConfig<TVersion>\n): Extract<Transaction, { version: TVersion }>;\nexport function createTransaction<TVersion extends TransactionVersion>({\n version,\n}: TransactionConfig<TVersion>): Transaction {\n const out: Transaction = {\n instructions: [],\n version,\n };\n Object.freeze(out);\n return out;\n}\n","/**\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 { Base58EncodedAddress } from '@solana/addresses';\nimport { AccountRole, IInstruction, IInstructionWithAccounts, IInstructionWithData } from '@solana/instructions';\nimport { ReadonlyAccount, ReadonlySignerAccount, WritableAccount } from '@solana/instructions/dist/types/accounts';\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>\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): Omit<TTransaction, keyof ITransactionWithSignatures> &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue> {\n const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction);\n if (\n isAlreadyDurableNonceTransaction &&\n transaction.lifetimeConstraint.nonce === nonce &&\n transaction.instructions[0].accounts[0].address === nonceAccountAddress &&\n transaction.instructions[0].accounts[2].address === nonceAuthorityAddress\n ) {\n return transaction as TTransaction &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...(isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions),\n ],\n lifetimeConstraint: {\n nonce,\n },\n } as TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport interface ITransactionWithFeePayer<TAddress extends string = string> {\n readonly feePayer: Base58EncodedAddress<TAddress>;\n}\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction: TTransaction | (TTransaction & ITransactionWithFeePayer<string>)\n): TTransaction & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | TTransaction\n | (TTransaction & ITransactionWithFeePayer<string>)\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n) {\n if ('feePayer' in transaction && feePayer === transaction.feePayer) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n feePayer,\n };\n Object.freeze(out);\n return out;\n}\n","import { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport function appendTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [...transaction.instructions, instruction],\n };\n Object.freeze(out);\n return out;\n}\n\nexport function prependTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [instruction, ...transaction.instructions],\n };\n Object.freeze(out);\n return out;\n}\n","import { CodecData } from './codec';\n\n/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n\n/**\n * Asserts that a given codec is fixed-size codec.\n */\nexport function assertFixedSizeCodec(\n data: Pick<CodecData, 'fixedSize'>,\n message?: string\n): asserts data is { fixedSize: number } {\n if (data.fixedSize === null) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<From, To extends From = From>(\n encoder: Encoder<From>,\n decoder: Decoder<To>,\n description?: string\n): Codec<From, To> {\n if (encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`\n );\n }\n\n if (encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`\n );\n }\n\n if (description === undefined && encoder.description !== decoder.description) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. ` +\n `Pass a custom description as a third argument if you want to override the description and bypass this error.`\n );\n }\n\n return {\n decode: decoder.decode,\n description: description ?? encoder.description,\n encode: encoder.encode,\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport { Codec, CodecData, Decoder, Encoder } from './codec';\nimport { combineCodec } from './combine-codec';\n\nfunction fixCodecHelper(data: CodecData, fixedBytes: number, description?: string): CodecData {\n return {\n description: description ?? `fixed(${fixedBytes}, ${data.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n };\n}\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @param description - A custom description for the encoder.\n */\nexport function fixEncoder<T>(encoder: Encoder<T>, fixedBytes: number, description?: string): Encoder<T> {\n return {\n ...fixCodecHelper(encoder, fixedBytes, description),\n encode: (value: T) => fixBytes(encoder.encode(value), fixedBytes),\n };\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the decoder.\n */\nexport function fixDecoder<T>(decoder: Decoder<T>, fixedBytes: number, description?: string): Decoder<T> {\n return {\n ...fixCodecHelper(decoder, fixedBytes, description),\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (decoder.fixedSize !== null) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.decode(bytes, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @param description - A custom description for the codec.\n */\nexport function fixCodec<T, U extends T = T>(\n codec: Codec<T, U>,\n fixedBytes: number,\n description?: string\n): Codec<T, U> {\n return combineCodec(fixEncoder(codec, fixedBytes, description), fixDecoder(codec, fixedBytes, description));\n}\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<T, U>(encoder: Encoder<T>, unmap: (value: U) => T): Encoder<U> {\n return {\n description: encoder.description,\n encode: (value: U) => encoder.encode(unmap(value)),\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<T, U>(\n decoder: Decoder<T>,\n map: (value: T, bytes: Uint8Array, offset: number) => U\n): Decoder<U> {\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n const [value, length] = decoder.decode(bytes, offset);\n return [map(value, bytes, offset), length];\n },\n description: decoder.description,\n fixedSize: decoder.fixedSize,\n maxSize: decoder.maxSize,\n };\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<NewFrom, OldFrom, To extends NewFrom & OldFrom>(\n codec: Codec<OldFrom, To>,\n unmap: (value: NewFrom) => OldFrom\n): Codec<NewFrom, To>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map?: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo> {\n return {\n decode: map ? mapDecoder(codec, map).decode : (codec.decode as unknown as Decoder<NewTo>['decode']),\n description: codec.description,\n encode: mapEncoder(codec, unmap).encode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n };\n}\n","/**\n * Asserts that a given number is between a given range.\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) {\n if (value < min || value > max) {\n // TODO: Coded error.\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`\n );\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'f32',\n options,\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n options,\n size: 4,\n });\n\nexport const getF32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getF32Encoder(options), getF32Decoder(options));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n CodecData,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecOptions, SingleByteNumberCodecOptions } from './common';\n\ntype NumberFactorySharedInput = {\n name: string;\n size: number;\n options: SingleByteNumberCodecOptions | NumberCodecOptions;\n};\n\ntype NumberFactoryEncoderInput<T> = NumberFactorySharedInput & {\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: T, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput<T> = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => T;\n};\n\nfunction sharedNumberFactory(input: NumberFactorySharedInput): CodecData & { littleEndian: boolean | undefined } {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian = !('endian' in input.options) || input.options.endian === Endian.LITTLE;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n littleEndian,\n maxSize: input.size,\n };\n}\n\nexport function numberEncoderFactory<T extends number | bigint>(input: NumberFactoryEncoderInput<T>): Encoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n description: codecData.description,\n encode(value: T): Uint8Array {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, codecData.littleEndian);\n return new Uint8Array(arrayBuffer);\n },\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\nexport function numberDecoderFactory<T extends number | bigint>(input: NumberFactoryDecoderInput<T>): Decoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n decode(bytes, offset = 0): [T, number] {\n assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, codecData.littleEndian), offset + input.size];\n },\n description: codecData.description,\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\n/**\n * Helper function to ensure that the ArrayBuffer is converted properly from a Uint8Array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nfunction toArrayBuffer(bytes: Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (options: NumberCodecOptions = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n name: 'u128',\n options,\n range: [0, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\nexport const getU128Decoder = (options: NumberCodecOptions = {}): Decoder<bigint> =>\n numberDecoderFactory({\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n options,\n size: 16,\n });\n\nexport const getU128Codec = (options: NumberCodecOptions = {}): Codec<number | bigint, bigint> =>\n combineCodec(getU128Encoder(options), getU128Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u16',\n options,\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, value, le),\n size: 2,\n });\n\nexport const getU16Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n options,\n size: 2,\n });\n\nexport const getU16Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU16Encoder(options), getU16Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u32',\n options,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, value, le),\n size: 4,\n });\n\nexport const getU32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n options,\n size: 4,\n });\n\nexport const getU32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU32Encoder(options), getU32Decoder(options));\n","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXEncoder = (alphabet: string): Encoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n encode(value: string): Uint8Array {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex(c => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * Decodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXDecoder = (alphabet: string): Decoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n decode(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), rawBytes.length];\n },\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * A string codec that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create codecs such as base10 or base58.\n */\nexport const getBaseXCodec = (alphabet: string): Codec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): Encoder<string> => ({\n description: 'base16',\n encode(value: string) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString('0123456789abcdef', lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n return Uint8Array.from(matches ? matches.map((byte: string) => parseInt(byte, 16)) : []);\n },\n fixedSize: null,\n maxSize: null,\n});\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): Decoder<string> => ({\n decode(bytes, offset = 0) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n description: 'base16',\n fixedSize: null,\n maxSize: null,\n});\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): Codec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Encodes strings in base64. */\nexport const getBase64Encoder = (): Encoder<string> => {\n if (__BROWSER__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n try {\n const bytes = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n return new Uint8Array(bytes);\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n return new Uint8Array(Buffer.from(value, 'base64'));\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/** Decodes strings in base64. */\nexport const getBase64Decoder = (): Decoder<string> => {\n if (__BROWSER__) {\n return {\n decode(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n decode: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString('base64'), bytes.length],\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '=')\n );\n};\n\n/** Encodes and decodes strings in base64. */\nexport const getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());\n","/**Removes null characters from a string. */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/** Pads a string with null characters at the end. */\nexport const padNullCharacters = (value: string, chars: number) => value.padEnd(chars, '\\u0000');\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixDecoder,\n fixEncoder,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { getUtf8Decoder, getUtf8Encoder } from './utf8';\n\n/** Defines the options for string codecs. */\nexport type StringCodecOptions<\n TPrefix extends NumberCodec | NumberEncoder | NumberDecoder,\n TEncoding extends Codec<string> | Encoder<string> | Decoder<string>\n> = BaseCodecOptions & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberCodec} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the byte array.\n * @defaultValue u32 prefix.\n */\n size?: TPrefix | number | 'variable';\n\n /**\n * The codec to use for encoding and decoding the content.\n * @defaultValue UTF-8 encoding.\n */\n encoding?: TEncoding;\n};\n\n/** Encodes strings from a given encoding and size strategy. */\nexport const getStringEncoder = (options: StringCodecOptions<NumberEncoder, Encoder<string>> = {}): Encoder<string> => {\n const size = options.size ?? getU32Encoder();\n const encoding = options.encoding ?? getUtf8Encoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixEncoder(encoding, size, description);\n }\n\n return {\n description,\n encode: (value: string) => {\n const contentBytes = encoding.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes strings from a given encoding and size strategy. */\nexport const getStringDecoder = (options: StringCodecOptions<NumberDecoder, Decoder<string>> = {}): Decoder<string> => {\n const size = options.size ?? getU32Decoder();\n const encoding = options.encoding ?? getUtf8Decoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixDecoder(encoding, size, description);\n }\n\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('string', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec('string', length, contentBytes);\n const [value, contentOffset] = encoding.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n },\n description,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes strings from a given encoding and size strategy. */\nexport const getStringCodec = (options: StringCodecOptions<NumberCodec, Codec<string>> = {}): Codec<string> =>\n combineCodec(getStringEncoder(options), getStringDecoder(options));\n\nfunction getSizeDescription(size: CodecData | number | 'variable'): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from 'text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/** Encodes UTF-8 strings using the native `TextEncoder` API. */\nexport const getUtf8Encoder = (): Encoder<string> => {\n let textEncoder: TextEncoder;\n return {\n description: 'utf8',\n encode: (value: string) => new Uint8Array((textEncoder ||= new TextEncoder()).encode(value)),\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes UTF-8 strings using the native `TextDecoder` API. */\nexport const getUtf8Decoder = (): Decoder<string> => {\n let textDecoder: TextDecoder;\n return {\n decode(bytes, offset = 0) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes UTF-8 strings using the native `TextEncoder` and `TextDecoder` API. */\nexport const getUtf8Codec = (): Codec<string> => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapEncoder } from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\nexport function isAddress(\n putativeBase58EncodedAddress: string\n): putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function address<TAddress extends string = string>(\n putativeBase58EncodedAddress: TAddress\n): Base58EncodedAddress<TAddress> {\n assertIsAddress(putativeBase58EncodedAddress);\n return putativeBase58EncodedAddress as Base58EncodedAddress<TAddress>;\n}\n\nexport function getAddressEncoder(config?: Readonly<{ description: string }>): Encoder<Base58EncodedAddress> {\n return mapEncoder(\n getStringEncoder({\n description: config?.description ?? 'Base58EncodedAddress',\n encoding: getMemoizedBase58Encoder(),\n size: 32,\n }),\n putativeAddress => address(putativeAddress)\n );\n}\n\nexport function getAddressDecoder(config?: Readonly<{ description: string }>): Decoder<Base58EncodedAddress> {\n return getStringDecoder({\n description: config?.description ?? 'Base58EncodedAddress',\n encoding: getMemoizedBase58Decoder(),\n size: 32,\n }) as Decoder<Base58EncodedAddress>;\n}\n\nexport function getAddressCodec(config?: Readonly<{ description: string }>): Codec<Base58EncodedAddress> {\n return combineCodec(getAddressEncoder(config), getAddressDecoder(config));\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\nimport { assertIsAddress, Base58EncodedAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve';\n\n/**\n * An address derived from a program address and a set of seeds.\n * It includes the bump seed used to derive the address and\n * ensure the address is not on the Ed25519 curve.\n */\nexport type ProgramDerivedAddress<TAddress extends string = string> = Readonly<\n [Base58EncodedAddress<TAddress>, ProgramDerivedAddressBump]\n>;\n\n/**\n * A number between 0 and 255, inclusive.\n */\nexport type ProgramDerivedAddressBump = number & {\n readonly __brand: unique symbol;\n};\n\n/**\n * Returns true if the input value is a program derived address.\n */\nexport function isProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): value is ProgramDerivedAddress<TAddress> {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * Fails if the input value is not a program derived address.\n */\nexport function assertIsProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): asserts value is ProgramDerivedAddress<TAddress> {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n // TODO: Coded error.\n throw new Error(\n `Expected given program derived address to have the following format: [Base58EncodedAddress, ProgramDerivedAddressBump].`\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n // TODO: Coded error.\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Base58EncodedAddress;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Base58EncodedAddress;\n programAddress: Base58EncodedAddress;\n seed: Seed;\n}>;\n\ntype Seed = string | Uint8Array;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\n// TODO: Coded error.\nclass PointOnCurveError extends Error {}\n\nasync function createProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<Base58EncodedAddress> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n // TODO: Coded error.\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n // TODO: Coded error.\n throw new PointOnCurveError('Invalid seeds; point must fall off the Ed25519 curve');\n }\n return base58EncodedAddressCodec.decode(addressBytes)[0];\n}\n\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<ProgramDerivedAddress> {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n // TODO: Coded error.\n throw new Error('Unable to find a viable program address bump seed');\n}\n\nexport async function createAddressWithSeed({\n baseAddress,\n programAddress,\n seed,\n}: SeedInput): Promise<Base58EncodedAddress> {\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])\n ) {\n // TODO: Coded error.\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes)[0];\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Base58EncodedAddress, getAddressDecoder } from './address';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n","import { Base58EncodedAddress, getAddressComparator } from '@solana/addresses';\nimport {\n AccountRole,\n IAccountLookupMeta,\n IAccountMeta,\n IInstruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit<WritableSignerAccount, 'address'> & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit<ReadonlyAccountLookup | WritableAccountLookup, 'address'> & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = (IAccountMeta | IAccountLookupMeta)[] & { readonly __brand: unique symbol };\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Base58EncodedAddress,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry | Record<never, never>\n ) => AddressMap[Base58EncodedAddress]\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(\n feePayer: Base58EncodedAddress,\n instructions: readonly IInstruction[]\n): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set<Base58EncodedAddress>();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and set as the fee payer. Program addresses may not pay fees.'\n );\n default:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and marked writable. Program addresses may not be writable.'\n );\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType<typeof getAddressComparator>;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry as FeePayerAccountEntry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry as LookupTableAccountEntry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${account.address}\\`) which is both invoked and ` +\n 'marked writable. Program addresses may not be ' +\n 'writable.'\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType<typeof getAddressComparator>;\n const orderedAccounts: (IAccountMeta | IAccountLookupMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Base58EncodedAddress<typeof address>,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Base58EncodedAddress, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype AddressTableLookup = Readonly<{\n lookupTableAddress: Base58EncodedAddress;\n readableIndices: readonly number[];\n writableIndices: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Base58EncodedAddress,\n { readonly readableIndices: number[]; readonly writableIndices: number[] }\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readableIndices: [],\n writableIndices: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndices.push(account.addressIndex);\n } else {\n entry.readableIndices.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Base58EncodedAddress,\n ...index[lookupTableAddress as unknown as Base58EncodedAddress],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype MessageHeader = Readonly<{\n numReadonlyNonSignerAccounts: number;\n numReadonlySignerAccounts: number;\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\nimport { IInstruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n accountIndices?: number[];\n data?: Uint8Array;\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record<Base58EncodedAddress, number> = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly IInstruction[],\n orderedAccounts: OrderedAccounts\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { IDurableNonceTransaction, ITransactionWithBlockhashLifetime } from './index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (ITransactionWithBlockhashLifetime | IDurableNonceTransaction)['lifetimeConstraint']\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Base58EncodedAddress[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { ITransactionWithBlockhashLifetime } from './blockhash';\nimport { getCompiledAddressTableLookups } from './compile-address-table-lookups';\nimport { getCompiledMessageHeader } from './compile-header';\nimport { getCompiledInstructions } from './compile-instructions';\nimport { getCompiledLifetimeToken } from './compile-lifetime-token';\nimport { getCompiledStaticAccounts } from './compile-static-accounts';\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithFeePayer } from './fee-payer';\nimport { BaseTransaction } from './types';\n\ntype BaseCompiledMessage = Readonly<{\n header: ReturnType<typeof getCompiledMessageHeader>;\n instructions: ReturnType<typeof getCompiledInstructions>;\n lifetimeToken: ReturnType<typeof getCompiledLifetimeToken>;\n staticAccounts: ReturnType<typeof getCompiledStaticAccounts>;\n}>;\n\ntype CompilableTransaction = BaseTransaction &\n ITransactionWithFeePayer &\n (ITransactionWithBlockhashLifetime | IDurableNonceTransaction);\n\nexport type CompiledMessage = LegacyCompiledMessage | VersionedCompiledMessage;\n\ntype LegacyCompiledMessage = BaseCompiledMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledMessage = BaseCompiledMessage &\n Readonly<{\n addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups>;\n version: number;\n }>;\n\nexport function compileMessage(\n transaction: CompilableTransaction & Readonly<{ version: 'legacy' }>\n): LegacyCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): VersionedCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): CompiledMessage {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...(transaction.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),\n lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transaction.version,\n };\n}\n","import { Ed25519Signature } from '@solana/keys';\n\nimport { CompiledMessage, compileMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\n\ntype CompiledTransaction = Readonly<{\n compiledMessage: CompiledMessage;\n signatures: Ed25519Signature[];\n}>;\n\ntype CompilableTransaction = Parameters<typeof compileMessage>[0];\n\nexport function getCompiledTransaction(\n transaction: CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n): CompiledTransaction {\n const compiledMessage = compileMessage(transaction);\n let signatures;\n if ('signatures' in transaction) {\n signatures = [];\n for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {\n signatures[ii] =\n transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));\n }\n } else {\n signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));\n }\n return {\n compiledMessage,\n signatures,\n };\n}\n","import { array, Serializer, shortU16, struct, StructToSerializerTuple, u8 } from '@metaplex-foundation/umi-serializers';\nimport { Base58EncodedAddress, getAddressCodec } from '@solana/addresses';\n\nimport { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\n\ntype AddressTableLookup = ReturnType<typeof getCompiledAddressTableLookups>[number];\n\n// Temporary, will use getAddressCodec directly when everything else is migrated\nfunction addressSerializerCompat(compat?: { description: string }): Serializer<Base58EncodedAddress> {\n const codec = getAddressCodec();\n return {\n description: compat?.description ?? codec.description,\n deserialize: codec.decode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n serialize: codec.encode,\n };\n}\n\nexport function getAddressTableLookupCodec(): Serializer<AddressTableLookup> {\n return struct(\n [\n [\n 'lookupTableAddress',\n addressSerializerCompat(\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","/** 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 {\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","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 { 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","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","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 {\n array,\n base58,\n mapSerializer,\n Serializer,\n shortU16,\n string,\n struct,\n StructToSerializerTuple,\n} from '@metaplex-foundation/umi-serializers';\nimport { getAddressCodec } from '@solana/addresses';\nimport { Codec } from '@solana/codecs-core';\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\n// Temporary, convert a codec to a serializer for compatiblity for now\nfunction toSerializer<T>(codec: Codec<T>): Serializer<T> {\n return {\n description: codec.description,\n deserialize: codec.decode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n serialize: codec.encode,\n };\n}\n\nfunction getPreludeStructSerializerTuple(): StructToSerializerTuple<CompiledMessage, CompiledMessage> {\n return [\n ['version', toSerializer(getTransactionVersionCodec())],\n ['header', toSerializer(getMessageHeaderCodec())],\n [\n 'staticAccounts',\n array(toSerializer(getAddressCodec()), {\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, 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 { 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 { base58 } from '@metaplex-foundation/umi-serializers';\nimport { Base58EncodedAddress, getAddressFromPublicKey } from '@solana/addresses';\nimport { Ed25519Signature, signBytes } from '@solana/keys';\n\nimport { ITransactionWithFeePayer } from './fee-payer';\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\nexport type TransactionSignature = string & { readonly __brand: unique symbol };\n\nexport function assertIsTransactionSignature(\n putativeTransactionSignature: string\n): asserts putativeTransactionSignature is TransactionSignature {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeTransactionSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeTransactionSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeTransactionSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeTransactionSignature}\\` is not a transaction signature`, {\n cause: e,\n });\n }\n}\n\nexport function isTransactionSignature(\n putativeTransactionSignature: string\n): putativeTransactionSignature is TransactionSignature {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeTransactionSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeTransactionSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeTransactionSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\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 function getSignatureFromTransaction(\n transaction: ITransactionWithFeePayer & ITransactionWithSignatures\n): TransactionSignature {\n const signature = transaction.signatures[transaction.feePayer];\n if (!signature) {\n // TODO: Coded error.\n throw new Error(\n \"Could not determine this transaction's signature. Make sure that the transaction \" +\n 'has been signed by its fee payer.'\n );\n }\n return signature as unknown as TransactionSignature;\n}\n\nexport async function signTransaction<TTransaction extends Parameters<typeof compileMessage>[0]>(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Promise<TTransaction & ITransactionWithSignatures> {\n const compiledMessage = compileMessage(transaction);\n const nextSignatures: Record<Base58EncodedAddress, Ed25519Signature> =\n 'signatures' in transaction ? { ...transaction.signatures } : {};\n const publicKeySignaturePairs = await Promise.all(\n keyPairs.map(keyPair =>\n Promise.all([\n getAddressFromPublicKey(keyPair.publicKey),\n getCompiledMessageSignature(compiledMessage, keyPair.privateKey),\n ])\n )\n );\n for (const [signerPublicKey, signature] of publicKeySignaturePairs) {\n nextSignatures[signerPublicKey] = signature;\n }\n const out = {\n ...transaction,\n signatures: nextSignatures,\n };\n Object.freeze(out);\n return out;\n}\n\nexport function transactionSignature(putativeTransactionSignature: string): TransactionSignature {\n assertIsTransactionSignature(putativeTransactionSignature);\n return putativeTransactionSignature;\n}\n","import { getTransactionEncoder } from './serializers/transaction';\n\nexport type Base64EncodedWireTransaction = string & {\n readonly __brand: unique symbol;\n};\n\nexport function getBase64EncodedWireTransaction(\n transaction: Parameters<ReturnType<typeof getTransactionEncoder>['serialize']>[0]\n): Base64EncodedWireTransaction {\n const wireTransactionBytes = getTransactionEncoder().serialize(transaction);\n if (__NODEJS__) {\n return Buffer.from(wireTransactionBytes).toString('base64') as Base64EncodedWireTransaction;\n } else {\n return (btoa as Window['btoa'])(String.fromCharCode(...wireTransactionBytes)) as Base64EncodedWireTransaction;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/transactions",
3
- "version": "2.0.0-experimental.71a42a7",
3
+ "version": "2.0.0-experimental.72efece",
4
4
  "description": "Helpers for creating and serializing transactions",
5
5
  "exports": {
6
6
  "browser": {
@@ -47,11 +47,11 @@
47
47
  ],
48
48
  "dependencies": {
49
49
  "@metaplex-foundation/umi-serializers": "^0.8.9",
50
- "@solana/addresses": "2.0.0-experimental.71a42a7",
51
- "@solana/codecs-core": "2.0.0-experimental.71a42a7",
52
- "@solana/codecs-data-structures": "2.0.0-experimental.71a42a7",
53
- "@solana/codecs-numbers": "2.0.0-experimental.71a42a7",
54
- "@solana/keys": "2.0.0-experimental.71a42a7"
50
+ "@solana/addresses": "2.0.0-experimental.72efece",
51
+ "@solana/codecs-core": "2.0.0-experimental.72efece",
52
+ "@solana/codecs-data-structures": "2.0.0-experimental.72efece",
53
+ "@solana/codecs-numbers": "2.0.0-experimental.72efece",
54
+ "@solana/keys": "2.0.0-experimental.72efece"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@solana/eslint-config-solana": "^1.0.2",
@@ -70,11 +70,11 @@
70
70
  "tsup": "7.2.0",
71
71
  "typescript": "^5.2.2",
72
72
  "version-from-git": "^1.1.1",
73
- "@solana/instructions": "2.0.0-experimental.71a42a7",
73
+ "@solana/instructions": "2.0.0-experimental.72efece",
74
74
  "build-scripts": "0.0.0",
75
75
  "test-config": "0.0.0",
76
- "test-matchers": "0.0.0",
77
- "tsconfig": "0.0.0"
76
+ "tsconfig": "0.0.0",
77
+ "test-matchers": "0.0.0"
78
78
  },
79
79
  "bundlewatch": {
80
80
  "defaultCompression": "gzip",