@solana/signers 2.0.0-experimental.fb88a79 → 2.0.0-experimental.fcff844
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.
package/dist/index.browser.cjs
CHANGED
|
@@ -323,5 +323,3 @@ exports.isTransactionWithSingleSendingSigner = isTransactionWithSingleSendingSig
|
|
|
323
323
|
exports.partiallySignTransactionWithSigners = partiallySignTransactionWithSigners;
|
|
324
324
|
exports.signAndSendTransactionWithSigners = signAndSendTransactionWithSigners;
|
|
325
325
|
exports.signTransactionWithSigners = signTransactionWithSigners;
|
|
326
|
-
//# sourceMappingURL=out.js.map
|
|
327
|
-
//# sourceMappingURL=index.browser.cjs.map
|
package/dist/index.browser.js
CHANGED
|
@@ -293,5 +293,3 @@ function assertIsTransactionWithSingleSendingSigner(transaction) {
|
|
|
293
293
|
}
|
|
294
294
|
|
|
295
295
|
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 };
|
|
296
|
-
//# sourceMappingURL=out.js.map
|
|
297
|
-
//# sourceMappingURL=index.browser.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/deduplicate-signers.ts","../src/account-signer-meta.ts","../../instructions/src/roles.ts","../src/add-signers.ts","../../codecs-core/src/assertions.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/codec.ts","../../codecs-core/src/fix-codec.ts","../../codecs-core/src/map-codec.ts","../../codecs-numbers/src/assertions.ts","../../codecs-numbers/src/f32.ts","../../codecs-numbers/src/utils.ts","../../codecs-numbers/src/i64.ts","../../codecs-numbers/src/i8.ts","../../codecs-numbers/src/u128.ts","../../codecs-numbers/src/u16.ts","../../codecs-strings/dist/index.browser.js","../../assertions/src/subtle-crypto.ts","../../addresses/src/address.ts","../../addresses/src/program-derived-address.ts","../../addresses/src/public-key.ts","../../keys/dist/index.browser.js","../../codecs-data-structures/src/array.ts","../../codecs-data-structures/src/utils.ts","../../codecs-data-structures/src/bit-array.ts","../../codecs-data-structures/src/boolean.ts","../../codecs-data-structures/src/nullable.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/decompile-transaction.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","../../text-encoding-impl/src/index.browser.ts","../src/signable-message.ts","../src/transaction-with-single-sending-signer.ts"],"names":["combineCodec","e","assertIsFixedSize","createDecoder","AccountRole","isSignerRole","address","getAddressDecoder","createEncoder","getStructDecoder","getU8Encoder","getU8Decoder","getStructEncoder","getArrayEncoder","mapEncoder","transaction","TextDecoder","TextEncoder","o"],"mappings":";AAMO,SAAS,mBACZ,SACkB;AAClB,QAAM,eAAyC,CAAC;AAChD,UAAQ,QAA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AAmB,GAAG,EAAE,YAAY,CAAC;AAChG,aAAO;AAAA,IACX,CAAC;AAAA,EACL;AACA,QAAM,oBAA+D;AAAA,IACjE,GAAG;AAAA,IACH,YAAY,OAAO;AAAA,MACf,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;;;AC9MO,IAAMC,KAAc,WAAW;AAA/B,IACMC,KAAc,WAAW;;;ACa/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","/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\ntype BaseEncoder<TFrom> = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => Uint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\nexport type FixedSizeEncoder<TFrom, TSize extends number = number> = BaseEncoder<TFrom> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeEncoder<TFrom> = BaseEncoder<TFrom> & {\n /** The total size of the encoded value in bytes. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value to a `Uint8Array`.\n */\nexport type Encoder<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>;\n\ntype BaseDecoder<TTo> = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\nexport type FixedSizeDecoder<TTo, TSize extends number = number> = BaseDecoder<TTo> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeDecoder<TTo> = BaseDecoder<TTo> & {\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a value from a `Uint8Array`.\n */\nexport type Decoder<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>;\n\nexport type FixedSizeCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number> = FixedSizeEncoder<\n TFrom,\n TSize\n> &\n FixedSizeDecoder<TTo, TSize>;\n\nexport type VariableSizeCodec<TFrom, TTo extends TFrom = TFrom> = VariableSizeEncoder<TFrom> & VariableSizeDecoder<TTo>;\n\n/**\n * An object that can encode and decode a value to and from a `Uint8Array`.\n * It supports encoding looser types than it decodes for convenience.\n * For example, a `bigint` encoder will always decode to a `bigint`\n * but can be used to encode a `number`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value. Defaults to `TFrom`.\n */\nexport type Codec<TFrom, TTo extends TFrom = TFrom> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>;\n\n/**\n * Get the encoded size of a given value in bytes.\n */\nexport function getEncodedSize<TFrom>(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number }\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/** Fills the missing `encode` function using the existing `write` function. */\nexport function createEncoder<TFrom, TSize extends number>(\n encoder: Omit<FixedSizeEncoder<TFrom, TSize>, 'encode'>\n): FixedSizeEncoder<TFrom, TSize>;\nexport function createEncoder<TFrom>(encoder: Omit<VariableSizeEncoder<TFrom>, 'encode'>): VariableSizeEncoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>\n): Encoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>\n): Encoder<TFrom> {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/** Fills the missing `decode` function using the existing `read` function. */\nexport function createDecoder<TTo, TSize extends number>(\n decoder: Omit<FixedSizeDecoder<TTo, TSize>, 'decode'>\n): FixedSizeDecoder<TTo, TSize>;\nexport function createDecoder<TTo>(decoder: Omit<VariableSizeDecoder<TTo>, 'decode'>): VariableSizeDecoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>\n): Decoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>\n): Decoder<TTo> {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/** Fills the missing `encode` and `decode` function using the existing `write` and `read` functions. */\nexport function createCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number>(\n codec: Omit<FixedSizeCodec<TFrom, TTo, TSize>, 'encode' | 'decode'>\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec: Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n): VariableSizeCodec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n): Codec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n): Codec<TFrom, TTo> {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\nexport function isFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>\n): encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function isFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>\n): decoder is FixedSizeDecoder<TTo, TSize>;\nexport function isFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>\n): codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function isFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number }\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\nexport function assertIsFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n message?: string\n): asserts encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function assertIsFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n message?: string\n): asserts decoder is FixedSizeDecoder<TTo, TSize>;\nexport function assertIsFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n message?: string\n): asserts codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function assertIsFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n message?: string\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n\nexport function isVariableSize<TFrom>(encoder: Encoder<TFrom>): encoder is VariableSizeEncoder<TFrom>;\nexport function isVariableSize<TTo>(decoder: Decoder<TTo>): decoder is VariableSizeDecoder<TTo>;\nexport function isVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>\n): codec is VariableSizeCodec<TFrom, TTo>;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\nexport function assertIsVariableSize<T>(\n encoder: Encoder<T>,\n message?: string\n): asserts encoder is VariableSizeEncoder<T>;\nexport function assertIsVariableSize<T>(\n decoder: Decoder<T>,\n message?: string\n): asserts decoder is VariableSizeDecoder<T>;\nexport function assertIsVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n message?: string\n): asserts codec is VariableSizeCodec<TFrom, TTo>;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a variable-size codec, got a fixed-size one.');\n }\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n Offset,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n */\nexport function fixEncoder<TFrom, TSize extends number>(\n encoder: Encoder<TFrom>,\n fixedBytes: TSize\n): FixedSizeEncoder<TFrom, TSize> {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value: TFrom, bytes: Uint8Array, offset: Offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function as using the nested `write` function on a fixed-sized byte\n // array may result in a out-of-bounds error on the nested encoder.\n const variableByteArray = encoder.encode(value);\n const fixedByteArray =\n variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n },\n });\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n */\nexport function fixDecoder<TTo, TSize extends number>(\n decoder: Decoder<TTo>,\n fixedBytes: TSize\n): FixedSizeDecoder<TTo, TSize> {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes: Uint8Array, offset: Offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n },\n });\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n */\nexport function fixCodec<TFrom, TTo extends TFrom, TSize extends number>(\n codec: Codec<TFrom, TTo>,\n fixedBytes: TSize\n): FixedSizeCodec<TFrom, TTo, TSize> {\n return combineCodec(fixEncoder(codec, fixedBytes), fixDecoder(codec, fixedBytes));\n}\n","import {\n Codec,\n createCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isVariableSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<TOldFrom, TNewFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TOldFrom, TSize>,\n unmap: (value: TNewFrom) => TOldFrom\n): FixedSizeEncoder<TNewFrom, TSize>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: VariableSizeEncoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom\n): VariableSizeEncoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom\n): Encoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom\n): Encoder<TNewFrom> {\n return createEncoder({\n ...(isVariableSize(encoder)\n ? { ...encoder, getSizeFromValue: (value: TNewFrom) => encoder.getSizeFromValue(unmap(value)) }\n : encoder),\n write: (value: TNewFrom, bytes, offset) => encoder.write(unmap(value), bytes, offset),\n });\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<TOldTo, TNewTo, TSize extends number>(\n decoder: FixedSizeDecoder<TOldTo, TSize>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): FixedSizeDecoder<TNewTo, TSize>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: VariableSizeDecoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): VariableSizeDecoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): Decoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): Decoder<TNewTo> {\n return createDecoder({\n ...decoder,\n read: (bytes: Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom\n): FixedSizeCodec<TNewFrom, TTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: VariableSizeCodec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom\n): VariableSizeCodec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: Codec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom\n): Codec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TOldTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): FixedSizeCodec<TNewFrom, TNewTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: VariableSizeCodec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): VariableSizeCodec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): Codec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): Codec<TNewFrom, TNewTo> {\n return createCodec({\n ...mapEncoder(codec, unmap),\n read: map ? mapDecoder(codec, map).read : (codec.read as unknown as Decoder<TNewTo>['read']),\n });\n}\n","/**\n * Asserts that a given number is between a given range.\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint,\n) {\n if (value < min || value > max) {\n // TODO: Coded error.\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`,\n );\n }\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number, 4> =>\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 = {}): FixedSizeDecoder<number, 4> =>\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 = {}): FixedSizeCodec<number, number, 4> =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n createDecoder,\n createEncoder,\n FixedSizeDecoder,\n FixedSizeEncoder,\n Offset,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput<TSize extends number> = {\n name: string;\n size: TSize;\n config?: NumberCodecConfig;\n};\n\ntype NumberFactoryEncoderInput<TFrom, TSize extends number> = NumberFactorySharedInput<TSize> & {\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: TFrom, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput<TTo, TSize extends number> = NumberFactorySharedInput<TSize> & {\n get: (view: DataView, littleEndian?: boolean) => TTo;\n};\n\nfunction isLittleEndian(config?: NumberCodecConfig): boolean {\n return config?.endian === Endian.BIG ? false : true;\n}\n\nexport function numberEncoderFactory<TFrom extends number | bigint, TSize extends number>(\n input: NumberFactoryEncoderInput<TFrom, TSize>\n): FixedSizeEncoder<TFrom, TSize> {\n return createEncoder({\n fixedSize: input.size,\n write(value: TFrom, bytes: Uint8Array, offset: Offset): Offset {\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, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n },\n });\n}\n\nexport function numberDecoderFactory<TTo extends number | bigint, TSize extends number>(\n input: NumberFactoryDecoderInput<TTo, TSize>\n): FixedSizeDecoder<TTo, TSize> {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0): [TTo, number] {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n },\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 { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number | bigint, 8> =>\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 = {}): FixedSizeDecoder<bigint, 8> =>\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 = {}): FixedSizeCodec<number | bigint, bigint, 8> =>\n combineCodec(getI64Encoder(config), getI64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getI8Encoder = (): FixedSizeEncoder<number, 1> =>\n numberEncoderFactory({\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 = (): FixedSizeDecoder<number, 1> =>\n numberDecoderFactory({\n get: view => view.getInt8(0),\n name: 'i8',\n size: 1,\n });\n\nexport const getI8Codec = (): FixedSizeCodec<number, number, 1> => combineCodec(getI8Encoder(), getI8Decoder());\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number | bigint, 16> =>\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 = {}): FixedSizeDecoder<bigint, 16> =>\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 = {}): FixedSizeCodec<number | bigint, bigint, 16> =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number, 2> =>\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 = {}): FixedSizeDecoder<number, 2> =>\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 = {}): FixedSizeCodec<number, number, 2> =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","import { createEncoder, createDecoder, combineCodec, fixEncoder, getEncodedSize, fixDecoder, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';\nimport { getU32Encoder, getU32Decoder } from '@solana/codecs-numbers';\n\n// src/assertions.ts\nfunction assertValidBaseString(alphabet4, testValue, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {\n throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);\n }\n}\nvar getBaseXEncoder = (alphabet4) => {\n return createEncoder({\n getSizeFromValue: (value) => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);\n if (tailChars === \"\")\n return value.length;\n const base10Number = getBigIntFromBaseX(tailChars, alphabet4);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value, bytes, offset) {\n assertValidBaseString(alphabet4, value);\n if (value === \"\")\n return offset;\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);\n if (tailChars === \"\") {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n let base10Number = getBigIntFromBaseX(tailChars, alphabet4);\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n }\n });\n};\nvar getBaseXDecoder = (alphabet4) => {\n return createDecoder({\n read(rawBytes, offset) {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0)\n return [\"\", 0];\n let trailIndex = bytes.findIndex((n) => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet4[0].repeat(trailIndex);\n if (trailIndex === bytes.length)\n return [leadingZeroes, rawBytes.length];\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n const tailChars = getBaseXFromBigInt(base10Number, alphabet4);\n return [leadingZeroes + tailChars, rawBytes.length];\n }\n });\n};\nvar getBaseXCodec = (alphabet4) => combineCodec(getBaseXEncoder(alphabet4), getBaseXDecoder(alphabet4));\nfunction partitionLeadingZeroes(value, zeroCharacter) {\n const leadingZeroIndex = [...value].findIndex((c) => c !== zeroCharacter);\n return leadingZeroIndex === -1 ? [value, \"\"] : [value.slice(0, leadingZeroIndex), value.slice(leadingZeroIndex)];\n}\nfunction getBigIntFromBaseX(value, alphabet4) {\n const base = BigInt(alphabet4.length);\n return [...value].reduce((sum, char) => sum * base + BigInt(alphabet4.indexOf(char)), 0n);\n}\nfunction getBaseXFromBigInt(value, alphabet4) {\n const base = BigInt(alphabet4.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet4[Number(value % base)]);\n value /= base;\n }\n return tailChars.join(\"\");\n}\n\n// src/base10.ts\nvar alphabet = \"0123456789\";\nvar getBase10Encoder = () => getBaseXEncoder(alphabet);\nvar getBase10Decoder = () => getBaseXDecoder(alphabet);\nvar getBase10Codec = () => getBaseXCodec(alphabet);\nvar getBase16Encoder = () => createEncoder({\n getSizeFromValue: (value) => Math.ceil(value.length / 2),\n write(value, bytes, offset) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString(\"0123456789abcdef\", lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n const hexBytes = matches ? matches.map((byte) => parseInt(byte, 16)) : [];\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n }\n});\nvar getBase16Decoder = () => createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, \"0\"), \"\");\n return [value, bytes.length];\n }\n});\nvar getBase16Codec = () => combineCodec(getBase16Encoder(), getBase16Decoder());\n\n// src/base58.ts\nvar alphabet2 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nvar getBase58Encoder = () => getBaseXEncoder(alphabet2);\nvar getBase58Decoder = () => getBaseXDecoder(alphabet2);\nvar getBase58Codec = () => getBaseXCodec(alphabet2);\nvar getBaseXResliceEncoder = (alphabet4, bits) => createEncoder({\n getSizeFromValue: (value) => Math.floor(value.length * bits / 8),\n write(value, bytes, offset) {\n assertValidBaseString(alphabet4, value);\n if (value === \"\")\n return offset;\n const charIndices = [...value].map((c) => alphabet4.indexOf(c));\n const reslicedBytes = reslice(charIndices, bits, 8, false);\n bytes.set(reslicedBytes, offset);\n return reslicedBytes.length + offset;\n }\n});\nvar getBaseXResliceDecoder = (alphabet4, bits) => createDecoder({\n read(rawBytes, offset = 0) {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0)\n return [\"\", rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map((i) => alphabet4[i]).join(\"\"), rawBytes.length];\n }\n});\nvar getBaseXResliceCodec = (alphabet4, bits) => combineCodec(getBaseXResliceEncoder(alphabet4, bits), getBaseXResliceDecoder(alphabet4, bits));\nfunction reslice(input, inputBits, outputBits, useRemainder) {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = accumulator << inputBits | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push(accumulator >> bitsInAccumulator & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push(accumulator << outputBits - bitsInAccumulator & mask);\n }\n return output;\n}\nvar getBase64Encoder = () => {\n {\n return createEncoder({\n getSizeFromValue: (value) => {\n try {\n return atob(value).length;\n } catch (e2) {\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n write(value, bytes, offset) {\n try {\n const bytesToAdd = atob(value).split(\"\").map((c) => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch (e2) {\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n }\n });\n }\n};\nvar getBase64Decoder = () => {\n {\n return createDecoder({\n read(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = btoa(String.fromCharCode(...slice));\n return [value, bytes.length];\n }\n });\n }\n};\nvar getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());\n\n// src/null-characters.ts\nvar removeNullCharacters = (value) => (\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, \"\")\n);\nvar padNullCharacters = (value, chars) => value.padEnd(chars, \"\\0\");\n\n// ../text-encoding-impl/dist/index.browser.js\nvar e = globalThis.TextDecoder;\nvar o = globalThis.TextEncoder;\n\n// src/utf8.ts\nvar getUtf8Encoder = () => {\n let textEncoder;\n return createEncoder({\n getSizeFromValue: (value) => (textEncoder ||= new o()).encode(value).length,\n write: (value, bytes, offset) => {\n const bytesToAdd = (textEncoder ||= new o()).encode(value);\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n }\n });\n};\nvar getUtf8Decoder = () => {\n let textDecoder;\n return createDecoder({\n read(bytes, offset) {\n const value = (textDecoder ||= new e()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n }\n });\n};\nvar getUtf8Codec = () => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n\n// src/string.ts\nfunction getStringEncoder(config = {}) {\n const size = config.size ?? getU32Encoder();\n const encoding = config.encoding ?? getUtf8Encoder();\n if (size === \"variable\") {\n return encoding;\n }\n if (typeof size === \"number\") {\n return fixEncoder(encoding, size);\n }\n return createEncoder({\n getSizeFromValue: (value) => {\n const contentSize = getEncodedSize(value, encoding);\n return getEncodedSize(contentSize, size) + contentSize;\n },\n write: (value, bytes, offset) => {\n const contentSize = getEncodedSize(value, encoding);\n offset = size.write(contentSize, bytes, offset);\n return encoding.write(value, bytes, offset);\n }\n });\n}\nfunction getStringDecoder(config = {}) {\n const size = config.size ?? getU32Decoder();\n const encoding = config.encoding ?? getUtf8Decoder();\n if (size === \"variable\") {\n return encoding;\n }\n if (typeof size === \"number\") {\n return fixDecoder(encoding, size);\n }\n return createDecoder({\n read: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"string\", bytes, offset);\n const [lengthBigInt, lengthOffset] = size.read(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.read(contentBytes, 0);\n offset += contentOffset;\n return [value, offset];\n }\n });\n}\nfunction getStringCodec(config = {}) {\n return combineCodec(getStringEncoder(config), getStringDecoder(config));\n}\n\nexport { assertValidBaseString, getBase10Codec, getBase10Decoder, getBase10Encoder, getBase16Codec, getBase16Decoder, getBase16Encoder, getBase58Codec, getBase58Decoder, getBase58Encoder, getBase64Codec, getBase64Decoder, getBase64Encoder, getBaseXCodec, getBaseXDecoder, getBaseXEncoder, getBaseXResliceCodec, getBaseXResliceDecoder, getBaseXResliceEncoder, getStringCodec, getStringDecoder, getStringEncoder, getUtf8Codec, getUtf8Decoder, getUtf8Encoder, padNullCharacters, removeNullCharacters };\n","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 {\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n mapEncoder,\n} 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(): FixedSizeEncoder<Address, 32> {\n return mapEncoder(getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }), putativeAddress =>\n address(putativeAddress),\n );\n}\n\nexport function getAddressDecoder(): FixedSizeDecoder<Address, 32> {\n return getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 }) as FixedSizeDecoder<Address, 32>;\n}\n\nexport function getAddressCodec(): FixedSizeCodec<Address, Address, 32> {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\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);\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);\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 return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n","import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\n// src/key-pair.ts\nasync function generateKeyPair() {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */\n \"Ed25519\",\n // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */\n false,\n // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */\n [\"sign\", \"verify\"]\n );\n return keyPair;\n}\n\n// src/private-key.ts\nfunction addPkcs8Header(bytes) {\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 48,\n // ASN.1 sequence tag\n 46,\n // Length of sequence (46 more bytes)\n 2,\n // ASN.1 integer tag\n 1,\n // Length of integer\n 0,\n // Version number\n 48,\n // ASN.1 sequence tag\n 5,\n // Length of sequence\n 6,\n // ASN.1 object identifier tag\n 3,\n // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 43,\n // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 101,\n // thawte(101)\n // Ed25519 identifier\n 112,\n // id-Ed25519(112)\n /**\n * Private key payload\n */\n 4,\n // ASN.1 octet string tag\n 34,\n // String length (34 more bytes)\n // Private key bytes as octet string\n 4,\n // ASN.1 octet string tag\n 32,\n // String length (32 bytes)\n ...bytes\n ]);\n}\nasync function createPrivateKeyFromBytes(bytes, extractable) {\n if (bytes.byteLength !== 32) {\n throw new Error(\"Private key bytes must be of length 32\");\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey(\"pkcs8\", privateKeyBytesPkcs8, \"Ed25519\", extractable ?? false, [\"sign\"]);\n}\nvar base58Encoder;\nfunction assertIsSignature(putativeSignature) {\n if (!base58Encoder)\n base58Encoder = getBase58Encoder();\n try {\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 || // 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 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}\nfunction isSignature(putativeSignature) {\n if (!base58Encoder)\n base58Encoder = getBase58Encoder();\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 || // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\nasync function signBytes(key, data) {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign(\"Ed25519\", key, data);\n return new Uint8Array(signedData);\n}\nfunction signature(putativeSignature) {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\nasync function verifySignature(key, signature2, data) {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify(\"Ed25519\", key, signature2, data);\n}\n\nexport { assertIsSignature, createPrivateKeyFromBytes, generateKeyPair, isSignature, signBytes, signature, verifySignature };\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n Offset,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { getFixedSize, getMaxSize } 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> =\n | TPrefix\n | number\n | 'remainder';\n\n/** Defines the configs for array codecs. */\nexport type ArrayCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = {\n /**\n * The size of the array.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\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<TFrom>(\n item: Encoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> & { size: 0 }\n): FixedSizeEncoder<TFrom[], 0>;\nexport function getArrayEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> & { size: number }\n): FixedSizeEncoder<TFrom[]>;\nexport function getArrayEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> & { size: 'remainder' }\n): VariableSizeEncoder<TFrom[]>;\nexport function getArrayEncoder<TFrom>(\n item: Encoder<TFrom>,\n config?: ArrayCodecConfig<NumberEncoder> & { size?: number | NumberEncoder }\n): VariableSizeEncoder<TFrom[]>;\nexport function getArrayEncoder<TFrom>(\n item: Encoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> = {}\n): Encoder<TFrom[]> {\n const size = config.size ?? getU32Encoder();\n if (size === 'remainder') {\n assertIsFixedSize(item, 'Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n const fixedSize = computeArrayLikeCodecSize(size, getFixedSize(item));\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize !== null\n ? { fixedSize }\n : {\n getSizeFromValue: (array: TFrom[]) => {\n const prefixSize = typeof size === 'object' ? getEncodedSize(array.length, size) : 0;\n return prefixSize + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);\n },\n maxSize,\n }),\n write: (array: TFrom[], bytes, offset) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, array.length);\n }\n if (typeof size === 'object') {\n offset = size.write(array.length, bytes, offset);\n }\n array.forEach(value => {\n offset = item.write(value, bytes, offset);\n });\n return offset;\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<TTo>(\n item: Decoder<TTo>,\n config: ArrayCodecConfig<NumberDecoder> & { size: 0 }\n): FixedSizeDecoder<TTo[], 0>;\nexport function getArrayDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: ArrayCodecConfig<NumberDecoder> & { size: number }\n): FixedSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: ArrayCodecConfig<NumberDecoder> & { size: 'remainder' }\n): VariableSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(\n item: Decoder<TTo>,\n config?: ArrayCodecConfig<NumberDecoder> & { size?: number | NumberDecoder }\n): VariableSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(item: Decoder<TTo>, config: ArrayCodecConfig<NumberDecoder> = {}): Decoder<TTo[]> {\n const size = config.size ?? getU32Decoder();\n if (size === 'remainder') {\n assertIsFixedSize(item, 'Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n const itemSize = getFixedSize(item);\n const fixedSize = computeArrayLikeCodecSize(size, itemSize);\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize !== null ? { fixedSize } : { maxSize }),\n read: (bytes: Uint8Array, offset) => {\n const array: TTo[] = [];\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [array, offset];\n }\n const [resolvedSize, newOffset] = readArrayLikeCodecSize(size, itemSize, bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, 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<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> & { size: 0 }\n): FixedSizeCodec<TFrom[], TTo[], 0>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> & { size: number }\n): FixedSizeCodec<TFrom[], TTo[]>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> & { size: 'remainder' }\n): VariableSizeCodec<TFrom[], TTo[]>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config?: ArrayCodecConfig<NumberCodec> & { size?: number | NumberCodec }\n): VariableSizeCodec<TFrom[], TTo[]>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> = {}\n): Codec<TFrom[], TTo[]> {\n return combineCodec(getArrayEncoder(item, config as object), getArrayDecoder(item, config as object));\n}\n\nfunction readArrayLikeCodecSize(\n size: ArrayLikeCodecSize<NumberDecoder>,\n itemSize: 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.read(bytes, offset);\n }\n\n if (size === 'remainder') {\n if (itemSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = Math.max(0, bytes.length - offset);\n if (remainder % itemSize !== 0) {\n // TODO: Coded error.\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${itemSize} bytes. ` +\n `Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainder} modulo ${itemSize} should be equal to zero.`\n );\n }\n return [remainder / itemSize, offset];\n }\n\n // TODO: Coded error.\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\n\nfunction computeArrayLikeCodecSize(size: object | number | 'remainder', itemSize: number | null): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n return itemSize === null ? null : itemSize * size;\n}\n","import { isFixedSize } from '@solana/codecs-core';\n\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\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\nexport function getFixedSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : null;\n}\n\nexport function getMaxSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from '@solana/codecs-core';\n\n/** Defines the config for bitArray codecs. */\nexport type BitArrayCodecConfig = {\n /**\n * Whether to read the bits in reverse order.\n * @defaultValue `false`\n */\n backward?: boolean;\n};\n\n/**\n * Encodes an array of booleans into bits.\n *\n * @param size - The amount of bytes to use for the bit array.\n * @param config - A set of config for the encoder.\n */\nexport function getBitArrayEncoder<TSize extends number>(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {}\n): FixedSizeEncoder<boolean[], TSize> {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createEncoder({\n fixedSize: size,\n write(value: boolean[], bytes, offset) {\n const bytesToAdd: number[] = [];\n\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 bytesToAdd.unshift(byte);\n } else {\n bytesToAdd.push(byte);\n }\n }\n\n bytes.set(bytesToAdd, offset);\n return size;\n },\n });\n}\n\n/**\n * Decodes bits into an array of booleans.\n *\n * @param size - The amount of bytes to use for the bit array.\n * @param config - A set of config for the decoder.\n */\nexport function getBitArrayDecoder<TSize extends number>(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {}\n): FixedSizeDecoder<boolean[], TSize> {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createDecoder({\n fixedSize: size,\n read(bytes, offset) {\n assertByteArrayHasEnoughBytesForCodec('bitArray', size, bytes, offset);\n const booleans: boolean[] = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n\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 & 0b1000_0000));\n byte <<= 1;\n }\n }\n });\n\n return [booleans, offset + size];\n },\n });\n}\n\n/**\n * An array of boolean codec that converts booleans to bits and vice versa.\n *\n * @param size - The amount of bytes to use for the bit array.\n * @param config - A set of config for the codec.\n */\nexport function getBitArrayCodec<TSize extends number>(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {}\n): FixedSizeCodec<boolean[], boolean[], TSize> {\n return combineCodec(getBitArrayEncoder(size, config), getBitArrayDecoder(size, config));\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n mapDecoder,\n mapEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\n/** Defines the config for boolean codecs. */\nexport type BooleanCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = {\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(): FixedSizeEncoder<boolean, 1>;\nexport function getBooleanEncoder<TSize extends number>(\n config: BooleanCodecConfig<NumberEncoder> & { size: FixedSizeNumberEncoder<TSize> }\n): FixedSizeEncoder<boolean, TSize>;\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder>): Encoder<boolean>;\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder> = {}): Encoder<boolean> {\n const size = config.size ?? getU8Encoder();\n assertIsFixedSize(size, 'Codec [bool] requires a fixed size.');\n return mapEncoder(size, (value: boolean) => (value ? 1 : 0));\n}\n\n/**\n * Decodes booleans.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBooleanDecoder(): FixedSizeDecoder<boolean, 1>;\nexport function getBooleanDecoder<TSize extends number>(\n config: BooleanCodecConfig<NumberDecoder> & { size: FixedSizeNumberDecoder<TSize> }\n): FixedSizeDecoder<boolean, TSize>;\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder>): Decoder<boolean>;\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder> = {}): Decoder<boolean> {\n const size = config.size ?? getU8Decoder();\n assertIsFixedSize(size, 'Codec [bool] requires a fixed size.');\n return mapDecoder(size, (value: number | bigint): boolean => Number(value) === 1);\n}\n\n/**\n * Creates a boolean codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBooleanCodec(): FixedSizeCodec<boolean, boolean, 1>;\nexport function getBooleanCodec<TSize extends number>(\n config: BooleanCodecConfig<NumberCodec> & { size: FixedSizeNumberCodec<TSize> }\n): FixedSizeCodec<boolean, boolean, TSize>;\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec>): Codec<boolean>;\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec> = {}): Codec<boolean> {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { getMaxSize, sumCodecSizes } from './utils';\n\n/** Defines the config for nullable codecs. */\nexport type NullableCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `null` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param config - A set of config for the encoder.\n */\nexport function getNullableEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: NullableCodecConfig<FixedSizeNumberEncoder> & { fixed: true }\n): FixedSizeEncoder<TFrom | null>;\nexport function getNullableEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom, 0>,\n config?: NullableCodecConfig<FixedSizeNumberEncoder>\n): FixedSizeEncoder<TFrom | null>;\nexport function getNullableEncoder<TFrom>(\n item: Encoder<TFrom>,\n config?: NullableCodecConfig<NumberEncoder> & { fixed?: false }\n): VariableSizeEncoder<TFrom | null>;\nexport function getNullableEncoder<TFrom>(\n item: Encoder<TFrom>,\n config: NullableCodecConfig<NumberEncoder> = {}\n): Encoder<TFrom | null> {\n const prefix = config.prefix ?? getU8Encoder();\n const fixed = config.fixed ?? false;\n\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item, 'Fixed nullables can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed nullables can only be used with fixed-size prefix.');\n const fixedSize = prefix.fixedSize + item.fixedSize;\n return createEncoder({\n fixedSize,\n write: (option: TFrom | null, bytes, offset) => {\n const prefixOffset = prefix.write(Number(option !== null), bytes, offset);\n if (option !== null) {\n item.write(option, bytes, prefixOffset);\n }\n return offset + fixedSize;\n },\n });\n }\n\n return createEncoder({\n getSizeFromValue: (option: TFrom | null) =>\n getEncodedSize(Number(option !== null), prefix) + (option !== null ? getEncodedSize(option, item) : 0),\n maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined,\n write: (option: TFrom | null, bytes, offset) => {\n offset = prefix.write(Number(option !== null), bytes, offset);\n if (option !== null) {\n offset = item.write(option, bytes, offset);\n }\n return offset;\n },\n });\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param config - A set of config for the decoder.\n */\nexport function getNullableDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: NullableCodecConfig<FixedSizeNumberDecoder> & { fixed: true }\n): FixedSizeDecoder<TTo | null>;\nexport function getNullableDecoder<TTo>(\n item: FixedSizeDecoder<TTo, 0>,\n config?: NullableCodecConfig<FixedSizeNumberDecoder>\n): FixedSizeDecoder<TTo | null>;\nexport function getNullableDecoder<TTo>(\n item: Decoder<TTo>,\n config?: NullableCodecConfig<NumberDecoder> & { fixed?: false }\n): VariableSizeDecoder<TTo | null>;\nexport function getNullableDecoder<TTo>(\n item: Decoder<TTo>,\n config: NullableCodecConfig<NumberDecoder> = {}\n): Decoder<TTo | null> {\n const prefix = config.prefix ?? getU8Decoder();\n const fixed = config.fixed ?? false;\n\n let fixedSize: number | null = null;\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item, 'Fixed nullables can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed nullables can only be used with fixed-size prefix.');\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return createDecoder({\n ...(fixedSize === null\n ? { maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined }\n : { fixedSize }),\n read: (bytes: Uint8Array, offset) => {\n if (bytes.length - offset <= 0) {\n return [null, offset];\n }\n const [isSome, prefixOffset] = prefix.read(bytes, offset);\n if (isSome === 0) {\n return [null, fixedSize !== null ? offset + fixedSize : prefixOffset];\n }\n const [value, newOffset] = item.read(bytes, prefixOffset);\n return [value, fixedSize !== null ? offset + fixedSize : newOffset];\n },\n });\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param config - A set of config for the codec.\n */\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: NullableCodecConfig<FixedSizeNumberCodec> & { fixed: true }\n): FixedSizeCodec<TFrom | null, TTo | null>;\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo, 0>,\n config?: NullableCodecConfig<FixedSizeNumberCodec>\n): FixedSizeCodec<TFrom | null, TTo | null>;\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config?: NullableCodecConfig<NumberCodec> & { fixed?: false }\n): VariableSizeCodec<TFrom | null, TTo | null>;\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: NullableCodecConfig<NumberCodec> = {}\n): Codec<TFrom | null, TTo | null> {\n const configCast = config as NullableCodecConfig<NumberCodec> & { fixed?: false };\n return combineCodec(getNullableEncoder<TFrom>(item, configCast), getNullableDecoder<TTo>(item, configCast));\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 {\n combineCodec,\n createEncoder,\n Decoder,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} 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 { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nfunction getCompiledMessageLegacyEncoder(): VariableSizeEncoder<CompiledMessage> {\n return getStructEncoder(getPreludeStructEncoderTuple());\n}\n\nfunction getCompiledMessageVersionedEncoder(): VariableSizeEncoder<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 ['staticAccounts', getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],\n ['lifetimeToken', getStringEncoder({ encoding: getBase58Encoder(), size: 32 })],\n ['instructions', getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })],\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 ['staticAccounts', getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],\n ['lifetimeToken', getStringDecoder({ encoding: getBase58Decoder(), size: 32 })],\n ['instructions', getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ];\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });\n}\n\nexport function getCompiledMessageEncoder(): VariableSizeEncoder<CompiledMessage> {\n return createEncoder({\n getSizeFromValue: (compiledMessage: CompiledMessage) => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);\n } else {\n return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);\n }\n },\n write: (compiledMessage, bytes, offset) => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);\n } else {\n return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);\n }\n },\n });\n}\n\nexport function getCompiledMessageDecoder(): VariableSizeDecoder<CompiledMessage> {\n return mapDecoder(getStructDecoder(getPreludeStructDecoderTuple()), ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups } as Exclude<CompiledMessage, { readonly version: 'legacy' }>;\n });\n}\n\nexport function getCompiledMessageCodec(): VariableSizeCodec<CompiledMessage> {\n return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n type Encoder,\n type VariableSizeCodec,\n type VariableSizeDecoder,\n type VariableSizeEncoder,\n} 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\nlet memoizedAddressTableLookupEncoder: VariableSizeEncoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupEncoder(): VariableSizeEncoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupEncoder) {\n memoizedAddressTableLookupEncoder = getStructEncoder([\n ['lookupTableAddress', getAddressEncoder()],\n [\n 'writableIndices',\n getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() }) as Encoder<readonly number[]>,\n ],\n [\n 'readableIndices',\n getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() }) as Encoder<readonly number[]>,\n ],\n ]);\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: VariableSizeDecoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupDecoder(): VariableSizeDecoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupDecoder) {\n memoizedAddressTableLookupDecoder = getStructDecoder([\n ['lookupTableAddress', getAddressDecoder()],\n ['writableIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n ['readableIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n ]);\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): VariableSizeCodec<AddressTableLookup> {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } 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: FixedSizeEncoder<number, 1> | undefined;\nfunction getMemoizedU8Encoder(): FixedSizeEncoder<number, 1> {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nlet memoizedU8Decoder: FixedSizeDecoder<number, 1> | undefined;\nfunction getMemoizedU8Decoder(): FixedSizeDecoder<number, 1> {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nlet memoizedU8Codec: FixedSizeCodec<number, number, 1> | undefined;\nfunction getMemoizedU8Codec(): FixedSizeCodec<number, number, 1> {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nexport function getMessageHeaderEncoder(): FixedSizeEncoder<MessageHeader, 3> {\n return getStructEncoder([\n ['numSignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Encoder()],\n ]) as FixedSizeEncoder<MessageHeader, 3>;\n}\n\nexport function getMessageHeaderDecoder(): FixedSizeDecoder<MessageHeader, 3> {\n return getStructDecoder([\n ['numSignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Decoder()],\n ]) as FixedSizeDecoder<MessageHeader, 3>;\n}\n\nexport function getMessageHeaderCodec(): FixedSizeCodec<MessageHeader, MessageHeader, 3> {\n return getStructCodec([\n ['numSignerAccounts', getMemoizedU8Codec()],\n ['numReadonlySignerAccounts', getMemoizedU8Codec()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Codec()],\n ]) as FixedSizeCodec<MessageHeader, MessageHeader, 3>;\n}\n","import {\n combineCodec,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} 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\nlet memoizedGetInstructionEncoder: VariableSizeEncoder<Instruction> | undefined;\nexport function getInstructionEncoder(): VariableSizeEncoder<Instruction> {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = mapEncoder<Required<Instruction>, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder()],\n ['accountIndices', getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],\n ['data', getBytesEncoder({ 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: VariableSizeDecoder<Instruction> | undefined;\nexport function getInstructionDecoder(): VariableSizeDecoder<Instruction> {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = mapDecoder<Required<Instruction>, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder()],\n ['accountIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n ['data', getBytesDecoder({ 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(): VariableSizeCodec<Instruction> {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { TransactionVersion } from '../types';\n\nconst VERSION_FLAG_MASK = 0x80;\n\nexport function getTransactionVersionEncoder(): VariableSizeEncoder<TransactionVersion> {\n return createEncoder({\n getSizeFromValue: value => (value === 'legacy' ? 0 : 1),\n maxSize: 1,\n write: (value, bytes, offset) => {\n if (value === 'legacy') {\n return offset;\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 bytes.set([value | VERSION_FLAG_MASK], offset);\n return offset + 1;\n },\n });\n}\n\nexport function getTransactionVersionDecoder(): VariableSizeDecoder<TransactionVersion> {\n return createDecoder({\n maxSize: 1,\n read: (bytes, offset) => {\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 });\n}\n\nexport function getTransactionVersionCodec(): VariableSizeCodec<TransactionVersion> {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { Address, assertIsAddress } from '@solana/addresses';\nimport { pipe } from '@solana/functional';\nimport { AccountRole, IAccountMeta, IInstruction } from '@solana/instructions';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { Blockhash, setTransactionLifetimeUsingBlockhash } from './blockhash';\nimport { CompilableTransaction } from './compilable-transaction';\nimport { CompiledTransaction } from './compile-transaction';\nimport { createTransaction } from './create-transaction';\nimport { isAdvanceNonceAccountInstruction, Nonce, setTransactionLifetimeUsingDurableNonce } from './durable-nonce';\nimport { setTransactionFeePayer } from './fee-payer';\nimport { appendTransactionInstruction } from './instructions';\nimport { CompiledMessage } from './message';\nimport { ITransactionWithSignatures } from './signatures';\nimport { TransactionVersion } from './types';\n\nfunction getAccountMetas(message: CompiledMessage): IAccountMeta[] {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts =\n message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n\n const accountMetas: IAccountMeta[] = [];\n\n let accountIndex = 0;\n for (let i = 0; i < numWritableSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlySignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY,\n });\n accountIndex++;\n }\n\n return accountMetas;\n}\n\nfunction convertInstruction(\n instruction: CompiledMessage['instructions'][0],\n accountMetas: IAccountMeta[],\n): IInstruction {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n // TODO coded error\n throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);\n }\n\n const accounts = instruction.accountIndices?.map(accountIndex => accountMetas[accountIndex]);\n const { data } = instruction;\n\n return {\n programAddress,\n ...(accounts && accounts.length ? { accounts } : {}),\n ...(data && data.length ? { data } : {}),\n };\n}\n\ntype LifetimeConstraint =\n | {\n blockhash: Blockhash;\n lastValidBlockHeight: bigint;\n }\n | {\n nonce: Nonce;\n nonceAccountAddress: Address;\n nonceAuthorityAddress: Address;\n };\n\nfunction getLifetimeConstraint(\n messageLifetimeToken: string,\n firstInstruction?: IInstruction,\n lastValidBlockHeight?: bigint,\n): LifetimeConstraint {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n // first instruction is not advance durable nonce, so use blockhash lifetime constraint\n return {\n blockhash: messageLifetimeToken as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n } else {\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = firstInstruction.accounts![0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = firstInstruction.accounts![2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n return {\n nonce: messageLifetimeToken as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n }\n}\n\nfunction convertSignatures(compiledTransaction: CompiledTransaction): ITransactionWithSignatures['signatures'] {\n const {\n compiledMessage: { staticAccounts },\n signatures,\n } = compiledTransaction;\n return signatures.reduce((acc, sig, index) => {\n // compiled transaction includes a fake all 0 signature if it hasn't been signed\n // we don't store those for the new tx model. So just skip if it's all 0s\n const allZeros = sig.every(byte => byte === 0);\n if (allZeros) return acc;\n\n const address = staticAccounts[index];\n return { ...acc, [address]: sig as SignatureBytes };\n }, {});\n}\n\nexport function decompileTransaction(\n compiledTransaction: CompiledTransaction,\n lastValidBlockHeight?: bigint,\n): CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures) {\n const { compiledMessage } = compiledTransaction;\n\n // TODO: add support for address lookup tables\n if ('addressTableLookups' in compiledMessage && compiledMessage.addressTableLookups!.length > 0) {\n // TODO: coded error\n throw new Error('Cannot convert transaction with addressTableLookups');\n }\n\n const feePayer = compiledMessage.staticAccounts[0];\n // TODO: coded error\n if (!feePayer) throw new Error('No fee payer set in CompiledTransaction');\n\n const accountMetas = getAccountMetas(compiledMessage);\n\n const instructions: IInstruction[] = compiledMessage.instructions.map(compiledInstruction =>\n convertInstruction(compiledInstruction, accountMetas),\n );\n\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledMessage.lifetimeToken,\n firstInstruction,\n lastValidBlockHeight,\n );\n\n const signatures = convertSignatures(compiledTransaction);\n\n return pipe(\n createTransaction({ version: compiledMessage.version as TransactionVersion }),\n tx => setTransactionFeePayer(feePayer, tx),\n tx =>\n instructions.reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n tx =>\n 'blockhash' in lifetimeConstraint\n ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx)\n : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),\n tx => (compiledTransaction.signatures.length ? { ...tx, signatures } : tx),\n );\n}\n","import {\n combineCodec,\n FixedSizeDecoder,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} 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\nfunction getCompiledTransactionEncoder(): VariableSizeEncoder<CompiledTransaction> {\n return getStructEncoder([\n ['signatures', getArrayEncoder(getBytesEncoder({ size: 64 }), { size: getShortU16Encoder() })],\n ['compiledMessage', getCompiledMessageEncoder()],\n ]);\n}\n\nfunction getCompiledTransactionDecoder(): VariableSizeDecoder<CompiledTransaction> {\n return getStructDecoder([\n [\n 'signatures',\n getArrayDecoder(getBytesDecoder({ size: 64 }) as FixedSizeDecoder<SignatureBytes, 64>, {\n size: getShortU16Decoder(),\n }),\n ],\n ['compiledMessage', getCompiledMessageDecoder()],\n ]);\n}\n\nexport function getTransactionEncoder(): VariableSizeEncoder<\n CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)\n> {\n return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);\n}\n\nexport function getTransactionDecoder(\n lastValidBlockHeight?: bigint,\n): VariableSizeDecoder<CompilableTransaction | (CompilableTransaction & ITransactionWithSignatures)> {\n return mapDecoder(getCompiledTransactionDecoder(), compiledTransaction =>\n decompileTransaction(compiledTransaction, lastValidBlockHeight),\n );\n}\n\nexport function getTransactionCodec(\n lastValidBlockHeight?: bigint,\n): VariableSizeCodec<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(\n async (transaction, modifyingSigner) => {\n abortSignal?.throwIfAborted();\n const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction], { abortSignal });\n return Object.freeze(tx);\n },\n Promise.resolve(transaction) as Promise<TTransaction>,\n );\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","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\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/src/assertions.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/codec.ts","../../codecs-core/src/fix-codec.ts","../../codecs-core/src/map-codec.ts","../../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","../../assertions/src/subtle-crypto.ts","../../addresses/dist/index.browser.js","../../keys/src/key-pair.ts","../../keys/src/signatures.ts","../../codecs-data-structures/src/array.ts","../../codecs-data-structures/src/utils.ts","../../codecs-data-structures/src/bit-array.ts","../../codecs-data-structures/src/boolean.ts","../../codecs-data-structures/src/nullable.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","../../text-encoding-impl/src/index.browser.ts","../src/signable-message.ts","../src/transaction-with-single-sending-signer.ts"],"names":["alphabet","createDecoder","createEncoder","combineCodec","e","assertIsFixedSize","isSignerRole","address","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;;;ACvBO,SAAS,wBACZ,SACA,aACsC;AACtC,MAAI,CAAC,YAAY,YAAY,YAAY,SAAS,WAAW,GAAG;AAC5D,WAAO;AAAA,EACX;AAEA,QAAM,kBAAkB,IAAI,IAAI,mBAAmB,OAAO,EAAE,IAAI,YAAU,CAAC,OAAO,SAAS,MAAM,CAAC,CAAC;AACnG,SAAO,OAAO,OAAO;AAAA,IACjB,GAAG;AAAA,IACH,UAAU,YAAY,SAAS,IAAI,aAAW;AAC1C,YAAM,SAAS,gBAAgB,IAAI,QAAQ,OAAO;AAClD,UAAI,CAAC,aAAa,QAAQ,IAAI,KAAK,YAAY,WAAW,CAAC,QAAQ;AAC/D,eAAO;AAAA,MACX;AACA,aAAO,OAAO,OAAO,EAAE,GAAG,SAAS,OAAO,CAAuB;AAAA,I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Q;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","/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0,\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\ntype BaseEncoder<TFrom> = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => Uint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\nexport type FixedSizeEncoder<TFrom, TSize extends number = number> = BaseEncoder<TFrom> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeEncoder<TFrom> = BaseEncoder<TFrom> & {\n /** The total size of the encoded value in bytes. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value to a `Uint8Array`.\n */\nexport type Encoder<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>;\n\ntype BaseDecoder<TTo> = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\nexport type FixedSizeDecoder<TTo, TSize extends number = number> = BaseDecoder<TTo> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeDecoder<TTo> = BaseDecoder<TTo> & {\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a value from a `Uint8Array`.\n */\nexport type Decoder<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>;\n\nexport type FixedSizeCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number> = FixedSizeEncoder<\n TFrom,\n TSize\n> &\n FixedSizeDecoder<TTo, TSize>;\n\nexport type VariableSizeCodec<TFrom, TTo extends TFrom = TFrom> = VariableSizeEncoder<TFrom> & VariableSizeDecoder<TTo>;\n\n/**\n * An object that can encode and decode a value to and from a `Uint8Array`.\n * It supports encoding looser types than it decodes for convenience.\n * For example, a `bigint` encoder will always decode to a `bigint`\n * but can be used to encode a `number`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value. Defaults to `TFrom`.\n */\nexport type Codec<TFrom, TTo extends TFrom = TFrom> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>;\n\n/**\n * Get the encoded size of a given value in bytes.\n */\nexport function getEncodedSize<TFrom>(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number },\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/** Fills the missing `encode` function using the existing `write` function. */\nexport function createEncoder<TFrom, TSize extends number>(\n encoder: Omit<FixedSizeEncoder<TFrom, TSize>, 'encode'>,\n): FixedSizeEncoder<TFrom, TSize>;\nexport function createEncoder<TFrom>(encoder: Omit<VariableSizeEncoder<TFrom>, 'encode'>): VariableSizeEncoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom> {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/** Fills the missing `decode` function using the existing `read` function. */\nexport function createDecoder<TTo, TSize extends number>(\n decoder: Omit<FixedSizeDecoder<TTo, TSize>, 'decode'>,\n): FixedSizeDecoder<TTo, TSize>;\nexport function createDecoder<TTo>(decoder: Omit<VariableSizeDecoder<TTo>, 'decode'>): VariableSizeDecoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo> {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/** Fills the missing `encode` and `decode` function using the existing `write` and `read` functions. */\nexport function createCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number>(\n codec: Omit<FixedSizeCodec<TFrom, TTo, TSize>, 'encode' | 'decode'>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec: Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): Codec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): Codec<TFrom, TTo> {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\nexport function isFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function isFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n): decoder is FixedSizeDecoder<TTo, TSize>;\nexport function isFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n): codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function isFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\nexport function assertIsFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n message?: string,\n): asserts encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function assertIsFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n message?: string,\n): asserts decoder is FixedSizeDecoder<TTo, TSize>;\nexport function assertIsFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n message?: string,\n): asserts codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function assertIsFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n message?: string,\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string,\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n\nexport function isVariableSize<TFrom>(encoder: Encoder<TFrom>): encoder is VariableSizeEncoder<TFrom>;\nexport function isVariableSize<TTo>(decoder: Decoder<TTo>): decoder is VariableSizeDecoder<TTo>;\nexport function isVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): codec is VariableSizeCodec<TFrom, TTo>;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\nexport function assertIsVariableSize<T>(\n encoder: Encoder<T>,\n message?: string,\n): asserts encoder is VariableSizeEncoder<T>;\nexport function assertIsVariableSize<T>(\n decoder: Decoder<T>,\n message?: string,\n): asserts decoder is VariableSizeDecoder<T>;\nexport function assertIsVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n message?: string,\n): asserts codec is VariableSizeCodec<TFrom, TTo>;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string,\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string,\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a variable-size codec, got a fixed-size one.');\n }\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n Offset,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n */\nexport function fixEncoder<TFrom, TSize extends number>(\n encoder: Encoder<TFrom>,\n fixedBytes: TSize,\n): FixedSizeEncoder<TFrom, TSize> {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value: TFrom, bytes: Uint8Array, offset: Offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function as using the nested `write` function on a fixed-sized byte\n // array may result in a out-of-bounds error on the nested encoder.\n const variableByteArray = encoder.encode(value);\n const fixedByteArray =\n variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n },\n });\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n */\nexport function fixDecoder<TTo, TSize extends number>(\n decoder: Decoder<TTo>,\n fixedBytes: TSize,\n): FixedSizeDecoder<TTo, TSize> {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes: Uint8Array, offset: Offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n },\n });\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n */\nexport function fixCodec<TFrom, TTo extends TFrom, TSize extends number>(\n codec: Codec<TFrom, TTo>,\n fixedBytes: TSize,\n): FixedSizeCodec<TFrom, TTo, TSize> {\n return combineCodec(fixEncoder(codec, fixedBytes), fixDecoder(codec, fixedBytes));\n}\n","import {\n Codec,\n createCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isVariableSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<TOldFrom, TNewFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TOldFrom, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder<TNewFrom, TSize>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: VariableSizeEncoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom> {\n return createEncoder({\n ...(isVariableSize(encoder)\n ? { ...encoder, getSizeFromValue: (value: TNewFrom) => encoder.getSizeFromValue(unmap(value)) }\n : encoder),\n write: (value: TNewFrom, bytes, offset) => encoder.write(unmap(value), bytes, offset),\n });\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<TOldTo, TNewTo, TSize extends number>(\n decoder: FixedSizeDecoder<TOldTo, TSize>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder<TNewTo, TSize>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: VariableSizeDecoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo> {\n return createDecoder({\n ...decoder,\n read: (bytes: Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeCodec<TNewFrom, TTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: VariableSizeCodec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: Codec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TOldTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec<TNewFrom, TNewTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: VariableSizeCodec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo> {\n return createCodec({\n ...mapEncoder(codec, unmap),\n read: map ? mapDecoder(codec, map).read : (codec.read as unknown as Decoder<TNewTo>['read']),\n });\n}\n","import { combineCodec, createEncoder, createDecoder, 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 isLittleEndian(config) {\n return config?.endian === 1 /* BIG */ ? false : true;\n}\nfunction numberEncoderFactory(input) {\n return createEncoder({\n fixedSize: input.size,\n write(value, bytes, offset) {\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, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n }\n });\n}\nfunction numberDecoderFactory(input) {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0) {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n }\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 = () => numberEncoderFactory({\n name: \"i8\",\n range: [-Number(\"0x7f\") - 1, Number(\"0x7f\")],\n set: (view, value) => view.setInt8(0, value),\n size: 1\n});\nvar getI8Decoder = () => numberDecoderFactory({\n get: (view) => view.getInt8(0),\n name: \"i8\",\n size: 1\n});\nvar getI8Codec = () => combineCodec(getI8Encoder(), getI8Decoder());\nvar getShortU16Encoder = () => createEncoder({\n getSizeFromValue: (value) => {\n if (value <= 127)\n return 1;\n if (value <= 16383)\n return 2;\n return 3;\n },\n maxSize: 3,\n write: (value, bytes, offset) => {\n assertNumberIsBetweenForCodec(\"shortU16\", 0, 65535, value);\n const shortU16Bytes = [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 shortU16Bytes[ii] = nextSevenBits;\n if (ii > 0) {\n shortU16Bytes[ii - 1] |= 128;\n }\n }\n bytes.set(shortU16Bytes, offset);\n return offset + shortU16Bytes.length;\n }\n});\nvar getShortU16Decoder = () => createDecoder({\n maxSize: 3,\n read: (bytes, offset) => {\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});\nvar getShortU16Codec = () => combineCodec(getShortU16Encoder(), getShortU16Decoder());\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 = () => numberEncoderFactory({\n name: \"u8\",\n range: [0, Number(\"0xff\")],\n set: (view, value) => view.setUint8(0, value),\n size: 1\n});\nvar getU8Decoder = () => numberDecoderFactory({\n get: (view) => view.getUint8(0),\n name: \"u8\",\n size: 1\n});\nvar getU8Codec = () => combineCodec(getU8Encoder(), getU8Decoder());\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 {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} 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): VariableSizeEncoder<string> => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (tailChars === '') return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (tailChars === '') {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\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): VariableSizeDecoder<string> => {\n return createDecoder({\n read(rawBytes, offset): [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 const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\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): VariableSizeCodec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(value: string, zeroCharacter: string): [string, string] {\n const leadingZeroIndex = [...value].findIndex(c => c !== zeroCharacter);\n return leadingZeroIndex === -1 ? [value, ''] : [value.slice(0, leadingZeroIndex), value.slice(leadingZeroIndex)];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n return [...value].reduce((sum, char) => sum * base + BigInt(alphabet.indexOf(char)), 0n);\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): VariableSizeEncoder<string> =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString('0123456789abcdef', lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n const hexBytes = matches ? matches.map((byte: string) => parseInt(byte, 16)) : [];\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): VariableSizeDecoder<string> =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): VariableSizeCodec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} 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 = (): VariableSizeEncoder<string> => {\n if (__BROWSER__) {\n return createEncoder({\n getSizeFromValue: (value: string) => {\n try {\n return (atob as Window['atob'])(value).length;\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n write(value: string, bytes, offset) {\n try {\n const bytesToAdd = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n });\n }\n\n if (__NODEJS__) {\n return createEncoder({\n getSizeFromValue: (value: string) => Buffer.from(value, 'base64').length,\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n const buffer = Buffer.from(value, 'base64');\n bytes.set(buffer, offset);\n return buffer.length + offset;\n },\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 = (): VariableSizeDecoder<string> => {\n if (__BROWSER__) {\n return createDecoder({\n read(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 });\n }\n\n if (__NODEJS__) {\n return createDecoder({\n read: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString('base64'), bytes.length],\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 = (): VariableSizeCodec<string> => 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 Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n fixDecoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoder,\n getEncodedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\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> = {\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 function getStringEncoder<TSize extends number>(\n config: StringCodecConfig<NumberEncoder, Encoder<string>> & { size: TSize },\n): FixedSizeEncoder<string, TSize>;\nexport function getStringEncoder<TSize extends number>(\n config: StringCodecConfig<NumberEncoder, Encoder<string>> & {\n size: 'variable';\n encoding: FixedSizeEncoder<string, TSize>;\n },\n): FixedSizeEncoder<string, TSize>;\nexport function getStringEncoder(\n config?: StringCodecConfig<NumberEncoder, Encoder<string>>,\n): VariableSizeEncoder<string>;\nexport function getStringEncoder(config: StringCodecConfig<NumberEncoder, Encoder<string>> = {}): Encoder<string> {\n const size = config.size ?? getU32Encoder();\n const encoding = config.encoding ?? getUtf8Encoder();\n\n if (size === 'variable') {\n return encoding;\n }\n\n if (typeof size === 'number') {\n return fixEncoder(encoding, size);\n }\n\n return createEncoder({\n getSizeFromValue: (value: string) => {\n const contentSize = getEncodedSize(value, encoding);\n return getEncodedSize(contentSize, size) + contentSize;\n },\n write: (value: string, bytes, offset) => {\n const contentSize = getEncodedSize(value, encoding);\n offset = size.write(contentSize, bytes, offset);\n return encoding.write(value, bytes, offset);\n },\n });\n}\n\n/** Decodes strings from a given encoding and size strategy. */\nexport function getStringDecoder<TSize extends number>(\n config: StringCodecConfig<NumberDecoder, Decoder<string>> & { size: TSize },\n): FixedSizeDecoder<string, TSize>;\nexport function getStringDecoder<TSize extends number>(\n config: StringCodecConfig<NumberDecoder, Decoder<string>> & {\n size: 'variable';\n encoding: FixedSizeDecoder<string, TSize>;\n },\n): FixedSizeDecoder<string, TSize>;\nexport function getStringDecoder(\n config?: StringCodecConfig<NumberDecoder, Decoder<string>>,\n): VariableSizeDecoder<string>;\nexport function getStringDecoder(config: StringCodecConfig<NumberDecoder, Decoder<string>> = {}): Decoder<string> {\n const size = config.size ?? getU32Decoder();\n const encoding = config.encoding ?? getUtf8Decoder();\n\n if (size === 'variable') {\n return encoding;\n }\n\n if (typeof size === 'number') {\n return fixDecoder(encoding, size);\n }\n\n return createDecoder({\n read: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec('string', bytes, offset);\n const [lengthBigInt, lengthOffset] = size.read(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.read(contentBytes, 0);\n offset += contentOffset;\n return [value, offset];\n },\n });\n}\n\n/** Encodes and decodes strings from a given encoding and size strategy. */\nexport function getStringCodec<TSize extends number>(\n config: StringCodecConfig<NumberCodec, Codec<string>> & { size: TSize },\n): FixedSizeCodec<string, string, TSize>;\nexport function getStringCodec<TSize extends number>(\n config: StringCodecConfig<NumberCodec, Codec<string>> & {\n size: 'variable';\n encoding: FixedSizeCodec<string, string, TSize>;\n },\n): FixedSizeCodec<string, string, TSize>;\nexport function getStringCodec(config?: StringCodecConfig<NumberCodec, Codec<string>>): VariableSizeCodec<string>;\nexport function getStringCodec(config: StringCodecConfig<NumberCodec, Codec<string>> = {}): Codec<string> {\n return combineCodec(getStringEncoder(config), getStringDecoder(config));\n}\n","import {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} 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 = (): VariableSizeEncoder<string> => {\n let textEncoder: TextEncoder;\n return createEncoder({\n getSizeFromValue: value => (textEncoder ||= new TextEncoder()).encode(value).length,\n write: (value: string, bytes, offset) => {\n const bytesToAdd = (textEncoder ||= new TextEncoder()).encode(value);\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/** Decodes UTF-8 strings using the native `TextDecoder` API. */\nexport const getUtf8Decoder = (): VariableSizeDecoder<string> => {\n let textDecoder: TextDecoder;\n return createDecoder({\n read(bytes, offset) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\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","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 { mapEncoder, combineCodec } from '@solana/codecs-core';\nimport { getStringEncoder, getStringDecoder, getBase58Encoder, getBase58Decoder } from '@solana/codecs-strings';\nimport { assertKeyExporterIsAvailable, assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\n// src/address.ts\nvar memoizedBase58Encoder;\nvar memoizedBase58Decoder;\nfunction getMemoizedBase58Encoder() {\n if (!memoizedBase58Encoder)\n memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\nfunction getMemoizedBase58Decoder() {\n if (!memoizedBase58Decoder)\n memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\nfunction isAddress(putativeAddress) {\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 || // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\nfunction assertIsAddress(putativeAddress) {\n try {\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 || // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new Error(\"Expected input string to decode to a byte array of length 32.\");\n }\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeAddress}\\` is not a base-58 encoded address`, {\n cause: e\n });\n }\n}\nfunction address(putativeAddress) {\n assertIsAddress(putativeAddress);\n return putativeAddress;\n}\nfunction getAddressEncoder() {\n return mapEncoder(\n getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }),\n (putativeAddress) => address(putativeAddress)\n );\n}\nfunction getAddressDecoder() {\n return getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 });\n}\nfunction getAddressCodec() {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\n}\nfunction getAddressComparator() {\n return new Intl.Collator(\"en\", {\n caseFirst: \"lower\",\n ignorePunctuation: false,\n localeMatcher: \"best fit\",\n numeric: false,\n sensitivity: \"variant\",\n usage: \"sort\"\n }).compare;\n}\n\n// src/vendor/noble/ed25519.ts\nvar D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nvar P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;\nvar RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;\nfunction mod(a) {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x, power) {\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x) {\n const x2 = x * x % P;\n const b2 = x2 * x % P;\n const b4 = pow2(b2, 2n) * b2 % P;\n const b5 = pow2(b4, 1n) * x % P;\n const b10 = pow2(b5, 5n) * b5 % P;\n const b20 = pow2(b10, 10n) * b10 % P;\n const b40 = pow2(b20, 20n) * b20 % P;\n const b80 = pow2(b40, 40n) * b40 % P;\n const b160 = pow2(b80, 80n) * b80 % P;\n const b240 = pow2(b160, 80n) * b80 % P;\n const b250 = pow2(b240, 10n) * b10 % P;\n const pow_p_5_8 = pow2(b250, 2n) * x % P;\n return pow_p_5_8;\n}\nfunction uvRatio(u, v) {\n const v3 = mod(v * v * v);\n const v7 = mod(v3 * v3 * v);\n const pow = pow_2_252_3(u * v7);\n let x = mod(u * v3 * pow);\n const vx2 = mod(v * x * x);\n const root1 = x;\n const root2 = mod(x * RM1);\n const useRoot1 = vx2 === u;\n const useRoot2 = vx2 === mod(-u);\n const noRoot = vx2 === mod(-u * RM1);\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2;\n if ((mod(x) & 1n) === 1n)\n x = mod(-x);\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\nfunction pointIsOnCurve(y, lastByte) {\n const y2 = mod(y * y);\n const u = mod(y2 - 1n);\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v);\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 128) !== 0;\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n\n// src/curve.ts\nfunction byteToHex(byte) {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\nfunction decompressPointBytes(bytes) {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, \"\");\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\nasync function compressedPointBytesAreOnCurve(bytes) {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n\n// src/program-derived-address.ts\nfunction isProgramDerivedAddress(value) {\n return Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\" && typeof value[1] === \"number\" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);\n}\nfunction assertIsProgramDerivedAddress(value) {\n const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\" && typeof value[1] === \"number\";\n if (!validFormat) {\n throw new Error(\n `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\nvar MAX_SEED_LENGTH = 32;\nvar MAX_SEEDS = 16;\nvar PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80,\n 114,\n 111,\n 103,\n 114,\n 97,\n 109,\n 68,\n 101,\n 114,\n 105,\n 118,\n 101,\n 100,\n 65,\n 100,\n 100,\n 114,\n 101,\n 115,\n 115\n];\nvar PointOnCurveError = class extends Error {\n};\nasync function createProgramDerivedAddress({ programAddress, seeds }) {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === \"string\" ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, []);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n \"SHA-256\",\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n throw new PointOnCurveError(\"Invalid seeds; point must fall off the Ed25519 curve\");\n }\n return base58EncodedAddressCodec.decode(addressBytes);\n}\nasync function getProgramDerivedAddress({\n programAddress,\n seeds\n}) {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address2 = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])]\n });\n return [address2, bumpSeed];\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n throw new Error(\"Unable to find a viable program address bump seed\");\n}\nasync function createAddressWithSeed({ baseAddress, programAddress, seed }) {\n const { encode, decode } = getAddressCodec();\n const seedBytes = typeof seed === \"string\" ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n const programAddressBytes = encode(programAddress);\n if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n const addressBytesBuffer = await crypto.subtle.digest(\n \"SHA-256\",\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n return decode(addressBytes);\n}\nasync function getAddressFromPublicKey(publicKey) {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== \"public\" || publicKey.algorithm.name !== \"Ed25519\") {\n throw new Error(\"The `CryptoKey` must be an `Ed25519` public key\");\n }\n const publicKeyBytes = await crypto.subtle.exportKey(\"raw\", publicKey);\n return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n\nexport { address, assertIsAddress, assertIsProgramDerivedAddress, createAddressWithSeed, getAddressCodec, getAddressComparator, getAddressDecoder, getAddressEncoder, getAddressFromPublicKey, getProgramDerivedAddress, isAddress, isProgramDerivedAddress };\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 {\n assertIsFixedSize,\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n Offset,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { getFixedSize, getMaxSize } 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> =\n | TPrefix\n | number\n | 'remainder';\n\n/** Defines the configs for array codecs. */\nexport type ArrayCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = {\n /**\n * The size of the array.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\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<TFrom>(\n item: Encoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> & { size: 0 },\n): FixedSizeEncoder<TFrom[], 0>;\nexport function getArrayEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> & { size: number },\n): FixedSizeEncoder<TFrom[]>;\nexport function getArrayEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> & { size: 'remainder' },\n): VariableSizeEncoder<TFrom[]>;\nexport function getArrayEncoder<TFrom>(\n item: Encoder<TFrom>,\n config?: ArrayCodecConfig<NumberEncoder> & { size?: number | NumberEncoder },\n): VariableSizeEncoder<TFrom[]>;\nexport function getArrayEncoder<TFrom>(\n item: Encoder<TFrom>,\n config: ArrayCodecConfig<NumberEncoder> = {},\n): Encoder<TFrom[]> {\n const size = config.size ?? getU32Encoder();\n if (size === 'remainder') {\n assertIsFixedSize(item, 'Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n const fixedSize = computeArrayLikeCodecSize(size, getFixedSize(item));\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize !== null\n ? { fixedSize }\n : {\n getSizeFromValue: (array: TFrom[]) => {\n const prefixSize = typeof size === 'object' ? getEncodedSize(array.length, size) : 0;\n return prefixSize + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);\n },\n maxSize,\n }),\n write: (array: TFrom[], bytes, offset) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, array.length);\n }\n if (typeof size === 'object') {\n offset = size.write(array.length, bytes, offset);\n }\n array.forEach(value => {\n offset = item.write(value, bytes, offset);\n });\n return offset;\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<TTo>(\n item: Decoder<TTo>,\n config: ArrayCodecConfig<NumberDecoder> & { size: 0 },\n): FixedSizeDecoder<TTo[], 0>;\nexport function getArrayDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: ArrayCodecConfig<NumberDecoder> & { size: number },\n): FixedSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: ArrayCodecConfig<NumberDecoder> & { size: 'remainder' },\n): VariableSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(\n item: Decoder<TTo>,\n config?: ArrayCodecConfig<NumberDecoder> & { size?: number | NumberDecoder },\n): VariableSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(item: Decoder<TTo>, config: ArrayCodecConfig<NumberDecoder> = {}): Decoder<TTo[]> {\n const size = config.size ?? getU32Decoder();\n if (size === 'remainder') {\n assertIsFixedSize(item, 'Codecs of \"remainder\" size must have fixed-size items.');\n }\n\n const itemSize = getFixedSize(item);\n const fixedSize = computeArrayLikeCodecSize(size, itemSize);\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize !== null ? { fixedSize } : { maxSize }),\n read: (bytes: Uint8Array, offset) => {\n const array: TTo[] = [];\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [array, offset];\n }\n const [resolvedSize, newOffset] = readArrayLikeCodecSize(size, itemSize, bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, 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<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> & { size: 0 },\n): FixedSizeCodec<TFrom[], TTo[], 0>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> & { size: number },\n): FixedSizeCodec<TFrom[], TTo[]>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> & { size: 'remainder' },\n): VariableSizeCodec<TFrom[], TTo[]>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config?: ArrayCodecConfig<NumberCodec> & { size?: number | NumberCodec },\n): VariableSizeCodec<TFrom[], TTo[]>;\nexport function getArrayCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: ArrayCodecConfig<NumberCodec> = {},\n): Codec<TFrom[], TTo[]> {\n return combineCodec(getArrayEncoder(item, config as object), getArrayDecoder(item, config as object));\n}\n\nfunction readArrayLikeCodecSize(\n size: ArrayLikeCodecSize<NumberDecoder>,\n itemSize: 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.read(bytes, offset);\n }\n\n if (size === 'remainder') {\n if (itemSize === null) {\n // TODO: Coded error.\n throw new Error('Codecs of \"remainder\" size must have fixed-size items.');\n }\n const remainder = Math.max(0, bytes.length - offset);\n if (remainder % itemSize !== 0) {\n // TODO: Coded error.\n throw new Error(\n `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${itemSize} bytes. ` +\n `Codecs of \"remainder\" size must have a remainder that is a multiple of its item size. ` +\n `In other words, ${remainder} modulo ${itemSize} should be equal to zero.`,\n );\n }\n return [remainder / itemSize, offset];\n }\n\n // TODO: Coded error.\n throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);\n}\n\nfunction computeArrayLikeCodecSize(size: object | number | 'remainder', itemSize: number | null): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n return itemSize === null ? null : itemSize * size;\n}\n","import { isFixedSize } from '@solana/codecs-core';\n\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\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\nexport function getFixedSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : null;\n}\n\nexport function getMaxSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from '@solana/codecs-core';\n\n/** Defines the config for bitArray codecs. */\nexport type BitArrayCodecConfig = {\n /**\n * Whether to read the bits in reverse order.\n * @defaultValue `false`\n */\n backward?: boolean;\n};\n\n/**\n * Encodes an array of booleans into bits.\n *\n * @param size - The amount of bytes to use for the bit array.\n * @param config - A set of config for the encoder.\n */\nexport function getBitArrayEncoder<TSize extends number>(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeEncoder<boolean[], TSize> {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createEncoder({\n fixedSize: size,\n write(value: boolean[], bytes, offset) {\n const bytesToAdd: number[] = [];\n\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 bytesToAdd.unshift(byte);\n } else {\n bytesToAdd.push(byte);\n }\n }\n\n bytes.set(bytesToAdd, offset);\n return size;\n },\n });\n}\n\n/**\n * Decodes bits into an array of booleans.\n *\n * @param size - The amount of bytes to use for the bit array.\n * @param config - A set of config for the decoder.\n */\nexport function getBitArrayDecoder<TSize extends number>(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeDecoder<boolean[], TSize> {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createDecoder({\n fixedSize: size,\n read(bytes, offset) {\n assertByteArrayHasEnoughBytesForCodec('bitArray', size, bytes, offset);\n const booleans: boolean[] = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n\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 & 0b1000_0000));\n byte <<= 1;\n }\n }\n });\n\n return [booleans, offset + size];\n },\n });\n}\n\n/**\n * An array of boolean codec that converts booleans to bits and vice versa.\n *\n * @param size - The amount of bytes to use for the bit array.\n * @param config - A set of config for the codec.\n */\nexport function getBitArrayCodec<TSize extends number>(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeCodec<boolean[], boolean[], TSize> {\n return combineCodec(getBitArrayEncoder(size, config), getBitArrayDecoder(size, config));\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n mapDecoder,\n mapEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\n/** Defines the config for boolean codecs. */\nexport type BooleanCodecConfig<TSize extends NumberCodec | NumberEncoder | NumberDecoder> = {\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(): FixedSizeEncoder<boolean, 1>;\nexport function getBooleanEncoder<TSize extends number>(\n config: BooleanCodecConfig<NumberEncoder> & { size: FixedSizeNumberEncoder<TSize> },\n): FixedSizeEncoder<boolean, TSize>;\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder>): Encoder<boolean>;\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder> = {}): Encoder<boolean> {\n const size = config.size ?? getU8Encoder();\n assertIsFixedSize(size, 'Codec [bool] requires a fixed size.');\n return mapEncoder(size, (value: boolean) => (value ? 1 : 0));\n}\n\n/**\n * Decodes booleans.\n *\n * @param config - A set of config for the decoder.\n */\nexport function getBooleanDecoder(): FixedSizeDecoder<boolean, 1>;\nexport function getBooleanDecoder<TSize extends number>(\n config: BooleanCodecConfig<NumberDecoder> & { size: FixedSizeNumberDecoder<TSize> },\n): FixedSizeDecoder<boolean, TSize>;\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder>): Decoder<boolean>;\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder> = {}): Decoder<boolean> {\n const size = config.size ?? getU8Decoder();\n assertIsFixedSize(size, 'Codec [bool] requires a fixed size.');\n return mapDecoder(size, (value: number | bigint): boolean => Number(value) === 1);\n}\n\n/**\n * Creates a boolean codec.\n *\n * @param config - A set of config for the codec.\n */\nexport function getBooleanCodec(): FixedSizeCodec<boolean, boolean, 1>;\nexport function getBooleanCodec<TSize extends number>(\n config: BooleanCodecConfig<NumberCodec> & { size: FixedSizeNumberCodec<TSize> },\n): FixedSizeCodec<boolean, boolean, TSize>;\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec>): Codec<boolean>;\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec> = {}): Codec<boolean> {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { getMaxSize, sumCodecSizes } from './utils';\n\n/** Defines the config for nullable codecs. */\nexport type NullableCodecConfig<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `null` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param config - A set of config for the encoder.\n */\nexport function getNullableEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: NullableCodecConfig<FixedSizeNumberEncoder> & { fixed: true },\n): FixedSizeEncoder<TFrom | null>;\nexport function getNullableEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom, 0>,\n config?: NullableCodecConfig<FixedSizeNumberEncoder>,\n): FixedSizeEncoder<TFrom | null>;\nexport function getNullableEncoder<TFrom>(\n item: Encoder<TFrom>,\n config?: NullableCodecConfig<NumberEncoder> & { fixed?: false },\n): VariableSizeEncoder<TFrom | null>;\nexport function getNullableEncoder<TFrom>(\n item: Encoder<TFrom>,\n config: NullableCodecConfig<NumberEncoder> = {},\n): Encoder<TFrom | null> {\n const prefix = config.prefix ?? getU8Encoder();\n const fixed = config.fixed ?? false;\n\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item, 'Fixed nullables can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed nullables can only be used with fixed-size prefix.');\n const fixedSize = prefix.fixedSize + item.fixedSize;\n return createEncoder({\n fixedSize,\n write: (option: TFrom | null, bytes, offset) => {\n const prefixOffset = prefix.write(Number(option !== null), bytes, offset);\n if (option !== null) {\n item.write(option, bytes, prefixOffset);\n }\n return offset + fixedSize;\n },\n });\n }\n\n return createEncoder({\n getSizeFromValue: (option: TFrom | null) =>\n getEncodedSize(Number(option !== null), prefix) + (option !== null ? getEncodedSize(option, item) : 0),\n maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined,\n write: (option: TFrom | null, bytes, offset) => {\n offset = prefix.write(Number(option !== null), bytes, offset);\n if (option !== null) {\n offset = item.write(option, bytes, offset);\n }\n return offset;\n },\n });\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param config - A set of config for the decoder.\n */\nexport function getNullableDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: NullableCodecConfig<FixedSizeNumberDecoder> & { fixed: true },\n): FixedSizeDecoder<TTo | null>;\nexport function getNullableDecoder<TTo>(\n item: FixedSizeDecoder<TTo, 0>,\n config?: NullableCodecConfig<FixedSizeNumberDecoder>,\n): FixedSizeDecoder<TTo | null>;\nexport function getNullableDecoder<TTo>(\n item: Decoder<TTo>,\n config?: NullableCodecConfig<NumberDecoder> & { fixed?: false },\n): VariableSizeDecoder<TTo | null>;\nexport function getNullableDecoder<TTo>(\n item: Decoder<TTo>,\n config: NullableCodecConfig<NumberDecoder> = {},\n): Decoder<TTo | null> {\n const prefix = config.prefix ?? getU8Decoder();\n const fixed = config.fixed ?? false;\n\n let fixedSize: number | null = null;\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item, 'Fixed nullables can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed nullables can only be used with fixed-size prefix.');\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return createDecoder({\n ...(fixedSize === null\n ? { maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined }\n : { fixedSize }),\n read: (bytes: Uint8Array, offset) => {\n if (bytes.length - offset <= 0) {\n return [null, offset];\n }\n const [isSome, prefixOffset] = prefix.read(bytes, offset);\n if (isSome === 0) {\n return [null, fixedSize !== null ? offset + fixedSize : prefixOffset];\n }\n const [value, newOffset] = item.read(bytes, prefixOffset);\n return [value, fixedSize !== null ? offset + fixedSize : newOffset];\n },\n });\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param config - A set of config for the codec.\n */\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: NullableCodecConfig<FixedSizeNumberCodec> & { fixed: true },\n): FixedSizeCodec<TFrom | null, TTo | null>;\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo, 0>,\n config?: NullableCodecConfig<FixedSizeNumberCodec>,\n): FixedSizeCodec<TFrom | null, TTo | null>;\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config?: NullableCodecConfig<NumberCodec> & { fixed?: false },\n): VariableSizeCodec<TFrom | null, TTo | null>;\nexport function getNullableCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: NullableCodecConfig<NumberCodec> = {},\n): Codec<TFrom | null, TTo | null> {\n const configCast = config as NullableCodecConfig<NumberCodec> & { fixed?: false };\n return combineCodec(getNullableEncoder<TFrom>(item, configCast), getNullableDecoder<TTo>(item, configCast));\n}\n","import { getBase58Encoder, getBase58Decoder, getBase64Decoder, getStringEncoder, getStringDecoder } from '@solana/codecs-strings';\nimport { getAddressFromPublicKey, getAddressComparator, getAddressEncoder, getAddressDecoder, assertIsAddress } from '@solana/addresses';\nimport { createEncoder, mapDecoder, combineCodec, mapEncoder, createDecoder } 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// src/blockhash.ts\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 isTransactionWithBlockhashLifetime(transaction) {\n const lifetimeConstraintShapeMatches = \"lifetimeConstraint\" in transaction && typeof transaction.lifetimeConstraint.blockhash === \"string\" && typeof transaction.lifetimeConstraint.lastValidBlockHeight === \"bigint\";\n if (!lifetimeConstraintShapeMatches)\n return false;\n try {\n assertIsBlockhash(transaction.lifetimeConstraint.blockhash);\n return true;\n } catch {\n return false;\n }\n}\nfunction assertIsTransactionWithBlockhashLifetime(transaction) {\n if (!isTransactionWithBlockhashLifetime(transaction)) {\n throw new Error(\"Transaction does not have a blockhash lifetime\");\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 memoizedAddressTableLookupEncoder;\nfunction getAddressTableLookupEncoder() {\n if (!memoizedAddressTableLookupEncoder) {\n memoizedAddressTableLookupEncoder = getStructEncoder([\n [\"lookupTableAddress\", getAddressEncoder()],\n [\n \"writableIndices\",\n getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })\n ],\n [\n \"readableIndices\",\n getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })\n ]\n ]);\n }\n return memoizedAddressTableLookupEncoder;\n}\nvar memoizedAddressTableLookupDecoder;\nfunction getAddressTableLookupDecoder() {\n if (!memoizedAddressTableLookupDecoder) {\n memoizedAddressTableLookupDecoder = getStructDecoder([\n [\"lookupTableAddress\", getAddressDecoder()],\n [\"writableIndices\", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n [\"readableIndices\", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })]\n ]);\n }\n return memoizedAddressTableLookupDecoder;\n}\nvar memoizedU8Encoder;\nfunction getMemoizedU8Encoder() {\n if (!memoizedU8Encoder)\n memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\nvar memoizedU8Decoder;\nfunction getMemoizedU8Decoder() {\n if (!memoizedU8Decoder)\n memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\nfunction getMessageHeaderEncoder() {\n return getStructEncoder([\n [\"numSignerAccounts\", getMemoizedU8Encoder()],\n [\"numReadonlySignerAccounts\", getMemoizedU8Encoder()],\n [\"numReadonlyNonSignerAccounts\", getMemoizedU8Encoder()]\n ]);\n}\nfunction getMessageHeaderDecoder() {\n return getStructDecoder([\n [\"numSignerAccounts\", getMemoizedU8Decoder()],\n [\"numReadonlySignerAccounts\", getMemoizedU8Decoder()],\n [\"numReadonlyNonSignerAccounts\", getMemoizedU8Decoder()]\n ]);\n}\nvar memoizedGetInstructionEncoder;\nfunction getInstructionEncoder() {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = mapEncoder(\n getStructEncoder([\n [\"programAddressIndex\", getU8Encoder()],\n [\"accountIndices\", getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],\n [\"data\", getBytesEncoder({ 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()],\n [\"accountIndices\", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n [\"data\", getBytesDecoder({ 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;\nfunction getTransactionVersionEncoder() {\n return createEncoder({\n getSizeFromValue: (value) => value === \"legacy\" ? 0 : 1,\n maxSize: 1,\n write: (value, bytes, offset) => {\n if (value === \"legacy\") {\n return offset;\n }\n if (value < 0 || value > 127) {\n throw new Error(`Transaction version must be in the range [0, 127]. \\`${value}\\` given.`);\n }\n bytes.set([value | VERSION_FLAG_MASK], offset);\n return offset + 1;\n }\n });\n}\nfunction getTransactionVersionDecoder() {\n return createDecoder({\n maxSize: 1,\n read: (bytes, offset) => {\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 }\n });\n}\n\n// src/serializers/message.ts\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 [\"staticAccounts\", getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],\n [\"lifetimeToken\", getStringEncoder({ encoding: getBase58Encoder(), size: 32 })],\n [\"instructions\", getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })]\n ];\n}\nfunction getPreludeStructDecoderTuple() {\n return [\n [\"version\", getTransactionVersionDecoder()],\n [\"header\", getMessageHeaderDecoder()],\n [\"staticAccounts\", getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],\n [\"lifetimeToken\", getStringDecoder({ encoding: getBase58Decoder(), size: 32 })],\n [\"instructions\", getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],\n [\"addressTableLookups\", getAddressTableLookupArrayDecoder()]\n ];\n}\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });\n}\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });\n}\nfunction getCompiledMessageEncoder() {\n return createEncoder({\n getSizeFromValue: (compiledMessage) => {\n if (compiledMessage.version === \"legacy\") {\n return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);\n } else {\n return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);\n }\n },\n write: (compiledMessage, bytes, offset) => {\n if (compiledMessage.version === \"legacy\") {\n return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);\n } else {\n return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);\n }\n }\n });\n}\nfunction getCompiledMessageDecoder() {\n return mapDecoder(getStructDecoder(getPreludeStructDecoderTuple()), ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === \"legacy\" || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups };\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\nfunction getCompiledTransactionEncoder() {\n return getStructEncoder([\n [\"signatures\", getArrayEncoder(getBytesEncoder({ size: 64 }), { size: getShortU16Encoder() })],\n [\"compiledMessage\", getCompiledMessageEncoder()]\n ]);\n}\nfunction getCompiledTransactionDecoder() {\n return getStructDecoder([\n [\n \"signatures\",\n getArrayDecoder(getBytesDecoder({ size: 64 }), {\n size: getShortU16Decoder()\n })\n ],\n [\"compiledMessage\", getCompiledMessageDecoder()]\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);\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);\n}\n\nexport { appendTransactionInstruction, assertIsBlockhash, assertIsDurableNonceTransaction, assertIsTransactionWithBlockhashLifetime, 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(\n async (transaction, modifyingSigner) => {\n abortSignal?.throwIfAborted();\n const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction], { abortSignal });\n return Object.freeze(tx);\n },\n Promise.resolve(transaction) as Promise<TTransaction>,\n );\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","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\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.node.cjs
CHANGED
|
@@ -323,5 +323,3 @@ exports.isTransactionWithSingleSendingSigner = isTransactionWithSingleSendingSig
|
|
|
323
323
|
exports.partiallySignTransactionWithSigners = partiallySignTransactionWithSigners;
|
|
324
324
|
exports.signAndSendTransactionWithSigners = signAndSendTransactionWithSigners;
|
|
325
325
|
exports.signTransactionWithSigners = signTransactionWithSigners;
|
|
326
|
-
//# sourceMappingURL=out.js.map
|
|
327
|
-
//# sourceMappingURL=index.node.cjs.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.fcff844",
|
|
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.fcff844",
|
|
53
|
+
"@solana/instructions": "2.0.0-experimental.fcff844",
|
|
54
|
+
"@solana/keys": "2.0.0-experimental.fcff844",
|
|
55
|
+
"@solana/transactions": "2.0.0-experimental.fcff844"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@solana/eslint-config-solana": "^1.0.2",
|