@solana/signers 2.0.0-experimental.d93c93b → 2.0.0-experimental.e4483d3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/deduplicate-signers.ts","../src/account-signer-meta.ts","../../instructions/src/roles.ts","../src/add-signers.ts","../../codecs-core/src/assertions.ts","../../codecs-core/src/bytes.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/u128.ts","../../codecs-numbers/src/u16.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/base64.ts","../../codecs-strings/src/null-characters.ts","../../codecs-strings/src/string.ts","../../codecs-strings/src/utf8.ts","../../text-encoding-impl/src/index.browser.ts","../../assertions/src/subtle-crypto.ts","../../addresses/src/address.ts","../../addresses/src/program-derived-address.ts","../../addresses/src/public-key.ts","../../keys/src/key-pair.ts","../../keys/src/signatures.ts","../../codecs-data-structures/src/utils.ts","../../codecs-data-structures/src/array-like-codec-size.ts","../../codecs-data-structures/src/assertions.ts","../../codecs-data-structures/src/array.ts","../../codecs-data-structures/src/boolean.ts","../../codecs-data-structures/src/bytes.ts","../../codecs-data-structures/src/scalar-enum.ts","../../codecs-data-structures/src/set.ts","../../transactions/dist/index.browser.js","../src/message-partial-signer.ts","../src/transaction-partial-signer.ts","../src/keypair-signer.ts","../src/message-modifying-signer.ts","../src/message-signer.ts","../src/noop-signer.ts","../src/transaction-modifying-signer.ts","../src/transaction-sending-signer.ts","../src/transaction-signer.ts","../src/sign-transaction.ts","../src/signable-message.ts","../src/transaction-with-single-sending-signer.ts"],"names":["combineCodec","alphabet","e","mergeBytes","getU32Decoder","__DEV__","isSignerRole","address","trans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AiB,QAAQ,OAAO,0BAA0B;AAEhE,MAAI,eAAe,WAAW,GAAG;AAE7B,UAAM,QAAQ,IAAI,MAAM,+CAA+C;AACvE,UAAM,OAAO;AACb,UAAM;AAAA,EACV;AAKA,QAAM,qBAAqB,eAAe;AAAA,IACtC,YAAU,CAAC,2BAA2B,MAAM,KAAK,CAAC,6BAA6B,MAAM;AAAA,EACzF;AAEA,MAAI,mBAAmB,SAAS,GAAG;AAE/B,UAAM,QAAQ,IAAI,MAAM,0DAA0D;AAClF,UAAM,OAAO;AACb,UAAM;AAAA,EACV;AACJ","sourcesContent":["import { Address } from '@solana/addresses';\n\nimport { MessageSigner } from './message-signer';\nimport { TransactionSigner } from './transaction-signer';\n\n/** Removes all duplicated signers from a provided array by comparing their addresses. */\nexport function deduplicateSigners<TSigner extends MessageSigner | TransactionSigner>(\n signers: readonly TSigner[]\n): readonly TSigner[] {\n const deduplicated: Record<Address, TSigner> = {};\n signers.forEach(signer => {\n if (!deduplicated[signer.address]) {\n deduplicated[signer.address] = signer;\n } else if (deduplicated[signer.address] !== signer) {\n // TODO: Coded error.\n throw new Error(\n `Multiple distinct signers were identified for address \"${signer.address}\". ` +\n `Please ensure that you are using the same signer instance for each address.`\n );\n }\n });\n return Object.values(deduplicated);\n}\n","import { AccountRole, IAccountLookupMeta, IAccountMeta, IInstruction } from '@solana/instructions';\nimport { BaseTransaction, TransactionVersion } from '@solana/transactions';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { TransactionSigner } from './transaction-signer';\n\n/** An extension of the IAccountMeta type that keeps track of its transaction signer. */\nexport interface IAccountSignerMeta<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner\n> extends IAccountMeta<TAddress> {\n readonly role: AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER;\n readonly signer: TSigner;\n}\n\ntype IAccountMetaWithWithSigner<TSigner extends TransactionSigner = TransactionSigner> =\n | IAccountMeta\n | IAccountLookupMeta\n | IAccountSignerMeta<string, TSigner>;\n\n/** A variation of the instruction type that allows IAccountSignerMeta in its account metas. */\nexport type IInstructionWithSigners<\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly IAccountMetaWithWithSigner<TSigner>[] = readonly IAccountMetaWithWithSigner<TSigner>[]\n> = Pick<IInstruction<string, TAccounts>, 'accounts'>;\n\n/** A variation of the transaction type that allows IAccountSignerMeta in its account metas. */\nexport type ITransactionWithSigners<\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly IAccountMetaWithWithSigner<TSigner>[] = readonly IAccountMetaWithWithSigner<TSigner>[]\n> = Pick<\n BaseTransaction<TransactionVersion, IInstruction & IInstructionWithSigners<TSigner, TAccounts>>,\n 'instructions'\n>;\n\n/** Extract all signers from an instruction that may contain IAccountSignerMeta accounts. */\nexport function getSignersFromInstruction<TSigner extends TransactionSigner = TransactionSigner>(\n instruction: IInstructionWithSigners<TSigner>\n): readonly TSigner[] {\n return deduplicateSigners(\n (instruction.accounts ?? []).flatMap(account => ('signer' in account ? account.signer : []))\n );\n}\n\n/** Extract all signers from a transaction that may contain IAccountSignerMeta accounts. */\nexport function getSignersFromTransaction<\n TSigner extends TransactionSigner = TransactionSigner,\n TTransaction extends ITransactionWithSigners<TSigner> = ITransactionWithSigners<TSigner>\n>(transaction: TTransaction): readonly TSigner[] {\n return deduplicateSigners(transaction.instructions.flatMap(getSignersFromInstruction));\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 { IInstruction, isSignerRole } from '@solana/instructions';\nimport { BaseTransaction } from '@solana/transactions';\n\nimport { IAccountSignerMeta, IInstructionWithSigners, ITransactionWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { TransactionSigner } from './transaction-signer';\n\n/** Attaches the provided signers to the account metas of an instruction when applicable. */\nexport function addSignersToInstruction<TInstruction extends IInstruction>(\n signers: TransactionSigner[],\n instruction: TInstruction | (TInstruction & IInstructionWithSigners)\n): TInstruction & IInstructionWithSigners {\n if (!instruction.accounts || instruction.accounts.length === 0) {\n return instruction as TInstruction & IInstructionWithSigners;\n }\n\n const signerByAddress = new Map(deduplicateSigners(signers).map(signer => [signer.address, signer]));\n return Object.freeze({\n ...instruction,\n accounts: instruction.accounts.map(account => {\n const signer = signerByAddress.get(account.address);\n if (!isSignerRole(account.role) || 'signer' in account || !signer) {\n return account;\n }\n return Object.freeze({ ...account, signer } as IAccountSignerMeta);\n }),\n });\n}\n\n/** Attaches the provided signers to the account metas of a transaction when applicable. */\nexport function addSignersToTransaction<TTransaction extends BaseTransaction>(\n signers: TransactionSigner[],\n transaction: TTransaction | (TTransaction & ITransactionWithSigners)\n): TTransaction & ITransactionWithSigners {\n if (transaction.instructions.length === 0) {\n return transaction as TTransaction & ITransactionWithSigners;\n }\n\n return Object.freeze({\n ...transaction,\n instructions: transaction.instructions.map(instruction => addSignersToInstruction(signers, instruction)),\n });\n}\n","import { CodecData } from './codec';\n\n/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n\n/**\n * Asserts that a given codec is fixed-size codec.\n */\nexport function assertFixedSizeCodec(\n data: Pick<CodecData, 'fixedSize'>,\n message?: string\n): asserts data is { fixedSize: number } {\n if (data.fixedSize === null) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","import { 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 { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (config: NumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'f32',\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (config: NumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n size: 4,\n });\n\nexport const getF32Codec = (config: NumberCodecConfig = {}): Codec<number> =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n CodecData,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig, SingleByteNumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput = {\n name: string;\n size: number;\n config: SingleByteNumberCodecConfig | NumberCodecConfig;\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.config) || input.config.endian === Endian.LITTLE;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.config.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 { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI64Encoder = (config: NumberCodecConfig = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n config,\n name: 'i64',\n range: [-BigInt('0x7fffffffffffffff') - 1n, BigInt('0x7fffffffffffffff')],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8,\n });\n\nexport const getI64Decoder = (config: NumberCodecConfig = {}): Decoder<bigint> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n size: 8,\n });\n\nexport const getI64Codec = (config: NumberCodecConfig = {}): Codec<number | bigint, bigint> =>\n combineCodec(getI64Encoder(config), getI64Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { SingleByteNumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI8Encoder = (config: SingleByteNumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'i8',\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, value),\n size: 1,\n });\n\nexport const getI8Decoder = (config: SingleByteNumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: view => view.getInt8(0),\n name: 'i8',\n size: 1,\n });\n\nexport const getI8Codec = (config: SingleByteNumberCodecConfig = {}): Codec<number> =>\n combineCodec(getI8Encoder(config), getI8Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (config: NumberCodecConfig = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n config,\n name: 'u128',\n range: [0, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\nexport const getU128Decoder = (config: NumberCodecConfig = {}): Decoder<bigint> =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n size: 16,\n });\n\nexport const getU128Codec = (config: NumberCodecConfig = {}): Codec<number | bigint, bigint> =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (config: NumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'u16',\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, value, le),\n size: 2,\n });\n\nexport const getU16Decoder = (config: NumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n size: 2,\n });\n\nexport const getU16Codec = (config: NumberCodecConfig = {}): Codec<number> =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import { 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 BaseCodecConfig,\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 config for string codecs. */\nexport type StringCodecConfig<\n TPrefix extends NumberCodec | NumberEncoder | NumberDecoder,\n TEncoding extends Codec<string> | Encoder<string> | Decoder<string>\n> = BaseCodecConfig & {\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 = (config: StringCodecConfig<NumberEncoder, Encoder<string>> = {}): Encoder<string> => {\n const size = config.size ?? getU32Encoder();\n const encoding = config.encoding ?? getUtf8Encoder();\n const description = config.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 = (config: StringCodecConfig<NumberDecoder, Decoder<string>> = {}): Decoder<string> => {\n const size = config.size ?? getU32Decoder();\n const encoding = config.encoding ?? getUtf8Decoder();\n const description = config.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 = (config: StringCodecConfig<NumberCodec, Codec<string>> = {}): Codec<string> =>\n combineCodec(getStringEncoder(config), getStringDecoder(config));\n\nfunction getSizeDescription(size: CodecData | number | 'variable'): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from 'text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/** Encodes UTF-8 strings using the native `TextEncoder` API. */\nexport const getUtf8Encoder = (): Encoder<string> => {\n let textEncoder: TextEncoder;\n return {\n description: 'utf8',\n encode: (value: string) => new Uint8Array((textEncoder ||= new TextEncoder()).encode(value)),\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes UTF-8 strings using the native `TextDecoder` API. */\nexport const getUtf8Decoder = (): Decoder<string> => {\n let textDecoder: TextDecoder;\n return {\n decode(bytes, offset = 0) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes UTF-8 strings using the native `TextEncoder` and `TextDecoder` API. */\nexport const getUtf8Codec = (): Codec<string> => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapEncoder } from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nexport type Address<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\nexport function isAddress(putativeAddress: string): putativeAddress is Address<typeof putativeAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address<typeof putativeAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function address<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address<TAddress>;\n}\n\nexport function getAddressEncoder(config?: Readonly<{ description: string }>): Encoder<Address> {\n return mapEncoder(\n getStringEncoder({\n description: config?.description ?? 'Address',\n encoding: getMemoizedBase58Encoder(),\n size: 32,\n }),\n putativeAddress => address(putativeAddress)\n );\n}\n\nexport function getAddressDecoder(config?: Readonly<{ description: string }>): Decoder<Address> {\n return getStringDecoder({\n description: config?.description ?? 'Address',\n encoding: getMemoizedBase58Decoder(),\n size: 32,\n }) as Decoder<Address>;\n}\n\nexport function getAddressCodec(config?: Readonly<{ description: string }>): Codec<Address> {\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 { Address, assertIsAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve';\n\n/**\n * An address derived from a program address and a set of seeds.\n * It includes the bump seed used to derive the address and\n * ensure the address is not on the Ed25519 curve.\n */\nexport type ProgramDerivedAddress<TAddress extends string = string> = Readonly<\n [Address<TAddress>, ProgramDerivedAddressBump]\n>;\n\n/**\n * A number between 0 and 255, inclusive.\n */\nexport type ProgramDerivedAddressBump = number & {\n readonly __brand: unique symbol;\n};\n\n/**\n * Returns true if the input value is a program derived address.\n */\nexport function isProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): value is ProgramDerivedAddress<TAddress> {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * Fails if the input value is not a program derived address.\n */\nexport function assertIsProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): asserts value is ProgramDerivedAddress<TAddress> {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n // TODO: Coded error.\n throw new Error(\n `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n // TODO: Coded error.\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Address;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Address;\n programAddress: Address;\n seed: Seed;\n}>;\n\ntype Seed = string | Uint8Array;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\n// TODO: Coded error.\nclass PointOnCurveError extends Error {}\n\nasync function createProgramDerivedAddress({ programAddress, seeds }: ProgramDerivedAddressInput): Promise<Address> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n // TODO: Coded error.\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n // TODO: Coded error.\n throw new PointOnCurveError('Invalid seeds; point must fall off the Ed25519 curve');\n }\n return base58EncodedAddressCodec.decode(addressBytes)[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({ baseAddress, programAddress, seed }: SeedInput): Promise<Address> {\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])\n ) {\n // TODO: Coded error.\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes)[0];\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Address, getAddressDecoder } from './address';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Address> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n","import { assertKeyGenerationIsAvailable } from '@solana/assertions';\n\nexport async function generateKeyPair(): Promise<CryptoKeyPair> {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ 'Ed25519', // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify']\n );\n return keyPair as CryptoKeyPair;\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n","/** Returns the max size or null if at least one size is null. */\nexport function maxCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : Math.max(all, size)),\n 0 as number | null\n );\n}\n\n/** Returns the sum of all sizes or null if at least one size is null. */\nexport function sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n","import { CodecData, Offset } from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { sumCodecSizes } from './utils';\n\n/**\n * Represents all the size options for array-like codecs\n * — i.e. `array`, `map` and `set`.\n *\n * It can be one of the following:\n * - a {@link NumberCodec} that prefixes its content with its size.\n * - a fixed number of items.\n * - or `'remainder'` to infer the number of items by dividing\n * the rest of the byte array by the fixed size of its item.\n * Note that this option is only available for fixed-size items.\n */\nexport type ArrayLikeCodecSize<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder | CodecData> =\n | TPrefix\n | number\n | 'remainder';\n\n/** Resolves the size of an array-like codec. */\nexport function decodeArrayLikeCodecSize(\n size: ArrayLikeCodecSize<NumberDecoder>,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: Offset\n): [number | bigint, Offset] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.decode(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumCodecSizes(childrenSizes);\n if (childrenSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n // TODO: Coded error.\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${childrenSize} bytes. ` +\n `Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainder} modulo ${childrenSize} should be equal to zero.`\n );\n }\n return [remainder / childrenSize, offset];\n }\n\n // TODO: Coded error.\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\n\nexport function getArrayLikeCodecSizeDescription(size: ArrayLikeCodecSize<CodecData>): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getArrayLikeCodecSizeFromChildren(\n size: ArrayLikeCodecSize<CodecData>,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumCodecSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getArrayLikeCodecSizePrefix(size: ArrayLikeCodecSize<NumberEncoder>, realSize: number): Uint8Array {\n return typeof size === 'object' ? size.encode(realSize) : new Uint8Array();\n}\n","/** Checks the number of items in an array-like structure is expected. */\nexport function assertValidNumberOfItemsForCodec(\n codecDescription: string,\n expected: number | bigint,\n actual: number | bigint\n) {\n if (expected !== actual) {\n // TODO: Coded error.\n throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);\n }\n}\n","import { BaseCodecConfig, Codec, CodecData, combineCodec, Decoder, Encoder, mergeBytes } from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport {\n ArrayLikeCodecSize,\n decodeArrayLikeCodecSize,\n getArrayLikeCodecSizeDescription,\n getArrayLikeCodecSizeFromChildren,\n getArrayLikeCodecSizePrefix,\n} from './array-like-codec-size';\nimport { assertValidNumberOfItemsForCodec } from './assertions';\n\n/** Defines the configs for array codecs. */\nexport type ArrayCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The size of the array.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\n};\n\nfunction arrayCodecHelper(item: CodecData, size: ArrayLikeCodecSize<CodecData>, description?: string): CodecData {\n if (size === 'remainder' && item.fixedSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n return {\n description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize]),\n };\n}\n\n/**\n * Encodes an array of items.\n *\n * @param item - The encoder to use for the array's items.\n * @param config - A set of config for the encoder.\n */\nexport function getArrayEncoder<T>(item: Encoder<T>, config: ArrayCodecConfig<NumberEncoder> = {}): Encoder<T[]> {\n const size = config.size ?? getU32Encoder();\n return {\n ...arrayCodecHelper(item, size, config.description),\n encode: (value: T[]) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, value.length);\n }\n return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map(v => item.encode(v))]);\n },\n };\n}\n\n/**\n * Decodes an array of items.\n *\n * @param item - The encoder to use for the array's items.\n * @param config - A set of config for the encoder.\n */\nexport function getArrayDecoder<T>(item: Decoder<T>, config: ArrayCodecConfig<NumberDecoder> = {}): Decoder<T[]> {\n const size = config.size ?? getU32Decoder();\n return {\n ...arrayCodecHelper(item, size, config.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n const values: T[] = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.decode(bytes, offset);\n values.push(value);\n offset = newOffset;\n }\n return [values, offset];\n },\n };\n}\n\n/**\n * Creates a codec for an array of items.\n *\n * @param item - The codec to use for the array's items.\n * @param config - A set of config for the codec.\n */\nexport function getArrayCodec<T, U extends T = T>(\n item: Codec<T, U>,\n config: ArrayCodecConfig<NumberCodec> = {}\n): Codec<T[], U[]> {\n return combineCodec(getArrayEncoder(item, config), getArrayDecoder(item, config));\n}\n","import {\n assertByteArrayIsNotEmptyForCodec,\n assertFixedSizeCodec,\n BaseCodecConfig,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/** Defines the config for boolean codecs. */\nexport type BooleanCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The number codec to delegate to.\n * @defaultValue u8 size.\n */\n size?: TSize;\n};\n\n/**\n * Encodes booleans.\n *\n * @param config - A set of config for the encoder.\n */\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder> = {}): Encoder<boolean> {\n const size = config.size ?? getU8Encoder();\n assertFixedSizeCodec(size, 'Codec [bool] requires a fixed size.');\n\n return {\n description: config.description ?? `bool(${size.description})`,\n encode: (value: boolean) => size.encode(value ? 1 : 0),\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize,\n };\n}\n\n/**\n * Decodes booleans.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder> = {}): Decoder<boolean> {\n const size = config.size ?? getU8Decoder();\n assertFixedSizeCodec(size, 'Codec [bool] requires a fixed size.');\n\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('bool', bytes, offset);\n const [value, vOffset] = size.decode(bytes, offset);\n return [value === 1, vOffset];\n },\n description: config.description ?? `bool(${size.description})`,\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize,\n };\n}\n\n/**\n * Creates a boolean codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec> = {}): Codec<boolean> {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecConfig,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n fixDecoder,\n fixEncoder,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/** Defines the config for bytes codecs. */\nexport type BytesCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The size of the byte array. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the byte array with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the byte array.\n * @defaultValue `'variable'`\n */\n size?: TSize | number | 'variable';\n};\n\n/**\n * Encodes sized bytes.\n *\n * @param config - A set of config for the encoder.\n */\nexport function getBytesEncoder(config: BytesCodecConfig<NumberEncoder> = {}): Encoder<Uint8Array> {\n const size = config.size ?? 'variable';\n const sizeDescription = typeof size === 'object' ? size.description : `${size}`;\n const description = config.description ?? `bytes(${sizeDescription})`;\n\n const byteEncoder: Encoder<Uint8Array> = {\n description,\n encode: (value: Uint8Array) => value,\n fixedSize: null,\n maxSize: null,\n };\n\n if (size === 'variable') {\n return byteEncoder;\n }\n\n if (typeof size === 'number') {\n return fixEncoder(byteEncoder, size, description);\n }\n\n return {\n ...byteEncoder,\n encode: (value: Uint8Array) => {\n const contentBytes = byteEncoder.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n };\n}\n\n/**\n * Decodes sized bytes.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBytesDecoder(config: BytesCodecConfig<NumberDecoder> = {}): Decoder<Uint8Array> {\n const size = config.size ?? 'variable';\n const sizeDescription = typeof size === 'object' ? size.description : `${size}`;\n const description = config.description ?? `bytes(${sizeDescription})`;\n\n const byteDecoder: Decoder<Uint8Array> = {\n decode: (bytes: Uint8Array, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n description,\n fixedSize: null,\n maxSize: null,\n };\n\n if (size === 'variable') {\n return byteDecoder;\n }\n\n if (typeof size === 'number') {\n return fixDecoder(byteDecoder, size, description);\n }\n\n return {\n ...byteDecoder,\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('bytes', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec('bytes', length, contentBytes);\n const [value, contentOffset] = byteDecoder.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n\n/**\n * Creates a sized bytes codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBytesCodec(config: BytesCodecConfig<NumberCodec> = {}): Codec<Uint8Array> {\n return combineCodec(getBytesEncoder(config), getBytesDecoder(config));\n}\n","import {\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecConfig,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/**\n * Defines a scalar enum as a type from its constructor.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionType = ScalarEnum<Direction>;\n * ```\n */\nexport type ScalarEnum<T> = ({ [key: number | string]: string | number | T } | number | T) & NonNullable<unknown>;\n\n/** Defines the config for scalar enum codecs. */\nexport type ScalarEnumCodecConfig<TDiscriminator extends NumberCodec | NumberEncoder | NumberDecoder> =\n BaseCodecConfig & {\n /**\n * The codec to use for the enum discriminator.\n * @defaultValue u8 discriminator.\n */\n size?: TDiscriminator;\n };\n\nfunction scalarEnumCoderHelper<T>(\n constructor: ScalarEnum<T>,\n prefix: CodecData,\n description?: string\n): CodecData & {\n enumKeys: string[];\n enumValues: T[];\n isNumericEnum: boolean;\n minRange: number;\n maxRange: number;\n stringValues: string[];\n} {\n const enumKeys = Object.keys(constructor);\n const enumValues = Object.values(constructor);\n const isNumericEnum = enumValues.some(v => typeof v === 'number');\n const valueDescriptions = enumValues.filter(v => typeof v === 'string').join(', ');\n const minRange = 0;\n const maxRange = isNumericEnum ? enumValues.length / 2 - 1 : enumValues.length - 1;\n const stringValues: string[] = isNumericEnum ? [...enumKeys] : [...new Set([...enumKeys, ...enumValues])];\n\n return {\n description: description ?? `enum(${valueDescriptions}; ${prefix.description})`,\n enumKeys,\n enumValues,\n fixedSize: prefix.fixedSize,\n isNumericEnum,\n maxRange,\n maxSize: prefix.maxSize,\n minRange,\n stringValues,\n };\n}\n\n/**\n * Creates a scalar enum encoder.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param config - A set of config for the encoder.\n */\nexport function getScalarEnumEncoder<T>(\n constructor: ScalarEnum<T>,\n config: ScalarEnumCodecConfig<NumberEncoder> = {}\n): Encoder<T> {\n const prefix = config.size ?? getU8Encoder();\n const { description, fixedSize, maxSize, minRange, maxRange, stringValues, enumKeys, enumValues } =\n scalarEnumCoderHelper(constructor, prefix, config.description);\n return {\n description,\n encode: (value: T) => {\n const isInvalidNumber = typeof value === 'number' && (value < minRange || value > maxRange);\n const isInvalidString = typeof value === 'string' && !stringValues.includes(value);\n if (isInvalidNumber || isInvalidString) {\n // TODO: Coded error.\n throw new Error(\n `Invalid scalar enum variant. ` +\n `Expected one of [${stringValues.join(', ')}] ` +\n `or a number between ${minRange} and ${maxRange}, ` +\n `got \"${value}\".`\n );\n }\n if (typeof value === 'number') return prefix.encode(value);\n const valueIndex = enumValues.indexOf(value);\n if (valueIndex >= 0) return prefix.encode(valueIndex);\n return prefix.encode(enumKeys.indexOf(value as string));\n },\n fixedSize,\n maxSize,\n };\n}\n\n/**\n * Creates a scalar enum decoder.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param config - A set of config for the decoder.\n */\nexport function getScalarEnumDecoder<T>(\n constructor: ScalarEnum<T>,\n config: ScalarEnumCodecConfig<NumberDecoder> = {}\n): Decoder<T> {\n const prefix = config.size ?? getU8Decoder();\n const { description, fixedSize, maxSize, minRange, maxRange, isNumericEnum, enumValues } = scalarEnumCoderHelper(\n constructor,\n prefix,\n config.description\n );\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('enum', bytes, offset);\n const [value, newOffset] = prefix.decode(bytes, offset);\n const valueAsNumber = Number(value);\n offset = newOffset;\n if (valueAsNumber < minRange || valueAsNumber > maxRange) {\n // TODO: Coded error.\n throw new Error(\n `Enum discriminator out of range. ` +\n `Expected a number between ${minRange} and ${maxRange}, got ${valueAsNumber}.`\n );\n }\n return [(isNumericEnum ? valueAsNumber : enumValues[valueAsNumber]) as T, offset];\n },\n description,\n fixedSize,\n maxSize,\n };\n}\n\n/**\n * Creates a scalar enum codec.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param config - A set of config for the codec.\n */\nexport function getScalarEnumCodec<T>(\n constructor: ScalarEnum<T>,\n config: ScalarEnumCodecConfig<NumberCodec> = {}\n): Codec<T> {\n return combineCodec(getScalarEnumEncoder(constructor, config), getScalarEnumDecoder(constructor, config));\n}\n","import { BaseCodecConfig, Codec, CodecData, combineCodec, Decoder, Encoder, mergeBytes } from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport {\n ArrayLikeCodecSize,\n decodeArrayLikeCodecSize,\n getArrayLikeCodecSizeDescription,\n getArrayLikeCodecSizeFromChildren,\n getArrayLikeCodecSizePrefix,\n} from './array-like-codec-size';\nimport { assertValidNumberOfItemsForCodec } from './assertions';\n\n/** Defines the config for set codecs. */\nexport type SetCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The size of the set.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\n};\n\nfunction setCodecHelper(item: CodecData, size: ArrayLikeCodecSize<CodecData>, description?: string): CodecData {\n if (size === 'remainder' && item.fixedSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n return {\n description: description ?? `set(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize]),\n };\n}\n\n/**\n * Encodes an set of items.\n *\n * @param item - The encoder to use for the set's items.\n * @param config - A set of config for the encoder.\n */\nexport function getSetEncoder<T>(item: Encoder<T>, config: SetCodecConfig<NumberEncoder> = {}): Encoder<Set<T>> {\n const size = config.size ?? getU32Encoder();\n return {\n ...setCodecHelper(item, size, config.description),\n encode: (set: Set<T>) => {\n if (typeof size === 'number' && set.size !== size) {\n assertValidNumberOfItemsForCodec('set', size, set.size);\n }\n const itemBytes = Array.from(set, value => item.encode(value));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, set.size), ...itemBytes]);\n },\n };\n}\n\n/**\n * Decodes an set of items.\n *\n * @param item - The encoder to use for the set's items.\n * @param config - A set of config for the encoder.\n */\nexport function getSetDecoder<T>(item: Decoder<T>, config: SetCodecConfig<NumberDecoder> = {}): Decoder<Set<T>> {\n const size = config.size ?? getU32Decoder();\n return {\n ...setCodecHelper(item, size, config.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n const set: Set<T> = new Set();\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [set, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n set.add(value);\n }\n return [set, offset];\n },\n };\n}\n\n/**\n * Creates a codec for an set of items.\n *\n * @param item - The codec to use for the set's items.\n * @param config - A set of config for the codec.\n */\nexport function getSetCodec<T, U extends T = T>(\n item: Codec<T, U>,\n config: SetCodecConfig<NumberCodec> = {}\n): Codec<Set<T>, Set<U>> {\n return combineCodec(getSetEncoder(item, config), getSetDecoder(item, config));\n}\n","import { getBase58Encoder, getBase58Decoder, getBase64Decoder, getStringEncoder, getStringDecoder } from '@solana/codecs-strings';\nimport { getAddressFromPublicKey, getAddressComparator, getAddressEncoder, getAddressDecoder, assertIsAddress } from '@solana/addresses';\nimport { mapDecoder, combineCodec, mapEncoder } from '@solana/codecs-core';\nimport { getStructDecoder, getStructEncoder, getArrayEncoder, getArrayDecoder, getBytesEncoder, getBytesDecoder } from '@solana/codecs-data-structures';\nimport { getShortU16Encoder, getShortU16Decoder, getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';\nimport { pipe } from '@solana/functional';\nimport { signBytes } from '@solana/keys';\n\n// ../build-scripts/env-shim.ts\nvar __DEV__ = /* @__PURE__ */ (() => process[\"env\"].NODE_ENV === \"development\")();\n\n// src/unsigned-transaction.ts\nfunction getUnsignedTransaction(transaction) {\n if (\"signatures\" in transaction) {\n const {\n signatures: _,\n // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n\n// src/blockhash.ts\nvar base58Encoder;\nfunction assertIsBlockhash(putativeBlockhash) {\n if (!base58Encoder)\n base58Encoder = getBase58Encoder();\n try {\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 || // Highest value (32 bytes of 255)\n putativeBlockhash.length > 44\n ) {\n throw new Error(\"Expected input string to decode to a byte array of length 32.\");\n }\n const 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}\nfunction setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) {\n if (\"lifetimeConstraint\" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n lifetimeConstraint: blockhashLifetimeConstraint\n };\n Object.freeze(out);\n return out;\n}\n\n// src/create-transaction.ts\nfunction createTransaction({\n version\n}) {\n const out = {\n instructions: [],\n version\n };\n Object.freeze(out);\n return out;\n}\n\n// ../instructions/dist/index.browser.js\nvar AccountRole = /* @__PURE__ */ ((AccountRole2) => {\n AccountRole2[AccountRole2[\"WRITABLE_SIGNER\"] = /* 3 */\n 3] = \"WRITABLE_SIGNER\";\n AccountRole2[AccountRole2[\"READONLY_SIGNER\"] = /* 2 */\n 2] = \"READONLY_SIGNER\";\n AccountRole2[AccountRole2[\"WRITABLE\"] = /* 1 */\n 1] = \"WRITABLE\";\n AccountRole2[AccountRole2[\"READONLY\"] = /* 0 */\n 0] = \"READONLY\";\n return AccountRole2;\n})(AccountRole || {});\nvar IS_WRITABLE_BITMASK = 1;\nfunction isSignerRole(role) {\n return role >= 2;\n}\nfunction isWritableRole(role) {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\nfunction mergeRoles(roleA, roleB) {\n return roleA | roleB;\n}\n\n// src/durable-nonce.ts\nvar RECENT_BLOCKHASHES_SYSVAR_ADDRESS = \"SysvarRecentB1ockHashes11111111111111111111\";\nvar SYSTEM_PROGRAM_ADDRESS = \"11111111111111111111111111111111\";\nfunction assertIsDurableNonceTransaction(transaction) {\n if (!isDurableNonceTransaction(transaction)) {\n throw new Error(\"Transaction is not a durable nonce transaction\");\n }\n}\nfunction createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) {\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]),\n programAddress: SYSTEM_PROGRAM_ADDRESS\n };\n}\nfunction isAdvanceNonceAccountInstruction(instruction) {\n return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts\n instruction.accounts?.length === 3 && // First account is nonce account address\n instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account\n instruction.accounts[2].address != null && isSignerRole(instruction.accounts[2].role);\n}\nfunction isAdvanceNonceAccountInstructionData(data) {\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\nfunction isDurableNonceTransaction(transaction) {\n return \"lifetimeConstraint\" in transaction && typeof transaction.lifetimeConstraint.nonce === \"string\" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);\n}\nfunction isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {\n return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;\n}\nfunction setTransactionLifetimeUsingDurableNonce({\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress\n}, transaction) {\n let newInstructions;\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;\n } else {\n newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];\n }\n } else {\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions.slice(1)\n ];\n }\n } else {\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions\n ];\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: newInstructions,\n lifetimeConstraint: {\n nonce\n }\n };\n Object.freeze(out);\n return out;\n}\n\n// src/fee-payer.ts\nfunction setTransactionFeePayer(feePayer, transaction) {\n if (\"feePayer\" in transaction && feePayer === transaction.feePayer) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n feePayer\n };\n Object.freeze(out);\n return out;\n}\n\n// src/instructions.ts\nfunction appendTransactionInstruction(instruction, transaction) {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [...transaction.instructions, instruction]\n };\n Object.freeze(out);\n return out;\n}\nfunction prependTransactionInstruction(instruction, transaction) {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [instruction, ...transaction.instructions]\n };\n Object.freeze(out);\n return out;\n}\nfunction upsert(addressMap, address, update) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\nvar TYPE = Symbol(\"AddressMapTypeProperty\");\nfunction getAddressMapFromInstructions(feePayer, instructions) {\n const addressMap = {\n [feePayer]: { [TYPE]: 0 /* FEE_PAYER */, role: AccountRole.WRITABLE_SIGNER }\n };\n const addressesOfInvokedPrograms = /* @__PURE__ */ new Set();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, (entry) => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case 0 /* FEE_PAYER */:\n throw new Error(\n `This transaction includes an address (\\`${instruction.programAddress}\\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`\n );\n default:\n throw new Error(\n `This transaction includes an address (\\`${instruction.programAddress}\\`) which is both invoked and marked writable. Program addresses may not be writable.`\n );\n }\n }\n if (entry[TYPE] === 2 /* STATIC */) {\n return entry;\n }\n }\n return { [TYPE]: 2 /* STATIC */, role: AccountRole.READONLY };\n });\n let addressComparator;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, (entry) => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case 0 /* FEE_PAYER */:\n return entry;\n case 1 /* LOOKUP_TABLE */: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\"lookupTableAddress\" in accountMeta) {\n const shouldReplaceEntry = (\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress\n ) < 0\n );\n if (shouldReplaceEntry) {\n return {\n [TYPE]: 1 /* LOOKUP_TABLE */,\n ...accountMeta,\n role: nextRole\n };\n }\n } else if (isSignerRole(accountMeta.role)) {\n return {\n [TYPE]: 2 /* STATIC */,\n role: nextRole\n };\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole\n };\n } else {\n return entry;\n }\n }\n case 2 /* STATIC */: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n throw new Error(\n `This transaction includes an address (\\`${account.address}\\`) which is both invoked and marked writable. Program addresses may not be writable.`\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole\n };\n } else {\n return entry;\n }\n } else if (\"lookupTableAddress\" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)) {\n return {\n ...accountMeta,\n [TYPE]: 1 /* LOOKUP_TABLE */,\n role: nextRole\n };\n } else {\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole\n };\n } else {\n return entry;\n }\n }\n }\n }\n }\n if (\"lookupTableAddress\" in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: 1 /* LOOKUP_TABLE */\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: 2 /* STATIC */\n };\n }\n });\n }\n }\n return addressMap;\n}\nfunction getOrderedAccountsFromAddressMap(addressMap) {\n let addressComparator;\n const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === 0 /* FEE_PAYER */) {\n return -1;\n } else if (rightEntry[TYPE] === 0 /* FEE_PAYER */) {\n return 1;\n } else if (leftEntry[TYPE] === 2 /* STATIC */) {\n return -1;\n } else if (rightEntry[TYPE] === 2 /* STATIC */) {\n return 1;\n }\n }\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n addressComparator ||= getAddressComparator();\n if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n }).map(([address, addressMeta]) => ({\n address,\n ...addressMeta\n }));\n return orderedAccounts;\n}\nfunction getCompiledAddressTableLookups(orderedAccounts) {\n const index = {};\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).sort(getAddressComparator()).map((lookupTableAddress) => ({\n lookupTableAddress,\n ...index[lookupTableAddress]\n }));\n}\n\n// src/compile-header.ts\nfunction getCompiledMessageHeader(orderedAccounts) {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if (\"lookupTableAddress\" in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts\n };\n}\n\n// src/compile-instructions.ts\nfunction getAccountIndex(orderedAccounts) {\n const out = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\nfunction getCompiledInstructions(instructions, orderedAccounts) {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null,\n ...data ? { data } : null\n };\n });\n}\n\n// src/compile-lifetime-token.ts\nfunction getCompiledLifetimeToken(lifetimeConstraint) {\n if (\"nonce\" in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n\n// src/compile-static-accounts.ts\nfunction getCompiledStaticAccounts(orderedAccounts) {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => \"lookupTableAddress\" in account);\n const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n\n// src/message.ts\nfunction compileMessage(transaction) {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...transaction.version !== \"legacy\" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null,\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),\n lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transaction.version\n };\n}\nvar lookupTableAddressDescription = __DEV__ ? \"The address of the address lookup table account from which instruction addresses should be looked up\" : \"lookupTableAddress\";\nvar writableIndicesDescription = __DEV__ ? \"The indices of the accounts in the lookup table that should be loaded as writeable\" : \"writableIndices\";\nvar readableIndicesDescription = __DEV__ ? \"The indices of the accounts in the lookup table that should be loaded as read-only\" : \"readableIndices\";\nvar addressTableLookupDescription = __DEV__ ? \"A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it\" : \"addressTableLookup\";\nvar memoizedAddressTableLookupEncoder;\nfunction getAddressTableLookupEncoder() {\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 })\n ],\n [\n \"readableIndices\",\n getArrayEncoder(getU8Encoder(), {\n description: readableIndicesDescription,\n size: getShortU16Encoder()\n })\n ]\n ],\n { description: addressTableLookupDescription }\n );\n }\n return memoizedAddressTableLookupEncoder;\n}\nvar memoizedAddressTableLookupDecoder;\nfunction getAddressTableLookupDecoder() {\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 return memoizedAddressTableLookupDecoder;\n}\nvar memoizedU8Encoder;\nfunction getMemoizedU8Encoder() {\n if (!memoizedU8Encoder)\n memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\nfunction getMemoizedU8EncoderDescription(description) {\n const encoder = getMemoizedU8Encoder();\n return {\n ...encoder,\n description: description ?? encoder.description\n };\n}\nvar memoizedU8Decoder;\nfunction getMemoizedU8Decoder() {\n if (!memoizedU8Decoder)\n memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\nfunction getMemoizedU8DecoderDescription(description) {\n const decoder = getMemoizedU8Decoder();\n return {\n ...decoder,\n description: description ?? decoder.description\n };\n}\nvar numSignerAccountsDescription = __DEV__ ? \"The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction\" : void 0;\nvar numReadonlySignerAccountsDescription = __DEV__ ? \"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\" : void 0;\nvar numReadonlyNonSignerAccountsDescription = __DEV__ ? \"The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable\" : void 0;\nvar messageHeaderDescription = __DEV__ ? \"The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses\" : void 0;\nfunction getMessageHeaderEncoder() {\n return getStructEncoder(\n [\n [\"numSignerAccounts\", getMemoizedU8EncoderDescription(numSignerAccountsDescription)],\n [\"numReadonlySignerAccounts\", getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],\n [\"numReadonlyNonSignerAccounts\", getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)]\n ],\n {\n description: messageHeaderDescription\n }\n );\n}\nfunction getMessageHeaderDecoder() {\n return getStructDecoder(\n [\n [\"numSignerAccounts\", getMemoizedU8DecoderDescription(numSignerAccountsDescription)],\n [\"numReadonlySignerAccounts\", getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],\n [\"numReadonlyNonSignerAccounts\", getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)]\n ],\n {\n description: messageHeaderDescription\n }\n );\n}\nvar programAddressIndexDescription = __DEV__ ? \"The index of the program being called, according to the well-ordered accounts list for this transaction\" : \"programAddressIndex\";\nvar accountIndexDescription = __DEV__ ? \"The index of an account, according to the well-ordered accounts list for this transaction\" : void 0;\nvar accountIndicesDescription = __DEV__ ? \"An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them\" : \"accountIndices\";\nvar dataDescription = __DEV__ ? \"An optional buffer of data passed to the instruction\" : \"data\";\nvar memoizedGetInstructionEncoder;\nfunction getInstructionEncoder() {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = mapEncoder(\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) => {\n if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {\n return instruction;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0)\n };\n }\n );\n }\n return memoizedGetInstructionEncoder;\n}\nvar memoizedGetInstructionDecoder;\nfunction getInstructionDecoder() {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = mapDecoder(\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) => {\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}\nvar VERSION_FLAG_MASK = 128;\nvar BASE_CONFIG = {\n description: __DEV__ ? \"A single byte that encodes the version of the transaction\" : \"\",\n fixedSize: null,\n maxSize: 1\n};\nfunction decode(bytes, offset = 0) {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n return [\"legacy\", offset];\n } else {\n const version = firstByte ^ VERSION_FLAG_MASK;\n return [version, offset + 1];\n }\n}\nfunction encode(value) {\n if (value === \"legacy\") {\n return new Uint8Array();\n }\n if (value < 0 || value > 127) {\n throw new Error(`Transaction version must be in the range [0, 127]. \\`${value}\\` given.`);\n }\n return new Uint8Array([value | VERSION_FLAG_MASK]);\n}\nfunction getTransactionVersionDecoder() {\n return {\n ...BASE_CONFIG,\n decode\n };\n}\nfunction getTransactionVersionEncoder() {\n return {\n ...BASE_CONFIG,\n encode\n };\n}\n\n// src/serializers/message.ts\nvar staticAccountsDescription = __DEV__ ? \"A compact-array of static account addresses belonging to this transaction\" : \"staticAccounts\";\nvar lifetimeTokenDescription = __DEV__ ? \"A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)\" : \"lifetimeToken\";\nvar instructionsDescription = __DEV__ ? \"A compact-array of instructions belonging to this transaction\" : \"instructions\";\nvar addressTableLookupsDescription = __DEV__ ? \"A compact array of address table lookups belonging to this transaction\" : \"addressTableLookups\";\nfunction getCompiledMessageLegacyEncoder() {\n return getStructEncoder(getPreludeStructEncoderTuple());\n}\nfunction getCompiledMessageVersionedEncoder() {\n return mapEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n [\"addressTableLookups\", getAddressTableLookupArrayEncoder()]\n ]),\n (value) => {\n if (value.version === \"legacy\") {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? []\n };\n }\n );\n}\nfunction getPreludeStructEncoderTuple() {\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}\nfunction getPreludeStructDecoderTuple() {\n return [\n [\"version\", getTransactionVersionDecoder()],\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}\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Encoder()\n });\n}\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Decoder()\n });\n}\nvar messageDescription = __DEV__ ? \"The wire format of a Solana transaction message\" : \"message\";\nfunction getCompiledMessageEncoder() {\n return {\n description: messageDescription,\n encode: (compiledMessage) => {\n if (compiledMessage.version === \"legacy\") {\n return getCompiledMessageLegacyEncoder().encode(compiledMessage);\n } else {\n return getCompiledMessageVersionedEncoder().encode(compiledMessage);\n }\n },\n fixedSize: null,\n maxSize: null\n };\n}\nfunction getCompiledMessageDecoder() {\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 };\n }\n );\n}\nfunction getCompiledMessageCodec() {\n return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());\n}\n\n// src/compile-transaction.ts\nfunction getCompiledTransaction(transaction) {\n const compiledMessage = compileMessage(transaction);\n let signatures;\n if (\"signatures\" in transaction) {\n signatures = [];\n for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {\n signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));\n }\n } else {\n signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));\n }\n return {\n compiledMessage,\n signatures\n };\n}\nfunction getAccountMetas(message) {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n const accountMetas = [];\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 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 for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE\n });\n accountIndex++;\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 return accountMetas;\n}\nfunction convertInstruction(instruction, accountMetas) {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);\n }\n const accounts = instruction.accountIndices?.map((accountIndex) => accountMetas[accountIndex]);\n const { data } = instruction;\n return {\n programAddress,\n ...accounts && accounts.length ? { accounts } : {},\n ...data && data.length ? { data } : {}\n };\n}\nfunction getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n return {\n blockhash: messageLifetimeToken,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n\n // U64 MAX\n };\n } else {\n const nonceAccountAddress = firstInstruction.accounts[0].address;\n assertIsAddress(nonceAccountAddress);\n const nonceAuthorityAddress = firstInstruction.accounts[2].address;\n assertIsAddress(nonceAuthorityAddress);\n return {\n nonce: messageLifetimeToken,\n nonceAccountAddress,\n nonceAuthorityAddress\n };\n }\n}\nfunction convertSignatures(compiledTransaction) {\n const {\n compiledMessage: { staticAccounts },\n signatures\n } = compiledTransaction;\n return signatures.reduce((acc, sig, index) => {\n const allZeros = sig.every((byte) => byte === 0);\n if (allZeros)\n return acc;\n const address = staticAccounts[index];\n return { ...acc, [address]: sig };\n }, {});\n}\nfunction decompileTransaction(compiledTransaction, lastValidBlockHeight) {\n const { compiledMessage } = compiledTransaction;\n if (\"addressTableLookups\" in compiledMessage && compiledMessage.addressTableLookups.length > 0) {\n throw new Error(\"Cannot convert transaction with addressTableLookups\");\n }\n const feePayer = compiledMessage.staticAccounts[0];\n if (!feePayer)\n throw new Error(\"No fee payer set in CompiledTransaction\");\n const accountMetas = getAccountMetas(compiledMessage);\n const instructions = compiledMessage.instructions.map(\n (compiledInstruction) => convertInstruction(compiledInstruction, accountMetas)\n );\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledMessage.lifetimeToken,\n firstInstruction,\n lastValidBlockHeight\n );\n const signatures = convertSignatures(compiledTransaction);\n return pipe(\n createTransaction({ version: compiledMessage.version }),\n (tx) => setTransactionFeePayer(feePayer, tx),\n (tx) => instructions.reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n (tx) => \"blockhash\" in lifetimeConstraint ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx) : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),\n (tx) => compiledTransaction.signatures.length ? { ...tx, signatures } : tx\n );\n}\n\n// src/serializers/transaction.ts\nvar signaturesDescription = __DEV__ ? \"A compact array of 64-byte, base-64 encoded Ed25519 signatures\" : \"signatures\";\nvar transactionDescription = __DEV__ ? \"The wire format of a Solana transaction\" : \"transaction\";\nfunction getCompiledTransactionEncoder() {\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}\nfunction getSignatureDecoder() {\n return mapDecoder(getBytesDecoder({ size: 64 }), (bytes) => bytes);\n}\nfunction getCompiledTransactionDecoder() {\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}\nfunction getTransactionEncoder() {\n return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);\n}\nfunction getTransactionDecoder(lastValidBlockHeight) {\n return mapDecoder(\n getCompiledTransactionDecoder(),\n (compiledTransaction) => decompileTransaction(compiledTransaction, lastValidBlockHeight)\n );\n}\nfunction getTransactionCodec(lastValidBlockHeight) {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));\n}\nvar base58Decoder;\nfunction getSignatureFromTransaction(transaction) {\n if (!base58Decoder)\n base58Decoder = getBase58Decoder();\n const signatureBytes = transaction.signatures[transaction.feePayer];\n if (!signatureBytes) {\n throw new Error(\n \"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.\"\n );\n }\n const transactionSignature = base58Decoder.decode(signatureBytes)[0];\n return transactionSignature;\n}\nasync function partiallySignTransaction(keyPairs, transaction) {\n const compiledMessage = compileMessage(transaction);\n const nextSignatures = \"signatures\" in transaction ? { ...transaction.signatures } : {};\n const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);\n const publicKeySignaturePairs = await Promise.all(\n keyPairs.map(\n (keyPair) => 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}\nasync function signTransaction(keyPairs, transaction) {\n const out = await partiallySignTransaction(keyPairs, transaction);\n assertTransactionIsFullySigned(out);\n Object.freeze(out);\n return out;\n}\nfunction assertTransactionIsFullySigned(transaction) {\n const signerAddressesFromInstructions = transaction.instructions.flatMap((i) => i.accounts?.filter((a) => isSignerRole(a.role)) ?? []).map((a) => a.address);\n const requiredSigners = /* @__PURE__ */ new Set([transaction.feePayer, ...signerAddressesFromInstructions]);\n requiredSigners.forEach((address) => {\n if (!transaction.signatures[address]) {\n throw new Error(`Transaction is missing signature for address \\`${address}\\``);\n }\n });\n}\nfunction getBase64EncodedWireTransaction(transaction) {\n const wireTransactionBytes = getTransactionEncoder().encode(transaction);\n return getBase64Decoder().decode(wireTransactionBytes)[0];\n}\n\nexport { appendTransactionInstruction, assertIsBlockhash, assertIsDurableNonceTransaction, assertTransactionIsFullySigned, compileMessage, createTransaction, getBase64EncodedWireTransaction, getCompiledMessageCodec, getCompiledMessageDecoder, getCompiledMessageEncoder, getSignatureFromTransaction, getTransactionCodec, getTransactionDecoder, getTransactionEncoder, isAdvanceNonceAccountInstruction, partiallySignTransaction, prependTransactionInstruction, setTransactionFeePayer, setTransactionLifetimeUsingBlockhash, setTransactionLifetimeUsingDurableNonce, signTransaction };\n","import { Address } from '@solana/addresses';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig, SignatureDictionary } from './types';\n\nexport type MessagePartialSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing messages. */\nexport type MessagePartialSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n signMessages(\n messages: readonly SignableMessage[],\n config?: MessagePartialSignerConfig\n ): Promise<readonly SignatureDictionary[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link MessagePartialSigner} interface. */\nexport function isMessagePartialSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is MessagePartialSigner<TAddress> {\n return 'signMessages' in value && typeof value.signMessages === 'function';\n}\n\n/** Asserts that the provided value implements the {@link MessagePartialSigner} interface. */\nexport function assertIsMessagePartialSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is MessagePartialSigner<TAddress> {\n if (!isMessagePartialSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the MessagePartialSigner interface');\n }\n}\n","import { Address } from '@solana/addresses';\nimport { CompilableTransaction } from '@solana/transactions';\n\nimport { BaseSignerConfig, SignatureDictionary } from './types';\n\nexport type TransactionPartialSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing transactions. */\nexport type TransactionPartialSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n signTransactions(\n transactions: readonly CompilableTransaction[],\n config?: TransactionPartialSignerConfig\n ): Promise<readonly SignatureDictionary[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link TransactionPartialSigner} interface. */\nexport function isTransactionPartialSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is TransactionPartialSigner<TAddress> {\n return 'signTransactions' in value && typeof value.signTransactions === 'function';\n}\n\n/** Asserts that the provided value implements the {@link TransactionPartialSigner} interface. */\nexport function assertIsTransactionPartialSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is TransactionPartialSigner<TAddress> {\n if (!isTransactionPartialSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the TransactionPartialSigner interface');\n }\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { generateKeyPair, signBytes } from '@solana/keys';\nimport { partiallySignTransaction } from '@solana/transactions';\n\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\n\n/** Defines a signer capable of signing messages and transactions using a CryptoKeyPair. */\nexport type KeyPairSigner<TAddress extends string = string> = MessagePartialSigner<TAddress> &\n TransactionPartialSigner<TAddress> & { keyPair: CryptoKeyPair };\n\n/** Checks whether the provided value implements the {@link KeyPairSigner} interface. */\nexport function isKeyPairSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is KeyPairSigner<TAddress> {\n return (\n 'keyPair' in value &&\n typeof value.keyPair === 'object' &&\n isMessagePartialSigner(value) &&\n isTransactionPartialSigner(value)\n );\n}\n\n/** Asserts that the provided value implements the {@link KeyPairSigner} interface. */\nexport function assertIsKeyPairSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is KeyPairSigner<TAddress> {\n if (!isKeyPairSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the KeyPairSigner interface');\n }\n}\n\n/** Creates a KeyPairSigner from the provided Crypto KeyPair. */\nexport async function createSignerFromKeyPair(keyPair: CryptoKeyPair): Promise<KeyPairSigner> {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const out: KeyPairSigner = {\n address,\n keyPair,\n signMessages: messages =>\n Promise.all(\n messages.map(async message =>\n Object.freeze({ [address]: await signBytes(keyPair.privateKey, message.content) })\n )\n ),\n signTransactions: transactions =>\n Promise.all(\n transactions.map(async transaction => {\n const signedTransaction = await partiallySignTransaction([keyPair], transaction);\n return Object.freeze({ [address]: signedTransaction.signatures[address] });\n })\n ),\n };\n\n return Object.freeze(out);\n}\n\n/** Securely generates a signer capable of signing messages and transactions using a Crypto KeyPair. */\nexport async function generateKeyPairSigner(): Promise<KeyPairSigner> {\n return createSignerFromKeyPair(await generateKeyPair());\n}\n","import { Address, isAddress } from '@solana/addresses';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig } from './types';\n\nexport type MessageModifyingSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing messages. */\nexport type MessageModifyingSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n modifyAndSignMessages(\n messages: readonly SignableMessage[],\n config?: MessageModifyingSignerConfig\n ): Promise<readonly SignableMessage[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link MessageModifyingSigner} interface. */\nexport function isMessageModifyingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is MessageModifyingSigner<TAddress> {\n return (\n isAddress(value.address) &&\n 'modifyAndSignMessages' in value &&\n typeof value.modifyAndSignMessages === 'function'\n );\n}\n\n/** Asserts that the provided value implements the {@link MessageModifyingSigner} interface. */\nexport function assertIsMessageModifyingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is MessageModifyingSigner<TAddress> {\n if (!isMessageModifyingSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the MessageModifyingSigner interface');\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { isMessageModifyingSigner, MessageModifyingSigner } from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\n\n/** Defines a signer capable of signing messages. */\nexport type MessageSigner<TAddress extends string = string> =\n | MessagePartialSigner<TAddress>\n | MessageModifyingSigner<TAddress>;\n\n/** Checks whether the provided value implements the {@link MessageSigner} interface. */\nexport function isMessageSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is MessageSigner<TAddress> {\n return isMessagePartialSigner(value) || isMessageModifyingSigner(value);\n}\n\n/** Asserts that the provided value implements the {@link MessageSigner} interface. */\nexport function assertIsMessageSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is MessageSigner<TAddress> {\n if (!isMessageSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement any of the MessageSigner interfaces');\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { MessagePartialSigner } from './message-partial-signer';\nimport { TransactionPartialSigner } from './transaction-partial-signer';\n\n/** Defines a no-operation signer that pretends to partially sign messages and transactions. */\nexport type NoopSigner<TAddress extends string = string> = MessagePartialSigner<TAddress> &\n TransactionPartialSigner<TAddress>;\n\n/** Creates a NoopSigner from the provided Address. */\nexport function createNoopSigner(address: Address): NoopSigner {\n const out: NoopSigner = {\n address,\n signMessages: async messages => messages.map(() => Object.freeze({})),\n signTransactions: async transactions => transactions.map(() => Object.freeze({})),\n };\n\n return Object.freeze(out);\n}\n","import { Address } from '@solana/addresses';\nimport { CompilableTransaction } from '@solana/transactions';\n\nimport { BaseSignerConfig } from './types';\n\nexport type TransactionModifyingSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing transactions. */\nexport type TransactionModifyingSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n modifyAndSignTransactions<TTransaction extends CompilableTransaction>(\n transactions: readonly TTransaction[],\n config?: TransactionModifyingSignerConfig\n ): Promise<readonly TTransaction[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link TransactionModifyingSigner} interface. */\nexport function isTransactionModifyingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is TransactionModifyingSigner<TAddress> {\n return 'modifyAndSignTransactions' in value && typeof value.modifyAndSignTransactions === 'function';\n}\n\n/** Asserts that the provided value implements the {@link TransactionModifyingSigner} interface. */\nexport function assertIsTransactionModifyingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is TransactionModifyingSigner<TAddress> {\n if (!isTransactionModifyingSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the TransactionModifyingSigner interface');\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SignatureBytes } from '@solana/keys';\nimport { CompilableTransaction } from '@solana/transactions';\n\nimport { BaseSignerConfig } from './types';\n\nexport type TransactionSendingSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing and sending transactions simultaneously. */\nexport type TransactionSendingSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n signAndSendTransactions(\n transactions: readonly CompilableTransaction[],\n config?: TransactionSendingSignerConfig\n ): Promise<readonly SignatureBytes[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link TransactionSendingSigner} interface. */\nexport function isTransactionSendingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is TransactionSendingSigner<TAddress> {\n return 'signAndSendTransactions' in value && typeof value.signAndSendTransactions === 'function';\n}\n\n/** Asserts that the provided value implements the {@link TransactionSendingSigner} interface. */\nexport function assertIsTransactionSendingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is TransactionSendingSigner<TAddress> {\n if (!isTransactionSendingSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the TransactionSendingSigner interface');\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { isTransactionModifyingSigner, TransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner, TransactionSendingSigner } from './transaction-sending-signer';\n\n/** Defines a signer capable of signing transactions. */\nexport type TransactionSigner<TAddress extends string = string> =\n | TransactionPartialSigner<TAddress>\n | TransactionModifyingSigner<TAddress>\n | TransactionSendingSigner<TAddress>;\n\n/** Checks whether the provided value implements the {@link TransactionSigner} interface. */\nexport function isTransactionSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is TransactionSigner<TAddress> {\n return (\n isTransactionPartialSigner(value) || isTransactionModifyingSigner(value) || isTransactionSendingSigner(value)\n );\n}\n\n/** Asserts that the provided value implements the {@link TransactionSigner} interface. */\nexport function assertIsTransactionSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is TransactionSigner<TAddress> {\n if (!isTransactionSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement any of the TransactionSigner interfaces');\n }\n}\n","import { SignatureBytes } from '@solana/keys';\nimport {\n assertTransactionIsFullySigned,\n CompilableTransaction,\n IFullySignedTransaction,\n ITransactionWithSignatures,\n} from '@solana/transactions';\n\nimport { getSignersFromTransaction, ITransactionWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isTransactionModifyingSigner, TransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner, TransactionSendingSigner } from './transaction-sending-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\nimport { ITransactionWithSingleSendingSigner } from './transaction-with-single-sending-signer';\n\ntype CompilableTransactionWithSigners = CompilableTransaction &\n ITransactionWithSigners &\n Partial<ITransactionWithSignatures>;\n\n/**\n * Signs a transaction using any signers that may be stored in IAccountSignerMeta instruction accounts\n * as well as any signers provided explicitly to this function.\n * It will ignore TransactionSendingSigners since this function does not send the transaction.\n */\nexport async function partiallySignTransactionWithSigners<\n TTransaction extends CompilableTransactionWithSigners = CompilableTransactionWithSigners\n>(\n transaction: TTransaction,\n config: { abortSignal?: AbortSignal } = {}\n): Promise<TTransaction & ITransactionWithSignatures> {\n const { partialSigners, modifyingSigners } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransaction(transaction).filter(isTransactionSigner)),\n { identifySendingSigner: false }\n );\n\n return signModifyingAndPartialTransactionSigners(transaction, modifyingSigners, partialSigners, config.abortSignal);\n}\n\n/**\n * Signs a transaction using any signers that may be stored in IAccountSignerMeta instruction accounts\n * as well as any signers provided explicitly to this function.\n * It will assert that the transaction is fully signed before returning.\n * It will ignore TransactionSendingSigners since this function does not send the transaction.\n */\nexport async function signTransactionWithSigners<\n TTransaction extends CompilableTransactionWithSigners = CompilableTransactionWithSigners\n>(\n transaction: TTransaction,\n config: { abortSignal?: AbortSignal } = {}\n): Promise<TTransaction & IFullySignedTransaction> {\n const signedTransaction = await partiallySignTransactionWithSigners(transaction, config);\n assertTransactionIsFullySigned(signedTransaction);\n return signedTransaction;\n}\n\n/**\n * Signs and sends a transaction using any signers that may be stored in IAccountSignerMeta\n * instruction accounts as well as any signers provided explicitly to this function.\n * It will identify a single TransactionSendingSigners to use for sending the transaction, if any.\n * Otherwise, it will send the transaction using the provided fallbackSender.\n */\nexport async function signAndSendTransactionWithSigners<\n TTransaction extends CompilableTransactionWithSigners &\n ITransactionWithSingleSendingSigner = CompilableTransactionWithSigners & ITransactionWithSingleSendingSigner\n>(transaction: TTransaction, config: { abortSignal?: AbortSignal } = {}): Promise<SignatureBytes> {\n const abortSignal = config.abortSignal;\n const { partialSigners, modifyingSigners, sendingSigner } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransaction(transaction).filter(isTransactionSigner))\n );\n\n abortSignal?.throwIfAborted();\n const signedTransaction = await signModifyingAndPartialTransactionSigners(\n transaction,\n modifyingSigners,\n partialSigners,\n abortSignal\n );\n\n if (!sendingSigner) {\n // TODO: Coded error.\n throw new Error(\n 'No `TransactionSendingSigner` was identified. Please provide a valid `ITransactionWithSingleSendingSigner` transaction.'\n );\n }\n\n abortSignal?.throwIfAborted();\n const [signature] = await sendingSigner.signAndSendTransactions([signedTransaction], { abortSignal });\n abortSignal?.throwIfAborted();\n\n return signature;\n}\n\n/**\n * Identifies each provided TransactionSigner and categorizes them into their respective types.\n * When a signer implements multiple interface, it will try to used to most powerful interface\n * but fallback to the least powerful interface when necessary.\n * For instance, if a signer implements TransactionSendingSigner and TransactionModifyingSigner,\n * it will be categorized as a TransactionSendingSigner if and only if no other signers implement\n * the TransactionSendingSigner interface.\n */\nfunction categorizeTransactionSigners(\n signers: readonly TransactionSigner[],\n config: { identifySendingSigner?: boolean } = {}\n): Readonly<{\n modifyingSigners: readonly TransactionModifyingSigner[];\n partialSigners: readonly TransactionPartialSigner[];\n sendingSigner: TransactionSendingSigner | null;\n}> {\n // Identify the unique sending signer that should be used.\n const identifySendingSigner = config.identifySendingSigner ?? true;\n const sendingSigner = identifySendingSigner ? identifyTransactionSendingSigner(signers) : null;\n\n // Now, focus on the other signers.\n // I.e. the modifying or partial signers that are not the identified sending signer.\n // Note that any other sending only signers will be discarded.\n const otherSigners = signers.filter(\n (signer): signer is TransactionModifyingSigner | TransactionPartialSigner =>\n signer !== sendingSigner && (isTransactionModifyingSigner(signer) || isTransactionPartialSigner(signer))\n );\n\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyTransactionModifyingSigners(otherSigners);\n\n // Use any remaining signers as partial signers.\n const partialSigners = otherSigners\n .filter(isTransactionPartialSigner)\n .filter(signer => !(modifyingSigners as typeof otherSigners).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners, sendingSigner });\n}\n\n/** Identifies the best signer to use as a TransactionSendingSigner, if any */\nfunction identifyTransactionSendingSigner(signers: readonly TransactionSigner[]): TransactionSendingSigner | null {\n // Ensure there are any TransactionSendingSigners in the first place.\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n if (sendingSigners.length === 0) return null;\n\n // Prefer sending signers that do not offer other interfaces.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionModifyingSigner(signer) && !isTransactionPartialSigner(signer)\n );\n if (sendingOnlySigners.length > 0) {\n return sendingOnlySigners[0];\n }\n\n // Otherwise, choose any sending signer.\n return sendingSigners[0];\n}\n\n/** Identifies the best signers to use as TransactionModifyingSigners, if any */\nfunction identifyTransactionModifyingSigners(\n signers: readonly (TransactionModifyingSigner | TransactionPartialSigner)[]\n): readonly TransactionModifyingSigner[] {\n // Ensure there are any TransactionModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isTransactionModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isTransactionPartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs a transaction using the provided TransactionModifyingSigners\n * sequentially followed by the TransactionPartialSigners in parallel.\n */\nasync function signModifyingAndPartialTransactionSigners<\n TTransaction extends CompilableTransactionWithSigners = CompilableTransactionWithSigners\n>(\n transaction: TTransaction,\n modifyingSigners: readonly TransactionModifyingSigner[] = [],\n partialSigners: readonly TransactionPartialSigner[] = [],\n abortSignal?: AbortSignal\n): Promise<TTransaction & ITransactionWithSignatures> {\n // Handle modifying signers sequentially.\n const modifiedTransaction = await modifyingSigners.reduce(async (transaction, modifyingSigner) => {\n abortSignal?.throwIfAborted();\n const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction], { abortSignal });\n return Object.freeze(tx);\n }, Promise.resolve(transaction) as Promise<TTransaction>);\n\n // Handle partial signers in parallel.\n abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signTransactions([modifiedTransaction], { abortSignal });\n return signatures;\n })\n );\n const signedTransaction: TTransaction & ITransactionWithSignatures = {\n ...modifiedTransaction,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedTransaction.signatures ?? {})\n ),\n };\n\n return Object.freeze(signedTransaction);\n}\n","import { TextEncoder } from 'text-encoding-impl';\n\nimport { SignatureDictionary } from './types';\n\n/** Defines a message that needs signing and its current set of signatures if any. */\nexport type SignableMessage = Readonly<{\n content: Uint8Array;\n signatures: SignatureDictionary;\n}>;\n\n/**\n * Creates a signable message from a provided content.\n * If a string is provided, it will be UTF-8 encoded.\n */\nexport function createSignableMessage(\n content: string | Uint8Array,\n signatures: SignatureDictionary = {}\n): SignableMessage {\n return Object.freeze({\n content: typeof content === 'string' ? new TextEncoder().encode(content) : content,\n signatures: Object.freeze({ ...signatures }),\n });\n}\n","import { CompilableTransaction } from '@solana/transactions';\n\nimport { getSignersFromTransaction, ITransactionWithSigners } from './account-signer-meta';\nimport { isTransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner } from './transaction-sending-signer';\n\n/** Defines a transaction with exactly one {@link TransactionSendingSigner}. */\nexport type ITransactionWithSingleSendingSigner = ITransactionWithSigners & {\n readonly __transactionWithSingleSendingSigner: unique symbol;\n};\n\n/** Checks whether the provided transaction has exactly one {@link TransactionSendingSigner}. */\nexport function isTransactionWithSingleSendingSigner<TTransaction extends CompilableTransaction>(\n transaction: TTransaction\n): transaction is TTransaction & ITransactionWithSingleSendingSigner {\n try {\n assertIsTransactionWithSingleSendingSigner(transaction);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Asserts that the provided transaction has exactly one {@link TransactionSendingSigner}. */\nexport function assertIsTransactionWithSingleSendingSigner<TTransaction extends CompilableTransaction>(\n transaction: TTransaction\n): asserts transaction is TTransaction & ITransactionWithSingleSendingSigner {\n const signers = getSignersFromTransaction(transaction);\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n\n if (sendingSigners.length === 0) {\n // TODO: Coded error.\n const error = new Error('No `TransactionSendingSigner` was identified.');\n error.name = 'MissingTransactionSendingSignerError';\n throw error;\n }\n\n // When identifying if there are multiple sending signers, we only need to check for\n // sending signers that do not implement other transaction signer interfaces as\n // they will be used as these other signer interfaces in case of a conflict.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionPartialSigner(signer) && !isTransactionModifyingSigner(signer)\n );\n\n if (sendingOnlySigners.length > 1) {\n // TODO: Coded error.\n const error = new Error('More than one `TransactionSendingSigner` was identified.');\n error.name = 'MultipleTransactionSendingSignersError';\n throw error;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/deduplicate-signers.ts","../src/account-signer-meta.ts","../../instructions/src/roles.ts","../src/add-signers.ts","../../codecs-core/dist/index.browser.js","../../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/u128.ts","../../codecs-numbers/src/u16.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/base64.ts","../../codecs-strings/src/null-characters.ts","../../codecs-strings/src/string.ts","../../codecs-strings/src/utf8.ts","../../text-encoding-impl/src/index.browser.ts","../../assertions/src/subtle-crypto.ts","../../addresses/src/address.ts","../../addresses/src/program-derived-address.ts","../../addresses/src/public-key.ts","../../keys/src/key-pair.ts","../../keys/src/signatures.ts","../../codecs-data-structures/src/utils.ts","../../codecs-data-structures/src/array-like-codec-size.ts","../../codecs-data-structures/src/assertions.ts","../../codecs-data-structures/src/array.ts","../../codecs-data-structures/src/boolean.ts","../../codecs-data-structures/src/bytes.ts","../../codecs-data-structures/src/scalar-enum.ts","../../codecs-data-structures/src/set.ts","../../transactions/dist/index.browser.js","../src/message-partial-signer.ts","../src/transaction-partial-signer.ts","../src/keypair-signer.ts","../src/message-modifying-signer.ts","../src/message-signer.ts","../src/noop-signer.ts","../src/transaction-modifying-signer.ts","../src/transaction-sending-signer.ts","../src/transaction-signer.ts","../src/sign-transaction.ts","../src/signable-message.ts","../src/transaction-with-single-sending-signer.ts"],"names":["combineCodec","alphabet","e","mergeBytes","getU32Decoder","__DEV__","isSignerRole","address","transaction","TextDecoder","TextEncoder","o"],"mappings":";AAMO,SAAS,mBACZ,SACkB;AAClB,QAAM,eAAyC,CAAC;AAChD,UAAQ,QAAQ,YAAU;AACtB,QAAI,CAAC,aAAa,O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BAA0B;AAEhE,MAAI,eAAe,WAAW,GAAG;AAE7B,UAAM,QAAQ,IAAI,MAAM,+CAA+C;AACvE,UAAM,OAAO;AACb,UAAM;AAAA,EACV;AAKA,QAAM,qBAAqB,eAAe;AAAA,IACtC,YAAU,CAAC,2BAA2B,MAAM,KAAK,CAAC,6BAA6B,MAAM;AAAA,EACzF;AAEA,MAAI,mBAAmB,SAAS,GAAG;AAE/B,UAAM,QAAQ,IAAI,MAAM,0DAA0D;AAClF,UAAM,OAAO;AACb,UAAM;AAAA,EACV;AACJ","sourcesContent":["import { Address } from '@solana/addresses';\n\nimport { MessageSigner } from './message-signer';\nimport { TransactionSigner } from './transaction-signer';\n\n/** Removes all duplicated signers from a provided array by comparing their addresses. */\nexport function deduplicateSigners<TSigner extends MessageSigner | TransactionSigner>(\n signers: readonly TSigner[]\n): readonly TSigner[] {\n const deduplicated: Record<Address, TSigner> = {};\n signers.forEach(signer => {\n if (!deduplicated[signer.address]) {\n deduplicated[signer.address] = signer;\n } else if (deduplicated[signer.address] !== signer) {\n // TODO: Coded error.\n throw new Error(\n `Multiple distinct signers were identified for address \"${signer.address}\". ` +\n `Please ensure that you are using the same signer instance for each address.`\n );\n }\n });\n return Object.values(deduplicated);\n}\n","import { AccountRole, IAccountLookupMeta, IAccountMeta, IInstruction } from '@solana/instructions';\nimport { BaseTransaction, TransactionVersion } from '@solana/transactions';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { TransactionSigner } from './transaction-signer';\n\n/** An extension of the IAccountMeta type that keeps track of its transaction signer. */\nexport interface IAccountSignerMeta<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner\n> extends IAccountMeta<TAddress> {\n readonly role: AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER;\n readonly signer: TSigner;\n}\n\ntype IAccountMetaWithWithSigner<TSigner extends TransactionSigner = TransactionSigner> =\n | IAccountMeta\n | IAccountLookupMeta\n | IAccountSignerMeta<string, TSigner>;\n\n/** A variation of the instruction type that allows IAccountSignerMeta in its account metas. */\nexport type IInstructionWithSigners<\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly IAccountMetaWithWithSigner<TSigner>[] = readonly IAccountMetaWithWithSigner<TSigner>[]\n> = Pick<IInstruction<string, TAccounts>, 'accounts'>;\n\n/** A variation of the transaction type that allows IAccountSignerMeta in its account metas. */\nexport type ITransactionWithSigners<\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly IAccountMetaWithWithSigner<TSigner>[] = readonly IAccountMetaWithWithSigner<TSigner>[]\n> = Pick<\n BaseTransaction<TransactionVersion, IInstruction & IInstructionWithSigners<TSigner, TAccounts>>,\n 'instructions'\n>;\n\n/** Extract all signers from an instruction that may contain IAccountSignerMeta accounts. */\nexport function getSignersFromInstruction<TSigner extends TransactionSigner = TransactionSigner>(\n instruction: IInstructionWithSigners<TSigner>\n): readonly TSigner[] {\n return deduplicateSigners(\n (instruction.accounts ?? []).flatMap(account => ('signer' in account ? account.signer : []))\n );\n}\n\n/** Extract all signers from a transaction that may contain IAccountSignerMeta accounts. */\nexport function getSignersFromTransaction<\n TSigner extends TransactionSigner = TransactionSigner,\n TTransaction extends ITransactionWithSigners<TSigner> = ITransactionWithSigners<TSigner>\n>(transaction: TTransaction): readonly TSigner[] {\n return deduplicateSigners(transaction.instructions.flatMap(getSignersFromInstruction));\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 { IInstruction, isSignerRole } from '@solana/instructions';\nimport { BaseTransaction } from '@solana/transactions';\n\nimport { IAccountSignerMeta, IInstructionWithSigners, ITransactionWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { TransactionSigner } from './transaction-signer';\n\n/** Attaches the provided signers to the account metas of an instruction when applicable. */\nexport function addSignersToInstruction<TInstruction extends IInstruction>(\n signers: TransactionSigner[],\n instruction: TInstruction | (TInstruction & IInstructionWithSigners)\n): TInstruction & IInstructionWithSigners {\n if (!instruction.accounts || instruction.accounts.length === 0) {\n return instruction as TInstruction & IInstructionWithSigners;\n }\n\n const signerByAddress = new Map(deduplicateSigners(signers).map(signer => [signer.address, signer]));\n return Object.freeze({\n ...instruction,\n accounts: instruction.accounts.map(account => {\n const signer = signerByAddress.get(account.address);\n if (!isSignerRole(account.role) || 'signer' in account || !signer) {\n return account;\n }\n return Object.freeze({ ...account, signer } as IAccountSignerMeta);\n }),\n });\n}\n\n/** Attaches the provided signers to the account metas of a transaction when applicable. */\nexport function addSignersToTransaction<TTransaction extends BaseTransaction>(\n signers: TransactionSigner[],\n transaction: TTransaction | (TTransaction & ITransactionWithSigners)\n): TTransaction & ITransactionWithSigners {\n if (transaction.instructions.length === 0) {\n return transaction as TTransaction & ITransactionWithSigners;\n }\n\n return Object.freeze({\n ...transaction,\n instructions: transaction.instructions.map(instruction => addSignersToInstruction(signers, instruction)),\n });\n}\n","// src/assertions.ts\nfunction assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {\n if (bytes.length - offset <= 0) {\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\nfunction assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\nfunction assertFixedSizeCodec(data, message) {\n if (data.fixedSize === null) {\n throw new Error(message ?? \"Expected a fixed-size codec, got a variable-size one.\");\n }\n}\n\n// src/bytes.ts\nvar mergeBytes = (byteArrays) => {\n const nonEmptyByteArrays = byteArrays.filter((arr) => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\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};\nvar padBytes = (bytes, length) => {\n if (bytes.length >= length)\n return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\nvar fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n\n// src/combine-codec.ts\nfunction combineCodec(encoder, decoder, description) {\n if (encoder.fixedSize !== decoder.fixedSize) {\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`\n );\n }\n if (encoder.maxSize !== decoder.maxSize) {\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`\n );\n }\n if (description === void 0 && encoder.description !== decoder.description) {\n throw new Error(\n `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. Pass a custom description as a third argument if you want to override the description and bypass this error.`\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\n// src/fix-codec.ts\nfunction fixCodecHelper(data, fixedBytes, description) {\n return {\n description: description ?? `fixed(${fixedBytes}, ${data.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes\n };\n}\nfunction fixEncoder(encoder, fixedBytes, description) {\n return {\n ...fixCodecHelper(encoder, fixedBytes, description),\n encode: (value) => fixBytes(encoder.encode(value), fixedBytes)\n };\n}\nfunction fixDecoder(decoder, fixedBytes, description) {\n return {\n ...fixCodecHelper(decoder, fixedBytes, description),\n decode: (bytes, offset = 0) => {\n assertByteArrayHasEnoughBytesForCodec(\"fixCodec\", fixedBytes, bytes, offset);\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n if (decoder.fixedSize !== null) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n const [value] = decoder.decode(bytes, 0);\n return [value, offset + fixedBytes];\n }\n };\n}\nfunction fixCodec(codec, fixedBytes, description) {\n return combineCodec(fixEncoder(codec, fixedBytes, description), fixDecoder(codec, fixedBytes, description));\n}\n\n// src/map-codec.ts\nfunction mapEncoder(encoder, unmap) {\n return {\n description: encoder.description,\n encode: (value) => encoder.encode(unmap(value)),\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize\n };\n}\nfunction mapDecoder(decoder, map) {\n return {\n decode: (bytes, 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}\nfunction mapCodec(codec, unmap, map) {\n return {\n decode: map ? mapDecoder(codec, map).decode : codec.decode,\n description: codec.description,\n encode: mapEncoder(codec, unmap).encode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize\n };\n}\n\n// src/reverse-codec.ts\nfunction reverseEncoder(encoder) {\n assertFixedSizeCodec(encoder, \"Cannot reverse a codec of variable size.\");\n return {\n ...encoder,\n encode: (value) => encoder.encode(value).reverse()\n };\n}\nfunction reverseDecoder(decoder) {\n assertFixedSizeCodec(decoder, \"Cannot reverse a codec of variable size.\");\n return {\n ...decoder,\n decode: (bytes, offset = 0) => {\n const reverseEnd = offset + decoder.fixedSize;\n if (offset === 0 && bytes.length === reverseEnd) {\n return decoder.decode(bytes.reverse(), offset);\n }\n const newBytes = mergeBytes([\n ...offset === 0 ? [] : [bytes.slice(0, offset)],\n bytes.slice(offset, reverseEnd).reverse(),\n ...bytes.length === reverseEnd ? [] : [bytes.slice(reverseEnd)]\n ]);\n return decoder.decode(newBytes, offset);\n }\n };\n}\nfunction reverseCodec(codec) {\n return combineCodec(reverseEncoder(codec), reverseDecoder(codec));\n}\n\nexport { assertByteArrayHasEnoughBytesForCodec, assertByteArrayIsNotEmptyForCodec, assertFixedSizeCodec, combineCodec, fixBytes, fixCodec, fixDecoder, fixEncoder, mapCodec, mapDecoder, mapEncoder, mergeBytes, padBytes, reverseCodec, reverseDecoder, reverseEncoder };\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 { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (config: NumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'f32',\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (config: NumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n size: 4,\n });\n\nexport const getF32Codec = (config: NumberCodecConfig = {}): Codec<number> =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n CodecData,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig, SingleByteNumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput = {\n name: string;\n size: number;\n config: SingleByteNumberCodecConfig | NumberCodecConfig;\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.config) || input.config.endian === Endian.LITTLE;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.config.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 { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI64Encoder = (config: NumberCodecConfig = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n config,\n name: 'i64',\n range: [-BigInt('0x7fffffffffffffff') - 1n, BigInt('0x7fffffffffffffff')],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8,\n });\n\nexport const getI64Decoder = (config: NumberCodecConfig = {}): Decoder<bigint> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n size: 8,\n });\n\nexport const getI64Codec = (config: NumberCodecConfig = {}): Codec<number | bigint, bigint> =>\n combineCodec(getI64Encoder(config), getI64Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { SingleByteNumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI8Encoder = (config: SingleByteNumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'i8',\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, value),\n size: 1,\n });\n\nexport const getI8Decoder = (config: SingleByteNumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: view => view.getInt8(0),\n name: 'i8',\n size: 1,\n });\n\nexport const getI8Codec = (config: SingleByteNumberCodecConfig = {}): Codec<number> =>\n combineCodec(getI8Encoder(config), getI8Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (config: NumberCodecConfig = {}): Encoder<number | bigint> =>\n numberEncoderFactory({\n config,\n name: 'u128',\n range: [0, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\nexport const getU128Decoder = (config: NumberCodecConfig = {}): Decoder<bigint> =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n size: 16,\n });\n\nexport const getU128Codec = (config: NumberCodecConfig = {}): Codec<number | bigint, bigint> =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (config: NumberCodecConfig = {}): Encoder<number> =>\n numberEncoderFactory({\n config,\n name: 'u16',\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, value, le),\n size: 2,\n });\n\nexport const getU16Decoder = (config: NumberCodecConfig = {}): Decoder<number> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n size: 2,\n });\n\nexport const getU16Codec = (config: NumberCodecConfig = {}): Codec<number> =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import { 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 BaseCodecConfig,\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 config for string codecs. */\nexport type StringCodecConfig<\n TPrefix extends NumberCodec | NumberEncoder | NumberDecoder,\n TEncoding extends Codec<string> | Encoder<string> | Decoder<string>\n> = BaseCodecConfig & {\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 = (config: StringCodecConfig<NumberEncoder, Encoder<string>> = {}): Encoder<string> => {\n const size = config.size ?? getU32Encoder();\n const encoding = config.encoding ?? getUtf8Encoder();\n const description = config.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 = (config: StringCodecConfig<NumberDecoder, Decoder<string>> = {}): Decoder<string> => {\n const size = config.size ?? getU32Decoder();\n const encoding = config.encoding ?? getUtf8Decoder();\n const description = config.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 = (config: StringCodecConfig<NumberCodec, Codec<string>> = {}): Codec<string> =>\n combineCodec(getStringEncoder(config), getStringDecoder(config));\n\nfunction getSizeDescription(size: CodecData | number | 'variable'): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from 'text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/** Encodes UTF-8 strings using the native `TextEncoder` API. */\nexport const getUtf8Encoder = (): Encoder<string> => {\n let textEncoder: TextEncoder;\n return {\n description: 'utf8',\n encode: (value: string) => new Uint8Array((textEncoder ||= new TextEncoder()).encode(value)),\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Decodes UTF-8 strings using the native `TextDecoder` API. */\nexport const getUtf8Decoder = (): Decoder<string> => {\n let textDecoder: TextDecoder;\n return {\n decode(bytes, offset = 0) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/** Encodes and decodes UTF-8 strings using the native `TextEncoder` and `TextDecoder` API. */\nexport const getUtf8Codec = (): Codec<string> => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapEncoder } from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nexport type Address<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\nexport function isAddress(putativeAddress: string): putativeAddress is Address<typeof putativeAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address<typeof putativeAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function address<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address<TAddress>;\n}\n\nexport function getAddressEncoder(config?: Readonly<{ description: string }>): Encoder<Address> {\n return mapEncoder(\n getStringEncoder({\n description: config?.description ?? 'Address',\n encoding: getMemoizedBase58Encoder(),\n size: 32,\n }),\n putativeAddress => address(putativeAddress)\n );\n}\n\nexport function getAddressDecoder(config?: Readonly<{ description: string }>): Decoder<Address> {\n return getStringDecoder({\n description: config?.description ?? 'Address',\n encoding: getMemoizedBase58Decoder(),\n size: 32,\n }) as Decoder<Address>;\n}\n\nexport function getAddressCodec(config?: Readonly<{ description: string }>): Codec<Address> {\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 { Address, assertIsAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve';\n\n/**\n * An address derived from a program address and a set of seeds.\n * It includes the bump seed used to derive the address and\n * ensure the address is not on the Ed25519 curve.\n */\nexport type ProgramDerivedAddress<TAddress extends string = string> = Readonly<\n [Address<TAddress>, ProgramDerivedAddressBump]\n>;\n\n/**\n * A number between 0 and 255, inclusive.\n */\nexport type ProgramDerivedAddressBump = number & {\n readonly __brand: unique symbol;\n};\n\n/**\n * Returns true if the input value is a program derived address.\n */\nexport function isProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): value is ProgramDerivedAddress<TAddress> {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * Fails if the input value is not a program derived address.\n */\nexport function assertIsProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): asserts value is ProgramDerivedAddress<TAddress> {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n // TODO: Coded error.\n throw new Error(\n `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n // TODO: Coded error.\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Address;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Address;\n programAddress: Address;\n seed: Seed;\n}>;\n\ntype Seed = string | Uint8Array;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\n// TODO: Coded error.\nclass PointOnCurveError extends Error {}\n\nasync function createProgramDerivedAddress({ programAddress, seeds }: ProgramDerivedAddressInput): Promise<Address> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n // TODO: Coded error.\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n // TODO: Coded error.\n throw new PointOnCurveError('Invalid seeds; point must fall off the Ed25519 curve');\n }\n return base58EncodedAddressCodec.decode(addressBytes)[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({ baseAddress, programAddress, seed }: SeedInput): Promise<Address> {\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])\n ) {\n // TODO: Coded error.\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes)[0];\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Address, getAddressDecoder } from './address';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Address> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n","import { assertKeyGenerationIsAvailable } from '@solana/assertions';\n\nexport async function generateKeyPair(): Promise<CryptoKeyPair> {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ 'Ed25519', // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify']\n );\n return keyPair as CryptoKeyPair;\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n","/** Returns the max size or null if at least one size is null. */\nexport function maxCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : Math.max(all, size)),\n 0 as number | null\n );\n}\n\n/** Returns the sum of all sizes or null if at least one size is null. */\nexport function sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n","import { CodecData, Offset } from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { sumCodecSizes } from './utils';\n\n/**\n * Represents all the size options for array-like codecs\n * — i.e. `array`, `map` and `set`.\n *\n * It can be one of the following:\n * - a {@link NumberCodec} that prefixes its content with its size.\n * - a fixed number of items.\n * - or `'remainder'` to infer the number of items by dividing\n * the rest of the byte array by the fixed size of its item.\n * Note that this option is only available for fixed-size items.\n */\nexport type ArrayLikeCodecSize<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder | CodecData> =\n | TPrefix\n | number\n | 'remainder';\n\n/** Resolves the size of an array-like codec. */\nexport function decodeArrayLikeCodecSize(\n size: ArrayLikeCodecSize<NumberDecoder>,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: Offset\n): [number | bigint, Offset] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.decode(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumCodecSizes(childrenSizes);\n if (childrenSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n // TODO: Coded error.\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${childrenSize} bytes. ` +\n `Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainder} modulo ${childrenSize} should be equal to zero.`\n );\n }\n return [remainder / childrenSize, offset];\n }\n\n // TODO: Coded error.\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\n\nexport function getArrayLikeCodecSizeDescription(size: ArrayLikeCodecSize<CodecData>): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getArrayLikeCodecSizeFromChildren(\n size: ArrayLikeCodecSize<CodecData>,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumCodecSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getArrayLikeCodecSizePrefix(size: ArrayLikeCodecSize<NumberEncoder>, realSize: number): Uint8Array {\n return typeof size === 'object' ? size.encode(realSize) : new Uint8Array();\n}\n","/** Checks the number of items in an array-like structure is expected. */\nexport function assertValidNumberOfItemsForCodec(\n codecDescription: string,\n expected: number | bigint,\n actual: number | bigint\n) {\n if (expected !== actual) {\n // TODO: Coded error.\n throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);\n }\n}\n","import { BaseCodecConfig, Codec, CodecData, combineCodec, Decoder, Encoder, mergeBytes } from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport {\n ArrayLikeCodecSize,\n decodeArrayLikeCodecSize,\n getArrayLikeCodecSizeDescription,\n getArrayLikeCodecSizeFromChildren,\n getArrayLikeCodecSizePrefix,\n} from './array-like-codec-size';\nimport { assertValidNumberOfItemsForCodec } from './assertions';\n\n/** Defines the configs for array codecs. */\nexport type ArrayCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The size of the array.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\n};\n\nfunction arrayCodecHelper(item: CodecData, size: ArrayLikeCodecSize<CodecData>, description?: string): CodecData {\n if (size === 'remainder' && item.fixedSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n return {\n description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize]),\n };\n}\n\n/**\n * Encodes an array of items.\n *\n * @param item - The encoder to use for the array's items.\n * @param config - A set of config for the encoder.\n */\nexport function getArrayEncoder<T>(item: Encoder<T>, config: ArrayCodecConfig<NumberEncoder> = {}): Encoder<T[]> {\n const size = config.size ?? getU32Encoder();\n return {\n ...arrayCodecHelper(item, size, config.description),\n encode: (value: T[]) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, value.length);\n }\n return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map(v => item.encode(v))]);\n },\n };\n}\n\n/**\n * Decodes an array of items.\n *\n * @param item - The encoder to use for the array's items.\n * @param config - A set of config for the encoder.\n */\nexport function getArrayDecoder<T>(item: Decoder<T>, config: ArrayCodecConfig<NumberDecoder> = {}): Decoder<T[]> {\n const size = config.size ?? getU32Decoder();\n return {\n ...arrayCodecHelper(item, size, config.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n const values: T[] = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.decode(bytes, offset);\n values.push(value);\n offset = newOffset;\n }\n return [values, offset];\n },\n };\n}\n\n/**\n * Creates a codec for an array of items.\n *\n * @param item - The codec to use for the array's items.\n * @param config - A set of config for the codec.\n */\nexport function getArrayCodec<T, U extends T = T>(\n item: Codec<T, U>,\n config: ArrayCodecConfig<NumberCodec> = {}\n): Codec<T[], U[]> {\n return combineCodec(getArrayEncoder(item, config), getArrayDecoder(item, config));\n}\n","import {\n assertByteArrayIsNotEmptyForCodec,\n assertFixedSizeCodec,\n BaseCodecConfig,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/** Defines the config for boolean codecs. */\nexport type BooleanCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The number codec to delegate to.\n * @defaultValue u8 size.\n */\n size?: TSize;\n};\n\n/**\n * Encodes booleans.\n *\n * @param config - A set of config for the encoder.\n */\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder> = {}): Encoder<boolean> {\n const size = config.size ?? getU8Encoder();\n assertFixedSizeCodec(size, 'Codec [bool] requires a fixed size.');\n\n return {\n description: config.description ?? `bool(${size.description})`,\n encode: (value: boolean) => size.encode(value ? 1 : 0),\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize,\n };\n}\n\n/**\n * Decodes booleans.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder> = {}): Decoder<boolean> {\n const size = config.size ?? getU8Decoder();\n assertFixedSizeCodec(size, 'Codec [bool] requires a fixed size.');\n\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('bool', bytes, offset);\n const [value, vOffset] = size.decode(bytes, offset);\n return [value === 1, vOffset];\n },\n description: config.description ?? `bool(${size.description})`,\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize,\n };\n}\n\n/**\n * Creates a boolean codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec> = {}): Codec<boolean> {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecConfig,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n fixDecoder,\n fixEncoder,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/** Defines the config for bytes codecs. */\nexport type BytesCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The size of the byte array. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the byte array with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the byte array.\n * @defaultValue `'variable'`\n */\n size?: TSize | number | 'variable';\n};\n\n/**\n * Encodes sized bytes.\n *\n * @param config - A set of config for the encoder.\n */\nexport function getBytesEncoder(config: BytesCodecConfig<NumberEncoder> = {}): Encoder<Uint8Array> {\n const size = config.size ?? 'variable';\n const sizeDescription = typeof size === 'object' ? size.description : `${size}`;\n const description = config.description ?? `bytes(${sizeDescription})`;\n\n const byteEncoder: Encoder<Uint8Array> = {\n description,\n encode: (value: Uint8Array) => value,\n fixedSize: null,\n maxSize: null,\n };\n\n if (size === 'variable') {\n return byteEncoder;\n }\n\n if (typeof size === 'number') {\n return fixEncoder(byteEncoder, size, description);\n }\n\n return {\n ...byteEncoder,\n encode: (value: Uint8Array) => {\n const contentBytes = byteEncoder.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n };\n}\n\n/**\n * Decodes sized bytes.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBytesDecoder(config: BytesCodecConfig<NumberDecoder> = {}): Decoder<Uint8Array> {\n const size = config.size ?? 'variable';\n const sizeDescription = typeof size === 'object' ? size.description : `${size}`;\n const description = config.description ?? `bytes(${sizeDescription})`;\n\n const byteDecoder: Decoder<Uint8Array> = {\n decode: (bytes: Uint8Array, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n description,\n fixedSize: null,\n maxSize: null,\n };\n\n if (size === 'variable') {\n return byteDecoder;\n }\n\n if (typeof size === 'number') {\n return fixDecoder(byteDecoder, size, description);\n }\n\n return {\n ...byteDecoder,\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('bytes', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec('bytes', length, contentBytes);\n const [value, contentOffset] = byteDecoder.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n\n/**\n * Creates a sized bytes codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBytesCodec(config: BytesCodecConfig<NumberCodec> = {}): Codec<Uint8Array> {\n return combineCodec(getBytesEncoder(config), getBytesDecoder(config));\n}\n","import {\n assertByteArrayIsNotEmptyForCodec,\n BaseCodecConfig,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\n/**\n * Defines a scalar enum as a type from its constructor.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionType = ScalarEnum<Direction>;\n * ```\n */\nexport type ScalarEnum<T> = ({ [key: number | string]: string | number | T } | number | T) & NonNullable<unknown>;\n\n/** Defines the config for scalar enum codecs. */\nexport type ScalarEnumCodecConfig<TDiscriminator extends NumberCodec | NumberEncoder | NumberDecoder> =\n BaseCodecConfig & {\n /**\n * The codec to use for the enum discriminator.\n * @defaultValue u8 discriminator.\n */\n size?: TDiscriminator;\n };\n\nfunction scalarEnumCoderHelper<T>(\n constructor: ScalarEnum<T>,\n prefix: CodecData,\n description?: string\n): CodecData & {\n enumKeys: string[];\n enumValues: T[];\n isNumericEnum: boolean;\n minRange: number;\n maxRange: number;\n stringValues: string[];\n} {\n const enumKeys = Object.keys(constructor);\n const enumValues = Object.values(constructor);\n const isNumericEnum = enumValues.some(v => typeof v === 'number');\n const valueDescriptions = enumValues.filter(v => typeof v === 'string').join(', ');\n const minRange = 0;\n const maxRange = isNumericEnum ? enumValues.length / 2 - 1 : enumValues.length - 1;\n const stringValues: string[] = isNumericEnum ? [...enumKeys] : [...new Set([...enumKeys, ...enumValues])];\n\n return {\n description: description ?? `enum(${valueDescriptions}; ${prefix.description})`,\n enumKeys,\n enumValues,\n fixedSize: prefix.fixedSize,\n isNumericEnum,\n maxRange,\n maxSize: prefix.maxSize,\n minRange,\n stringValues,\n };\n}\n\n/**\n * Creates a scalar enum encoder.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param config - A set of config for the encoder.\n */\nexport function getScalarEnumEncoder<T>(\n constructor: ScalarEnum<T>,\n config: ScalarEnumCodecConfig<NumberEncoder> = {}\n): Encoder<T> {\n const prefix = config.size ?? getU8Encoder();\n const { description, fixedSize, maxSize, minRange, maxRange, stringValues, enumKeys, enumValues } =\n scalarEnumCoderHelper(constructor, prefix, config.description);\n return {\n description,\n encode: (value: T) => {\n const isInvalidNumber = typeof value === 'number' && (value < minRange || value > maxRange);\n const isInvalidString = typeof value === 'string' && !stringValues.includes(value);\n if (isInvalidNumber || isInvalidString) {\n // TODO: Coded error.\n throw new Error(\n `Invalid scalar enum variant. ` +\n `Expected one of [${stringValues.join(', ')}] ` +\n `or a number between ${minRange} and ${maxRange}, ` +\n `got \"${value}\".`\n );\n }\n if (typeof value === 'number') return prefix.encode(value);\n const valueIndex = enumValues.indexOf(value);\n if (valueIndex >= 0) return prefix.encode(valueIndex);\n return prefix.encode(enumKeys.indexOf(value as string));\n },\n fixedSize,\n maxSize,\n };\n}\n\n/**\n * Creates a scalar enum decoder.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param config - A set of config for the decoder.\n */\nexport function getScalarEnumDecoder<T>(\n constructor: ScalarEnum<T>,\n config: ScalarEnumCodecConfig<NumberDecoder> = {}\n): Decoder<T> {\n const prefix = config.size ?? getU8Decoder();\n const { description, fixedSize, maxSize, minRange, maxRange, isNumericEnum, enumValues } = scalarEnumCoderHelper(\n constructor,\n prefix,\n config.description\n );\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('enum', bytes, offset);\n const [value, newOffset] = prefix.decode(bytes, offset);\n const valueAsNumber = Number(value);\n offset = newOffset;\n if (valueAsNumber < minRange || valueAsNumber > maxRange) {\n // TODO: Coded error.\n throw new Error(\n `Enum discriminator out of range. ` +\n `Expected a number between ${minRange} and ${maxRange}, got ${valueAsNumber}.`\n );\n }\n return [(isNumericEnum ? valueAsNumber : enumValues[valueAsNumber]) as T, offset];\n },\n description,\n fixedSize,\n maxSize,\n };\n}\n\n/**\n * Creates a scalar enum codec.\n *\n * @param constructor - The constructor of the scalar enum.\n * @param config - A set of config for the codec.\n */\nexport function getScalarEnumCodec<T>(\n constructor: ScalarEnum<T>,\n config: ScalarEnumCodecConfig<NumberCodec> = {}\n): Codec<T> {\n return combineCodec(getScalarEnumEncoder(constructor, config), getScalarEnumDecoder(constructor, config));\n}\n","import { BaseCodecConfig, Codec, CodecData, combineCodec, Decoder, Encoder, mergeBytes } from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport {\n ArrayLikeCodecSize,\n decodeArrayLikeCodecSize,\n getArrayLikeCodecSizeDescription,\n getArrayLikeCodecSizeFromChildren,\n getArrayLikeCodecSizePrefix,\n} from './array-like-codec-size';\nimport { assertValidNumberOfItemsForCodec } from './assertions';\n\n/** Defines the config for set codecs. */\nexport type SetCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecConfig & {\n /**\n * The size of the set.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\n};\n\nfunction setCodecHelper(item: CodecData, size: ArrayLikeCodecSize<CodecData>, description?: string): CodecData {\n if (size === 'remainder' && item.fixedSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n return {\n description: description ?? `set(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize]),\n };\n}\n\n/**\n * Encodes an set of items.\n *\n * @param item - The encoder to use for the set's items.\n * @param config - A set of config for the encoder.\n */\nexport function getSetEncoder<T>(item: Encoder<T>, config: SetCodecConfig<NumberEncoder> = {}): Encoder<Set<T>> {\n const size = config.size ?? getU32Encoder();\n return {\n ...setCodecHelper(item, size, config.description),\n encode: (set: Set<T>) => {\n if (typeof size === 'number' && set.size !== size) {\n assertValidNumberOfItemsForCodec('set', size, set.size);\n }\n const itemBytes = Array.from(set, value => item.encode(value));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, set.size), ...itemBytes]);\n },\n };\n}\n\n/**\n * Decodes an set of items.\n *\n * @param item - The encoder to use for the set's items.\n * @param config - A set of config for the encoder.\n */\nexport function getSetDecoder<T>(item: Decoder<T>, config: SetCodecConfig<NumberDecoder> = {}): Decoder<Set<T>> {\n const size = config.size ?? getU32Decoder();\n return {\n ...setCodecHelper(item, size, config.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n const set: Set<T> = new Set();\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [set, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n set.add(value);\n }\n return [set, offset];\n },\n };\n}\n\n/**\n * Creates a codec for an set of items.\n *\n * @param item - The codec to use for the set's items.\n * @param config - A set of config for the codec.\n */\nexport function getSetCodec<T, U extends T = T>(\n item: Codec<T, U>,\n config: SetCodecConfig<NumberCodec> = {}\n): Codec<Set<T>, Set<U>> {\n return combineCodec(getSetEncoder(item, config), getSetDecoder(item, config));\n}\n","import { getBase58Encoder, getBase58Decoder, getBase64Decoder, getStringEncoder, getStringDecoder } from '@solana/codecs-strings';\nimport { getAddressFromPublicKey, getAddressComparator, getAddressEncoder, getAddressDecoder, assertIsAddress } from '@solana/addresses';\nimport { mapDecoder, combineCodec, mapEncoder } from '@solana/codecs-core';\nimport { getStructDecoder, getStructEncoder, getArrayEncoder, getArrayDecoder, getBytesEncoder, getBytesDecoder } from '@solana/codecs-data-structures';\nimport { getShortU16Encoder, getShortU16Decoder, getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';\nimport { pipe } from '@solana/functional';\nimport { signBytes } from '@solana/keys';\n\n// ../build-scripts/env-shim.ts\nvar __DEV__ = /* @__PURE__ */ (() => process[\"env\"].NODE_ENV === \"development\")();\n\n// src/unsigned-transaction.ts\nfunction getUnsignedTransaction(transaction) {\n if (\"signatures\" in transaction) {\n const {\n signatures: _,\n // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n\n// src/blockhash.ts\nvar base58Encoder;\nfunction assertIsBlockhash(putativeBlockhash) {\n if (!base58Encoder)\n base58Encoder = getBase58Encoder();\n try {\n if (\n // Lowest value (32 bytes of zeroes)\n putativeBlockhash.length < 32 || // Highest value (32 bytes of 255)\n putativeBlockhash.length > 44\n ) {\n throw new Error(\"Expected input string to decode to a byte array of length 32.\");\n }\n const 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}\nfunction setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) {\n if (\"lifetimeConstraint\" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n lifetimeConstraint: blockhashLifetimeConstraint\n };\n Object.freeze(out);\n return out;\n}\n\n// src/create-transaction.ts\nfunction createTransaction({\n version\n}) {\n const out = {\n instructions: [],\n version\n };\n Object.freeze(out);\n return out;\n}\n\n// ../instructions/dist/index.browser.js\nvar AccountRole = /* @__PURE__ */ ((AccountRole2) => {\n AccountRole2[AccountRole2[\"WRITABLE_SIGNER\"] = /* 3 */\n 3] = \"WRITABLE_SIGNER\";\n AccountRole2[AccountRole2[\"READONLY_SIGNER\"] = /* 2 */\n 2] = \"READONLY_SIGNER\";\n AccountRole2[AccountRole2[\"WRITABLE\"] = /* 1 */\n 1] = \"WRITABLE\";\n AccountRole2[AccountRole2[\"READONLY\"] = /* 0 */\n 0] = \"READONLY\";\n return AccountRole2;\n})(AccountRole || {});\nvar IS_WRITABLE_BITMASK = 1;\nfunction isSignerRole(role) {\n return role >= 2;\n}\nfunction isWritableRole(role) {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\nfunction mergeRoles(roleA, roleB) {\n return roleA | roleB;\n}\n\n// src/durable-nonce.ts\nvar RECENT_BLOCKHASHES_SYSVAR_ADDRESS = \"SysvarRecentB1ockHashes11111111111111111111\";\nvar SYSTEM_PROGRAM_ADDRESS = \"11111111111111111111111111111111\";\nfunction assertIsDurableNonceTransaction(transaction) {\n if (!isDurableNonceTransaction(transaction)) {\n throw new Error(\"Transaction is not a durable nonce transaction\");\n }\n}\nfunction createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) {\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]),\n programAddress: SYSTEM_PROGRAM_ADDRESS\n };\n}\nfunction isAdvanceNonceAccountInstruction(instruction) {\n return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts\n instruction.accounts?.length === 3 && // First account is nonce account address\n instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account\n instruction.accounts[2].address != null && isSignerRole(instruction.accounts[2].role);\n}\nfunction isAdvanceNonceAccountInstructionData(data) {\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\nfunction isDurableNonceTransaction(transaction) {\n return \"lifetimeConstraint\" in transaction && typeof transaction.lifetimeConstraint.nonce === \"string\" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);\n}\nfunction isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {\n return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;\n}\nfunction setTransactionLifetimeUsingDurableNonce({\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress\n}, transaction) {\n let newInstructions;\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;\n } else {\n newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];\n }\n } else {\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions.slice(1)\n ];\n }\n } else {\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions\n ];\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: newInstructions,\n lifetimeConstraint: {\n nonce\n }\n };\n Object.freeze(out);\n return out;\n}\n\n// src/fee-payer.ts\nfunction setTransactionFeePayer(feePayer, transaction) {\n if (\"feePayer\" in transaction && feePayer === transaction.feePayer) {\n return transaction;\n }\n const out = {\n ...getUnsignedTransaction(transaction),\n feePayer\n };\n Object.freeze(out);\n return out;\n}\n\n// src/instructions.ts\nfunction appendTransactionInstruction(instruction, transaction) {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [...transaction.instructions, instruction]\n };\n Object.freeze(out);\n return out;\n}\nfunction prependTransactionInstruction(instruction, transaction) {\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: [instruction, ...transaction.instructions]\n };\n Object.freeze(out);\n return out;\n}\nfunction upsert(addressMap, address, update) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\nvar TYPE = Symbol(\"AddressMapTypeProperty\");\nfunction getAddressMapFromInstructions(feePayer, instructions) {\n const addressMap = {\n [feePayer]: { [TYPE]: 0 /* FEE_PAYER */, role: AccountRole.WRITABLE_SIGNER }\n };\n const addressesOfInvokedPrograms = /* @__PURE__ */ new Set();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, (entry) => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case 0 /* FEE_PAYER */:\n throw new Error(\n `This transaction includes an address (\\`${instruction.programAddress}\\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`\n );\n default:\n throw new Error(\n `This transaction includes an address (\\`${instruction.programAddress}\\`) which is both invoked and marked writable. Program addresses may not be writable.`\n );\n }\n }\n if (entry[TYPE] === 2 /* STATIC */) {\n return entry;\n }\n }\n return { [TYPE]: 2 /* STATIC */, role: AccountRole.READONLY };\n });\n let addressComparator;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, (entry) => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case 0 /* FEE_PAYER */:\n return entry;\n case 1 /* LOOKUP_TABLE */: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\"lookupTableAddress\" in accountMeta) {\n const shouldReplaceEntry = (\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress\n ) < 0\n );\n if (shouldReplaceEntry) {\n return {\n [TYPE]: 1 /* LOOKUP_TABLE */,\n ...accountMeta,\n role: nextRole\n };\n }\n } else if (isSignerRole(accountMeta.role)) {\n return {\n [TYPE]: 2 /* STATIC */,\n role: nextRole\n };\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole\n };\n } else {\n return entry;\n }\n }\n case 2 /* STATIC */: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n throw new Error(\n `This transaction includes an address (\\`${account.address}\\`) which is both invoked and marked writable. Program addresses may not be writable.`\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole\n };\n } else {\n return entry;\n }\n } else if (\"lookupTableAddress\" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)) {\n return {\n ...accountMeta,\n [TYPE]: 1 /* LOOKUP_TABLE */,\n role: nextRole\n };\n } else {\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole\n };\n } else {\n return entry;\n }\n }\n }\n }\n }\n if (\"lookupTableAddress\" in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: 1 /* LOOKUP_TABLE */\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: 2 /* STATIC */\n };\n }\n });\n }\n }\n return addressMap;\n}\nfunction getOrderedAccountsFromAddressMap(addressMap) {\n let addressComparator;\n const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === 0 /* FEE_PAYER */) {\n return -1;\n } else if (rightEntry[TYPE] === 0 /* FEE_PAYER */) {\n return 1;\n } else if (leftEntry[TYPE] === 2 /* STATIC */) {\n return -1;\n } else if (rightEntry[TYPE] === 2 /* STATIC */) {\n return 1;\n }\n }\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n addressComparator ||= getAddressComparator();\n if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n }).map(([address, addressMeta]) => ({\n address,\n ...addressMeta\n }));\n return orderedAccounts;\n}\nfunction getCompiledAddressTableLookups(orderedAccounts) {\n const index = {};\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).sort(getAddressComparator()).map((lookupTableAddress) => ({\n lookupTableAddress,\n ...index[lookupTableAddress]\n }));\n}\n\n// src/compile-header.ts\nfunction getCompiledMessageHeader(orderedAccounts) {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if (\"lookupTableAddress\" in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts\n };\n}\n\n// src/compile-instructions.ts\nfunction getAccountIndex(orderedAccounts) {\n const out = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\nfunction getCompiledInstructions(instructions, orderedAccounts) {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null,\n ...data ? { data } : null\n };\n });\n}\n\n// src/compile-lifetime-token.ts\nfunction getCompiledLifetimeToken(lifetimeConstraint) {\n if (\"nonce\" in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n\n// src/compile-static-accounts.ts\nfunction getCompiledStaticAccounts(orderedAccounts) {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => \"lookupTableAddress\" in account);\n const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n\n// src/message.ts\nfunction compileMessage(transaction) {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...transaction.version !== \"legacy\" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null,\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),\n lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transaction.version\n };\n}\nvar lookupTableAddressDescription = __DEV__ ? \"The address of the address lookup table account from which instruction addresses should be looked up\" : \"lookupTableAddress\";\nvar writableIndicesDescription = __DEV__ ? \"The indices of the accounts in the lookup table that should be loaded as writeable\" : \"writableIndices\";\nvar readableIndicesDescription = __DEV__ ? \"The indices of the accounts in the lookup table that should be loaded as read-only\" : \"readableIndices\";\nvar addressTableLookupDescription = __DEV__ ? \"A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it\" : \"addressTableLookup\";\nvar memoizedAddressTableLookupEncoder;\nfunction getAddressTableLookupEncoder() {\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 })\n ],\n [\n \"readableIndices\",\n getArrayEncoder(getU8Encoder(), {\n description: readableIndicesDescription,\n size: getShortU16Encoder()\n })\n ]\n ],\n { description: addressTableLookupDescription }\n );\n }\n return memoizedAddressTableLookupEncoder;\n}\nvar memoizedAddressTableLookupDecoder;\nfunction getAddressTableLookupDecoder() {\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 return memoizedAddressTableLookupDecoder;\n}\nvar memoizedU8Encoder;\nfunction getMemoizedU8Encoder() {\n if (!memoizedU8Encoder)\n memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\nfunction getMemoizedU8EncoderDescription(description) {\n const encoder = getMemoizedU8Encoder();\n return {\n ...encoder,\n description: description ?? encoder.description\n };\n}\nvar memoizedU8Decoder;\nfunction getMemoizedU8Decoder() {\n if (!memoizedU8Decoder)\n memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\nfunction getMemoizedU8DecoderDescription(description) {\n const decoder = getMemoizedU8Decoder();\n return {\n ...decoder,\n description: description ?? decoder.description\n };\n}\nvar numSignerAccountsDescription = __DEV__ ? \"The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction\" : void 0;\nvar numReadonlySignerAccountsDescription = __DEV__ ? \"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\" : void 0;\nvar numReadonlyNonSignerAccountsDescription = __DEV__ ? \"The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable\" : void 0;\nvar messageHeaderDescription = __DEV__ ? \"The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses\" : void 0;\nfunction getMessageHeaderEncoder() {\n return getStructEncoder(\n [\n [\"numSignerAccounts\", getMemoizedU8EncoderDescription(numSignerAccountsDescription)],\n [\"numReadonlySignerAccounts\", getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],\n [\"numReadonlyNonSignerAccounts\", getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)]\n ],\n {\n description: messageHeaderDescription\n }\n );\n}\nfunction getMessageHeaderDecoder() {\n return getStructDecoder(\n [\n [\"numSignerAccounts\", getMemoizedU8DecoderDescription(numSignerAccountsDescription)],\n [\"numReadonlySignerAccounts\", getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],\n [\"numReadonlyNonSignerAccounts\", getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)]\n ],\n {\n description: messageHeaderDescription\n }\n );\n}\nvar programAddressIndexDescription = __DEV__ ? \"The index of the program being called, according to the well-ordered accounts list for this transaction\" : \"programAddressIndex\";\nvar accountIndexDescription = __DEV__ ? \"The index of an account, according to the well-ordered accounts list for this transaction\" : void 0;\nvar accountIndicesDescription = __DEV__ ? \"An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them\" : \"accountIndices\";\nvar dataDescription = __DEV__ ? \"An optional buffer of data passed to the instruction\" : \"data\";\nvar memoizedGetInstructionEncoder;\nfunction getInstructionEncoder() {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = mapEncoder(\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) => {\n if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {\n return instruction;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0)\n };\n }\n );\n }\n return memoizedGetInstructionEncoder;\n}\nvar memoizedGetInstructionDecoder;\nfunction getInstructionDecoder() {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = mapDecoder(\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) => {\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}\nvar VERSION_FLAG_MASK = 128;\nvar BASE_CONFIG = {\n description: __DEV__ ? \"A single byte that encodes the version of the transaction\" : \"\",\n fixedSize: null,\n maxSize: 1\n};\nfunction decode(bytes, offset = 0) {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n return [\"legacy\", offset];\n } else {\n const version = firstByte ^ VERSION_FLAG_MASK;\n return [version, offset + 1];\n }\n}\nfunction encode(value) {\n if (value === \"legacy\") {\n return new Uint8Array();\n }\n if (value < 0 || value > 127) {\n throw new Error(`Transaction version must be in the range [0, 127]. \\`${value}\\` given.`);\n }\n return new Uint8Array([value | VERSION_FLAG_MASK]);\n}\nfunction getTransactionVersionDecoder() {\n return {\n ...BASE_CONFIG,\n decode\n };\n}\nfunction getTransactionVersionEncoder() {\n return {\n ...BASE_CONFIG,\n encode\n };\n}\n\n// src/serializers/message.ts\nvar staticAccountsDescription = __DEV__ ? \"A compact-array of static account addresses belonging to this transaction\" : \"staticAccounts\";\nvar lifetimeTokenDescription = __DEV__ ? \"A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)\" : \"lifetimeToken\";\nvar instructionsDescription = __DEV__ ? \"A compact-array of instructions belonging to this transaction\" : \"instructions\";\nvar addressTableLookupsDescription = __DEV__ ? \"A compact array of address table lookups belonging to this transaction\" : \"addressTableLookups\";\nfunction getCompiledMessageLegacyEncoder() {\n return getStructEncoder(getPreludeStructEncoderTuple());\n}\nfunction getCompiledMessageVersionedEncoder() {\n return mapEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n [\"addressTableLookups\", getAddressTableLookupArrayEncoder()]\n ]),\n (value) => {\n if (value.version === \"legacy\") {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? []\n };\n }\n );\n}\nfunction getPreludeStructEncoderTuple() {\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}\nfunction getPreludeStructDecoderTuple() {\n return [\n [\"version\", getTransactionVersionDecoder()],\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}\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Encoder()\n });\n}\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Decoder()\n });\n}\nvar messageDescription = __DEV__ ? \"The wire format of a Solana transaction message\" : \"message\";\nfunction getCompiledMessageEncoder() {\n return {\n description: messageDescription,\n encode: (compiledMessage) => {\n if (compiledMessage.version === \"legacy\") {\n return getCompiledMessageLegacyEncoder().encode(compiledMessage);\n } else {\n return getCompiledMessageVersionedEncoder().encode(compiledMessage);\n }\n },\n fixedSize: null,\n maxSize: null\n };\n}\nfunction getCompiledMessageDecoder() {\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 };\n }\n );\n}\nfunction getCompiledMessageCodec() {\n return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());\n}\n\n// src/compile-transaction.ts\nfunction getCompiledTransaction(transaction) {\n const compiledMessage = compileMessage(transaction);\n let signatures;\n if (\"signatures\" in transaction) {\n signatures = [];\n for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {\n signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));\n }\n } else {\n signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));\n }\n return {\n compiledMessage,\n signatures\n };\n}\nfunction getAccountMetas(message) {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n const accountMetas = [];\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 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 for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE\n });\n accountIndex++;\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 return accountMetas;\n}\nfunction convertInstruction(instruction, accountMetas) {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);\n }\n const accounts = instruction.accountIndices?.map((accountIndex) => accountMetas[accountIndex]);\n const { data } = instruction;\n return {\n programAddress,\n ...accounts && accounts.length ? { accounts } : {},\n ...data && data.length ? { data } : {}\n };\n}\nfunction getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n return {\n blockhash: messageLifetimeToken,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n\n // U64 MAX\n };\n } else {\n const nonceAccountAddress = firstInstruction.accounts[0].address;\n assertIsAddress(nonceAccountAddress);\n const nonceAuthorityAddress = firstInstruction.accounts[2].address;\n assertIsAddress(nonceAuthorityAddress);\n return {\n nonce: messageLifetimeToken,\n nonceAccountAddress,\n nonceAuthorityAddress\n };\n }\n}\nfunction convertSignatures(compiledTransaction) {\n const {\n compiledMessage: { staticAccounts },\n signatures\n } = compiledTransaction;\n return signatures.reduce((acc, sig, index) => {\n const allZeros = sig.every((byte) => byte === 0);\n if (allZeros)\n return acc;\n const address = staticAccounts[index];\n return { ...acc, [address]: sig };\n }, {});\n}\nfunction decompileTransaction(compiledTransaction, lastValidBlockHeight) {\n const { compiledMessage } = compiledTransaction;\n if (\"addressTableLookups\" in compiledMessage && compiledMessage.addressTableLookups.length > 0) {\n throw new Error(\"Cannot convert transaction with addressTableLookups\");\n }\n const feePayer = compiledMessage.staticAccounts[0];\n if (!feePayer)\n throw new Error(\"No fee payer set in CompiledTransaction\");\n const accountMetas = getAccountMetas(compiledMessage);\n const instructions = compiledMessage.instructions.map(\n (compiledInstruction) => convertInstruction(compiledInstruction, accountMetas)\n );\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledMessage.lifetimeToken,\n firstInstruction,\n lastValidBlockHeight\n );\n const signatures = convertSignatures(compiledTransaction);\n return pipe(\n createTransaction({ version: compiledMessage.version }),\n (tx) => setTransactionFeePayer(feePayer, tx),\n (tx) => instructions.reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n (tx) => \"blockhash\" in lifetimeConstraint ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx) : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),\n (tx) => compiledTransaction.signatures.length ? { ...tx, signatures } : tx\n );\n}\n\n// src/serializers/transaction.ts\nvar signaturesDescription = __DEV__ ? \"A compact array of 64-byte, base-64 encoded Ed25519 signatures\" : \"signatures\";\nvar transactionDescription = __DEV__ ? \"The wire format of a Solana transaction\" : \"transaction\";\nfunction getCompiledTransactionEncoder() {\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}\nfunction getSignatureDecoder() {\n return mapDecoder(getBytesDecoder({ size: 64 }), (bytes) => bytes);\n}\nfunction getCompiledTransactionDecoder() {\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}\nfunction getTransactionEncoder() {\n return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);\n}\nfunction getTransactionDecoder(lastValidBlockHeight) {\n return mapDecoder(\n getCompiledTransactionDecoder(),\n (compiledTransaction) => decompileTransaction(compiledTransaction, lastValidBlockHeight)\n );\n}\nfunction getTransactionCodec(lastValidBlockHeight) {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));\n}\nvar base58Decoder;\nfunction getSignatureFromTransaction(transaction) {\n if (!base58Decoder)\n base58Decoder = getBase58Decoder();\n const signatureBytes = transaction.signatures[transaction.feePayer];\n if (!signatureBytes) {\n throw new Error(\n \"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.\"\n );\n }\n const transactionSignature = base58Decoder.decode(signatureBytes)[0];\n return transactionSignature;\n}\nasync function partiallySignTransaction(keyPairs, transaction) {\n const compiledMessage = compileMessage(transaction);\n const nextSignatures = \"signatures\" in transaction ? { ...transaction.signatures } : {};\n const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);\n const publicKeySignaturePairs = await Promise.all(\n keyPairs.map(\n (keyPair) => 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}\nasync function signTransaction(keyPairs, transaction) {\n const out = await partiallySignTransaction(keyPairs, transaction);\n assertTransactionIsFullySigned(out);\n Object.freeze(out);\n return out;\n}\nfunction assertTransactionIsFullySigned(transaction) {\n const signerAddressesFromInstructions = transaction.instructions.flatMap((i) => i.accounts?.filter((a) => isSignerRole(a.role)) ?? []).map((a) => a.address);\n const requiredSigners = /* @__PURE__ */ new Set([transaction.feePayer, ...signerAddressesFromInstructions]);\n requiredSigners.forEach((address) => {\n if (!transaction.signatures[address]) {\n throw new Error(`Transaction is missing signature for address \\`${address}\\``);\n }\n });\n}\nfunction getBase64EncodedWireTransaction(transaction) {\n const wireTransactionBytes = getTransactionEncoder().encode(transaction);\n return getBase64Decoder().decode(wireTransactionBytes)[0];\n}\n\nexport { appendTransactionInstruction, assertIsBlockhash, assertIsDurableNonceTransaction, assertTransactionIsFullySigned, compileMessage, createTransaction, getBase64EncodedWireTransaction, getCompiledMessageCodec, getCompiledMessageDecoder, getCompiledMessageEncoder, getSignatureFromTransaction, getTransactionCodec, getTransactionDecoder, getTransactionEncoder, isAdvanceNonceAccountInstruction, partiallySignTransaction, prependTransactionInstruction, setTransactionFeePayer, setTransactionLifetimeUsingBlockhash, setTransactionLifetimeUsingDurableNonce, signTransaction };\n","import { Address } from '@solana/addresses';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig, SignatureDictionary } from './types';\n\nexport type MessagePartialSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing messages. */\nexport type MessagePartialSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n signMessages(\n messages: readonly SignableMessage[],\n config?: MessagePartialSignerConfig\n ): Promise<readonly SignatureDictionary[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link MessagePartialSigner} interface. */\nexport function isMessagePartialSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is MessagePartialSigner<TAddress> {\n return 'signMessages' in value && typeof value.signMessages === 'function';\n}\n\n/** Asserts that the provided value implements the {@link MessagePartialSigner} interface. */\nexport function assertIsMessagePartialSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is MessagePartialSigner<TAddress> {\n if (!isMessagePartialSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the MessagePartialSigner interface');\n }\n}\n","import { Address } from '@solana/addresses';\nimport { CompilableTransaction } from '@solana/transactions';\n\nimport { BaseSignerConfig, SignatureDictionary } from './types';\n\nexport type TransactionPartialSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing transactions. */\nexport type TransactionPartialSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n signTransactions(\n transactions: readonly CompilableTransaction[],\n config?: TransactionPartialSignerConfig\n ): Promise<readonly SignatureDictionary[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link TransactionPartialSigner} interface. */\nexport function isTransactionPartialSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is TransactionPartialSigner<TAddress> {\n return 'signTransactions' in value && typeof value.signTransactions === 'function';\n}\n\n/** Asserts that the provided value implements the {@link TransactionPartialSigner} interface. */\nexport function assertIsTransactionPartialSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is TransactionPartialSigner<TAddress> {\n if (!isTransactionPartialSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the TransactionPartialSigner interface');\n }\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { generateKeyPair, signBytes } from '@solana/keys';\nimport { partiallySignTransaction } from '@solana/transactions';\n\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\n\n/** Defines a signer capable of signing messages and transactions using a CryptoKeyPair. */\nexport type KeyPairSigner<TAddress extends string = string> = MessagePartialSigner<TAddress> &\n TransactionPartialSigner<TAddress> & { keyPair: CryptoKeyPair };\n\n/** Checks whether the provided value implements the {@link KeyPairSigner} interface. */\nexport function isKeyPairSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is KeyPairSigner<TAddress> {\n return (\n 'keyPair' in value &&\n typeof value.keyPair === 'object' &&\n isMessagePartialSigner(value) &&\n isTransactionPartialSigner(value)\n );\n}\n\n/** Asserts that the provided value implements the {@link KeyPairSigner} interface. */\nexport function assertIsKeyPairSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is KeyPairSigner<TAddress> {\n if (!isKeyPairSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the KeyPairSigner interface');\n }\n}\n\n/** Creates a KeyPairSigner from the provided Crypto KeyPair. */\nexport async function createSignerFromKeyPair(keyPair: CryptoKeyPair): Promise<KeyPairSigner> {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const out: KeyPairSigner = {\n address,\n keyPair,\n signMessages: messages =>\n Promise.all(\n messages.map(async message =>\n Object.freeze({ [address]: await signBytes(keyPair.privateKey, message.content) })\n )\n ),\n signTransactions: transactions =>\n Promise.all(\n transactions.map(async transaction => {\n const signedTransaction = await partiallySignTransaction([keyPair], transaction);\n return Object.freeze({ [address]: signedTransaction.signatures[address] });\n })\n ),\n };\n\n return Object.freeze(out);\n}\n\n/** Securely generates a signer capable of signing messages and transactions using a Crypto KeyPair. */\nexport async function generateKeyPairSigner(): Promise<KeyPairSigner> {\n return createSignerFromKeyPair(await generateKeyPair());\n}\n","import { Address, isAddress } from '@solana/addresses';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig } from './types';\n\nexport type MessageModifyingSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing messages. */\nexport type MessageModifyingSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n modifyAndSignMessages(\n messages: readonly SignableMessage[],\n config?: MessageModifyingSignerConfig\n ): Promise<readonly SignableMessage[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link MessageModifyingSigner} interface. */\nexport function isMessageModifyingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is MessageModifyingSigner<TAddress> {\n return (\n isAddress(value.address) &&\n 'modifyAndSignMessages' in value &&\n typeof value.modifyAndSignMessages === 'function'\n );\n}\n\n/** Asserts that the provided value implements the {@link MessageModifyingSigner} interface. */\nexport function assertIsMessageModifyingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is MessageModifyingSigner<TAddress> {\n if (!isMessageModifyingSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the MessageModifyingSigner interface');\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { isMessageModifyingSigner, MessageModifyingSigner } from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\n\n/** Defines a signer capable of signing messages. */\nexport type MessageSigner<TAddress extends string = string> =\n | MessagePartialSigner<TAddress>\n | MessageModifyingSigner<TAddress>;\n\n/** Checks whether the provided value implements the {@link MessageSigner} interface. */\nexport function isMessageSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is MessageSigner<TAddress> {\n return isMessagePartialSigner(value) || isMessageModifyingSigner(value);\n}\n\n/** Asserts that the provided value implements the {@link MessageSigner} interface. */\nexport function assertIsMessageSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is MessageSigner<TAddress> {\n if (!isMessageSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement any of the MessageSigner interfaces');\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { MessagePartialSigner } from './message-partial-signer';\nimport { TransactionPartialSigner } from './transaction-partial-signer';\n\n/** Defines a no-operation signer that pretends to partially sign messages and transactions. */\nexport type NoopSigner<TAddress extends string = string> = MessagePartialSigner<TAddress> &\n TransactionPartialSigner<TAddress>;\n\n/** Creates a NoopSigner from the provided Address. */\nexport function createNoopSigner(address: Address): NoopSigner {\n const out: NoopSigner = {\n address,\n signMessages: async messages => messages.map(() => Object.freeze({})),\n signTransactions: async transactions => transactions.map(() => Object.freeze({})),\n };\n\n return Object.freeze(out);\n}\n","import { Address } from '@solana/addresses';\nimport { CompilableTransaction } from '@solana/transactions';\n\nimport { BaseSignerConfig } from './types';\n\nexport type TransactionModifyingSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing transactions. */\nexport type TransactionModifyingSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n modifyAndSignTransactions<TTransaction extends CompilableTransaction>(\n transactions: readonly TTransaction[],\n config?: TransactionModifyingSignerConfig\n ): Promise<readonly TTransaction[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link TransactionModifyingSigner} interface. */\nexport function isTransactionModifyingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is TransactionModifyingSigner<TAddress> {\n return 'modifyAndSignTransactions' in value && typeof value.modifyAndSignTransactions === 'function';\n}\n\n/** Asserts that the provided value implements the {@link TransactionModifyingSigner} interface. */\nexport function assertIsTransactionModifyingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is TransactionModifyingSigner<TAddress> {\n if (!isTransactionModifyingSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the TransactionModifyingSigner interface');\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SignatureBytes } from '@solana/keys';\nimport { CompilableTransaction } from '@solana/transactions';\n\nimport { BaseSignerConfig } from './types';\n\nexport type TransactionSendingSignerConfig = BaseSignerConfig;\n\n/** Defines a signer capable of signing and sending transactions simultaneously. */\nexport type TransactionSendingSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n signAndSendTransactions(\n transactions: readonly CompilableTransaction[],\n config?: TransactionSendingSignerConfig\n ): Promise<readonly SignatureBytes[]>;\n}>;\n\n/** Checks whether the provided value implements the {@link TransactionSendingSigner} interface. */\nexport function isTransactionSendingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is TransactionSendingSigner<TAddress> {\n return 'signAndSendTransactions' in value && typeof value.signAndSendTransactions === 'function';\n}\n\n/** Asserts that the provided value implements the {@link TransactionSendingSigner} interface. */\nexport function assertIsTransactionSendingSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is TransactionSendingSigner<TAddress> {\n if (!isTransactionSendingSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement the TransactionSendingSigner interface');\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { isTransactionModifyingSigner, TransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner, TransactionSendingSigner } from './transaction-sending-signer';\n\n/** Defines a signer capable of signing transactions. */\nexport type TransactionSigner<TAddress extends string = string> =\n | TransactionPartialSigner<TAddress>\n | TransactionModifyingSigner<TAddress>\n | TransactionSendingSigner<TAddress>;\n\n/** Checks whether the provided value implements the {@link TransactionSigner} interface. */\nexport function isTransactionSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): value is TransactionSigner<TAddress> {\n return (\n isTransactionPartialSigner(value) || isTransactionModifyingSigner(value) || isTransactionSendingSigner(value)\n );\n}\n\n/** Asserts that the provided value implements the {@link TransactionSigner} interface. */\nexport function assertIsTransactionSigner<TAddress extends string>(value: {\n address: Address<TAddress>;\n [key: string]: unknown;\n}): asserts value is TransactionSigner<TAddress> {\n if (!isTransactionSigner(value)) {\n // TODO: Coded error.\n throw new Error('The provided value does not implement any of the TransactionSigner interfaces');\n }\n}\n","import { SignatureBytes } from '@solana/keys';\nimport {\n assertTransactionIsFullySigned,\n CompilableTransaction,\n IFullySignedTransaction,\n ITransactionWithSignatures,\n} from '@solana/transactions';\n\nimport { getSignersFromTransaction, ITransactionWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isTransactionModifyingSigner, TransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner, TransactionSendingSigner } from './transaction-sending-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\nimport { ITransactionWithSingleSendingSigner } from './transaction-with-single-sending-signer';\n\ntype CompilableTransactionWithSigners = CompilableTransaction &\n ITransactionWithSigners &\n Partial<ITransactionWithSignatures>;\n\n/**\n * Signs a transaction using any signers that may be stored in IAccountSignerMeta instruction accounts\n * as well as any signers provided explicitly to this function.\n * It will ignore TransactionSendingSigners since this function does not send the transaction.\n */\nexport async function partiallySignTransactionWithSigners<\n TTransaction extends CompilableTransactionWithSigners = CompilableTransactionWithSigners\n>(\n transaction: TTransaction,\n config: { abortSignal?: AbortSignal } = {}\n): Promise<TTransaction & ITransactionWithSignatures> {\n const { partialSigners, modifyingSigners } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransaction(transaction).filter(isTransactionSigner)),\n { identifySendingSigner: false }\n );\n\n return signModifyingAndPartialTransactionSigners(transaction, modifyingSigners, partialSigners, config.abortSignal);\n}\n\n/**\n * Signs a transaction using any signers that may be stored in IAccountSignerMeta instruction accounts\n * as well as any signers provided explicitly to this function.\n * It will assert that the transaction is fully signed before returning.\n * It will ignore TransactionSendingSigners since this function does not send the transaction.\n */\nexport async function signTransactionWithSigners<\n TTransaction extends CompilableTransactionWithSigners = CompilableTransactionWithSigners\n>(\n transaction: TTransaction,\n config: { abortSignal?: AbortSignal } = {}\n): Promise<TTransaction & IFullySignedTransaction> {\n const signedTransaction = await partiallySignTransactionWithSigners(transaction, config);\n assertTransactionIsFullySigned(signedTransaction);\n return signedTransaction;\n}\n\n/**\n * Signs and sends a transaction using any signers that may be stored in IAccountSignerMeta\n * instruction accounts as well as any signers provided explicitly to this function.\n * It will identify a single TransactionSendingSigners to use for sending the transaction, if any.\n * Otherwise, it will send the transaction using the provided fallbackSender.\n */\nexport async function signAndSendTransactionWithSigners<\n TTransaction extends CompilableTransactionWithSigners &\n ITransactionWithSingleSendingSigner = CompilableTransactionWithSigners & ITransactionWithSingleSendingSigner\n>(transaction: TTransaction, config: { abortSignal?: AbortSignal } = {}): Promise<SignatureBytes> {\n const abortSignal = config.abortSignal;\n const { partialSigners, modifyingSigners, sendingSigner } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransaction(transaction).filter(isTransactionSigner))\n );\n\n abortSignal?.throwIfAborted();\n const signedTransaction = await signModifyingAndPartialTransactionSigners(\n transaction,\n modifyingSigners,\n partialSigners,\n abortSignal\n );\n\n if (!sendingSigner) {\n // TODO: Coded error.\n throw new Error(\n 'No `TransactionSendingSigner` was identified. Please provide a valid `ITransactionWithSingleSendingSigner` transaction.'\n );\n }\n\n abortSignal?.throwIfAborted();\n const [signature] = await sendingSigner.signAndSendTransactions([signedTransaction], { abortSignal });\n abortSignal?.throwIfAborted();\n\n return signature;\n}\n\n/**\n * Identifies each provided TransactionSigner and categorizes them into their respective types.\n * When a signer implements multiple interface, it will try to used to most powerful interface\n * but fallback to the least powerful interface when necessary.\n * For instance, if a signer implements TransactionSendingSigner and TransactionModifyingSigner,\n * it will be categorized as a TransactionSendingSigner if and only if no other signers implement\n * the TransactionSendingSigner interface.\n */\nfunction categorizeTransactionSigners(\n signers: readonly TransactionSigner[],\n config: { identifySendingSigner?: boolean } = {}\n): Readonly<{\n modifyingSigners: readonly TransactionModifyingSigner[];\n partialSigners: readonly TransactionPartialSigner[];\n sendingSigner: TransactionSendingSigner | null;\n}> {\n // Identify the unique sending signer that should be used.\n const identifySendingSigner = config.identifySendingSigner ?? true;\n const sendingSigner = identifySendingSigner ? identifyTransactionSendingSigner(signers) : null;\n\n // Now, focus on the other signers.\n // I.e. the modifying or partial signers that are not the identified sending signer.\n // Note that any other sending only signers will be discarded.\n const otherSigners = signers.filter(\n (signer): signer is TransactionModifyingSigner | TransactionPartialSigner =>\n signer !== sendingSigner && (isTransactionModifyingSigner(signer) || isTransactionPartialSigner(signer))\n );\n\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyTransactionModifyingSigners(otherSigners);\n\n // Use any remaining signers as partial signers.\n const partialSigners = otherSigners\n .filter(isTransactionPartialSigner)\n .filter(signer => !(modifyingSigners as typeof otherSigners).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners, sendingSigner });\n}\n\n/** Identifies the best signer to use as a TransactionSendingSigner, if any */\nfunction identifyTransactionSendingSigner(signers: readonly TransactionSigner[]): TransactionSendingSigner | null {\n // Ensure there are any TransactionSendingSigners in the first place.\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n if (sendingSigners.length === 0) return null;\n\n // Prefer sending signers that do not offer other interfaces.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionModifyingSigner(signer) && !isTransactionPartialSigner(signer)\n );\n if (sendingOnlySigners.length > 0) {\n return sendingOnlySigners[0];\n }\n\n // Otherwise, choose any sending signer.\n return sendingSigners[0];\n}\n\n/** Identifies the best signers to use as TransactionModifyingSigners, if any */\nfunction identifyTransactionModifyingSigners(\n signers: readonly (TransactionModifyingSigner | TransactionPartialSigner)[]\n): readonly TransactionModifyingSigner[] {\n // Ensure there are any TransactionModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isTransactionModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isTransactionPartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs a transaction using the provided TransactionModifyingSigners\n * sequentially followed by the TransactionPartialSigners in parallel.\n */\nasync function signModifyingAndPartialTransactionSigners<\n TTransaction extends CompilableTransactionWithSigners = CompilableTransactionWithSigners\n>(\n transaction: TTransaction,\n modifyingSigners: readonly TransactionModifyingSigner[] = [],\n partialSigners: readonly TransactionPartialSigner[] = [],\n abortSignal?: AbortSignal\n): Promise<TTransaction & ITransactionWithSignatures> {\n // Handle modifying signers sequentially.\n const modifiedTransaction = await modifyingSigners.reduce(async (transaction, modifyingSigner) => {\n abortSignal?.throwIfAborted();\n const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction], { abortSignal });\n return Object.freeze(tx);\n }, Promise.resolve(transaction) as Promise<TTransaction>);\n\n // Handle partial signers in parallel.\n abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signTransactions([modifiedTransaction], { abortSignal });\n return signatures;\n })\n );\n const signedTransaction: TTransaction & ITransactionWithSignatures = {\n ...modifiedTransaction,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedTransaction.signatures ?? {})\n ),\n };\n\n return Object.freeze(signedTransaction);\n}\n","import { TextEncoder } from 'text-encoding-impl';\n\nimport { SignatureDictionary } from './types';\n\n/** Defines a message that needs signing and its current set of signatures if any. */\nexport type SignableMessage = Readonly<{\n content: Uint8Array;\n signatures: SignatureDictionary;\n}>;\n\n/**\n * Creates a signable message from a provided content.\n * If a string is provided, it will be UTF-8 encoded.\n */\nexport function createSignableMessage(\n content: string | Uint8Array,\n signatures: SignatureDictionary = {}\n): SignableMessage {\n return Object.freeze({\n content: typeof content === 'string' ? new TextEncoder().encode(content) : content,\n signatures: Object.freeze({ ...signatures }),\n });\n}\n","import { CompilableTransaction } from '@solana/transactions';\n\nimport { getSignersFromTransaction, ITransactionWithSigners } from './account-signer-meta';\nimport { isTransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner } from './transaction-sending-signer';\n\n/** Defines a transaction with exactly one {@link TransactionSendingSigner}. */\nexport type ITransactionWithSingleSendingSigner = ITransactionWithSigners & {\n readonly __transactionWithSingleSendingSigner: unique symbol;\n};\n\n/** Checks whether the provided transaction has exactly one {@link TransactionSendingSigner}. */\nexport function isTransactionWithSingleSendingSigner<TTransaction extends CompilableTransaction>(\n transaction: TTransaction\n): transaction is TTransaction & ITransactionWithSingleSendingSigner {\n try {\n assertIsTransactionWithSingleSendingSigner(transaction);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Asserts that the provided transaction has exactly one {@link TransactionSendingSigner}. */\nexport function assertIsTransactionWithSingleSendingSigner<TTransaction extends CompilableTransaction>(\n transaction: TTransaction\n): asserts transaction is TTransaction & ITransactionWithSingleSendingSigner {\n const signers = getSignersFromTransaction(transaction);\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n\n if (sendingSigners.length === 0) {\n // TODO: Coded error.\n const error = new Error('No `TransactionSendingSigner` was identified.');\n error.name = 'MissingTransactionSendingSignerError';\n throw error;\n }\n\n // When identifying if there are multiple sending signers, we only need to check for\n // sending signers that do not implement other transaction signer interfaces as\n // they will be used as these other signer interfaces in case of a conflict.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionPartialSigner(signer) && !isTransactionModifyingSigner(signer)\n );\n\n if (sendingOnlySigners.length > 1) {\n // TODO: Coded error.\n const error = new Error('More than one `TransactionSendingSigner` was identified.');\n error.name = 'MultipleTransactionSendingSignersError';\n throw error;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/signers",
3
- "version": "2.0.0-experimental.d93c93b",
3
+ "version": "2.0.0-experimental.e4483d3",
4
4
  "description": "An abstraction layer over signing messages and transactions in Solana",
5
5
  "exports": {
6
6
  "browser": {
@@ -49,10 +49,10 @@
49
49
  "node": ">=17.4"
50
50
  },
51
51
  "dependencies": {
52
- "@solana/addresses": "2.0.0-development",
53
- "@solana/instructions": "2.0.0-development",
54
- "@solana/keys": "2.0.0-development",
55
- "@solana/transactions": "2.0.0-experimental.d93c93b"
52
+ "@solana/addresses": "2.0.0-experimental.e4483d3",
53
+ "@solana/instructions": "2.0.0-experimental.e4483d3",
54
+ "@solana/keys": "2.0.0-experimental.e4483d3",
55
+ "@solana/transactions": "2.0.0-experimental.e4483d3"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@solana/eslint-config-solana": "^1.0.2",