@solana/signers 2.0.0-experimental.e4483d3 → 2.0.0-experimental.e72afd8
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/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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AS,2CACZ,aACyE;AACzE,QAAM,UAAU,0BAA0B,WAAW;AACrD,QAAM,iBAAiB,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","// 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"]}
|
|
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/dist/index.browser.js","../../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/dist/index.browser.js","../../transactions/src/unsigned-transaction.ts","../../transactions/src/durable-nonce.ts","../../transactions/src/accounts.ts","../../transactions/src/compile-address-table-lookups.ts","../../transactions/src/compile-header.ts","../../transactions/src/compile-instructions.ts","../../transactions/src/compile-lifetime-token.ts","../../transactions/src/compile-static-accounts.ts","../../transactions/src/message.ts","../../transactions/src/serializers/message.ts","../../transactions/src/serializers/address-table-lookup.ts","../../transactions/src/serializers/header.ts","../../transactions/src/serializers/instruction.ts","../../transactions/src/serializers/transaction-version.ts","../../transactions/src/serializers/transaction.ts","../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":["alphabet","e","__DEV__","AccountRole","isSignerRole","address","getAddressComparator","getAddressDecoder","getArrayDecoder","getArrayEncoder","getStructEncoder","getU8Encoder","getStructDecoder","mapEncoder","getShortU16Decoder","mapDecoder","getBytesDecoder","transaction","TextDecoder","TextEncoder","o"],"mappings":";AAMO,SAAS,mBACZ,SACkB;AAClB,QAAM,eAAyC,CAAC;AAChD,UAAQ,QAAQ,YAAU;AACtB,QAAI,CAAC,aAAa,OAAO,OAAO,GAAG;AAC/B,mBAAa,OAAO,OAAO,IAAI;AAAA,IACnC,WAAW,aAAa,OAAO,OAAO,MAAM,QAAQ;AAEhD,YAAM,IAAI;AAAA,QACN,0DAA0D,OAAO,OAAO;AAAA,MAE5E;AAAA,IACJ;AAAA,EACJ,CAAC;AACD,SAAO,OAAO,OAAO,YAAY;AACrC;;;ACcO,SAAS,0BACZ,aACkB;AAtCtB;AAuCI,SAAO;AAAA,MACF,iBAAY,aAAZ,YAAwB,CAAC,GAAG,QAAQ,aAAY,YAAY,UAAU,QAAQ,SAAS,CAAC,CAAE;AAAA,EAC/F;AACJ;AAGO,SAAS,0BAGd,aAA+C;AAC7C,SAAO,mBAAmB,YAAY,aAAa,QAAQ,yBAAyB,CAAC;AACzF;;;ACrBO,SAAS,aAAa,MAAsF;AAC/G,SAAO,QAAQ;AACnB;;;AC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f,sBAAsB,OAAO,CAAC,YAAY,wBAAwB;AAC9D,eAAO,EAAE,GAAG,YAAY,GAAG,oBAAoB;AAAA,MACnD,IAAG,yBAAoB,eAApB,YAAkC,CAAC,CAAC;AAAA,IAC3C;AAAA,EACJ;AAEA,SAAO,OAAO,OAAO,iBAAiB;AAC1C;;;AhC3MO,IAAMC,KAAc,WAAW;AAA/B,IACMC,KAAc,WAAW;;;AiCa/B,SAAS,sBACZ,SACA,aAAkC,CAAC,GACpB;AACf,SAAO,OAAO,OAAO;AAAA,IACjB,SAAS,OAAO,YAAY,WAAW,IAAIC,GAAY,EAAE,OAAO,OAAO,IAAI;AAAA,IAC3E,YAAY,OAAO,OAAO,EAAE,GAAG,WAAW,CAAC;AAAA,EAC/C,CAAC;AACL;;;ACTO,SAAS,qCACZ,aACiE;AACjE,MAAI;AACA,+CAA2C,WAAW;AACtD,WAAO;AAAA,EACX,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAGO,SAAS,2CACZ,aACyE;AACzE,QAAM,UAAU,0BAA0B,WAAW;AACrD,QAAM,iBAAiB,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","// 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","import { combineCodec, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';\n\n// src/assertions.ts\nfunction assertNumberIsBetweenForCodec(codecDescription, min, max, value) {\n if (value < min || value > max) {\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`\n );\n }\n}\n\n// src/common.ts\nvar Endian = /* @__PURE__ */ ((Endian2) => {\n Endian2[Endian2[\"LITTLE\"] = 0] = \"LITTLE\";\n Endian2[Endian2[\"BIG\"] = 1] = \"BIG\";\n return Endian2;\n})(Endian || {});\nfunction sharedNumberFactory(input) {\n let littleEndian;\n let defaultDescription = input.name;\n if (input.size > 1) {\n littleEndian = !(\"endian\" in input.config) || input.config.endian === 0 /* LITTLE */;\n defaultDescription += littleEndian ? \"(le)\" : \"(be)\";\n }\n return {\n description: input.config.description ?? defaultDescription,\n fixedSize: input.size,\n littleEndian,\n maxSize: input.size\n };\n}\nfunction numberEncoderFactory(input) {\n const codecData = sharedNumberFactory(input);\n return {\n description: codecData.description,\n encode(value) {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, codecData.littleEndian);\n return new Uint8Array(arrayBuffer);\n },\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize\n };\n}\nfunction numberDecoderFactory(input) {\n const codecData = sharedNumberFactory(input);\n return {\n decode(bytes, offset = 0) {\n assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, codecData.littleEndian), offset + input.size];\n },\n description: codecData.description,\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize\n };\n}\nfunction toArrayBuffer(bytes, offset, length) {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n\n// src/f32.ts\nvar getF32Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"f32\",\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4\n});\nvar getF32Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: \"f32\",\n size: 4\n});\nvar getF32Codec = (config = {}) => combineCodec(getF32Encoder(config), getF32Decoder(config));\nvar getF64Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"f64\",\n set: (view, value, le) => view.setFloat64(0, value, le),\n size: 8\n});\nvar getF64Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat64(0, le),\n name: \"f64\",\n size: 8\n});\nvar getF64Codec = (config = {}) => combineCodec(getF64Encoder(config), getF64Decoder(config));\nvar getI128Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i128\",\n range: [-BigInt(\"0x7fffffffffffffffffffffffffffffff\") - 1n, BigInt(\"0x7fffffffffffffffffffffffffffffff\")],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16\n});\nvar getI128Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigInt64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: \"i128\",\n size: 16\n});\nvar getI128Codec = (config = {}) => combineCodec(getI128Encoder(config), getI128Decoder(config));\nvar getI16Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i16\",\n range: [-Number(\"0x7fff\") - 1, Number(\"0x7fff\")],\n set: (view, value, le) => view.setInt16(0, value, le),\n size: 2\n});\nvar getI16Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getInt16(0, le),\n name: \"i16\",\n size: 2\n});\nvar getI16Codec = (config = {}) => combineCodec(getI16Encoder(config), getI16Decoder(config));\nvar getI32Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i32\",\n range: [-Number(\"0x7fffffff\") - 1, Number(\"0x7fffffff\")],\n set: (view, value, le) => view.setInt32(0, value, le),\n size: 4\n});\nvar getI32Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getInt32(0, le),\n name: \"i32\",\n size: 4\n});\nvar getI32Codec = (config = {}) => combineCodec(getI32Encoder(config), getI32Decoder(config));\nvar getI64Encoder = (config = {}) => 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});\nvar getI64Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: \"i64\",\n size: 8\n});\nvar getI64Codec = (config = {}) => combineCodec(getI64Encoder(config), getI64Decoder(config));\nvar getI8Encoder = (config = {}) => 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});\nvar getI8Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view) => view.getInt8(0),\n name: \"i8\",\n size: 1\n});\nvar getI8Codec = (config = {}) => combineCodec(getI8Encoder(config), getI8Decoder(config));\nvar getShortU16Encoder = (config = {}) => ({\n description: config.description ?? \"shortU16\",\n encode: (value) => {\n assertNumberIsBetweenForCodec(\"shortU16\", 0, 65535, value);\n const bytes = [0];\n for (let ii = 0; ; ii += 1) {\n const alignedValue = value >> ii * 7;\n if (alignedValue === 0) {\n break;\n }\n const nextSevenBits = 127 & alignedValue;\n bytes[ii] = nextSevenBits;\n if (ii > 0) {\n bytes[ii - 1] |= 128;\n }\n }\n return new Uint8Array(bytes);\n },\n fixedSize: null,\n maxSize: 3\n});\nvar getShortU16Decoder = (config = {}) => ({\n decode: (bytes, offset = 0) => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 127 & currentByte;\n value |= nextSevenBits << byteIndex * 7;\n if ((currentByte & 128) === 0) {\n break;\n }\n }\n return [value, offset + byteCount];\n },\n description: config.description ?? \"shortU16\",\n fixedSize: null,\n maxSize: 3\n});\nvar getShortU16Codec = (config = {}) => combineCodec(getShortU16Encoder(config), getShortU16Decoder(config));\nvar getU128Encoder = (config = {}) => 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});\nvar getU128Decoder = (config = {}) => 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});\nvar getU128Codec = (config = {}) => combineCodec(getU128Encoder(config), getU128Decoder(config));\nvar getU16Encoder = (config = {}) => 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});\nvar getU16Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: \"u16\",\n size: 2\n});\nvar getU16Codec = (config = {}) => combineCodec(getU16Encoder(config), getU16Decoder(config));\nvar getU32Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u32\",\n range: [0, Number(\"0xffffffff\")],\n set: (view, value, le) => view.setUint32(0, value, le),\n size: 4\n});\nvar getU32Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getUint32(0, le),\n name: \"u32\",\n size: 4\n});\nvar getU32Codec = (config = {}) => combineCodec(getU32Encoder(config), getU32Decoder(config));\nvar getU64Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u64\",\n range: [0, BigInt(\"0xffffffffffffffff\")],\n set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),\n size: 8\n});\nvar getU64Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getBigUint64(0, le),\n name: \"u64\",\n size: 8\n});\nvar getU64Codec = (config = {}) => combineCodec(getU64Encoder(config), getU64Decoder(config));\nvar getU8Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u8\",\n range: [0, Number(\"0xff\")],\n set: (view, value) => view.setUint8(0, value),\n size: 1\n});\nvar getU8Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view) => view.getUint8(0),\n name: \"u8\",\n size: 1\n});\nvar getU8Codec = (config = {}) => combineCodec(getU8Encoder(config), getU8Decoder(config));\n\nexport { Endian, assertNumberIsBetweenForCodec, getF32Codec, getF32Decoder, getF32Encoder, getF64Codec, getF64Decoder, getF64Encoder, getI128Codec, getI128Decoder, getI128Encoder, getI16Codec, getI16Decoder, getI16Encoder, getI32Codec, getI32Decoder, getI32Encoder, getI64Codec, getI64Decoder, getI64Encoder, getI8Codec, getI8Decoder, getI8Encoder, getShortU16Codec, getShortU16Decoder, getShortU16Encoder, getU128Codec, getU128Decoder, getU128Encoder, getU16Codec, getU16Decoder, getU16Encoder, getU32Codec, getU32Decoder, getU32Encoder, getU64Codec, getU64Decoder, getU64Encoder, getU8Codec, getU8Decoder, getU8Encoder };\n","/**\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","import { mergeBytes, combineCodec, assertByteArrayHasEnoughBytesForCodec, assertFixedSizeCodec, assertByteArrayIsNotEmptyForCodec, fixEncoder, fixDecoder, fixBytes } from '@solana/codecs-core';\nimport { getU32Encoder, getU32Decoder, getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';\n\n// src/array.ts\n\n// src/utils.ts\nfunction maxCodecSizes(sizes) {\n return sizes.reduce(\n (all, size) => all === null || size === null ? null : Math.max(all, size),\n 0\n );\n}\nfunction sumCodecSizes(sizes) {\n return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);\n}\n\n// src/array-like-codec-size.ts\nfunction decodeArrayLikeCodecSize(size, childrenSizes, bytes, offset) {\n if (typeof size === \"number\") {\n return [size, offset];\n }\n if (typeof size === \"object\") {\n return size.decode(bytes, offset);\n }\n if (size === \"remainder\") {\n const childrenSize = sumCodecSizes(childrenSizes);\n if (childrenSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${childrenSize} bytes. Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. In other words, ${remainder} modulo ${childrenSize} should be equal to zero.`\n );\n }\n return [remainder / childrenSize, offset];\n }\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\nfunction getArrayLikeCodecSizeDescription(size) {\n return typeof size === \"object\" ? size.description : `${size}`;\n}\nfunction getArrayLikeCodecSizeFromChildren(size, childrenSizes) {\n if (typeof size !== \"number\")\n return null;\n if (size === 0)\n return 0;\n const childrenSize = sumCodecSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\nfunction getArrayLikeCodecSizePrefix(size, realSize) {\n return typeof size === \"object\" ? size.encode(realSize) : new Uint8Array();\n}\n\n// src/assertions.ts\nfunction assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {\n if (expected !== actual) {\n throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);\n }\n}\n\n// src/array.ts\nfunction arrayCodecHelper(item, size, description) {\n if (size === \"remainder\" && item.fixedSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n return {\n description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize])\n };\n}\nfunction getArrayEncoder(item, config = {}) {\n const size = config.size ?? getU32Encoder();\n return {\n ...arrayCodecHelper(item, size, config.description),\n encode: (value) => {\n if (typeof size === \"number\") {\n assertValidNumberOfItemsForCodec(\"array\", size, value.length);\n }\n return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map((v) => item.encode(v))]);\n }\n };\n}\nfunction getArrayDecoder(item, config = {}) {\n const size = config.size ?? getU32Decoder();\n return {\n ...arrayCodecHelper(item, size, config.description),\n decode: (bytes, offset = 0) => {\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [[], offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n const values = [];\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset2] = item.decode(bytes, offset);\n values.push(value);\n offset = newOffset2;\n }\n return [values, offset];\n }\n };\n}\nfunction getArrayCodec(item, config = {}) {\n return combineCodec(getArrayEncoder(item, config), getArrayDecoder(item, config));\n}\nvar getBitArrayEncoder = (size, config = {}) => {\n const parsedConfig = typeof config === \"boolean\" ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n const backwardSuffix = backward ? \"; backward\" : \"\";\n return {\n description: parsedConfig.description ?? `bitArray(${size}${backwardSuffix})`,\n encode(value) {\n const bytes = [];\n for (let i = 0; i < size; i += 1) {\n let byte = 0;\n for (let j = 0; j < 8; j += 1) {\n const feature = Number(value[i * 8 + j] ?? 0);\n byte |= feature << (backward ? j : 7 - j);\n }\n if (backward) {\n bytes.unshift(byte);\n } else {\n bytes.push(byte);\n }\n }\n return new Uint8Array(bytes);\n },\n fixedSize: size,\n maxSize: size\n };\n};\nvar getBitArrayDecoder = (size, config = {}) => {\n const parsedConfig = typeof config === \"boolean\" ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n const backwardSuffix = backward ? \"; backward\" : \"\";\n return {\n decode(bytes, offset = 0) {\n assertByteArrayHasEnoughBytesForCodec(\"bitArray\", size, bytes, offset);\n const booleans = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n slice.forEach((byte) => {\n for (let i = 0; i < 8; i += 1) {\n if (backward) {\n booleans.push(Boolean(byte & 1));\n byte >>= 1;\n } else {\n booleans.push(Boolean(byte & 128));\n byte <<= 1;\n }\n }\n });\n return [booleans, offset + size];\n },\n description: parsedConfig.description ?? `bitArray(${size}${backwardSuffix})`,\n fixedSize: size,\n maxSize: size\n };\n};\nvar getBitArrayCodec = (size, config = {}) => combineCodec(getBitArrayEncoder(size, config), getBitArrayDecoder(size, config));\nfunction getBooleanEncoder(config = {}) {\n const size = config.size ?? getU8Encoder();\n assertFixedSizeCodec(size, \"Codec [bool] requires a fixed size.\");\n return {\n description: config.description ?? `bool(${size.description})`,\n encode: (value) => size.encode(value ? 1 : 0),\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize\n };\n}\nfunction getBooleanDecoder(config = {}) {\n const size = config.size ?? getU8Decoder();\n assertFixedSizeCodec(size, \"Codec [bool] requires a fixed size.\");\n return {\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"bool\", bytes, offset);\n const [value, vOffset] = size.decode(bytes, offset);\n return [value === 1, vOffset];\n },\n description: config.description ?? `bool(${size.description})`,\n fixedSize: size.fixedSize,\n maxSize: size.fixedSize\n };\n}\nfunction getBooleanCodec(config = {}) {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\nfunction getBytesEncoder(config = {}) {\n const size = config.size ?? \"variable\";\n const sizeDescription = typeof size === \"object\" ? size.description : `${size}`;\n const description = config.description ?? `bytes(${sizeDescription})`;\n const byteEncoder = {\n description,\n encode: (value) => value,\n fixedSize: null,\n maxSize: null\n };\n if (size === \"variable\") {\n return byteEncoder;\n }\n if (typeof size === \"number\") {\n return fixEncoder(byteEncoder, size, description);\n }\n return {\n ...byteEncoder,\n encode: (value) => {\n const contentBytes = byteEncoder.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n }\n };\n}\nfunction getBytesDecoder(config = {}) {\n const size = config.size ?? \"variable\";\n const sizeDescription = typeof size === \"object\" ? size.description : `${size}`;\n const description = config.description ?? `bytes(${sizeDescription})`;\n const byteDecoder = {\n decode: (bytes, offset = 0) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n description,\n fixedSize: null,\n maxSize: null\n };\n if (size === \"variable\") {\n return byteDecoder;\n }\n if (typeof size === \"number\") {\n return fixDecoder(byteDecoder, size, description);\n }\n return {\n ...byteDecoder,\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"bytes\", bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec(\"bytes\", length, contentBytes);\n const [value, contentOffset] = byteDecoder.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n }\n };\n}\nfunction getBytesCodec(config = {}) {\n return combineCodec(getBytesEncoder(config), getBytesDecoder(config));\n}\nfunction dataEnumCodecHelper(variants, prefix, description) {\n const fieldDescriptions = variants.map(([name, codec]) => `${String(name)}${codec ? `: ${codec.description}` : \"\"}`).join(\", \");\n const allVariantHaveTheSameFixedSize = variants.every((one, _i, all) => one[1].fixedSize === all[0][1].fixedSize);\n const fixedVariantSize = allVariantHaveTheSameFixedSize ? variants[0][1].fixedSize : null;\n const maxVariantSize = maxCodecSizes(variants.map(([, field]) => field.maxSize));\n return {\n description: description ?? `dataEnum(${fieldDescriptions}; ${prefix.description})`,\n fixedSize: variants.length === 0 ? prefix.fixedSize : sumCodecSizes([prefix.fixedSize, fixedVariantSize]),\n maxSize: variants.length === 0 ? prefix.maxSize : sumCodecSizes([prefix.maxSize, maxVariantSize])\n };\n}\nfunction getDataEnumEncoder(variants, config = {}) {\n const prefix = config.size ?? getU8Encoder();\n return {\n ...dataEnumCodecHelper(variants, prefix, config.description),\n encode: (variant) => {\n const discriminator = variants.findIndex(([key]) => variant.__kind === key);\n if (discriminator < 0) {\n throw new Error(\n `Invalid data enum variant. Expected one of [${variants.map(([key]) => key).join(\", \")}], got \"${variant.__kind}\".`\n );\n }\n const variantPrefix = prefix.encode(discriminator);\n const variantSerializer = variants[discriminator][1];\n const variantBytes = variantSerializer.encode(variant);\n return mergeBytes([variantPrefix, variantBytes]);\n }\n };\n}\nfunction getDataEnumDecoder(variants, config = {}) {\n const prefix = config.size ?? getU8Decoder();\n return {\n ...dataEnumCodecHelper(variants, prefix, config.description),\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"dataEnum\", bytes, offset);\n const [discriminator, dOffset] = prefix.decode(bytes, offset);\n offset = dOffset;\n const variantField = variants[Number(discriminator)] ?? null;\n if (!variantField) {\n throw new Error(\n `Enum discriminator out of range. Expected a number between 0 and ${variants.length - 1}, got ${discriminator}.`\n );\n }\n const [variant, vOffset] = variantField[1].decode(bytes, offset);\n offset = vOffset;\n return [{ __kind: variantField[0], ...variant ?? {} }, offset];\n }\n };\n}\nfunction getDataEnumCodec(variants, config = {}) {\n return combineCodec(getDataEnumEncoder(variants, config), getDataEnumDecoder(variants, config));\n}\nfunction mapCodecHelper(key, value, size, description) {\n if (size === \"remainder\" && (key.fixedSize === null || value.fixedSize === null)) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n return {\n description: description ?? `map(${key.description}, ${value.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [key.fixedSize, value.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [key.maxSize, value.maxSize])\n };\n}\nfunction getMapEncoder(key, value, config = {}) {\n const size = config.size ?? getU32Encoder();\n return {\n ...mapCodecHelper(key, value, size, config.description),\n encode: (map) => {\n if (typeof size === \"number\") {\n assertValidNumberOfItemsForCodec(\"map\", size, map.size);\n }\n const itemBytes = Array.from(map, ([k, v]) => mergeBytes([key.encode(k), value.encode(v)]));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, map.size), ...itemBytes]);\n }\n };\n}\nfunction getMapDecoder(key, value, config = {}) {\n const size = config.size ?? getU32Decoder();\n return {\n ...mapCodecHelper(key, value, size, config.description),\n decode: (bytes, offset = 0) => {\n const map = /* @__PURE__ */ new Map();\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [map, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(\n size,\n [key.fixedSize, value.fixedSize],\n bytes,\n offset\n );\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [decodedKey, kOffset] = key.decode(bytes, offset);\n offset = kOffset;\n const [decodedValue, vOffset] = value.decode(bytes, offset);\n offset = vOffset;\n map.set(decodedKey, decodedValue);\n }\n return [map, offset];\n }\n };\n}\nfunction getMapCodec(key, value, config = {}) {\n return combineCodec(getMapEncoder(key, value, config), getMapDecoder(key, value, config));\n}\nfunction nullableCodecHelper(item, prefix, fixed, description) {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, \"Fixed nullables can only be used with fixed-size codecs.\");\n assertFixedSizeCodec(prefix, \"Fixed nullables can only be used with fixed-size prefix.\");\n descriptionSuffix += \"; fixed\";\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n return {\n description: description ?? `nullable(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize])\n };\n}\nfunction getNullableEncoder(item, config = {}) {\n const prefix = config.prefix ?? getU8Encoder();\n const fixed = config.fixed ?? false;\n return {\n ...nullableCodecHelper(item, prefix, fixed, config.description),\n encode: (option) => {\n const prefixByte = prefix.encode(Number(option !== null));\n let itemBytes = option !== null ? item.encode(option) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n }\n };\n}\nfunction getNullableDecoder(item, config = {}) {\n const prefix = config.prefix ?? getU8Decoder();\n const fixed = config.fixed ?? false;\n return {\n ...nullableCodecHelper(item, prefix, fixed, config.description),\n decode: (bytes, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [null, offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [null, fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [value, fixed ? fixedOffset : offset];\n }\n };\n}\nfunction getNullableCodec(item, config = {}) {\n return combineCodec(getNullableEncoder(item, config), getNullableDecoder(item, config));\n}\nfunction scalarEnumCoderHelper(constructor, prefix, description) {\n const enumKeys = Object.keys(constructor);\n const enumValues = Object.values(constructor);\n const isNumericEnum = enumValues.some((v) => typeof v === \"number\");\n const valueDescriptions = enumValues.filter((v) => typeof v === \"string\").join(\", \");\n const minRange = 0;\n const maxRange = isNumericEnum ? enumValues.length / 2 - 1 : enumValues.length - 1;\n const stringValues = isNumericEnum ? [...enumKeys] : [.../* @__PURE__ */ new Set([...enumKeys, ...enumValues])];\n return {\n description: description ?? `enum(${valueDescriptions}; ${prefix.description})`,\n enumKeys,\n enumValues,\n fixedSize: prefix.fixedSize,\n isNumericEnum,\n maxRange,\n maxSize: prefix.maxSize,\n minRange,\n stringValues\n };\n}\nfunction getScalarEnumEncoder(constructor, config = {}) {\n const prefix = config.size ?? getU8Encoder();\n const { description, fixedSize, maxSize, minRange, maxRange, stringValues, enumKeys, enumValues } = scalarEnumCoderHelper(constructor, prefix, config.description);\n return {\n description,\n encode: (value) => {\n const isInvalidNumber = typeof value === \"number\" && (value < minRange || value > maxRange);\n const isInvalidString = typeof value === \"string\" && !stringValues.includes(value);\n if (isInvalidNumber || isInvalidString) {\n throw new Error(\n `Invalid scalar enum variant. Expected one of [${stringValues.join(\", \")}] or a number between ${minRange} and ${maxRange}, got \"${value}\".`\n );\n }\n if (typeof value === \"number\")\n return prefix.encode(value);\n const valueIndex = enumValues.indexOf(value);\n if (valueIndex >= 0)\n return prefix.encode(valueIndex);\n return prefix.encode(enumKeys.indexOf(value));\n },\n fixedSize,\n maxSize\n };\n}\nfunction getScalarEnumDecoder(constructor, config = {}) {\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, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"enum\", bytes, offset);\n const [value, newOffset] = prefix.decode(bytes, offset);\n const valueAsNumber = Number(value);\n offset = newOffset;\n if (valueAsNumber < minRange || valueAsNumber > maxRange) {\n throw new Error(\n `Enum discriminator out of range. Expected a number between ${minRange} and ${maxRange}, got ${valueAsNumber}.`\n );\n }\n return [isNumericEnum ? valueAsNumber : enumValues[valueAsNumber], offset];\n },\n description,\n fixedSize,\n maxSize\n };\n}\nfunction getScalarEnumCodec(constructor, config = {}) {\n return combineCodec(getScalarEnumEncoder(constructor, config), getScalarEnumDecoder(constructor, config));\n}\nfunction setCodecHelper(item, size, description) {\n if (size === \"remainder\" && item.fixedSize === null) {\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n return {\n description: description ?? `set(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,\n fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),\n maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize])\n };\n}\nfunction getSetEncoder(item, config = {}) {\n const size = config.size ?? getU32Encoder();\n return {\n ...setCodecHelper(item, size, config.description),\n encode: (set) => {\n if (typeof size === \"number\" && set.size !== size) {\n assertValidNumberOfItemsForCodec(\"set\", size, set.size);\n }\n const itemBytes = Array.from(set, (value) => item.encode(value));\n return mergeBytes([getArrayLikeCodecSizePrefix(size, set.size), ...itemBytes]);\n }\n };\n}\nfunction getSetDecoder(item, config = {}) {\n const size = config.size ?? getU32Decoder();\n return {\n ...setCodecHelper(item, size, config.description),\n decode: (bytes, offset = 0) => {\n const set = /* @__PURE__ */ new Set();\n if (typeof size === \"object\" && bytes.slice(offset).length === 0) {\n return [set, offset];\n }\n const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset2] = item.decode(bytes, offset);\n offset = newOffset2;\n set.add(value);\n }\n return [set, offset];\n }\n };\n}\nfunction getSetCodec(item, config = {}) {\n return combineCodec(getSetEncoder(item, config), getSetDecoder(item, config));\n}\nfunction structCodecHelper(fields, description) {\n const fieldDescriptions = fields.map(([name, codec]) => `${String(name)}: ${codec.description}`).join(\", \");\n return {\n description: description ?? `struct(${fieldDescriptions})`,\n fixedSize: sumCodecSizes(fields.map(([, field]) => field.fixedSize)),\n maxSize: sumCodecSizes(fields.map(([, field]) => field.maxSize))\n };\n}\nfunction getStructEncoder(fields, config = {}) {\n return {\n ...structCodecHelper(fields, config.description),\n encode: (struct) => {\n const fieldBytes = fields.map(([key, codec]) => codec.encode(struct[key]));\n return mergeBytes(fieldBytes);\n }\n };\n}\nfunction getStructDecoder(fields, config = {}) {\n return {\n ...structCodecHelper(fields, config.description),\n decode: (bytes, offset = 0) => {\n const struct = {};\n fields.forEach(([key, codec]) => {\n const [value, newOffset] = codec.decode(bytes, offset);\n offset = newOffset;\n struct[key] = value;\n });\n return [struct, offset];\n }\n };\n}\nfunction getStructCodec(fields, config = {}) {\n return combineCodec(getStructEncoder(fields, config), getStructDecoder(fields, config));\n}\nfunction tupleCodecHelper(items, description) {\n const itemDescriptions = items.map((item) => item.description).join(\", \");\n return {\n description: description ?? `tuple(${itemDescriptions})`,\n fixedSize: sumCodecSizes(items.map((item) => item.fixedSize)),\n maxSize: sumCodecSizes(items.map((item) => item.maxSize))\n };\n}\nfunction getTupleEncoder(items, config = {}) {\n return {\n ...tupleCodecHelper(items, config.description),\n encode: (value) => {\n assertValidNumberOfItemsForCodec(\"tuple\", items.length, value.length);\n return mergeBytes(items.map((item, index) => item.encode(value[index])));\n }\n };\n}\nfunction getTupleDecoder(items, config = {}) {\n return {\n ...tupleCodecHelper(items, config.description),\n decode: (bytes, offset = 0) => {\n const values = [];\n items.forEach((codec) => {\n const [newValue, newOffset] = codec.decode(bytes, offset);\n values.push(newValue);\n offset = newOffset;\n });\n return [values, offset];\n }\n };\n}\nfunction getTupleCodec(items, config = {}) {\n return combineCodec(\n getTupleEncoder(items, config),\n getTupleDecoder(items, config)\n );\n}\nfunction getUnitEncoder(config = {}) {\n return {\n description: config.description ?? \"unit\",\n encode: () => new Uint8Array(),\n fixedSize: 0,\n maxSize: 0\n };\n}\nfunction getUnitDecoder(config = {}) {\n return {\n decode: (_bytes, offset = 0) => [void 0, offset],\n description: config.description ?? \"unit\",\n fixedSize: 0,\n maxSize: 0\n };\n}\nfunction getUnitCodec(config = {}) {\n return combineCodec(getUnitEncoder(config), getUnitDecoder(config));\n}\n\nexport { assertValidNumberOfItemsForCodec, decodeArrayLikeCodecSize, getArrayCodec, getArrayDecoder, getArrayEncoder, getArrayLikeCodecSizeDescription, getArrayLikeCodecSizeFromChildren, getArrayLikeCodecSizePrefix, getBitArrayCodec, getBitArrayDecoder, getBitArrayEncoder, getBooleanCodec, getBooleanDecoder, getBooleanEncoder, getBytesCodec, getBytesDecoder, getBytesEncoder, getDataEnumCodec, getDataEnumDecoder, getDataEnumEncoder, getMapCodec, getMapDecoder, getMapEncoder, getNullableCodec, getNullableDecoder, getNullableEncoder, getScalarEnumCodec, getScalarEnumDecoder, getScalarEnumEncoder, getSetCodec, getSetDecoder, getSetEncoder, getStructCodec, getStructDecoder, getStructEncoder, getTupleCodec, getTupleDecoder, getTupleEncoder, getUnitCodec, getUnitDecoder, getUnitEncoder };\n","import { ITransactionWithSignatures } from '.';\nimport { BaseTransaction } from './types';\n\nexport function getUnsignedTransaction<TTransaction extends BaseTransaction>(\n transaction: TTransaction | (TTransaction & ITransactionWithSignatures)\n): TTransaction | Omit<TTransaction & ITransactionWithSignatures, keyof ITransactionWithSignatures> {\n if ('signatures' in transaction) {\n // The implication of the lifetime constraint changing is that any existing signatures are invalid.\n const {\n signatures: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...unsignedTransaction\n } = transaction;\n return unsignedTransaction;\n } else {\n return transaction;\n }\n}\n","import { Address } from '@solana/addresses';\nimport {\n AccountRole,\n IInstruction,\n IInstructionWithAccounts,\n IInstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nimport { ITransactionWithSignatures } from './signatures';\nimport { BaseTransaction } from './types';\nimport { getUnsignedTransaction } from './unsigned-transaction';\n\ntype AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n> = IInstruction<'11111111111111111111111111111111'> &\n IInstructionWithAccounts<\n readonly [\n WritableAccount<TNonceAccountAddress>,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount<TNonceAuthorityAddress> | WritableSignerAccount<TNonceAuthorityAddress>\n ]\n > &\n IInstructionWithData<AdvanceNonceAccountInstructionData>;\ntype AdvanceNonceAccountInstructionData = Uint8Array & {\n readonly __brand: unique symbol;\n};\ntype DurableNonceConfig<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> = Readonly<{\n readonly nonce: Nonce<TNonceValue>;\n readonly nonceAccountAddress: Address<TNonceAccountAddress>;\n readonly nonceAuthorityAddress: Address<TNonceAuthorityAddress>;\n}>;\nexport type Nonce<TNonceValue extends string = string> = TNonceValue & { readonly __brand: unique symbol };\ntype NonceLifetimeConstraint<TNonceValue extends string = string> = Readonly<{\n nonce: Nonce<TNonceValue>;\n}>;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Address<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\nexport interface IDurableNonceTransaction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint<TNonceValue>;\n}\n\nexport function assertIsDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): asserts transaction is BaseTransaction & IDurableNonceTransaction {\n if (!isDurableNonceTransaction(transaction)) {\n // TODO: Coded error.\n throw new Error('Transaction is not a durable nonce transaction');\n }\n}\n\nfunction createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string\n>(\n nonceAccountAddress: Address<TNonceAccountAddress>,\n nonceAuthorityAddress: Address<TNonceAuthorityAddress>\n): AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\nexport function isAdvanceNonceAccountInstruction(\n instruction: IInstruction\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.programAddress === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accounts?.length === 3 &&\n // First account is nonce account address\n instruction.accounts[0].address != null &&\n instruction.accounts[0].role === AccountRole.WRITABLE &&\n // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS &&\n instruction.accounts[1].role === AccountRole.READONLY &&\n // Third account is nonce authority account\n instruction.accounts[2].address != null &&\n isSignerRole(instruction.accounts[2].role)\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: Uint8Array): data is AdvanceNonceAccountInstructionData {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n\nfunction isDurableNonceTransaction(\n transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)\n): transaction is BaseTransaction & IDurableNonceTransaction {\n return (\n 'lifetimeConstraint' in transaction &&\n typeof transaction.lifetimeConstraint.nonce === 'string' &&\n transaction.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transaction.instructions[0])\n );\n}\n\nfunction isAdvanceNonceAccountInstructionForNonce<\n TNonceAccountAddress extends Address = Address,\n TNonceAuthorityAddress extends Address = Address\n>(\n instruction: AdvanceNonceAccountInstruction,\n nonceAccountAddress: TNonceAccountAddress,\n nonceAuthorityAddress: TNonceAuthorityAddress\n): instruction is AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress> {\n return (\n instruction.accounts[0].address === nonceAccountAddress &&\n instruction.accounts[2].address === nonceAuthorityAddress\n );\n}\n\nexport function setTransactionLifetimeUsingDurableNonce<\n TTransaction extends BaseTransaction,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string\n>(\n {\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n }: DurableNonceConfig<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>,\n transaction: TTransaction | (TTransaction & IDurableNonceTransaction)\n): Omit<TTransaction, keyof ITransactionWithSignatures> &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue> {\n let newInstructions: [\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...IInstruction[]\n ];\n\n const firstInstruction = transaction.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {\n return transaction as TTransaction &\n IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions.slice(1),\n ];\n }\n } else {\n // we don't have an existing advance nonce instruction as the first instruction, prepend one\n newInstructions = [\n createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),\n ...transaction.instructions,\n ];\n }\n\n const out = {\n ...getUnsignedTransaction(transaction),\n instructions: newInstructions,\n lifetimeConstraint: {\n nonce,\n },\n } as TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>;\n Object.freeze(out);\n return out;\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport {\n AccountRole,\n IAccountLookupMeta,\n IAccountMeta,\n IInstruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit<WritableSignerAccount, 'address'> & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit<ReadonlyAccountLookup | WritableAccountLookup, 'address'> & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = (IAccountMeta | IAccountLookupMeta)[] & { readonly __brand: unique symbol };\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Address,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry | Record<never, never>\n ) => AddressMap[Address]\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(feePayer: Address, instructions: readonly IInstruction[]): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set<Address>();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and set as the fee payer. Program addresses may not pay fees.'\n );\n default:\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${instruction.programAddress}\\`) which is both invoked ` +\n 'and marked writable. Program addresses may not be writable.'\n );\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType<typeof getAddressComparator>;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry as FeePayerAccountEntry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry as LookupTableAccountEntry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n // TODO: Coded error.\n throw new Error(\n 'This transaction includes an address ' +\n `(\\`${account.address}\\`) which is both invoked and ` +\n 'marked writable. Program addresses may not be ' +\n 'writable.'\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry as StaticAccountEntry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType<typeof getAddressComparator>;\n const orderedAccounts: (IAccountMeta | IAccountLookupMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Address<typeof address>,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype AddressTableLookup = Readonly<{\n lookupTableAddress: Address;\n readableIndices: readonly number[];\n writableIndices: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<Address, { readonly readableIndices: number[]; readonly writableIndices: number[] }> = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readableIndices: [],\n writableIndices: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndices.push(account.addressIndex);\n } else {\n entry.readableIndices.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Address,\n ...index[lookupTableAddress as unknown as Address],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype MessageHeader = Readonly<{\n numReadonlyNonSignerAccounts: number;\n numReadonlySignerAccounts: number;\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Address } from '@solana/addresses';\nimport { IInstruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n accountIndices?: number[];\n data?: Uint8Array;\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record<Address, number> = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly IInstruction[],\n orderedAccounts: OrderedAccounts\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { IDurableNonceTransaction, ITransactionWithBlockhashLifetime } from './index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (ITransactionWithBlockhashLifetime | IDurableNonceTransaction)['lifetimeConstraint']\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Address } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Address[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { CompilableTransaction } from './compilable-transaction';\nimport { getCompiledAddressTableLookups } from './compile-address-table-lookups';\nimport { getCompiledMessageHeader } from './compile-header';\nimport { getCompiledInstructions } from './compile-instructions';\nimport { getCompiledLifetimeToken } from './compile-lifetime-token';\nimport { getCompiledStaticAccounts } from './compile-static-accounts';\n\ntype BaseCompiledMessage = Readonly<{\n header: ReturnType<typeof getCompiledMessageHeader>;\n instructions: ReturnType<typeof getCompiledInstructions>;\n lifetimeToken: ReturnType<typeof getCompiledLifetimeToken>;\n staticAccounts: ReturnType<typeof getCompiledStaticAccounts>;\n}>;\n\nexport type CompiledMessage = LegacyCompiledMessage | VersionedCompiledMessage;\n\ntype LegacyCompiledMessage = BaseCompiledMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledMessage = BaseCompiledMessage &\n Readonly<{\n addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups>;\n version: number;\n }>;\n\nexport function compileMessage(\n transaction: CompilableTransaction & Readonly<{ version: 'legacy' }>\n): LegacyCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): VersionedCompiledMessage;\nexport function compileMessage(transaction: CompilableTransaction): CompiledMessage {\n const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n return {\n ...(transaction.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),\n lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transaction.version,\n };\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n StructToDecoderTuple,\n StructToEncoderTuple,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\nimport { CompiledMessage } from '../message';\nimport { SerializedMessageBytes } from '../types';\nimport { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nconst staticAccountsDescription = __DEV__\n ? 'A compact-array of static account addresses belonging to this transaction'\n : 'staticAccounts';\nconst lifetimeTokenDescription = __DEV__\n ? 'A 32-byte token that specifies the lifetime of this transaction (eg. a ' +\n 'recent blockhash, or a durable nonce)'\n : 'lifetimeToken';\nconst instructionsDescription = __DEV__\n ? 'A compact-array of instructions belonging to this transaction'\n : 'instructions';\nconst addressTableLookupsDescription = __DEV__\n ? 'A compact array of address table lookups belonging to this transaction'\n : 'addressTableLookups';\n\nfunction getCompiledMessageLegacyEncoder(): Encoder<CompiledMessage> {\n return getStructEncoder(getPreludeStructEncoderTuple());\n}\n\nfunction getCompiledMessageVersionedEncoder(): Encoder<CompiledMessage> {\n return mapEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ] as StructToEncoderTuple<CompiledMessage>),\n (value: CompiledMessage) => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n } as Exclude<CompiledMessage, { readonly version: 'legacy' }>;\n }\n );\n}\n\nfunction getPreludeStructEncoderTuple(): StructToEncoderTuple<CompiledMessage> {\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n [\n 'staticAccounts',\n getArrayEncoder(getAddressEncoder(), {\n description: staticAccountsDescription,\n size: getShortU16Encoder(),\n }),\n ],\n [\n 'lifetimeToken',\n getStringEncoder({\n description: lifetimeTokenDescription,\n encoding: getBase58Encoder(),\n size: 32,\n }),\n ],\n [\n 'instructions',\n getArrayEncoder(getInstructionEncoder(), {\n description: instructionsDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ];\n}\n\nfunction getPreludeStructDecoderTuple(): StructToDecoderTuple<\n CompiledMessage & { addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups> }\n> {\n return [\n ['version', getTransactionVersionDecoder() as Decoder<number>],\n ['header', getMessageHeaderDecoder()],\n [\n 'staticAccounts',\n getArrayDecoder(getAddressDecoder(), {\n description: staticAccountsDescription,\n size: getShortU16Decoder(),\n }),\n ],\n [\n 'lifetimeToken',\n getStringDecoder({\n description: lifetimeTokenDescription,\n encoding: getBase58Decoder(),\n size: 32,\n }),\n ],\n [\n 'instructions',\n getArrayDecoder(getInstructionDecoder(), {\n description: instructionsDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ];\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Encoder(),\n });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), {\n description: addressTableLookupsDescription,\n size: getShortU16Decoder(),\n });\n}\n\nconst messageDescription = __DEV__ ? 'The wire format of a Solana transaction message' : 'message';\n\nexport function getCompiledMessageEncoder(): Encoder<CompiledMessage> {\n return {\n description: messageDescription,\n encode: compiledMessage => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().encode(compiledMessage) as SerializedMessageBytes;\n } else {\n return getCompiledMessageVersionedEncoder().encode(compiledMessage) as SerializedMessageBytes;\n }\n },\n fixedSize: null,\n maxSize: null,\n };\n}\n\nexport function getCompiledMessageDecoder(): Decoder<CompiledMessage> {\n return mapDecoder(\n getStructDecoder(getPreludeStructDecoderTuple(), {\n description: messageDescription,\n }),\n ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups } as Exclude<\n CompiledMessage,\n { readonly version: 'legacy' }\n >;\n }\n );\n}\n\nexport function getCompiledMessageCodec(): Codec<CompiledMessage> {\n return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport { type Codec, combineCodec, type Decoder, type Encoder } from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport type { getCompiledAddressTableLookups } from '../compile-address-table-lookups';\n\ntype AddressTableLookup = ReturnType<typeof getCompiledAddressTableLookups>[number];\n\nconst lookupTableAddressDescription = __DEV__\n ? 'The address of the address lookup table account from which instruction addresses should be looked up'\n : 'lookupTableAddress';\n\nconst writableIndicesDescription = __DEV__\n ? 'The indices of the accounts in the lookup table that should be loaded as writeable'\n : 'writableIndices';\n\nconst readableIndicesDescription = __DEV__\n ? 'The indices of the accounts in the lookup table that should be loaded as read-only'\n : 'readableIndices';\n\nconst addressTableLookupDescription = __DEV__\n ? 'A pointer to the address of an address lookup table, along with the ' +\n 'readonly/writeable indices of the addresses that should be loaded from it'\n : 'addressTableLookup';\n\nlet memoizedAddressTableLookupEncoder: Encoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupEncoder(): Encoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupEncoder) {\n memoizedAddressTableLookupEncoder = getStructEncoder(\n [\n ['lookupTableAddress', getAddressEncoder({ description: lookupTableAddressDescription })],\n [\n 'writableIndices',\n getArrayEncoder(getU8Encoder(), {\n description: writableIndicesDescription,\n size: getShortU16Encoder(),\n }) as Encoder<readonly number[]>,\n ],\n [\n 'readableIndices',\n getArrayEncoder(getU8Encoder(), {\n description: readableIndicesDescription,\n size: getShortU16Encoder(),\n }) as Encoder<readonly number[]>,\n ],\n ],\n { description: addressTableLookupDescription }\n );\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: Decoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupDecoder(): Decoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupDecoder) {\n memoizedAddressTableLookupDecoder = getStructDecoder(\n [\n ['lookupTableAddress', getAddressDecoder({ description: lookupTableAddressDescription })],\n [\n 'writableIndices',\n getArrayDecoder(getU8Decoder(), {\n description: writableIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n [\n 'readableIndices',\n getArrayDecoder(getU8Decoder(), {\n description: readableIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ],\n { description: addressTableLookupDescription }\n );\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): Codec<AddressTableLookup> {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { Codec, Decoder, Encoder } from '@solana/codecs-core';\nimport { getStructCodec, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getU8Codec, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledMessageHeader } from '../compile-header';\n\ntype MessageHeader = ReturnType<typeof getCompiledMessageHeader>;\n\nlet memoizedU8Encoder: Encoder<number> | undefined;\nfunction getMemoizedU8Encoder(): Encoder<number> {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nfunction getMemoizedU8EncoderDescription(description?: string): Encoder<number> {\n const encoder = getMemoizedU8Encoder();\n return {\n ...encoder,\n description: description ?? encoder.description,\n };\n}\n\nlet memoizedU8Decoder: Decoder<number> | undefined;\nfunction getMemoizedU8Decoder(): Decoder<number> {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nfunction getMemoizedU8DecoderDescription(description?: string): Decoder<number> {\n const decoder = getMemoizedU8Decoder();\n return {\n ...decoder,\n description: description ?? decoder.description,\n };\n}\n\nlet memoizedU8Codec: Codec<number> | undefined;\nfunction getMemoizedU8Codec(): Codec<number> {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nfunction getMemoizedU8CodecDescription(description?: string): Codec<number> {\n const codec = getMemoizedU8Codec();\n return {\n ...codec,\n description: description ?? codec.description,\n };\n}\n\nconst numSignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction'\n : undefined;\n\nconst numReadonlySignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable'\n : undefined;\n\nconst numReadonlyNonSignerAccountsDescription = __DEV__\n ? 'The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable'\n : undefined;\n\nconst messageHeaderDescription = __DEV__\n ? 'The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses'\n : undefined;\n\nexport function getMessageHeaderEncoder(): Encoder<MessageHeader> {\n return getStructEncoder(\n [\n ['numSignerAccounts', getMemoizedU8EncoderDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n\nexport function getMessageHeaderDecoder(): Decoder<MessageHeader> {\n return getStructDecoder(\n [\n ['numSignerAccounts', getMemoizedU8DecoderDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n\nexport function getMessageHeaderCodec(): Codec<MessageHeader> {\n return getStructCodec(\n [\n ['numSignerAccounts', getMemoizedU8CodecDescription(numSignerAccountsDescription)],\n ['numReadonlySignerAccounts', getMemoizedU8CodecDescription(numReadonlySignerAccountsDescription)],\n ['numReadonlyNonSignerAccounts', getMemoizedU8CodecDescription(numReadonlyNonSignerAccountsDescription)],\n ],\n {\n description: messageHeaderDescription,\n }\n );\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledInstructions } from '../compile-instructions';\n\ntype Instruction = ReturnType<typeof getCompiledInstructions>[number];\n\nconst programAddressIndexDescription = __DEV__\n ? 'The index of the program being called, according to the well-ordered accounts list for this transaction'\n : 'programAddressIndex';\n\nconst accountIndexDescription = __DEV__\n ? 'The index of an account, according to the well-ordered accounts list for this transaction'\n : undefined;\n\nconst accountIndicesDescription = __DEV__\n ? 'An optional list of account indices, according to the ' +\n 'well-ordered accounts list for this transaction, in the order in ' +\n 'which the program being called expects them'\n : 'accountIndices';\n\nconst dataDescription = __DEV__ ? 'An optional buffer of data passed to the instruction' : 'data';\n\nlet memoizedGetInstructionEncoder: Encoder<Instruction> | undefined;\nexport function getInstructionEncoder(): Encoder<Instruction> {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = mapEncoder<Required<Instruction>, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder({ description: programAddressIndexDescription })],\n [\n 'accountIndices',\n getArrayEncoder(getU8Encoder({ description: accountIndexDescription }), {\n description: accountIndicesDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ['data', getBytesEncoder({ description: dataDescription, size: getShortU16Encoder() })],\n ]),\n // Convert an instruction to have all fields defined\n (instruction: Instruction): Required<Instruction> => {\n if (instruction.accountIndices !== undefined && instruction.data !== undefined) {\n return instruction as Required<Instruction>;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0),\n } as Required<Instruction>;\n }\n );\n }\n\n return memoizedGetInstructionEncoder;\n}\n\nlet memoizedGetInstructionDecoder: Decoder<Instruction> | undefined;\nexport function getInstructionDecoder(): Decoder<Instruction> {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = mapDecoder<Required<Instruction>, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder({ description: programAddressIndexDescription })],\n [\n 'accountIndices',\n getArrayDecoder(getU8Decoder({ description: accountIndexDescription }), {\n description: accountIndicesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['data', getBytesDecoder({ description: dataDescription, size: getShortU16Decoder() })],\n ]),\n // Convert an instruction to exclude optional fields if they are empty\n (instruction: Required<Instruction>): Instruction => {\n if (instruction.accountIndices.length && instruction.data.byteLength) {\n return instruction;\n }\n const { accountIndices, data, ...rest } = instruction;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n }\n );\n }\n return memoizedGetInstructionDecoder;\n}\n\nexport function getInstructionCodec(): Codec<Instruction> {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { TransactionVersion } from '../types';\n\nconst VERSION_FLAG_MASK = 0x80;\n\nconst BASE_CONFIG = {\n description: __DEV__ ? 'A single byte that encodes the version of the transaction' : '',\n fixedSize: null,\n maxSize: 1,\n} as const;\n\nfunction decode(bytes: Uint8Array, offset = 0): [TransactionVersion, number] {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n // No version flag set; it's a legacy (unversioned) transaction.\n return ['legacy', offset];\n } else {\n const version = (firstByte ^ VERSION_FLAG_MASK) as TransactionVersion;\n return [version, offset + 1];\n }\n}\n\nfunction encode(value: TransactionVersion): Uint8Array {\n if (value === 'legacy') {\n return new Uint8Array();\n }\n if (value < 0 || value > 127) {\n // TODO: Coded error.\n throw new Error(`Transaction version must be in the range [0, 127]. \\`${value}\\` given.`);\n }\n return new Uint8Array([value | VERSION_FLAG_MASK]);\n}\n\nexport function getTransactionVersionDecoder(): Decoder<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n decode,\n };\n}\n\nexport function getTransactionVersionEncoder(): Encoder<TransactionVersion> {\n return {\n ...BASE_CONFIG,\n encode,\n };\n}\n\nexport function getTransactionVersionCodec(): Codec<TransactionVersion> {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { Codec, combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { CompilableTransaction } from '../compilable-transaction';\nimport { CompiledTransaction, getCompiledTransaction } from '../compile-transaction';\nimport { decompileTransaction } from '../decompile-transaction';\nimport { ITransactionWithSignatures } from '../signatures';\nimport { getCompiledMessageDecoder, getCompiledMessageEncoder } from './message';\n\nconst signaturesDescription = __DEV__ ? 'A compact array of 64-byte, base-64 encoded Ed25519 signatures' : 'signatures';\nconst transactionDescription = __DEV__ ? 'The wire format of a Solana transaction' : 'transaction';\n\nfunction getCompiledTransactionEncoder(): Encoder<CompiledTransaction> {\n return getStructEncoder(\n [\n [\n 'signatures',\n getArrayEncoder(getBytesEncoder({ size: 64 }), {\n description: signaturesDescription,\n size: getShortU16Encoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageEncoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nfunction getSignatureDecoder(): Decoder<SignatureBytes> {\n return mapDecoder(getBytesDecoder({ size: 64 }), bytes => bytes as SignatureBytes);\n}\n\nfunction getCompiledTransactionDecoder(): Decoder<CompiledTransaction> {\n return getStructDecoder(\n [\n [\n 'signatures',\n getArrayDecoder(getSignatureDecoder(), {\n description: signaturesDescription,\n size: getShortU16Decoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageDecoder()],\n ],\n {\n description: transactionDescription,\n }\n );\n}\n\nexport function getTransactionEncoder(): Encoder<\n CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n> {\n return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);\n}\n\nexport function getTransactionDecoder(\n lastValidBlockHeight?: bigint\n): Decoder<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return mapDecoder(getCompiledTransactionDecoder(), compiledTransaction =>\n decompileTransaction(compiledTransaction, lastValidBlockHeight)\n );\n}\n\nexport function getTransactionCodec(\n lastValidBlockHeight?: bigint\n): Codec<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));\n}\n","import { Address } 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/dist/index.native.js
CHANGED
|
@@ -290,5 +290,3 @@ function assertIsTransactionWithSingleSendingSigner(transaction) {
|
|
|
290
290
|
}
|
|
291
291
|
|
|
292
292
|
export { addSignersToInstruction, addSignersToTransaction, assertIsKeyPairSigner, assertIsMessageModifyingSigner, assertIsMessagePartialSigner, assertIsMessageSigner, assertIsTransactionModifyingSigner, assertIsTransactionPartialSigner, assertIsTransactionSendingSigner, assertIsTransactionSigner, assertIsTransactionWithSingleSendingSigner, createNoopSigner, createSignableMessage, createSignerFromKeyPair, generateKeyPairSigner, getSignersFromInstruction, getSignersFromTransaction, isKeyPairSigner, isMessageModifyingSigner, isMessagePartialSigner, isMessageSigner, isTransactionModifyingSigner, isTransactionPartialSigner, isTransactionSendingSigner, isTransactionSigner, isTransactionWithSingleSendingSigner, partiallySignTransactionWithSigners, signAndSendTransactionWithSigners, signTransactionWithSigners };
|
|
293
|
-
//# sourceMappingURL=out.js.map
|
|
294
|
-
//# sourceMappingURL=index.native.js.map
|
package/dist/index.node.cjs
CHANGED
|
@@ -320,5 +320,3 @@ exports.isTransactionWithSingleSendingSigner = isTransactionWithSingleSendingSig
|
|
|
320
320
|
exports.partiallySignTransactionWithSigners = partiallySignTransactionWithSigners;
|
|
321
321
|
exports.signAndSendTransactionWithSigners = signAndSendTransactionWithSigners;
|
|
322
322
|
exports.signTransactionWithSigners = signTransactionWithSigners;
|
|
323
|
-
//# sourceMappingURL=out.js.map
|
|
324
|
-
//# sourceMappingURL=index.node.cjs.map
|
package/dist/index.node.js
CHANGED
|
@@ -290,5 +290,3 @@ function assertIsTransactionWithSingleSendingSigner(transaction) {
|
|
|
290
290
|
}
|
|
291
291
|
|
|
292
292
|
export { addSignersToInstruction, addSignersToTransaction, assertIsKeyPairSigner, assertIsMessageModifyingSigner, assertIsMessagePartialSigner, assertIsMessageSigner, assertIsTransactionModifyingSigner, assertIsTransactionPartialSigner, assertIsTransactionSendingSigner, assertIsTransactionSigner, assertIsTransactionWithSingleSendingSigner, createNoopSigner, createSignableMessage, createSignerFromKeyPair, generateKeyPairSigner, getSignersFromInstruction, getSignersFromTransaction, isKeyPairSigner, isMessageModifyingSigner, isMessagePartialSigner, isMessageSigner, isTransactionModifyingSigner, isTransactionPartialSigner, isTransactionSendingSigner, isTransactionSigner, isTransactionWithSingleSendingSigner, partiallySignTransactionWithSigners, signAndSendTransactionWithSigners, signTransactionWithSigners };
|
|
293
|
-
//# sourceMappingURL=out.js.map
|
|
294
|
-
//# sourceMappingURL=index.node.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@solana/signers",
|
|
3
|
-
"version": "2.0.0-experimental.
|
|
3
|
+
"version": "2.0.0-experimental.e72afd8",
|
|
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-experimental.
|
|
53
|
-
"@solana/instructions": "2.0.0-experimental.
|
|
54
|
-
"@solana/keys": "2.0.0-experimental.
|
|
55
|
-
"@solana/transactions": "2.0.0-experimental.
|
|
52
|
+
"@solana/addresses": "2.0.0-experimental.e72afd8",
|
|
53
|
+
"@solana/instructions": "2.0.0-experimental.e72afd8",
|
|
54
|
+
"@solana/keys": "2.0.0-experimental.e72afd8",
|
|
55
|
+
"@solana/transactions": "2.0.0-experimental.e72afd8"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@solana/eslint-config-solana": "^1.0.2",
|