@solana/transactions 2.0.0-experimental.0099b2a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +334 -0
  3. package/dist/index.browser.cjs +1098 -0
  4. package/dist/index.browser.cjs.map +1 -0
  5. package/dist/index.browser.js +1080 -0
  6. package/dist/index.browser.js.map +1 -0
  7. package/dist/index.development.js +1778 -0
  8. package/dist/index.development.js.map +1 -0
  9. package/dist/index.native.js +1080 -0
  10. package/dist/index.native.js.map +1 -0
  11. package/dist/index.node.cjs +1098 -0
  12. package/dist/index.node.cjs.map +1 -0
  13. package/dist/index.node.js +1080 -0
  14. package/dist/index.node.js.map +1 -0
  15. package/dist/index.production.min.js +29 -0
  16. package/dist/types/accounts.d.ts +28 -0
  17. package/dist/types/blockhash.d.ts +18 -0
  18. package/dist/types/compile-address-table-lookups.d.ts +10 -0
  19. package/dist/types/compile-header.d.ts +9 -0
  20. package/dist/types/compile-instructions.d.ts +10 -0
  21. package/dist/types/compile-lifetime-token.d.ts +3 -0
  22. package/dist/types/compile-static-accounts.d.ts +4 -0
  23. package/dist/types/compile-transaction.d.ts +11 -0
  24. package/dist/types/create-transaction.d.ts +9 -0
  25. package/dist/types/decompile-transaction.d.ts +7 -0
  26. package/dist/types/durable-nonce.d.ts +35 -0
  27. package/dist/types/fee-payer.d.ts +9 -0
  28. package/dist/types/index.d.ts +10 -0
  29. package/dist/types/instructions.d.ts +5 -0
  30. package/dist/types/message.d.ts +30 -0
  31. package/dist/types/serializers/address-table-lookup.d.ts +8 -0
  32. package/dist/types/serializers/header.d.ts +8 -0
  33. package/dist/types/serializers/index.d.ts +2 -0
  34. package/dist/types/serializers/instruction.d.ts +8 -0
  35. package/dist/types/serializers/message.d.ts +6 -0
  36. package/dist/types/serializers/transaction-version.d.ts +6 -0
  37. package/dist/types/serializers/transaction.d.ts +9 -0
  38. package/dist/types/signatures.d.ts +20 -0
  39. package/dist/types/types.d.ts +26 -0
  40. package/dist/types/unsigned-transaction.d.ts +4 -0
  41. package/dist/types/wire-transaction.d.ts +6 -0
  42. package/package.json +103 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../codecs-core/src/assertions.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/combine-codec.ts","../../codecs-core/src/fix-codec.ts","../../codecs-core/src/map-codec.ts","../../codecs-numbers/src/assertions.ts","../../codecs-numbers/src/f32.ts","../../codecs-numbers/src/utils.ts","../../codecs-numbers/src/i64.ts","../../codecs-numbers/src/i8.ts","../../codecs-numbers/src/short-u16.ts","../../codecs-numbers/src/u128.ts","../../codecs-numbers/src/u16.ts","../../codecs-numbers/src/u32.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/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","../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-data-structures/dist/index.browser.js","../../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","../../functional/src/pipe.ts","../src/decompile-transaction.ts","../src/serializers/address-table-lookup.ts","../src/serializers/header.ts","../src/serializers/instruction.ts","../src/serializers/transaction-version.ts","../src/serializers/message.ts","../src/serializers/transaction.ts","../../keys/src/signatures.ts","../src/signatures.ts","../src/wire-transaction.ts"],"names":["combineCodec","alphabet","e","AccountRole","base58Encoder","address","transactionSignature"],"mappings":";AAKO,SAAS,kCAAkC,kBAA0B,OAAm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AC,wBAAwB,QAAQ,SAAS,GAAG,UAAU,QAAQ,YAAY,gBAAgB,CAAC,CAAC;AAAA,IAC7G;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;AAEO,SAAS,+BACZ,aAC6D;AAC7D,QAAM,kCAAkC,YAAY,aAC/C,QAAQ,OAAK,EAAE,UAAU,OAAO,OAAK,aAAa,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,EAChE,IAAI,OAAK,EAAE,OAAO;AACvB,QAAM,kBAAkB,oBAAI,IAAI,CAAC,YAAY,UAAU,GAAG,+BAA+B,CAAC;AAE1F,kBAAgB,QAAQ,CAAAD,aAAW;AAC/B,QAAI,CAAC,YAAY,WAAWA,QAAO,GAAG;AAElC,YAAM,IAAI,MAAM,kDAAkDA,QAAO,IAAI;AAAA,IACjF;AAAA,EACJ,CAAC;AACL;;;AC/HO,SAAS,gCACZ,aAC4B;AAC5B,QAAM,uBAAuB,sBAAsB,EAAE,OAAO,WAAW;AACvE,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":["import { CodecData } from './codec';\n\n/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n\n/**\n * Asserts that a given codec is fixed-size codec.\n */\nexport function assertFixedSizeCodec(\n data: Pick<CodecData, 'fixedSize'>,\n message?: string\n): asserts data is { fixedSize: number } {\n if (data.fixedSize === null) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<From, To extends From = From>(\n encoder: Encoder<From>,\n decoder: Decoder<To>,\n description?: string\n): Codec<From, To> {\n if (encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`\n );\n }\n\n if (encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`\n );\n }\n\n if (description === undefined && encoder.description !== decoder.description) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. ` +\n `Pass a custom description as a third argument if you want to override the description and bypass this error.`\n );\n }\n\n return {\n decode: decoder.decode,\n description: description ?? encoder.description,\n encode: encoder.encode,\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport { Codec, CodecData, Decoder, Encoder } from './codec';\nimport { combineCodec } from './combine-codec';\n\nfunction fixCodecHelper(data: CodecData, fixedBytes: number, description?: string): CodecData {\n return {\n description: description ?? `fixed(${fixedBytes}, ${data.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n };\n}\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @param description - A custom description for the encoder.\n */\nexport function fixEncoder<T>(encoder: Encoder<T>, fixedBytes: number, description?: string): Encoder<T> {\n return {\n ...fixCodecHelper(encoder, fixedBytes, description),\n encode: (value: T) => fixBytes(encoder.encode(value), fixedBytes),\n };\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the decoder.\n */\nexport function fixDecoder<T>(decoder: Decoder<T>, fixedBytes: number, description?: string): Decoder<T> {\n return {\n ...fixCodecHelper(decoder, fixedBytes, description),\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (decoder.fixedSize !== null) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.decode(bytes, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @param description - A custom description for the codec.\n */\nexport function fixCodec<T, U extends T = T>(\n codec: Codec<T, U>,\n fixedBytes: number,\n description?: string\n): Codec<T, U> {\n return combineCodec(fixEncoder(codec, fixedBytes, description), fixDecoder(codec, fixedBytes, description));\n}\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<T, U>(encoder: Encoder<T>, unmap: (value: U) => T): Encoder<U> {\n return {\n description: encoder.description,\n encode: (value: U) => encoder.encode(unmap(value)),\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<T, U>(\n decoder: Decoder<T>,\n map: (value: T, bytes: Uint8Array, offset: number) => U\n): Decoder<U> {\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n const [value, length] = decoder.decode(bytes, offset);\n return [map(value, bytes, offset), length];\n },\n description: decoder.description,\n fixedSize: decoder.fixedSize,\n maxSize: decoder.maxSize,\n };\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<NewFrom, OldFrom, To extends NewFrom & OldFrom>(\n codec: Codec<OldFrom, To>,\n unmap: (value: NewFrom) => OldFrom\n): Codec<NewFrom, To>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map?: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo> {\n return {\n decode: map ? mapDecoder(codec, map).decode : (codec.decode as unknown as Decoder<NewTo>['decode']),\n description: codec.description,\n encode: mapEncoder(codec, unmap).encode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n };\n}\n","/**\n * Asserts that a given number is between a given range.\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) {\n if (value < min || value > max) {\n // TODO: Coded error.\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`\n );\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'f32',\n options,\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n options,\n size: 4,\n });\n\nexport const getF32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getF32Encoder(options), getF32Decoder(options));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n CodecData,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecOptions, SingleByteNumberCodecOptions } from './common';\n\ntype NumberFactorySharedInput = {\n name: string;\n size: number;\n options: SingleByteNumberCodecOptions | NumberCodecOptions;\n};\n\ntype NumberFactoryEncoderInput<T> = NumberFactorySharedInput & {\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: T, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput<T> = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => T;\n};\n\nfunction sharedNumberFactory(input: NumberFactorySharedInput): CodecData & { littleEndian: boolean | undefined } {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian = !('endian' in input.options) || input.options.endian === Endian.LITTLE;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n littleEndian,\n maxSize: input.size,\n };\n}\n\nexport function numberEncoderFactory<T extends number | bigint>(input: NumberFactoryEncoderInput<T>): Encoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n description: codecData.description,\n encode(value: T): Uint8Array {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, codecData.littleEndian);\n return new Uint8Array(arrayBuffer);\n },\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\nexport function numberDecoderFactory<T extends number | bigint>(input: NumberFactoryDecoderInput<T>): Decoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n decode(bytes, offset = 0): [T, number] {\n assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, codecData.littleEndian), offset + input.size];\n },\n description: codecData.description,\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\n/**\n * Helper function to ensure that the ArrayBuffer is converted properly from a Uint8Array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nfunction toArrayBuffer(bytes: Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI64Encoder = (options: NumberCodecOptions = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n name: 'i64',\n options,\n range: [-BigInt('0x7fffffffffffffff') - 1n, BigInt('0x7fffffffffffffff')],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8,\n });\n\nexport const getI64Decoder = (options: NumberCodecOptions = {}): Decoder<bigint> =>\n numberDecoderFactory({\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n options,\n size: 8,\n });\n\nexport const getI64Codec = (options: NumberCodecOptions = {}): Codec<number | bigint, bigint> =>\n combineCodec(getI64Encoder(options), getI64Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { SingleByteNumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI8Encoder = (options: SingleByteNumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'i8',\n options,\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, value),\n size: 1,\n });\n\nexport const getI8Decoder = (options: SingleByteNumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: view => view.getInt8(0),\n name: 'i8',\n options,\n size: 1,\n });\n\nexport const getI8Codec = (options: SingleByteNumberCodecOptions = {}): Codec<number> =>\n combineCodec(getI8Encoder(options), getI8Decoder(options));\n","import { BaseCodecOptions, Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\n\n/**\n * Defines the options for the shortU16 serializer.\n */\nexport type ShortU16CodecOptions = BaseCodecOptions;\n\n/**\n * Encodes short u16 numbers.\n * @see {@link getShortU16Codec} for a more detailed description.\n */\nexport const getShortU16Encoder = (options: ShortU16CodecOptions = {}): Encoder<number> => ({\n description: options.description ?? 'shortU16',\n encode: (value: number): Uint8Array => {\n assertNumberIsBetweenForCodec('shortU16', 0, 65535, value);\n const bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = value >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n bytes[ii - 1] |= 0b10000000;\n }\n }\n return new Uint8Array(bytes);\n },\n fixedSize: null,\n maxSize: 3,\n});\n\n/**\n * Decodes short u16 numbers.\n * @see {@link getShortU16Codec} for a more detailed description.\n */\nexport const getShortU16Decoder = (options: ShortU16CodecOptions = {}): Decoder<number> => ({\n decode: (bytes: Uint8Array, offset = 0): [number, number] => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n description: options.description ?? 'shortU16',\n fixedSize: null,\n maxSize: 3,\n});\n\n/**\n * Encodes and decodes short u16 numbers.\n *\n * Short u16 numbers are the same as u16, but serialized with 1 to 3 bytes.\n * If the value is above 0x7f, the top bit is set and the remaining\n * value is stored in the next bytes. Each byte follows the same\n * pattern until the 3rd byte. The 3rd byte, if needed, uses\n * all 8 bits to store the last byte of the original value.\n */\nexport const getShortU16Codec = (options: ShortU16CodecOptions = {}): Codec<number> =>\n combineCodec(getShortU16Encoder(options), getShortU16Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (options: NumberCodecOptions = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n name: 'u128',\n options,\n range: [0, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\nexport const getU128Decoder = (options: NumberCodecOptions = {}): Decoder<bigint> =>\n numberDecoderFactory({\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n options,\n size: 16,\n });\n\nexport const getU128Codec = (options: NumberCodecOptions = {}): Codec<number | bigint, bigint> =>\n combineCodec(getU128Encoder(options), getU128Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u16',\n options,\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, value, le),\n size: 2,\n });\n\nexport const getU16Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n options,\n size: 2,\n });\n\nexport const getU16Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU16Encoder(options), getU16Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u32',\n options,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, value, le),\n size: 4,\n });\n\nexport const getU32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n options,\n size: 4,\n });\n\nexport const getU32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU32Encoder(options), getU32Decoder(options));\n","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXEncoder = (alphabet: string): Encoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n encode(value: string): Uint8Array {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex(c => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * Decodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXDecoder = (alphabet: string): Decoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n decode(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), rawBytes.length];\n },\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * A string codec that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create codecs such as base10 or base58.\n */\nexport const getBaseXCodec = (alphabet: string): Codec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): Encoder<string> => ({\n description: 'base16',\n encode(value: string) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString('0123456789abcdef', lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n return Uint8Array.from(matches ? matches.map((byte: string) => parseInt(byte, 16)) : []);\n },\n fixedSize: null,\n maxSize: null,\n});\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): Decoder<string> => ({\n decode(bytes, offset = 0) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n description: 'base16',\n fixedSize: null,\n maxSize: null,\n});\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): Codec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { 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","import { ITransactionWithSignatures } from '.';\nimport { BaseTransaction } from './types';\n\nexport function getUnsignedTransaction<TTransaction extends BaseTransaction>(\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction & ITransactionWithSignatures, keyof ITransactionWithSignatures> {\n if ('signatures' in transaction) {\n // The implication of the lifetime constraint changing is that any existing signatures are invalid.\n const {\n signatures: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n","import { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nimport { IDurableNonceTransaction } from './durable-nonce';\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport type Blockhash = string & { readonly __brand: unique symbol };\n\ntype BlockhashLifetimeConstraint = Readonly<{\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n}>;\n\nexport interface ITransactionWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 ||\n // Highest value (32 bytes of 255)\n putativeBlockhash.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeBlockhash);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBlockhash}\\` is not a blockhash`, {\n cause: e,\n });\n }\n}\n\nexport function setTransactionLifetimeUsingBlockhash<TTransaction extends BaseTransaction & IDurableNonceTransaction>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures | 'lifetimeConstraint'> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash<\n TTransaction extends BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithBlockhashLifetime;\n\nexport function setTransactionLifetimeUsingBlockhash(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transaction: BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)\n) {\n if (\n 'lifetimeConstraint' in transaction &&\n transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n lifetimeConstraint: blockhashLifetimeConstraint,\n };\n Object.freeze(out);\n return out;\n}\n","import { Transaction, TransactionVersion } from './types';\n\ntype TransactionConfig<TVersion extends TransactionVersion> = Readonly<{\n version: TVersion;\n}>;\n\nexport function createTransaction<TVersion extends TransactionVersion>(\n config: TransactionConfig<TVersion>\n): Extract<Transaction, { version: TVersion }>;\nexport function createTransaction<TVersion extends TransactionVersion>({\n version,\n}: TransactionConfig<TVersion>): Transaction {\n const out: Transaction = {\n instructions: [],\n version,\n };\n Object.freeze(out);\n return out;\n}\n","/**\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 {\n AccountRole,\n IInstruction,\n IInstructionWithAccounts,\n IInstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\ntype AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n> = IInstruction<'11111111111111111111111111111111'> &\n IInstructionWithAccounts<\n readonly [\n WritableAccount<TNonceAccountAddress>,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount<TNonceAuthorityAddress> | WritableSignerAccount<TNonceAuthorityAddress>\n ]\n > &\n IInstructionWithData<AdvanceNonceAccountInstructionData>;\ntype AdvanceNonceAccountInstructionData = Uint8Array & {\n readonly __brand: unique symbol;\n};\ntype DurableNonceConfig<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> = Readonly<{\n readonly nonce: Nonce<TNonceValue>;\n readonly nonceAccountAddress: Base58EncodedAddress<TNonceAccountAddress>;\n readonly nonceAuthorityAddress: Base58EncodedAddress<TNonceAuthorityAddress>;\n}>;\nexport type Nonce<TNonceValue extends string = string> = TNonceValue & { readonly __brand: unique symbol };\ntype NonceLifetimeConstraint<TNonceValue extends string = string> = Readonly<{\n nonce: Nonce<TNonceValue>;\n}>;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Base58EncodedAddress<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS =\n '11111111111111111111111111111111' as Base58EncodedAddress<'11111111111111111111111111111111'>;\n\nexport interface IDurableNonceTransaction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint<TNonceValue>;\n}\n\nexport function assertIsDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): asserts transaction is BaseTransaction & IDurableNonceTransaction {\n if (!isDurableNonceTransaction(transaction)) {\n // TODO: Coded error.\n throw new Error('Transaction is not a durable nonce transaction');\n }\n}\n\nfunction createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n>(\n nonceAccountAddress: Base58EncodedAddress<TNonceAccountAddress>,\n nonceAuthorityAddress: Base58EncodedAddress<TNonceAuthorityAddress>\n): AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\nexport function isAdvanceNonceAccountInstruction(\n instruction: IInstruction\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.programAddress === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accounts?.length === 3 &&\n // First account is nonce account address\n instruction.accounts[0].address != null &&\n instruction.accounts[0].role === AccountRole.WRITABLE &&\n // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS &&\n instruction.accounts[1].role === AccountRole.READONLY &&\n // Third account is nonce authority account\n instruction.accounts[2].address != null &&\n isSignerRole(instruction.accounts[2].role)\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: Uint8Array): data is AdvanceNonceAccountInstructionData {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n\nfunction isDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): transaction is BaseTransaction & IDurableNonceTransaction {\n return (\n 'lifetimeConstraint' in transaction &&\n typeof transaction.lifetimeConstraint.nonce === 'string' &&\n transaction.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transaction.instructions[0])\n );\n}\n\nfunction isAdvanceNonceAccountInstructionForNonce<\n TNonceAccountAddress extends Base58EncodedAddress = Base58EncodedAddress,\n TNonceAuthorityAddress extends Base58EncodedAddress = Base58EncodedAddress\n>(\n instruction: AdvanceNonceAccountInstruction,\n nonceAccountAddress: TNonceAccountAddress,\n nonceAuthorityAddress: TNonceAuthorityAddress\n): instruction is AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return (\n instruction.accounts[0].address === nonceAccountAddress &&\n instruction.accounts[2].address === nonceAuthorityAddress\n );\n}\n\nexport function setTransactionLifetimeUsingDurableNonce<\n TTransaction extends BaseTransaction,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n>(\n {\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n }: DurableNonceConfig<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>,\n transaction: TTransaction | (TTransaction & IDurableNonceTransaction)\n): Omit<TTransaction, keyof ITransactionWithSignatures> &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue> {\n let newInstructions: [\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n\n const firstInstruction = transaction.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {\n return transaction as TTransaction &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions.slice(1),\n ];\n }\n } else {\n // we don't have an existing advance nonce instruction as the first instruction, prepend one\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions,\n ];\n }\n\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: newInstructions,\n lifetimeConstraint: {\n nonce,\n },\n } as TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n Object.freeze(out);\n return out;\n}\n","import { Base58EncodedAddress } from '@solana/addresses';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport interface ITransactionWithFeePayer<TAddress extends string = string> {\n readonly feePayer: Base58EncodedAddress<TAddress>;\n}\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction: TTransaction | (TTransaction & ITransactionWithFeePayer<string>)\n): TTransaction & ITransactionWithFeePayer<TFeePayerAddress>;\n\nexport function setTransactionFeePayer<TFeePayerAddress extends string, TTransaction extends BaseTransaction>(\n feePayer: Base58EncodedAddress<TFeePayerAddress>,\n transaction:\n | TTransaction\n | (TTransaction & ITransactionWithFeePayer<string>)\n | (TTransaction & ITransactionWithSignatures)\n | (TTransaction & ITransactionWithFeePayer<string> & ITransactionWithSignatures)\n) {\n if ('feePayer' in transaction && feePayer === transaction.feePayer) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n feePayer,\n };\n Object.freeze(out);\n return out;\n}\n","import { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\nexport function appendTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [...transaction.instructions, instruction],\n };\n Object.freeze(out);\n return out;\n}\n\nexport function prependTransactionInstruction<TTransaction extends BaseTransaction>(\n instruction: TTransaction['instructions'][number],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction, keyof ITransactionWithSignatures> {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [instruction, ...transaction.instructions],\n };\n Object.freeze(out);\n return out;\n}\n","import { 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","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","/**\n * General pipe function.\n * Provide an initial value and a list of functions to pipe it through.\n *\n * Following common implementations of pipe functions that use TypeScript,\n * this function supports a maximum arity of 10 for type safety.\n * @see https://github.com/ramda/ramda/blob/master/source/pipe.js\n * @see https://github.com/darky/rocket-pipes/blob/master/index.ts\n *\n * Note you can use nested pipes to extend this limitation, like so:\n * ```typescript\n * const myValue = pipe(\n * pipe(\n * 1,\n * (x) => x + 1,\n * (x) => x * 2,\n * (x) => x - 1,\n * ),\n * (y) => y / 3,\n * (y) => y + 1,\n * );\n * ```\n * @param init The initial value\n * @param fns Any number of functions to pipe the value through\n * @returns The final value with all functions applied\n */\nexport function pipe<TInitial>(init: TInitial): TInitial;\nexport function pipe<TInitial, R1>(init: TInitial, init_r1: (init: TInitial) => R1): R1;\nexport function pipe<TInitial, R1, R2>(init: TInitial, init_r1: (init: TInitial) => R1, r1_r2: (r1: R1) => R2): R2;\nexport function pipe<TInitial, R1, R2, R3>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3\n): R3;\nexport function pipe<TInitial, R1, R2, R3, R4>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4\n): R4;\nexport function pipe<TInitial, R1, R2, R3, R4, R5>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5\n): R5;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6\n): R6;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7\n): R7;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8\n): R8;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8,\n r8_r9: (r8: R8) => R9\n): R9;\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10>(\n init: TInitial,\n init_r1: (init: TInitial) => R1,\n r1_r2: (r1: R1) => R2,\n r2_r3: (r2: R2) => R3,\n r3_r4: (r3: R3) => R4,\n r4_r5: (r4: R4) => R5,\n r5_r6: (r5: R5) => R6,\n r6_r7: (r6: R6) => R7,\n r7_r8: (r7: R7) => R8,\n r8_r9: (r8: R8) => R9,\n r9_r10: (r9: R9) => R10\n): R10;\nexport function pipe<TInitial>(init: TInitial, ...fns: CallableFunction[]) {\n return fns.reduce((acc, fn) => fn(acc), init);\n}\n","import { assertIsAddress, Base58EncodedAddress } from '@solana/addresses';\nimport { pipe } from '@solana/functional';\nimport { AccountRole, IAccountMeta, IInstruction } from '@solana/instructions';\nimport { Ed25519Signature } from '@solana/keys';\n\nimport { Blockhash, setTransactionLifetimeUsingBlockhash } from './blockhash';\nimport { getCompiledTransaction } from './compile-transaction';\nimport { createTransaction } from './create-transaction';\nimport { isAdvanceNonceAccountInstruction, Nonce, setTransactionLifetimeUsingDurableNonce } from './durable-nonce';\nimport { setTransactionFeePayer } from './fee-payer';\nimport { appendTransactionInstruction } from './instructions';\nimport { CompiledMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\nimport { TransactionVersion } from './types';\n\ntype CompiledTransaction = ReturnType<typeof getCompiledTransaction>;\ntype CompilableTransaction = Parameters<typeof getCompiledTransaction>[0];\n\nfunction getAccountMetas(message: CompiledMessage): IAccountMeta[] {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts =\n message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n\n const accountMetas: IAccountMeta[] = [];\n\n let accountIndex = 0;\n for (let i = 0; i < numWritableSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlySignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY,\n });\n accountIndex++;\n }\n\n return accountMetas;\n}\n\nfunction convertInstruction(\n instruction: CompiledMessage['instructions'][0],\n accountMetas: IAccountMeta[]\n): IInstruction {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n // TODO coded error\n throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);\n }\n\n const accounts = instruction.accountIndices?.map(accountIndex => accountMetas[accountIndex]);\n const { data } = instruction;\n\n return {\n programAddress,\n ...(accounts && accounts.length ? { accounts } : {}),\n ...(data && data.length ? { data } : {}),\n };\n}\n\ntype LifetimeConstraint =\n | {\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n }\n | {\n nonce: Nonce;\n nonceAccountAddress: Base58EncodedAddress;\n nonceAuthorityAddress: Base58EncodedAddress;\n };\n\nfunction getLifetimeConstraint(\n messageLifetimeToken: string,\n firstInstruction?: IInstruction,\n lastValidBlockHeight?: bigint\n): LifetimeConstraint {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n // first instruction is not advance durable nonce, so use blockhash lifetime constraint\n return {\n blockhash: messageLifetimeToken as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n } else {\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = firstInstruction.accounts![0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = firstInstruction.accounts![2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n return {\n nonce: messageLifetimeToken as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n }\n}\n\nfunction convertSignatures(compiledTransaction: CompiledTransaction): ITransactionWithSignatures['signatures'] {\n const {\n compiledMessage: { staticAccounts },\n signatures,\n } = compiledTransaction;\n return signatures.reduce((acc, sig, index) => {\n // compiled transaction includes a fake all 0 signature if it hasn't been signed\n // we don't store those for the new tx model. So just skip if it's all 0s\n const allZeros = sig.every(byte => byte === 0);\n if (allZeros) return acc;\n\n const address = staticAccounts[index];\n return { ...acc, [address]: sig as Ed25519Signature };\n }, {});\n}\n\nexport function decompileTransaction(\n compiledTransaction: CompiledTransaction,\n lastValidBlockHeight?: bigint\n): CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures) {\n const { compiledMessage } = compiledTransaction;\n\n // TODO: add support for address lookup tables\n if ('addressTableLookups' in compiledMessage && compiledMessage.addressTableLookups!.length > 0) {\n // TODO: coded error\n throw new Error('Cannot convert transaction with addressTableLookups');\n }\n\n const feePayer = compiledMessage.staticAccounts[0];\n // TODO: coded error\n if (!feePayer) throw new Error('No fee payer set in CompiledTransaction');\n\n const accountMetas = getAccountMetas(compiledMessage);\n\n const instructions: IInstruction[] = compiledMessage.instructions.map(compiledInstruction =>\n convertInstruction(compiledInstruction, accountMetas)\n );\n\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledMessage.lifetimeToken,\n firstInstruction,\n lastValidBlockHeight\n );\n\n const signatures = convertSignatures(compiledTransaction);\n\n return pipe(\n createTransaction({ version: compiledMessage.version as TransactionVersion }),\n tx => setTransactionFeePayer(feePayer, tx),\n tx =>\n instructions.reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n tx =>\n 'blockhash' in lifetimeConstraint\n ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx)\n : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),\n tx => (compiledTransaction.signatures.length ? { ...tx, signatures } : tx)\n );\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport { type Codec, combineCodec, type Decoder, type Encoder } from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport type { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\n\ntype AddressTableLookup = ReturnType<typeof getCompiledAddressTableLookups>[number];\n\nconst lookupTableAddressDescription = __DEV__\n ? 'The address of the address lookup table account from which instruction addresses should be looked up'\n : 'lookupTableAddress';\n\nconst writableIndicesDescription = __DEV__\n ? 'The indices of the accounts in the lookup table that should be loaded as writeable'\n : 'writableIndices';\n\nconst readableIndicesDescription = __DEV__\n ? 'The indices of the accounts in the lookup table that should be loaded as read-only'\n : 'readableIndices';\n\nconst addressTableLookupDescription = __DEV__\n ? 'A pointer to the address of an address lookup table, along with the ' +\n 'readonly/writeable indices of the addresses that should be loaded from it'\n : 'addressTableLookup';\n\nlet memoizedAddressTableLookupEncoder: Encoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupEncoder(): Encoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupEncoder) {\n memoizedAddressTableLookupEncoder = getStructEncoder(\n [\n ['lookupTableAddress', getAddressEncoder({ description: lookupTableAddressDescription })],\n [\n 'writableIndices',\n getArrayEncoder(getU8Encoder(), {\n description: writableIndicesDescription,\n size: getShortU16Encoder(),\n }) as Encoder<readonly number[]>,\n ],\n [\n 'readableIndices',\n getArrayEncoder(getU8Encoder(), {\n description: readableIndicesDescription,\n size: getShortU16Encoder(),\n }) as Encoder<readonly number[]>,\n ],\n ],\n { description: addressTableLookupDescription }\n );\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: Decoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupDecoder(): Decoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupDecoder) {\n memoizedAddressTableLookupDecoder = getStructDecoder(\n [\n ['lookupTableAddress', getAddressDecoder({ description: lookupTableAddressDescription })],\n [\n 'writableIndices',\n getArrayDecoder(getU8Decoder(), {\n description: writableIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n [\n 'readableIndices',\n getArrayDecoder(getU8Decoder(), {\n description: readableIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ],\n { description: addressTableLookupDescription }\n );\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): Codec<AddressTableLookup> {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { Codec, Decoder, Encoder } from '@solana/codecs-core';\nimport { getStructCodec, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getU8Codec, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledMessageHeader } from '../compile-header';\n\ntype MessageHeader = ReturnType<typeof getCompiledMessageHeader>;\n\nlet memoizedU8Encoder: Encoder<number> | undefined;\nfunction getMemoizedU8Encoder(): Encoder<number> {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nfunction getMemoizedU8EncoderDescription(description?: string): Encoder<number> {\n const encoder = getMemoizedU8Encoder();\n return {\n ...encoder,\n description: description ?? encoder.description,\n };\n}\n\nlet memoizedU8Decoder: Decoder<number> | undefined;\nfunction getMemoizedU8Decoder(): Decoder<number> {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nfunction getMemoizedU8DecoderDescription(description?: string): Decoder<number> {\n const decoder = getMemoizedU8Decoder();\n return {\n ...decoder,\n description: description ?? decoder.description,\n };\n}\n\nlet memoizedU8Codec: Codec<number> | undefined;\nfunction getMemoizedU8Codec(): Codec<number> {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nfunction getMemoizedU8CodecDescription(description?: string): Codec<number> {\n const codec = getMemoizedU8Codec();\n return {\n ...codec,\n description: description ?? codec.description,\n };\n}\n\nconst numSignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction'\n : undefined;\n\nconst numReadonlySignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable'\n : undefined;\n\nconst numReadonlyNonSignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable'\n : undefined;\n\nconst messageHeaderDescription = __DEV__\n ? 'The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses'\n : undefined;\n\nexport function getMessageHeaderEncoder(): Encoder<MessageHeader> {\n return getStructEncoder(\n [\n ['numSignerAccounts', getMemoizedU8EncoderDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n\nexport function getMessageHeaderDecoder(): Decoder<MessageHeader> {\n return getStructDecoder(\n [\n ['numSignerAccounts', getMemoizedU8DecoderDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n\nexport function getMessageHeaderCodec(): Codec<MessageHeader> {\n return getStructCodec(\n [\n ['numSignerAccounts', getMemoizedU8CodecDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8CodecDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8CodecDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledInstructions } from '../compile-instructions';\n\ntype Instruction = ReturnType<typeof getCompiledInstructions>[number];\n\nconst programAddressIndexDescription = __DEV__\n ? 'The index of the program being called, according to the well-ordered accounts list for this transaction'\n : 'programAddressIndex';\n\nconst accountIndexDescription = __DEV__\n ? 'The index of an account, according to the well-ordered accounts list for this transaction'\n : undefined;\n\nconst accountIndicesDescription = __DEV__\n ? 'An optional list of account indices, according to the ' +\n 'well-ordered accounts list for this transaction, in the order in ' +\n 'which the program being called expects them'\n : 'accountIndices';\n\nconst dataDescription = __DEV__ ? 'An optional buffer of data passed to the instruction' : 'data';\n\nlet memoizedGetInstructionEncoder: Encoder<Instruction> | undefined;\nexport function getInstructionEncoder(): Encoder<Instruction> {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = mapEncoder<Required<Instruction>, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder({ description: programAddressIndexDescription })],\n [\n 'accountIndices',\n getArrayEncoder(getU8Encoder({ description: accountIndexDescription }), {\n description: accountIndicesDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ['data', getBytesEncoder({ description: dataDescription, size: getShortU16Encoder() })],\n ]),\n // Convert an instruction to have all fields defined\n (instruction: Instruction): Required<Instruction> => {\n if (instruction.accountIndices !== undefined && instruction.data !== undefined) {\n return instruction as Required<Instruction>;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0),\n } as Required<Instruction>;\n }\n );\n }\n\n return memoizedGetInstructionEncoder;\n}\n\nlet memoizedGetInstructionDecoder: Decoder<Instruction> | undefined;\nexport function getInstructionDecoder(): Decoder<Instruction> {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = mapDecoder<Required<Instruction>, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder({ description: programAddressIndexDescription })],\n [\n 'accountIndices',\n getArrayDecoder(getU8Decoder({ description: accountIndexDescription }), {\n description: accountIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['data', getBytesDecoder({ description: dataDescription, size: getShortU16Decoder() })],\n ]),\n // Convert an instruction to exclude optional fields if they are empty\n (instruction: Required<Instruction>): Instruction => {\n if (instruction.accountIndices.length && instruction.data.byteLength) {\n return instruction;\n }\n const { accountIndices, data, ...rest } = instruction;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n }\n );\n }\n return memoizedGetInstructionDecoder;\n}\n\nexport function getInstructionCodec(): Codec<Instruction> {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { TransactionVersion } from '../types';\n\nconst VERSION_FLAG_MASK = 0x80;\n\nconst BASE_CONFIG = {\n description: __DEV__ ? 'A single byte that encodes the version of the transaction' : '',\n fixedSize: null,\n maxSize: 1,\n} as const;\n\nfunction decode(bytes: Uint8Array, offset = 0): [TransactionVersion, number] {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n // No version flag set; it's a legacy (unversioned) transaction.\n return ['legacy', offset];\n } else {\n const version = (firstByte ^ VERSION_FLAG_MASK) as TransactionVersion;\n return [version, offset + 1];\n }\n}\n\nfunction encode(value: TransactionVersion): Uint8Array {\n if (value === 'legacy') {\n return new Uint8Array();\n }\n if (value < 0 || value > 127) {\n // TODO: Coded error.\n throw new Error(`Transaction version must be in the range [0, 127]. \\`${value}\\` given.`);\n }\n return new Uint8Array([value | VERSION_FLAG_MASK]);\n}\n\nexport function getTransactionVersionDecoder(): Decoder<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n decode,\n };\n}\n\nexport function getTransactionVersionEncoder(): Encoder<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n encode,\n };\n}\n\nexport function getTransactionVersionCodec(): Codec<TransactionVersion> {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n StructToDecoderTuple,\n StructToEncoderTuple,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\nimport { CompiledMessage } from '../message';\nimport { SerializedMessageBytes } from '../types';\nimport { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nconst staticAccountsDescription = __DEV__\n ? 'A compact-array of static account addresses belonging to this transaction'\n : 'staticAccounts';\nconst lifetimeTokenDescription = __DEV__\n ? 'A 32-byte token that specifies the lifetime of this transaction (eg. a ' +\n 'recent blockhash, or a durable nonce)'\n : 'lifetimeToken';\nconst instructionsDescription = __DEV__\n ? 'A compact-array of instructions belonging to this transaction'\n : 'instructions';\nconst addressTableLookupsDescription = __DEV__\n ? 'A compact array of address table lookups belonging to this transaction'\n : 'addressTableLookups';\n\nfunction getCompiledMessageLegacyEncoder(): Encoder<CompiledMessage> {\n return getStructEncoder(getPreludeStructEncoderTuple());\n}\n\nfunction getCompiledMessageVersionedEncoder(): Encoder<CompiledMessage> {\n return mapEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ] as StructToEncoderTuple<CompiledMessage>),\n (value: CompiledMessage) => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n } as Exclude<CompiledMessage, { readonly version: 'legacy' }>;\n }\n );\n}\n\nfunction getPreludeStructEncoderTuple(): StructToEncoderTuple<CompiledMessage> {\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n [\n 'staticAccounts',\n getArrayEncoder(getAddressEncoder(), {\n description: staticAccountsDescription,\n size: getShortU16Encoder(),\n }),\n ],\n [\n 'lifetimeToken',\n getStringEncoder({\n description: lifetimeTokenDescription,\n encoding: getBase58Encoder(),\n size: 32,\n }),\n ],\n [\n 'instructions',\n getArrayEncoder(getInstructionEncoder(), {\n description: instructionsDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ];\n}\n\nfunction getPreludeStructDecoderTuple(): StructToDecoderTuple<\n CompiledMessage & { addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups> }\n> {\n return [\n ['version', getTransactionVersionDecoder() as Decoder<number>],\n ['header', getMessageHeaderDecoder()],\n [\n 'staticAccounts',\n getArrayDecoder(getAddressDecoder(), {\n description: staticAccountsDescription,\n size: getShortU16Decoder(),\n }),\n ],\n [\n 'lifetimeToken',\n getStringDecoder({\n description: lifetimeTokenDescription,\n encoding: getBase58Decoder(),\n size: 32,\n }),\n ],\n [\n 'instructions',\n getArrayDecoder(getInstructionDecoder(), {\n description: instructionsDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ];\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Encoder(),\n });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Decoder(),\n });\n}\n\nconst messageDescription = __DEV__ ? 'The wire format of a Solana transaction message' : 'message';\n\nexport function getCompiledMessageEncoder(): Encoder<CompiledMessage> {\n return {\n description: messageDescription,\n encode: compiledMessage => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().encode(compiledMessage) as SerializedMessageBytes;\n } else {\n return getCompiledMessageVersionedEncoder().encode(compiledMessage) as SerializedMessageBytes;\n }\n },\n fixedSize: null,\n maxSize: null,\n };\n}\n\nexport function getCompiledMessageDecoder(): Decoder<CompiledMessage> {\n return mapDecoder(\n getStructDecoder(getPreludeStructDecoderTuple(), {\n description: messageDescription,\n }),\n ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups } as Exclude<\n CompiledMessage,\n { readonly version: 'legacy' }\n >;\n }\n );\n}\n\nexport function getCompiledMessageCodec(): Codec<CompiledMessage> {\n return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { Ed25519Signature } from '@solana/keys';\n\nimport { getCompiledTransaction } from '../compile-transaction';\nimport { decompileTransaction } from '../decompile-transaction';\nimport { compileMessage } from '../message';\nimport { ITransactionWithSignatures } from '../signatures';\nimport { getCompiledMessageDecoder, getCompiledMessageEncoder } from './message';\n\ntype CompilableTransaction = Parameters<typeof compileMessage>[0];\ntype CompiledTransaction = ReturnType<typeof getCompiledTransaction>;\n\nconst signaturesDescription = __DEV__ ? 'A compact array of 64-byte, base-64 encoded Ed25519 signatures' : 'signatures';\nconst transactionDescription = __DEV__ ? 'The wire format of a Solana transaction' : 'transaction';\n\nfunction getCompiledTransactionEncoder(): Encoder<CompiledTransaction> {\n return getStructEncoder(\n [\n [\n 'signatures',\n getArrayEncoder(getBytesEncoder({ size: 64 }), {\n description: signaturesDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageEncoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nfunction getSignatureDecoder(): Decoder<Ed25519Signature> {\n return mapDecoder(getBytesDecoder({ size: 64 }), bytes => bytes as Ed25519Signature);\n}\n\nfunction getCompiledTransactionDecoder(): Decoder<CompiledTransaction> {\n return getStructDecoder(\n [\n [\n 'signatures',\n getArrayDecoder(getSignatureDecoder(), {\n description: signaturesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageDecoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nexport function getTransactionEncoder(): Encoder<\n CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n> {\n return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);\n}\n\nexport function getTransactionDecoder(\n lastValidBlockHeight?: bigint\n): Decoder<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return mapDecoder(getCompiledTransactionDecoder(), compiledTransaction =>\n decompileTransaction(compiledTransaction, lastValidBlockHeight)\n );\n}\n\nexport function getTransactionCodec(\n lastValidBlockHeight?: bigint\n): Codec<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));\n}\n","import { 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 { Base58EncodedAddress, getAddressFromPublicKey } from '@solana/addresses';\nimport { Decoder, Encoder } from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\nimport { isSignerRole } from '@solana/instructions';\nimport { Ed25519Signature, signBytes } from '@solana/keys';\n\nimport { ITransactionWithFeePayer } from './fee-payer';\nimport { compileMessage } from './message';\nimport { getCompiledMessageEncoder } from './serializers/message';\n\nexport interface IFullySignedTransaction extends ITransactionWithSignatures {\n readonly __brand: unique symbol;\n}\nexport interface ITransactionWithSignatures {\n readonly signatures: Readonly<Record<Base58EncodedAddress, Ed25519Signature>>;\n}\n\nexport type TransactionSignature = string & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\nlet base58Decoder: Decoder<string> | undefined;\n\nexport function assertIsTransactionSignature(\n putativeTransactionSignature: string\n): asserts putativeTransactionSignature is TransactionSignature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeTransactionSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeTransactionSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeTransactionSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeTransactionSignature}\\` is not a transaction signature`, {\n cause: e,\n });\n }\n}\n\nexport function isTransactionSignature(\n putativeTransactionSignature: string\n): putativeTransactionSignature is TransactionSignature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeTransactionSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeTransactionSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeTransactionSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport function getSignatureFromTransaction(\n transaction: ITransactionWithFeePayer & ITransactionWithSignatures\n): TransactionSignature {\n if (!base58Decoder) base58Decoder = getBase58Decoder();\n\n const signatureBytes = transaction.signatures[transaction.feePayer];\n if (!signatureBytes) {\n // TODO: Coded error.\n throw new Error(\n \"Could not determine this transaction's signature. Make sure that the transaction \" +\n 'has been signed by its fee payer.'\n );\n }\n const transactionSignature = base58Decoder.decode(signatureBytes)[0];\n return transactionSignature as TransactionSignature;\n}\n\nexport async function signTransaction<TTransaction extends Parameters<typeof compileMessage>[0]>(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): Promise<TTransaction & ITransactionWithSignatures> {\n const compiledMessage = compileMessage(transaction);\n const nextSignatures: Record<Base58EncodedAddress, Ed25519Signature> =\n 'signatures' in transaction ? { ...transaction.signatures } : {};\n const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);\n const publicKeySignaturePairs = await Promise.all(\n keyPairs.map(keyPair =>\n Promise.all([getAddressFromPublicKey(keyPair.publicKey), signBytes(keyPair.privateKey, wireMessageBytes)])\n )\n );\n for (const [signerPublicKey, signature] of publicKeySignaturePairs) {\n nextSignatures[signerPublicKey] = signature;\n }\n const out = {\n ...transaction,\n signatures: nextSignatures,\n };\n Object.freeze(out);\n return out;\n}\n\nexport function transactionSignature(putativeTransactionSignature: string): TransactionSignature {\n assertIsTransactionSignature(putativeTransactionSignature);\n return putativeTransactionSignature;\n}\n\nexport function assertTransactionIsFullySigned<TTransaction extends Parameters<typeof compileMessage>[0]>(\n transaction: TTransaction & ITransactionWithSignatures\n): asserts transaction is TTransaction & IFullySignedTransaction {\n const signerAddressesFromInstructions = transaction.instructions\n .flatMap(i => i.accounts?.filter(a => isSignerRole(a.role)) ?? [])\n .map(a => a.address);\n const requiredSigners = new Set([transaction.feePayer, ...signerAddressesFromInstructions]);\n\n requiredSigners.forEach(address => {\n if (!transaction.signatures[address]) {\n // TODO coded error\n throw new Error(`Transaction is missing signature for address \\`${address}\\``);\n }\n });\n}\n","import { 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>['encode']>[0]\n): Base64EncodedWireTransaction {\n const wireTransactionBytes = getTransactionEncoder().encode(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"]}