@revibase/lite 0.7.1 → 0.7.3
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/README.md +2 -2
- package/dist/index.cjs +4 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -3
- package/dist/index.d.ts +10 -3
- package/dist/index.js +4 -10
- package/dist/index.js.map +1 -1
- package/package.json +9 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.pnpm/@solana+errors@5.0.0_typescript@6.0.3/node_modules/@solana/errors/src/codes.ts","../../../node_modules/.pnpm/@solana+errors@5.0.0_typescript@6.0.3/node_modules/@solana/errors/src/context.ts","../../../node_modules/.pnpm/@solana+errors@5.0.0_typescript@6.0.3/node_modules/@solana/errors/src/messages.ts","../../../node_modules/.pnpm/@solana+errors@5.0.0_typescript@6.0.3/node_modules/@solana/errors/src/message-formatter.ts","../../../node_modules/.pnpm/@solana+errors@5.0.0_typescript@6.0.3/node_modules/@solana/errors/src/error.ts","../../../node_modules/.pnpm/@solana+codecs-core@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-core/src/bytes.ts","../../../node_modules/.pnpm/@solana+codecs-core@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-core/src/codec.ts","../../../node_modules/.pnpm/@solana+codecs-core@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-core/src/assertions.ts","../../../node_modules/.pnpm/@solana+codecs-core@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-core/src/add-codec-size-prefix.ts","../../../node_modules/.pnpm/@solana+codecs-core@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-core/src/fix-codec-size.ts","../../../node_modules/.pnpm/@solana+codecs-core@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-core/src/transform-codec.ts","../../../node_modules/.pnpm/@solana+codecs-strings@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/codecs-strings/src/assertions.ts","../../../node_modules/.pnpm/@solana+codecs-strings@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/codecs-strings/src/baseX.ts","../../../node_modules/.pnpm/@solana+codecs-strings@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/codecs-strings/src/base58.ts","../../../node_modules/.pnpm/@solana+codecs-strings@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/codecs-strings/src/base64.ts","../../../node_modules/.pnpm/@solana+accounts@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/accounts/src/decode-account.ts","../../../node_modules/.pnpm/@solana+accounts@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/accounts/src/parse-account.ts","../../../node_modules/.pnpm/@solana+accounts@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/accounts/src/fetch-account.ts","../../../node_modules/.pnpm/@solana+accounts@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/accounts/src/maybe-account.ts","../../../node_modules/.pnpm/@solana+assertions@5.0.0_typescript@6.0.3/node_modules/@solana/assertions/src/subtle-crypto.ts","../../../node_modules/.pnpm/@solana+addresses@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/addresses/src/address.ts","../../../node_modules/.pnpm/@solana+addresses@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/addresses/src/public-key.ts","../../../node_modules/.pnpm/@solana+codecs-numbers@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-numbers/src/assertions.ts","../../../node_modules/.pnpm/@solana+codecs-numbers@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-numbers/src/utils.ts","../../../node_modules/.pnpm/@solana+codecs-numbers@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-numbers/src/short-u16.ts","../../../node_modules/.pnpm/@solana+codecs-numbers@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-numbers/src/u16.ts","../../../node_modules/.pnpm/@solana+codecs-numbers@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-numbers/src/u32.ts","../../../node_modules/.pnpm/@solana+codecs-numbers@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-numbers/src/u64.ts","../../../node_modules/.pnpm/@solana+codecs-numbers@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-numbers/src/u8.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/assertions.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/utils.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/array.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/boolean.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/bytes.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-strings/src/base16.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/constant.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/tuple.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/union.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/unit.ts","../../../node_modules/.pnpm/@solana+codecs-data-structures@5.0.0_typescript@6.0.3/node_modules/@solana/codecs-data-structures/src/struct.ts","../../../node_modules/.pnpm/@solana+options@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/options/src/option.ts","../../../node_modules/.pnpm/@solana+options@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/options/src/option-codec.ts","../../../node_modules/.pnpm/@solana+functional@5.0.0_typescript@6.0.3/node_modules/@solana/functional/src/pipe.ts","../../../node_modules/.pnpm/@solana+instructions@5.0.0_typescript@6.0.3/node_modules/@solana/instructions/src/roles.ts","../../../node_modules/.pnpm/@solana+rpc-types@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/rpc-types/src/blockhash.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/blockhash.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/codecs-strings/src/assertions.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/codecs-strings/src/baseX.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/codecs-strings/src/base58.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/codecs/address-table-lookup.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/codecs/header.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/codecs/instruction.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/transaction-message.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/codecs/transaction-version.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/codecs/message.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/compile/accounts.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/compile/address-table-lookups.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/compile/header.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/compile/instructions.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/compile/lifetime-token.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/compile/static-accounts.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/compile/message.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/compress-transaction-message.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/create-transaction-message.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/durable-nonce-instruction.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/durable-nonce.ts","../../../node_modules/.pnpm/@solana+transaction-messages@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transaction-messages/src/instructions.ts","../../../node_modules/.pnpm/@solana+keys@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/keys/src/algorithm.ts","../../../node_modules/.pnpm/@solana+keys@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/keys/src/signatures.ts","../../../node_modules/.pnpm/@solana+transactions@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transactions/src/codecs/signatures-encoder.ts","../../../node_modules/.pnpm/@solana+transactions@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transactions/src/codecs/transaction-codec.ts","../../../node_modules/.pnpm/@solana+transactions@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transactions/src/compile-transaction.ts","../../../node_modules/.pnpm/@solana+transactions@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transactions/src/signatures.ts","../../../node_modules/.pnpm/@solana+transactions@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/transactions/src/wire-transaction.ts","../../../node_modules/.pnpm/@solana+signers@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/signers/src/deduplicate-signers.ts","../../../node_modules/.pnpm/@solana+signers@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/signers/src/transaction-modifying-signer.ts","../../../node_modules/.pnpm/@solana+signers@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/signers/src/transaction-partial-signer.ts","../../../node_modules/.pnpm/@solana+signers@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/signers/src/transaction-sending-signer.ts","../../../node_modules/.pnpm/@solana+signers@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/signers/src/transaction-signer.ts","../../../node_modules/.pnpm/@solana+signers@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/signers/src/account-signer-meta.ts","../../../node_modules/.pnpm/@solana+signers@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/signers/src/fee-payer-signer.ts","../../../node_modules/.pnpm/@solana+signers@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3/node_modules/@solana/signers/src/sign-transaction.ts","../../../node_modules/.pnpm/@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6.0.3_ws@8.20.0_b_4eb254813adfd75eda5d5606215179c7/node_modules/@solana/kit/src/fetch-lookup-tables.ts","../../../node_modules/.pnpm/@solana-program+compute-budget@0.11.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecod_b2909efeb0cbf83c314d85222a049614/node_modules/@solana-program/compute-budget/src/generated/programs/computeBudget.ts","../../../node_modules/.pnpm/@solana-program+compute-budget@0.11.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecod_b2909efeb0cbf83c314d85222a049614/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitLimit.ts","../../../node_modules/.pnpm/@solana-program+compute-budget@0.11.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecod_b2909efeb0cbf83c314d85222a049614/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitPrice.ts","../../../node_modules/.pnpm/gill@0.14.0_@solana+sysvars@6.5.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6_b9fa60a5d5957e79079eaa322e2d6bec/node_modules/gill/src/core/verify-signature.ts","../src/utils/consts.ts","../src/utils/errors.ts","../src/provider/utils.ts","../src/provider/main.ts","../src/utils/internal.ts","../src/utils/retry.ts","../src/utils/message/fetchSIgnatureFromTransactionManager.ts","../src/utils/message/index.ts","../src/client/signIn.ts","../../../node_modules/.pnpm/@solana-program+system@0.10.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.2_7bd7a67a07ba69964cdb4585e7658289/node_modules/@solana-program/system/src/generated/programs/system.ts","../../../node_modules/.pnpm/@solana-program+system@0.10.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.2_7bd7a67a07ba69964cdb4585e7658289/node_modules/@solana-program/system/src/generated/errors/system.ts","../../../node_modules/.pnpm/gill@0.14.0_@solana+sysvars@6.5.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@6_b9fa60a5d5957e79079eaa322e2d6bec/node_modules/gill/src/programs/token/addresses.ts","../../../node_modules/.pnpm/@solana-program+address-lookup-table@0.10.0_@solana+kit@5.0.0_fastestsmallesttextencode_bcedd89bd010a3756fb5e2724d400ee9/node_modules/@solana-program/address-lookup-table/src/generated/accounts/addressLookupTable.ts","../src/utils/transactions/solana-send.ts","../src/utils/transactions/utils.ts","../src/utils/transactions/processBundledTransaction.ts","../src/utils/transactions/processSyncTransaction.ts","../src/utils/transactions/processTokenTransfer.ts","../src/utils/transactions/pollTransactionConfirmation.ts","../src/utils/transactions/sendTransaction.ts","../src/client/transactions.ts","../src/client/transfer.ts","../src/server/startRequest.ts","../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/utils.ts","../src/server/verifyMessage.ts","../src/server/verifyTransaction.ts","../src/server/processClientAuthCallback.ts","../src/server/processEstimateJitoTipsCallback.ts","../src/server/processSendJitoBundleCallback.ts"],"names":["SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED","SOLANA_ERROR__INVALID_NONCE","SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND","SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE","SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH","SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE","SOLANA_ERROR__MALFORMED_BIGINT_STRING","SOLANA_ERROR__MALFORMED_NUMBER_STRING","SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE","SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR","SOLANA_ERROR__JSON_RPC__PARSE_ERROR","SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR","SOLANA_ERROR__JSON_RPC__INVALID_PARAMS","SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND","SOLANA_ERROR__JSON_RPC__INVALID_REQUEST","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH","SOLANA_ERROR__JSON_RPC__SCAN_ERROR","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE","SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP","SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH","SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE","SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS","SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY","SOLANA_ERROR__ADDRESSES__MALFORMED_PDA","SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE","SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED","SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED","SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE","SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED","SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER","SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS","SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND","SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND","SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT","SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT","SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED","SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT","SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED","SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED","SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED","SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED","SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED","SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED","SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY","SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED","SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH","SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH","SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH","SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE","SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY","SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS","SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA","SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH","SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN","SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR","SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT","SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA","SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA","SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL","SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS","SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID","SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE","SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED","SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT","SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION","SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID","SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND","SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED","SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE","SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED","SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX","SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED","SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED","SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS","SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED","SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE","SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED","SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING","SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC","SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM","SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR","SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED","SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE","SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT","SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID","SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH","SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT","SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED","SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED","SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS","SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC","SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED","SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION","SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE","SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE","SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE","SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE","SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY","SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR","SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT","SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER","SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW","SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR","SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER","SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED","SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED","SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED","SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS","SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS","SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER","SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER","SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER","SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER","SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER","SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER","SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER","SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER","SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS","SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING","SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED","SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES","SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE","SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME","SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME","SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE","SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING","SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE","SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND","SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING","SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING","SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING","SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING","SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING","SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING","SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE","SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION","SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES","SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH","SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT","SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT","SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT","SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED","SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE","SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN","SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE","SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE","SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND","SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND","SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE","SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE","SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED","SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND","SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP","SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE","SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX","SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE","SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION","SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE","SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE","SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING","SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT","SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION","SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT","SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT","SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT","SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS","SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND","SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER","SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA","SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX","SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT","SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT","SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT","SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION","SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT","SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED","SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT","SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED","SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED","SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION","SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN","SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE","SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN","SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN","SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY","SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH","SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH","SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH","SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH","SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH","SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH","SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS","SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE","SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT","SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT","SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE","SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE","SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH","SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE","SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT","SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE","SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE","SOLANA_ERROR__CODECS__INVALID_CONSTANT","SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE","SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL","SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES","SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS","SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY","SOLANA_ERROR__RPC__INTEGER_OVERFLOW","SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN","SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR","SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD","SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN","SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID","SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED","SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED","SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE","SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING","SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE","SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND","encodeValue","value","encodeObjectContextEntry","key","encodeContextObject","context","searchParamsString","SolanaErrorMessages","START_INDEX","TYPE","getHumanReadableErrorMessage","code","messageFormatString","state","commitStateUpTo","endIndex","variableName","fragments","char","ii","nextState","getErrorMessage","decodingAdviceMessage","SolanaError","contextAndErrorOptions","errorOptions","name","descriptor","message","padBytes","bytes","length","paddedBytes","fixBytes","containsBytes","data","offset","slice","b","getEncodedSize","encoder","createEncoder","createDecoder","decoder","isFixedSize","codec","assertIsFixedSize","isVariableSize","assertByteArrayIsNotEmptyForCodec","codecDescription","assertByteArrayHasEnoughBytesForCodec","expected","bytesLength","addEncoderSizePrefix","prefix","write","encoderBytes","prefixMaxSize","encoderMaxSize","maxSize","encoderSize","fixEncoderSize","fixedBytes","variableByteArray","fixedByteArray","fixDecoderSize","transformEncoder","unmap","transformDecoder","map","newOffset","assertValidBaseString","alphabet","testValue","givenValue","getBaseXEncoder","leadingZeroes","tailChars","partitionLeadingZeroes","base10Number","getBigIntFromBaseX","tailBytes","bytesToAdd","getBaseXDecoder","rawBytes","trailIndex","n","sum","byte","getBaseXFromBigInt","zeroCharacter","leadingZeros","base","getBase58Encoder","getBase58Decoder","getBase64Encoder","buffer","getBase64Decoder","decodeAccount","encodedAccount","accountExists","account","assertAccountsDecoded","accounts","encoded","a","encodedAddresses","parseBase64RpcAccount","address","rpcAccount","parseBaseAccount","parseJsonRpcAccount","fetchEncodedAccount","rpc","config","abortSignal","rpcConfig","response","fetchJsonParsedAccounts","addresses","index","assertAccountsExist","missingAccounts","missingAddresses","assertVerificationCapabilityIsAvailable","memoizedBase58Encoder","memoizedBase58Decoder","getMemoizedBase58Encoder","getMemoizedBase58Decoder","isAddress","putativeAddress","base58Encoder","assertIsAddress","numBytes","getAddressEncoder","getAddressDecoder","getAddressComparator","getPublicKeyFromAddress","addressBytes","assertNumberIsBetweenForCodec","min","max","isLittleEndian","numberEncoderFactory","input","arrayBuffer","numberDecoderFactory","view","toArrayBuffer","bytesOffset","getShortU16Encoder","shortU16Bytes","alignedValue","nextSevenBits","getU16Decoder","le","getU32Encoder","getU32Decoder","getU64Encoder","getU64Decoder","getU8Encoder","getU8Decoder","assertValidNumberOfItemsForCodec","actual","maxCodecSizes","sizes","all","size","sumCodecSizes","getFixedSize","getMaxSize","getArrayEncoder","item","fixedSize","computeArrayLikeCodecSize","array","getArrayDecoder","itemSize","resolvedSize","i","getBooleanDecoder","getBytesEncoder","getBase16Decoder","str","getConstantEncoder","constant","_","getConstantDecoder","base16","getTupleDecoder","items","values","newValue","getUnionEncoder","variants","getIndexFromValue","getUnionFixedSize","variant","assertValidVariantIndex","getUnionMaxSize","getUnionDecoder","getIndexFromBytes","read","variantSize","getUnitDecoder","_bytes","getStructEncoder","fields","fieldCodecs","one","struct","getStructDecoder","some","none","getOptionDecoder","noneValue","zeroValue","pipe","init","fns","acc","fn","AccountRole","AccountRole2","IS_WRITABLE_BITMASK","isSignerRole","role","isWritableRole","mergeRoles","roleA","roleB","isBlockhash","putativeBlockhash","getBlockhashDecoder","isTransactionMessageWithBlockhashLifetime","transactionMessage","setTransactionMessageLifetimeUsingBlockhash","blockhashLifetimeConstraint","memoizedAddressTableLookupEncoder","getAddressTableLookupEncoder","indexEncoder","memoizedU8Encoder","getMemoizedU8Encoder","getMessageHeaderEncoder","memoizedGetInstructionEncoder","getInstructionEncoder","instruction","MAX_SUPPORTED_TRANSACTION_VERSION","VERSION_FLAG_MASK","getTransactionVersionEncoder","getCompiledMessageLegacyEncoder","getPreludeStructEncoderTuple","getCompiledMessageVersionedEncoder","getAddressTableLookupArrayEncoder","lifetimeTokenEncoder","getCompiledTransactionMessageEncoder","compiledMessage","upsert","addressMap","update","getAddressMapFromInstructions","feePayer","instructions","addressesOfInvokedPrograms","entry","addressComparator","accountMeta","nextRole","getOrderedAccountsFromAddressMap","leftAddress","leftEntry","rightAddress","rightEntry","leftIsSigner","leftIsWritable","addressMeta","getCompiledAddressTableLookups","orderedAccounts","lookupTableAddress","getCompiledMessageHeader","numReadonlyNonSignerAccounts","numReadonlySignerAccounts","numSignerAccounts","accountIsWritable","getAccountIndex","out","getCompiledInstructions","accountIndex","programAddress","getCompiledLifetimeToken","lifetimeConstraint","getCompiledStaticAccounts","firstLookupTableAccountIndex","compileTransactionMessage","findAddressInLookupTables","addressesByLookupTableAddress","compressTransactionMessageUsingAddressLookupTables","programAddresses","ix","eligibleLookupAddresses","newInstructions","updatedAnyInstructions","newAccounts","updatedAnyAccounts","lookupMetaAccount","createTransactionMessage","RECENT_BLOCKHASHES_SYSVAR_ADDRESS","SYSTEM_PROGRAM_ADDRESS","isAdvanceNonceAccountInstruction","isAdvanceNonceAccountInstructionData","isTransactionMessageWithDurableNonceLifetime","appendTransactionMessageInstructions","prependTransactionMessageInstructions","ED25519_ALGORITHM_IDENTIFIER","verifySignature","signature","getSignaturesToEncode","signaturesMap","signatures","getSignaturesEncoder","getTransactionEncoder","compileTransaction","messageBytes","transactionSigners","signerAddress","base58Decoder","getSignatureFromTransaction","transaction","signatureBytes","assertIsFullySignedTransaction","missingSigs","getBase64EncodedWireTransaction","wireTransactionBytes","deduplicateSigners","signers","deduplicated","signer","isTransactionModifyingSigner","isTransactionPartialSigner","isTransactionSendingSigner","isTransactionSigner","getSignersFromInstruction","getSignersFromTransactionMessage","setTransactionMessageFeePayerSigner","partiallySignTransactionMessageWithSigners","partialSigners","modifyingSigners","categorizeTransactionSigners","signModifyingAndPartialTransactionSigners","signTransactionMessageWithSigners","signedTransaction","sendingSigner","identifyTransactionSendingSigner","otherSigners","identifyTransactionModifyingSigners","sendingSigners","sendingOnlySigners","nonPartialSigners","modifiedTransaction","modifyingSigner","tx","signatureDictionaries","partialSigner","signatureDictionary","fetchAddressesForLookupTables","lookupTableAddresses","fetchedLookupTables","lookup","COMPUTE_BUDGET_PROGRAM_ADDRESS","SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR","getSetComputeUnitLimitInstructionDataEncoder","getSetComputeUnitLimitInstruction","args","SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR","getSetComputeUnitPriceInstructionDataEncoder","getSetComputeUnitPriceInstruction","verifySignatureForAddress","publicKey","REVIBASE_AUTH_URL","REVIBASE_RP_ID","REVIBASE_API_ENDPOINT","REVIBASE_LOOKUP_TABLE_ADDRESS","DEFAULT_JITO_BLOCK_ENGINE_SEND_BUNDLE_URL","DEFAULT_JITO_TIPS_URL","RevibaseError","_RevibaseError","RevibasePopupBlockedError","_RevibasePopupBlockedError","RevibasePopupClosedError","_RevibasePopupClosedError","RevibaseTimeoutError","_RevibaseTimeoutError","RevibaseFlowInProgressError","_RevibaseFlowInProgressError","RevibaseAbortedError","_RevibaseAbortedError","RevibasePopupNotOpenError","_RevibasePopupNotOpenError","RevibaseAuthError","_RevibaseAuthError","RevibaseApiError","_RevibaseApiError","RevibaseEnvironmentError","_RevibaseEnvironmentError","DEFAULT_TIMEOUT","HEARTBEAT_INTERVAL","CONNECT_TIMEOUT","defaultSendJitoBundleCallback","request","res","defaultEstimateJitoTipsCallback","defaultClientAuthorizationCallback","createPopUp","url","availW","availH","isMobile","width","height","top","left","screenLeft","screenTop","viewportW","viewportH","features","createProviderFrame","signal","onDismiss","scrollY","previousBodyStyles","lockScroll","unlockScroll","host","shadow","overlay","frameWrapper","iframe","closeBtn","keyHandler","e","dismiss","closed","close","abortHandler","RevibaseProvider","options","rpId","rpcEndpoint","providerOrigin","ui","onClientAuthorizationCallback","onSendJitoBundleCallback","onEstimateJitoTipsCallback","initialize","onConnectedCallback","onSuccessCallback","rid","clientOrigin","popupUrl","detachForwardAbort","flowAbortController","forwardAbort","originalSignal","resolve","reject","params","fail","port","finished","heartbeatInterval","connectTimeoutId","requestTimeoutId","cleanup","onConnect","err","succeed","result","event","channel","lastPong","ev","msg","timeoutDuration","createSignInMessageText","isNetworkError","withRetry","maxAttempts","initialDelay","maxDelay","lastError","attempt","error","delay","fetchSignatureFromTransactionManager","wsUrl","toWebSocketUrl","pendingApprovalsCallback","ws","openWebSocket","readWebSocketJsonEvents","httpUrl","u","onAbort","onEvent","settled","onMessage","onError","onClose","finish","parsed","send2FARequestIfNeeded","user","startRequest","transactionManager","fetchSettings","getSolanaRpc","getSettingsFromIndex","x","UserRole","convertMemberKeyToString","userAccountData","fetchUser","getUserAddress","signIn","provider","payload","validTill","UserInfoSchema","SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE","SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS","SYSTEM_ERROR__INVALID_PROGRAM_ID","SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH","SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED","SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH","SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES","SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED","SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE","TOKEN_PROGRAM_ADDRESS","getAddressLookupTableDecoder","decodeAddressLookupTable","fetchMaybeAddressLookupTable","maybeAccount","signAndSendTransaction","payer","latestBlockHash","unitsConsumed","priorityFees","getComputeUnitsEstimate","getMedianPriorityFees","computeUnits","signAndSendBundledTransactions","bundle","simulationBundle","createEncodedBundle","simulateBundle","getSolanaRpcEndpoint","encodedBundle","connectionUrl","TransactionFailure","programError","isSimulate","transactionMessageWithComputeUnitAndPriorityFees","simulatedTransaction","errorMessage","connection","fees","f","mid","payerCache","getRandomPayer","cached","randomPayer","createTransactionSigner","transactions","signResponse","sig","getTransactionManagerSigner","transactionManagerAddress","transactionMessageBytes","authResponses","onPendingApprovalsCallback","onPendingApprovalsSuccess","abortControllerArg","abortController","ac","txManagerUrl","createTransactionManagerSigner","fetchAdditionalLoopUpTableIfNecessary","fetched","processBundledTransaction","authResponse","settings","additionalSigners","transactionActionType","settingsData","signedSigner","getSignedSecp256r1Key","tm","retrieveTransactionManager","transactionManagerSigner","jitoBundlesTipAmount","prepareTransactionBundle","bundlesWithLookupTables","processSyncTransaction","prepareTransactionSync","processTokenTransfer","transactionAddress","amount","destination","mint","tokenTransferIntent","nativeTransferIntent","pollTransactionConfirmation","txSig","maxRetries","delayMs","confirmation","sendTransaction","confirmTransaction","executeTransaction","settingsIndexWithAddress","prepareTransactionMessage","settingsArgs","hasTxManager","transactionPayload","transferTokens","tokenProgram","allowedClientOrigins","privateKey","pKey","convertBase64StringToJWK","CompactSign","createClientAuthorizationStartRequestChallenge","equalBytes","diff","verifyMessage","expectedClientJwk","requireTwoFactorAuthentication","importJWK","compactVerify","getDeviceMessageHash","expectedChallenge","createMessageChallenge","verified","verifyAuthenticationResponse","bufferToBase64URLString","convertPubkeyCompressedToCose","delegateTo","fetchUserAccountByFilters","getDomainConfigAddress","verifyTransaction","createTransactionChallenge","createClientAuthorizationCompleteRequestChallenge","initialized","ensureInitialize","processClientAuthCallback","processEstimateJitoTipsCallback","priority","processSendJitoBundleCallback","serializedTransactions","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CAACA,CAAAA,CAAK,MAAA,CACR,MAAM,IAAI,KAAA,CAAM,iCAAiC,CAAA,CAGnD,OAAOA,EAAK,MACd,CAEA,IAAMqnB,EAAAA,CAASC,GAAe,IAAI,OAAA,CAAeC,GAAM,UAAA,CAAWA,CAAAA,CAAGD,CAAE,CAAC,CAAA","file":"index.js","sourcesContent":["/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @module\n * @privateRemarks\n * WARNING:\n * - Don't remove error codes\n * - Don't change or reorder error codes.\n *\n * Good naming conventions:\n * - Prefixing common errors — e.g. under the same package — can be a good way to namespace them. E.g. All codec-related errors start with `SOLANA_ERROR__CODECS__`.\n * - Use consistent names — e.g. choose `PDA` or `PROGRAM_DERIVED_ADDRESS` and stick with it. Ensure your names are consistent with existing error codes. The decision might have been made for you.\n * - Recommended prefixes and suffixes:\n * - `MALFORMED_`: Some input was not constructed properly. E.g. `MALFORMED_BASE58_ENCODED_ADDRESS`.\n * - `INVALID_`: Some input is invalid (other than because it was MALFORMED). E.g. `INVALID_NUMBER_OF_BYTES`.\n * - `EXPECTED_`: Some input was different than expected, no need to specify the \"GOT\" part unless necessary. E.g. `EXPECTED_DECODED_ACCOUNT`.\n * - `_CANNOT_`: Some operation cannot be performed or some input cannot be used due to some condition. E.g. `CANNOT_DECODE_EMPTY_BYTE_ARRAY` or `PDA_CANNOT_END_WITH_PDA_MARKER`.\n * - `_MUST_BE_`: Some condition must be true. E.g. `NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE`.\n * - `_FAILED_TO_`: Tried to perform some operation and failed. E.g. `FAILED_TO_DECODE_ACCOUNT`.\n * - `_NOT_FOUND`: Some operation lead to not finding something. E.g. `ACCOUNT_NOT_FOUND`.\n * - `_OUT_OF_RANGE`: Some value is out of range. E.g. `ENUM_DISCRIMINATOR_OUT_OF_RANGE`.\n * - `_EXCEEDED`: Some limit was exceeded. E.g. `PDA_MAX_SEED_LENGTH_EXCEEDED`.\n * - `_MISMATCH`: Some elements do not match. E.g. `ENCODER_DECODER_FIXED_SIZE_MISMATCH`.\n * - `_MISSING`: Some required input is missing. E.g. `TRANSACTION_FEE_PAYER_MISSING`.\n * - `_UNIMPLEMENTED`: Some required component is not available in the environment. E.g. `SUBTLE_CRYPTO_VERIFY_FUNCTION_UNIMPLEMENTED`.\n */\nexport const SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;\nexport const SOLANA_ERROR__INVALID_NONCE = 2;\nexport const SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;\nexport const SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;\nexport const SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;\nexport const SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;\nexport const SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;\nexport const SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;\nexport const SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;\nexport const SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;\n\n// JSON-RPC-related errors.\n// Reserve error codes in the range [-32768, -32000]\n// Keep in sync with https://github.com/anza-xyz/agave/blob/master/rpc-client-api/src/custom_error.rs\nexport const SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;\nexport const SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;\nexport const SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE = -32019;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY = -32018;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE = -32017;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;\nexport const SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;\n\n// Addresses-related errors.\n// Reserve error codes in the range [2800000-2800999].\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 2800000;\nexport const SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;\nexport const SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;\nexport const SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;\nexport const SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;\nexport const SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;\nexport const SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;\nexport const SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;\n\n// Account-related errors.\n// Reserve error codes in the range [3230000-3230999].\nexport const SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 3230000;\nexport const SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;\nexport const SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;\n\n// Subtle-Crypto-related errors.\n// Reserve error codes in the range [3610000-3610999].\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 3610000;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;\n\n// Crypto-related errors.\n// Reserve error codes in the range [3611000-3611050].\nexport const SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611000;\n\n// Key-related errors.\n// Reserve error codes in the range [3704000-3704999].\nexport const SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704000;\nexport const SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;\nexport const SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;\nexport const SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;\nexport const SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;\n\n// Instruction-related errors.\n// Reserve error codes in the range [4128000-4128999].\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128000;\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;\nexport const SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;\n\n// Instruction errors.\n// Reserve error codes starting with [4615000-4615999] for the Rust enum `InstructionError`.\n// Error names here are dictated by the RPC (see ./instruction-error.ts).\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615000;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;\n\n// Signer-related errors.\n// Reserve error codes in the range [5508000-5508999].\nexport const SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508000;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;\nexport const SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;\n\n// Transaction-related errors.\n// Reserve error codes in the range [5663000-5663999].\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663000;\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;\nexport const SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;\nexport const SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;\nexport const SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;\nexport const SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED = 5663021;\nexport const SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE = 5663022;\n\n// Transaction errors.\n// Reserve error codes starting with [7050000-7050999] for the Rust enum `TransactionError`.\n// Error names here are dictated by the RPC (see ./transaction-error.ts).\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 7050000;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;\n// `InstructionError` intentionally omitted.\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;\n\n// Instruction plan related errors.\n// Reserve error codes in the range [7618000-7618999].\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN = 7618000;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE = 7618001;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN = 7618002;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN = 7618003;\n\n// Codec-related errors.\n// Reserve error codes in the range [8078000-8078999].\nexport const SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078000;\nexport const SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;\nexport const SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;\nexport const SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;\nexport const SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;\nexport const SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;\nexport const SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;\nexport const SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;\nexport const SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;\nexport const SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;\nexport const SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;\nexport const SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;\nexport const SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;\nexport const SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;\nexport const SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;\nexport const SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;\nexport const SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;\nexport const SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;\nexport const SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;\nexport const SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;\nexport const SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY = 8078023;\n\n// RPC-related errors.\n// Reserve error codes in the range [8100000-8100999].\nexport const SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 8100000;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;\nexport const SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;\n\n// RPC-Subscriptions-related errors.\n// Reserve error codes in the range [8190000-8190999].\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 8190000;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;\n\n// Invariant violation errors.\n// Reserve error codes in the range [9900000-9900999].\n// These errors should only be thrown when there is a bug with the\n// library itself and should, in theory, never reach the end user.\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 9900000;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND = 9900005;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND = 9900006;\n\n/**\n * A union of every Solana error code\n *\n * @privateRemarks\n * You might be wondering why this is not a TypeScript enum or const enum.\n *\n * One of the goals of this library is to enable people to use some or none of it without having to\n * bundle all of it.\n *\n * If we made the set of error codes an enum then anyone who imported it (even if to only use a\n * single error code) would be forced to bundle every code and its label.\n *\n * Const enums appear to solve this problem by letting the compiler inline only the codes that are\n * actually used. Unfortunately exporting ambient (const) enums from a library like `@solana/errors`\n * is not safe, for a variety of reasons covered here: https://stackoverflow.com/a/28818850\n */\nexport type SolanaErrorCode =\n | typeof SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND\n | typeof SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE\n | typeof SOLANA_ERROR__ADDRESSES__MALFORMED_PDA\n | typeof SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE\n | typeof SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER\n | typeof SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED\n | typeof SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS\n | typeof SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE\n | typeof SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__INVALID_CONSTANT\n | typeof SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS\n | typeof SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE\n | typeof SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES\n | typeof SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA\n | typeof SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE\n | typeof SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH\n | typeof SOLANA_ERROR__INVALID_NONCE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE\n | typeof SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_PARAMS\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_REQUEST\n | typeof SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND\n | typeof SOLANA_ERROR__JSON_RPC__PARSE_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SCAN_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION\n | typeof SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY\n | typeof SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE\n | typeof SOLANA_ERROR__MALFORMED_BIGINT_STRING\n | typeof SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR\n | typeof SOLANA_ERROR__MALFORMED_NUMBER_STRING\n | typeof SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD\n | typeof SOLANA_ERROR__RPC__INTEGER_OVERFLOW\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID\n | typeof SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING\n | typeof SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES\n | typeof SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE\n | typeof SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH\n | typeof SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE\n | typeof SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT;\n\n/**\n * Errors of this type are understood to have an optional {@link SolanaError} nested inside as\n * `cause`.\n */\nexport type SolanaErrorCodeWithCause = typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE;\n","/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @privateRemarks\n * WARNING:\n * - Don't change or remove members of an error's context.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SolanaErrorCode,\n} from './codes';\nimport { RpcSimulateTransactionResult } from './json-rpc-error';\n\ntype BasicInstructionErrorContext<T extends SolanaErrorCode> = Readonly<{ [P in T]: { index: number } }>;\n\ntype DefaultUnspecifiedErrorContextToUndefined<T> = {\n [P in SolanaErrorCode]: P extends keyof T ? T[P] : undefined;\n};\n\ntype TypedArrayMutableProperties = 'copyWithin' | 'fill' | 'reverse' | 'set' | 'sort';\ninterface ReadonlyUint8Array extends Omit<Uint8Array, TypedArrayMutableProperties> {\n readonly [n: number]: number;\n}\n\n/** A amount of bytes. */\ntype Bytes = number;\n\n/**\n * A map of every {@link SolanaError} code to the type of its `context` property.\n */\nexport type SolanaErrorContext = DefaultUnspecifiedErrorContextToUndefined<\n BasicInstructionErrorContext<\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n > & {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: {\n addresses: string[];\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: {\n addresses: string[];\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: {\n putativeAddress: string;\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: {\n actual: number;\n maxSeeds: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: {\n actual: number;\n index: number;\n maxSeedLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: {\n bump: number;\n };\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: {\n currentBlockHeight: bigint;\n lastValidBlockHeight: bigint;\n };\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: {\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: {\n stringValues: string[];\n };\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: {\n encodedBytes: ReadonlyUint8Array;\n hexEncodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: {\n decoderFixedSize: number;\n encoderFixedSize: number;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: {\n decoderMaxSize: number | undefined;\n encoderMaxSize: number | undefined;\n };\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n formattedValidDiscriminators: string;\n validDiscriminators: number[];\n };\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]: {\n expectedLength: number;\n numExcessBytes: number;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: {\n codecDescription: string;\n expectedSize: number;\n hexZeroValue: string;\n zeroValue: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n expected: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: {\n constant: ReadonlyUint8Array;\n data: ReadonlyUint8Array;\n hexConstant: string;\n hexData: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: {\n formattedNumericalValues: string;\n numericalValues: number[];\n stringValues: string[];\n variant: number | string | symbol;\n };\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: {\n actual: bigint | number;\n codecDescription: string;\n expected: bigint | number;\n };\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: {\n alphabet: string;\n base: number;\n value: string;\n };\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n maxRange: number;\n minRange: number;\n };\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: {\n codecDescription: string;\n max: bigint | number;\n min: bigint | number;\n value: bigint | number;\n };\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: {\n bytesLength: number;\n codecDescription: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: {\n decodedBytes: ReadonlyUint8Array;\n hexDecodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: {\n maxRange: number;\n minRange: number;\n variant: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: {\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: {\n code: number;\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: {\n errorName: string;\n index: number;\n instructionErrorContext?: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]: {\n numBytesRequired: number;\n numFreeBytes: number;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: {\n data?: ReadonlyUint8Array;\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: {\n accountAddresses?: string[];\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: {\n actualProgramAddress: string;\n expectedProgramAddress: string;\n };\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__INVALID_NONCE]: {\n actualNonceValue: string;\n expectedNonceValue: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: {\n cacheKey: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: {\n channelName: string;\n supportedChannelNames: string[];\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: {\n unexpectedValue: unknown;\n };\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]: {\n currentBlockHeight: bigint;\n rewardsCompleteBlockHeight: bigint;\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: {\n contextSlot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: {\n numSlotsBehind?: number;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: Omit<\n RpcSimulateTransactionResult,\n 'err'\n >;\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]: {\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: {\n byteLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: {\n error: unknown;\n message: string;\n };\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: {\n nonceAccountAddress: string;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: {\n notificationName: string;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: {\n errorEvent: Event;\n };\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: {\n method: string;\n params: unknown[];\n };\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: {\n argumentLabel: string;\n keyPath: readonly (number | string | symbol)[];\n methodName: string;\n optionalPathLabel: string;\n path?: string;\n value: bigint;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: {\n headers: Headers;\n message: string;\n statusCode: number;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: {\n headers: string[];\n };\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: {\n key: CryptoKey;\n };\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: {\n value: bigint;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: {\n errorName: string;\n transactionErrorContext?: unknown;\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: {\n expectedAddresses: string[];\n unexpectedAddresses: string[];\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: {\n transactionSize: Bytes;\n transactionSizeLimit: Bytes;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: {\n lookupTableAddresses: string[];\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: {\n highestKnownIndex: number;\n highestRequestedIndex: number;\n lookupTableAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: {\n unitsConsumed: number;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: {\n numRequiredSignatures: number;\n signaturesLength: number;\n signerAddresses: string[];\n };\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]: {\n nonce: string;\n };\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: {\n addresses: string[];\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]: {\n unsupportedVersion: number;\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: {\n actualVersion: number;\n };\n }\n>;\n\nexport function decodeEncodedContext(encodedContext: string): object {\n const decodedUrlString = __NODEJS__ ? Buffer.from(encodedContext, 'base64').toString('utf8') : atob(encodedContext);\n return Object.fromEntries(new URLSearchParams(decodedUrlString).entries());\n}\n\nfunction encodeValue(value: unknown): string {\n if (Array.isArray(value)) {\n const commaSeparatedValues = value.map(encodeValue).join('%2C%20' /* \", \" */);\n return '%5B' /* \"[\" */ + commaSeparatedValues + /* \"]\" */ '%5D';\n } else if (typeof value === 'bigint') {\n return `${value}n`;\n } else {\n return encodeURIComponent(\n String(\n value != null && Object.getPrototypeOf(value) === null\n ? // Plain objects with no prototype don't have a `toString` method.\n // Convert them before stringifying them.\n { ...(value as object) }\n : value,\n ),\n );\n }\n}\n\nfunction encodeObjectContextEntry([key, value]: [string, unknown]): `${typeof key}=${string}` {\n return `${key}=${encodeValue(value)}`;\n}\n\nexport function encodeContextObject(context: object): string {\n const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join('&');\n return __NODEJS__ ? Buffer.from(searchParamsString, 'utf8').toString('base64') : btoa(searchParamsString);\n}\n","/* eslint-disable sort-keys-fix/sort-keys-fix */\n/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors#adding-a-new-error\n *\n * WARNING:\n * - Don't change the meaning of an error message.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY,\n SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,\n SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,\n SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,\n SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED,\n SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP,\n SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS,\n SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT,\n SolanaErrorCode,\n} from './codes';\n\n/**\n * A map of every {@link SolanaError} code to the error message shown to developers in development\n * mode.\n */\nexport const SolanaErrorMessages: Readonly<{\n // This type makes this data structure exhaustive with respect to `SolanaErrorCode`.\n // TypeScript will fail to build this project if add an error code without a message.\n [P in SolanaErrorCode]: string;\n}> = {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: 'Account not found at address: $address',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]:\n 'Not all accounts were decoded. Encoded accounts found at addresses: $addresses.',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: 'Expected decoded account at address: $address',\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: 'Failed to decode account data at address: $address',\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: 'Accounts not found at addresses: $addresses',\n [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]:\n 'Unable to find a viable program address bump seed.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: '$putativeAddress is not a base58-encoded address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]:\n 'Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: 'The `CryptoKey` must be an `Ed25519` public key.',\n [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]:\n '$putativeOffCurveAddress is not a base58-encoded off-curve address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: 'Invalid seeds; point must fall off the Ed25519 curve.',\n [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]:\n 'Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].',\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]:\n 'A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.',\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]:\n 'The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.',\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]:\n 'Expected program derived address bump to be in the range [0, 255], got: $bump.',\n [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: 'Program address cannot end with PDA marker.',\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]:\n 'The network has progressed past the last block for which this transaction could have been committed.',\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]:\n 'Codec [$codecDescription] cannot decode empty byte arrays.',\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]:\n 'Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.',\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]:\n 'Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]:\n 'Encoder and decoder must either both be fixed-size or variable-size.',\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.',\n [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: 'Expected a fixed-size codec, got a variable-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected a positive byte length, got $bytesLength.',\n [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: 'Expected a variable-size codec, got a fixed-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]:\n 'Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].',\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected $expected bytes, got $bytesLength.',\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]:\n 'Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].',\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]:\n 'Invalid discriminated union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]:\n 'Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.',\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]:\n 'Invalid literal union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]:\n 'Expected [$codecDescription] to have $expected items, got $actual.',\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: 'Invalid value $value for base $base with alphabet $alphabet.',\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.',\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.',\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.',\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]:\n 'Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].',\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]:\n 'Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.',\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]:\n 'This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?',\n [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: 'No random values implementation could be found.',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: 'instruction requires an uninitialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]:\n 'instruction tries to borrow reference for an account which is already borrowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'instruction left account with an outstanding borrowed reference',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]:\n \"program other than the account's owner changed the size of the account data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: 'account data too small for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: 'instruction expected an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]:\n 'An account does not have enough lamports to be rent-exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: 'Program arithmetic overflowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: 'Failed to serialize or deserialize account data: $encodedData',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]:\n 'Builtin programs must consume compute units',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: 'Cross-program invocation call depth too deep',\n [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: 'Computational budget exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: 'custom program error: #$code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: 'instruction contains duplicate accounts',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]:\n 'instruction modifications of multiply-passed account differ',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: 'executable accounts must be rent exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: 'instruction changed executable accounts data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]:\n 'instruction changed the balance of an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: 'instruction changed executable bit of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]:\n 'instruction modified data of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]:\n 'instruction spent from the balance of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: 'generic instruction error',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: 'Provided owner is not allowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: 'Account is immutable',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: 'Incorrect authority provided',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: 'incorrect program id for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: 'insufficient funds for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: 'invalid account data for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: 'Invalid account owner',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: 'invalid program argument',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: 'program returned invalid error code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: 'invalid instruction data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: 'Failed to reallocate account data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: 'Provided seeds do not result in a valid address',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]:\n 'Accounts data allocations exceeded the maximum allowed per transaction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: 'Max accounts exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: 'Max instruction trace length exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]:\n 'Length of the seed is too long for address generation',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: 'An account required by the instruction is missing',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: 'missing required signature for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]:\n 'instruction illegally modified the program id of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: 'insufficient account keys for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]:\n 'Cross-program invocation with unauthorized signer or writable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]:\n 'Failed to create program execution environment',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: 'Program failed to compile',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: 'Program failed to complete',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: 'instruction modified data of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]:\n 'instruction changed the balance of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]:\n 'Cross-program invocation reentrancy not allowed for this instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: 'instruction modified rent epoch of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]:\n 'sum of account balances before and after instruction do not match',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: 'instruction requires an initialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: '',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: 'Unsupported program id',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: 'Unsupported sysvar',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: 'Invalid instruction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]: 'The provided instruction plan is empty.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]:\n 'The provided transaction plan failed to execute. See the `transactionPlanResult` attribute and the `cause` error for more details.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]:\n 'The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: 'Invalid transaction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]:\n 'No more instructions to pack; the message packer has completed the instruction plan.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: 'The instruction does not have any accounts.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: 'The instruction does not have any data.',\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]:\n 'Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.',\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]:\n 'Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__INVALID_NONCE]:\n 'The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`',\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]:\n 'Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It ' +\n 'should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]:\n 'Invariant violation: This data publisher does not publish to the channel named ' +\n '`$channelName`. Supported channels include $supportedChannelNames.',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]:\n 'Invariant violation: WebSocket message iterator state is corrupt; iterated without first ' +\n 'resolving existing message promise. It should be impossible to hit this error; please ' +\n 'file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]:\n 'Invariant violation: WebSocket message iterator is missing state storage. It should be ' +\n 'impossible to hit this error; please file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]:\n 'Invariant violation: Switch statement non-exhaustive. Received unexpected value ' +\n '`$unexpectedValue`. It should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: 'JSON-RPC error: Internal JSON-RPC error ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: 'JSON-RPC error: Invalid method parameter(s) ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]:\n 'JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]:\n 'JSON-RPC error: The method does not exist / is not available ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]:\n 'JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]:\n 'Epoch rewards period still active at slot $slot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]:\n 'Failed to query long-term storage; please try again',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: 'Minimum context slot has not been reached',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: 'Node is unhealthy; behind by $numSlotsBehind slots',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: 'No snapshot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: 'Transaction simulation failed',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]:\n \"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]:\n 'Transaction history is not available from this node',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: 'Transaction signature length mismatch',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]:\n 'Transaction signature verification failure',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: '$__serverMessage',\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: 'Key pair bytes must be of length 64, got $byteLength.',\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]:\n 'Expected private key bytes with length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]:\n 'Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]:\n 'The provided private key does not match the provided public key.',\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.',\n [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: 'Lamports value must be in the range [0, 2e64-1]',\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: '`$value` cannot be parsed as a `BigInt`',\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: '$message',\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: '`$value` cannot be parsed as a `Number`',\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: 'No nonce account could be found at address `$nonceAccountAddress`',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]:\n \"The notification name must end in 'Notifications' and the API must supply a \" +\n \"subscription plan creator function for the notification '$notificationName'.\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]:\n 'WebSocket was closed before payload could be added to the send buffer',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: 'WebSocket connection closed',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: 'WebSocket failed to connect',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]:\n 'Failed to obtain a subscription id from the server',\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: 'Could not find an API plan for RPC method: `$method`',\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]:\n 'The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was ' +\n '`$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: 'HTTP error ($statusCode): $message',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]:\n 'HTTP header(s) forbidden: $headers. Learn more at ' +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.',\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]:\n 'Multiple distinct signers were identified for address `$address`. Please ensure that ' +\n 'you are using the same signer instance for each address.',\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]:\n 'The provided value does not implement the `KeyPairSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]:\n 'The provided value does not implement the `MessageModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]:\n 'The provided value does not implement the `MessagePartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]:\n 'The provided value does not implement any of the `MessageSigner` interfaces',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]:\n 'The provided value does not implement the `TransactionModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]:\n 'The provided value does not implement the `TransactionPartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]:\n 'The provided value does not implement the `TransactionSendingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]:\n 'The provided value does not implement any of the `TransactionSigner` interfaces',\n [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]:\n 'More than one `TransactionSendingSigner` was identified.',\n [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]:\n 'No `TransactionSendingSigner` was identified. Please provide a valid ' +\n '`TransactionWithSingleSendingSigner` transaction.',\n [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]:\n 'Wallet account signers do not support signing multiple messages/transactions in a single operation',\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: 'Cannot export a non-extractable key.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: 'No digest implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]:\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 [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]:\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall ' +\n '@solana/webcrypto-ed25519-polyfill and call its `install` function 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 [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]:\n 'No signature verification implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: 'No key generation implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: 'No signing implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: 'No key export implementation could be found.',\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]:\n 'Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'Transaction processing left an account with an outstanding borrowed reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: 'Account in use',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: 'Account loaded twice',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]:\n 'Attempt to debit an account but found no record of a prior credit.',\n [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]:\n \"Transaction loads an address table account that doesn't exist\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: 'This transaction has already been processed',\n [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: 'Blockhash not found',\n [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: 'Loader call chain is too deep',\n [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]:\n 'Transactions are currently disabled due to cluster maintenance',\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]:\n 'Transaction contains a duplicate instruction ($index) that is not allowed',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: 'Insufficient funds for fee',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]:\n 'Transaction results in an account ($accountIndex) with insufficient funds for rent',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: 'This account may not be used to pay transaction fees',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: 'Transaction contains an invalid account reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]:\n 'Transaction loads an address table account with invalid data',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]:\n 'Transaction address table lookup uses an invalid index',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]:\n 'Transaction loads an address table account with an invalid owner',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]:\n 'LoadedAccountsDataSizeLimit set for transaction must be greater than 0.',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]:\n 'This program may not be used for executing instructions',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]:\n 'Transaction leaves an account with a lower balance than rent-exempt minimum',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]:\n 'Transaction loads a writable account that cannot be written',\n [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]:\n 'Transaction exceeded max loaded accounts data size cap',\n [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]:\n 'Transaction requires a fee but has no signature present',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: 'Attempt to load a program that does not exist',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]:\n 'Execution of the program referenced by account at index $accountIndex is temporarily restricted.',\n [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: 'ResanitizationNeeded',\n [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: 'Transaction failed to sanitize accounts offsets correctly',\n [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: 'Transaction did not pass signature verification',\n [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: 'Transaction locked too many accounts',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]:\n 'Sum of account balances before and after transaction do not match',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: 'The transaction failed with the error `$errorName`',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: 'Transaction version is unsupported',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]:\n 'Transaction would exceed account data limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]:\n 'Transaction would exceed total account data limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]:\n 'Transaction would exceed max account limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]:\n 'Transaction would exceed max Block Cost Limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: 'Transaction would exceed max Vote Cost Limit',\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]:\n 'Attempted to sign a transaction with an address that is not a signer for it',\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: 'Transaction is missing an address at index: $index.',\n [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]:\n 'Transaction has no expected signers therefore it cannot be encoded',\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]:\n 'Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: 'Transaction does not have a blockhash lifetime',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: 'Transaction is not a durable nonce transaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]:\n 'Contents of these address lookup tables unknown: $lookupTableAddresses',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]:\n 'Lookup of address at index $highestRequestedIndex failed for lookup table ' +\n '`$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table ' +\n 'may have been extended since its contents were retrieved',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: 'No fee payer set in CompiledTransaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]:\n 'Could not find program address at index $index',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Failed to estimate the compute unit consumption for this transaction message. This is ' +\n 'likely because simulating the transaction failed. Inspect the `cause` property of this ' +\n 'error to learn more',\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Transaction failed when it was simulated in order to estimate the compute unit consumption. ' +\n 'The compute unit estimate provided is for a transaction that failed when simulated and may not ' +\n 'be representative of the compute units this transaction would consume if successful. Inspect the ' +\n '`cause` property of this error to learn more',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: 'Transaction is missing a fee payer.',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]:\n \"Could not determine this transaction's signature. Make sure that the transaction has \" +\n 'been signed by its fee payer.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]:\n 'Transaction first instruction is not advance nonce account instruction.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]:\n 'Transaction with no instructions cannot be durable nonce transaction.',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]:\n 'This transaction includes an address (`$programAddress`) which is both ' +\n 'invoked and set as the fee payer. Program addresses may not pay fees',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]:\n 'This transaction includes an address (`$programAddress`) which is both invoked and ' +\n 'marked writable. Program addresses may not be writable',\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]:\n 'The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.',\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: 'Transaction is missing signatures for addresses: $addresses.',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]:\n 'Transaction version must be in the range [0, 127]. `$actualVersion` given',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]:\n 'This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.',\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]:\n 'The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction.',\n};\n","import { SolanaErrorCode } from './codes';\nimport { encodeContextObject } from './context';\nimport { SolanaErrorMessages } from './messages';\n\nconst enum StateType {\n EscapeSequence,\n Text,\n Variable,\n}\ntype State = Readonly<{\n [START_INDEX]: number;\n [TYPE]: StateType;\n}>;\nconst START_INDEX = 'i';\nconst TYPE = 't';\n\nexport function getHumanReadableErrorMessage<TErrorCode extends SolanaErrorCode>(\n code: TErrorCode,\n context: object = {},\n): string {\n const messageFormatString = SolanaErrorMessages[code];\n if (messageFormatString.length === 0) {\n return '';\n }\n let state: State;\n function commitStateUpTo(endIndex?: number) {\n if (state[TYPE] === StateType.Variable) {\n const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);\n\n fragments.push(\n variableName in context\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${context[variableName as keyof typeof context]}`\n : `$${variableName}`,\n );\n } else if (state[TYPE] === StateType.Text) {\n fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));\n }\n }\n const fragments: string[] = [];\n messageFormatString.split('').forEach((char, ii) => {\n if (ii === 0) {\n state = {\n [START_INDEX]: 0,\n [TYPE]:\n messageFormatString[0] === '\\\\'\n ? StateType.EscapeSequence\n : messageFormatString[0] === '$'\n ? StateType.Variable\n : StateType.Text,\n };\n return;\n }\n let nextState;\n switch (state[TYPE]) {\n case StateType.EscapeSequence:\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n break;\n case StateType.Text:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n }\n break;\n case StateType.Variable:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n } else if (!char.match(/\\w/)) {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n }\n break;\n }\n if (nextState) {\n if (state !== nextState) {\n commitStateUpTo(ii);\n }\n state = nextState;\n }\n });\n commitStateUpTo();\n return fragments.join('');\n}\n\nexport function getErrorMessage<TErrorCode extends SolanaErrorCode>(\n code: TErrorCode,\n context: Record<string, unknown> = {},\n): string {\n if (process.env.NODE_ENV !== \"production\") {\n return getHumanReadableErrorMessage(code, context);\n } else {\n let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \\`npx @solana/errors decode -- ${code}`;\n if (Object.keys(context).length) {\n /**\n * DANGER: Be sure that the shell command is escaped in such a way that makes it\n * impossible for someone to craft malicious context values that would result in\n * an exploit against anyone who bindly copy/pastes it into their terminal.\n */\n decodingAdviceMessage += ` '${encodeContextObject(context)}'`;\n }\n return `${decodingAdviceMessage}\\``;\n }\n}\n","import { SolanaErrorCode, SolanaErrorCodeWithCause } from './codes';\nimport { SolanaErrorContext } from './context';\nimport { getErrorMessage } from './message-formatter';\n\n/**\n * A type guard that returns `true` if the input is a {@link SolanaError}, optionally with a\n * particular error code.\n *\n * When the `code` argument is supplied and the input is a {@link SolanaError}, TypeScript will\n * refine the error's {@link SolanaError#context | `context`} property to the type associated with\n * that error code. You can use that context to render useful error messages, or to make\n * context-aware decisions that help your application to recover from the error.\n *\n * @example\n * ```ts\n * import {\n * SOLANA_ERROR__TRANSACTION__MISSING_SIGNATURE,\n * SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n * isSolanaError,\n * } from '@solana/errors';\n * import { assertIsFullySignedTransaction, getSignatureFromTransaction } from '@solana/transactions';\n *\n * try {\n * const transactionSignature = getSignatureFromTransaction(tx);\n * assertIsFullySignedTransaction(tx);\n * /* ... *\\/\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * displayError(\n * \"We can't send this transaction without signatures for these addresses:\\n- %s\",\n * // The type of the `context` object is now refined to contain `addresses`.\n * e.context.addresses.join('\\n- '),\n * );\n * return;\n * } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING)) {\n * if (!tx.feePayer) {\n * displayError('Choose a fee payer for this transaction before sending it');\n * } else {\n * displayError('The fee payer still needs to sign for this transaction');\n * }\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport function isSolanaError<TErrorCode extends SolanaErrorCode>(\n e: unknown,\n /**\n * When supplied, this function will require that the input is a {@link SolanaError} _and_ that\n * its error code is exactly this value.\n */\n code?: TErrorCode,\n): e is SolanaError<TErrorCode> {\n const isSolanaError = e instanceof Error && e.name === 'SolanaError';\n if (isSolanaError) {\n if (code !== undefined) {\n return (e as SolanaError<TErrorCode>).context.__code === code;\n }\n return true;\n }\n return false;\n}\n\ntype SolanaErrorCodedContext = Readonly<{\n [P in SolanaErrorCode]: (SolanaErrorContext[P] extends undefined ? object : SolanaErrorContext[P]) & {\n __code: P;\n };\n}>;\n\n/**\n * Encapsulates an error's stacktrace, a Solana-specific numeric code that indicates what went\n * wrong, and optional context if the type of error indicated by the code supports it.\n */\nexport class SolanaError<TErrorCode extends SolanaErrorCode = SolanaErrorCode> extends Error {\n /**\n * Indicates the root cause of this {@link SolanaError}, if any.\n *\n * For example, a transaction error might have an instruction error as its root cause. In this\n * case, you will be able to access the instruction error on the transaction error as `cause`.\n */\n readonly cause?: TErrorCode extends SolanaErrorCodeWithCause ? SolanaError : unknown = this.cause;\n /**\n * Contains context that can assist in understanding or recovering from a {@link SolanaError}.\n */\n readonly context: SolanaErrorCodedContext[TErrorCode];\n constructor(\n ...[code, contextAndErrorOptions]: SolanaErrorContext[TErrorCode] extends undefined\n ? [code: TErrorCode, errorOptions?: ErrorOptions | undefined]\n : [code: TErrorCode, contextAndErrorOptions: SolanaErrorContext[TErrorCode] & (ErrorOptions | undefined)]\n ) {\n let context: SolanaErrorContext[TErrorCode] | undefined;\n let errorOptions: ErrorOptions | undefined;\n if (contextAndErrorOptions) {\n Object.entries(Object.getOwnPropertyDescriptors(contextAndErrorOptions)).forEach(([name, descriptor]) => {\n // If the `ErrorOptions` type ever changes, update this code.\n if (name === 'cause') {\n errorOptions = { cause: descriptor.value };\n } else {\n if (context === undefined) {\n context = {} as SolanaErrorContext[TErrorCode];\n }\n Object.defineProperty(context, name, descriptor);\n }\n });\n }\n const message = getErrorMessage(code, context);\n super(message, errorOptions);\n this.context = (context === undefined ? {} : context) as SolanaErrorCodedContext[TErrorCode];\n this.context.__code = code;\n // This is necessary so that `isSolanaError()` can identify a `SolanaError` without having\n // to import the class for use in an `instanceof` check.\n this.name = 'SolanaError';\n }\n}\n","import { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n *\n * @param byteArrays - The array of byte arrays to concatenate.\n *\n * @example\n * ```ts\n * const bytes1 = new Uint8Array([0x01, 0x02]);\n * const bytes2 = new Uint8Array([]);\n * const bytes3 = new Uint8Array([0x03, 0x04]);\n * const bytes = mergeBytes([bytes1, bytes2, bytes3]);\n * // ^ [0x01, 0x02, 0x03, 0x04]\n * ```\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 *\n * @param bytes - The byte array to pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 2);\n * // bytes === paddedBytes\n * ```\n */\nexport function padBytes(bytes: Uint8Array, length: number): Uint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array {\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 *\n * @param bytes - The byte array to truncate or pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Truncates the byte array to the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // ^ [0x01, 0x02]\n * ```\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // bytes === fixedBytes\n * ```\n */\nexport const fixBytes = (bytes: ReadonlyUint8Array | Uint8Array, length: number): ReadonlyUint8Array | Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n\n/**\n * Returns true if and only if the provided `data` byte array contains\n * the provided `bytes` byte array at the specified `offset`.\n *\n * @param data - The byte sequence to search for.\n * @param bytes - The byte array in which to search for `data`.\n * @param offset - The position in `bytes` where the search begins.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const data = new Uint8Array([0x02, 0x03]);\n * containsBytes(bytes, data, 1); // true\n * containsBytes(bytes, data, 2); // false\n * ```\n */\nexport function containsBytes(\n data: ReadonlyUint8Array | Uint8Array,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset: number,\n): boolean {\n const slice = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length);\n if (slice.length !== bytes.length) return false;\n return bytes.every((b, i) => b === slice[i]);\n}\n","import {\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * This is a common interface for {@link FixedSizeEncoder} and {@link VariableSizeEncoder}.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n */\ntype BaseEncoder<TFrom> = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => ReadonlyUint8Array;\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\n/**\n * An object that can encode a value of type {@link TFrom} into a fixed-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const encoder: FixedSizeEncoder<number, 4>;\n * const bytes = encoder.encode(42);\n * const size = encoder.fixedSize; // 4\n * ```\n *\n * @see {@link Encoder}\n * @see {@link VariableSizeEncoder}\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\n/**\n * An object that can encode a value of type {@link TFrom} into a variable-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * ```ts\n * const encoder: VariableSizeEncoder<string>;\n * const bytes = encoder.encode('hello');\n * const size = encoder.getSizeFromValue('hello');\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n */\nexport type VariableSizeEncoder<TFrom> = BaseEncoder<TFrom> & {\n /** Returns the size of the encoded value in bytes for a given input. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * An `Encoder` can be either:\n * - A {@link FixedSizeEncoder}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeEncoder}, where encoded values can vary in size.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * Encoding a value into a new byte array.\n * ```ts\n * const encoder: Encoder<string>;\n * const bytes = encoder.encode('hello');\n * ```\n *\n * @example\n * Writing the encoded value into an existing byte array.\n * ```ts\n * const encoder: Encoder<string>;\n * const bytes = new Uint8Array(100);\n * const nextOffset = encoder.write('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Encoders` manually using the {@link createEncoder} function but it is more common\n * to compose multiple `Encoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Encoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructEncoder, addEncoderSizePrefix, getUtf8Encoder, getU32Encoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonEncoder = (): Encoder<Person> =>\n * getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * ```\n *\n * Note that composed `Encoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Encoder()` is\n * a fixed-size encoder, while `addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())`\n * is a variable-size encoder. This makes the final `Person` encoder a variable-size encoder.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link createEncoder}\n */\nexport type Encoder<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>;\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * This is a common interface for {@link FixedSizeDecoder} and {@link VariableSizeDecoder}.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\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: ReadonlyUint8Array | 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: ReadonlyUint8Array | Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\n/**\n * An object that can decode a fixed-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const decoder: FixedSizeDecoder<number, 4>;\n * const value = decoder.decode(bytes);\n * const size = decoder.fixedSize; // 4\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\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\n/**\n * An object that can decode a variable-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const decoder: VariableSizeDecoder<number>;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type VariableSizeDecoder<TTo> = BaseDecoder<TTo> & {\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * An `Decoder` can be either:\n * - A {@link FixedSizeDecoder}, where all byte arrays have the same fixed size.\n * - A {@link VariableSizeDecoder}, where byte arrays can vary in size.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * Getting the decoded value from a byte array.\n * ```ts\n * const decoder: Decoder<string>;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @example\n * Reading the decoded value from a byte array at a specific offset\n * and getting the offset of the next byte to read.\n * ```ts\n * const decoder: Decoder<string>;\n * const [value, nextOffset] = decoder.read('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Decoders` manually using the {@link createDecoder} function but it is more common\n * to compose multiple `Decoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Decoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructDecoder, addDecoderSizePrefix, getUtf8Decoder, getU32Decoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonDecoder = (): Decoder<Person> =>\n * getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * ```\n *\n * Note that composed `Decoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Decoder()` is\n * a fixed-size decoder, while `addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())`\n * is a variable-size decoder. This makes the final `Person` decoder a variable-size decoder.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link createDecoder}\n */\nexport type Decoder<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>;\n\n/**\n * An object that can encode and decode a value to and from a fixed-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const codec: FixedSizeCodec<number | bigint, bigint, 8>;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.fixedSize; // 8\n * ```\n *\n * @see {@link Codec}\n * @see {@link VariableSizeCodec}\n */\nexport type FixedSizeCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number> = FixedSizeDecoder<\n TTo,\n TSize\n> &\n FixedSizeEncoder<TFrom, TSize>;\n\n/**\n * An object that can encode and decode a value to and from a variable-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const codec: VariableSizeCodec<number | bigint, bigint>;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.getSizeFromValue(42);\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n */\nexport type VariableSizeCodec<TFrom, TTo extends TFrom = TFrom> = VariableSizeDecoder<TTo> & VariableSizeEncoder<TFrom>;\n\n/**\n * An object that can encode and decode a value to and from a byte array.\n *\n * A `Codec` can be either:\n * - A {@link FixedSizeCodec}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeCodec}, where encoded values can vary in size.\n *\n * @example\n * ```ts\n * const codec: Codec<string>;\n * const bytes = codec.encode('hello');\n * const value = codec.decode(bytes); // 'hello'\n * ```\n *\n * @remarks\n * For convenience, codecs can encode looser types than they decode.\n * That is, type {@link TFrom} can be a superset of type {@link TTo}.\n * For instance, a `Codec<bigint | number, bigint>` can encode both\n * `bigint` and `number` values, but will always decode to a `bigint`.\n *\n * ```ts\n * const codec: Codec<bigint | number, bigint>;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * It is worth noting that codecs are the union of encoders and decoders.\n * This means that a `Codec<TFrom, TTo>` can be combined from an `Encoder<TFrom>`\n * and a `Decoder<TTo>` using the {@link combineCodec} function. This is particularly\n * useful for library authors who want to expose all three types of objects to their users.\n *\n * ```ts\n * const encoder: Encoder<bigint | number>;\n * const decoder: Decoder<bigint>;\n * const codec: Codec<bigint | number, bigint> = combineCodec(encoder, decoder);\n * ```\n *\n * Aside from combining encoders and decoders, codecs can also be created from scratch using\n * the {@link createCodec} function but it is more common to compose multiple codecs together\n * using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create a `Codec` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructCodec, addCodecSizePrefix, getUtf8Codec, getU32Codec } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonCodec = (): Codec<Person> =>\n * getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * ```\n *\n * Note that composed `Codec` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Codec()` is\n * a fixed-size codec, while `addCodecSizePrefix(getUtf8Codec(), getU32Codec())`\n * is a variable-size codec. This makes the final `Person` codec a variable-size codec.\n *\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link combineCodec}\n * @see {@link createCodec}\n */\nexport type Codec<TFrom, TTo extends TFrom = TFrom> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>;\n\n/**\n * Gets the encoded size of a given value in bytes using the provided encoder.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @param value - The value to be encoded.\n * @param encoder - The encoder used to determine the encoded size.\n * @returns The size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const fixedSizeEncoder = { fixedSize: 4 };\n * getEncodedSize(123, fixedSizeEncoder); // Returns 4.\n *\n * const variableSizeEncoder = { getSizeFromValue: (value: string) => value.length };\n * getEncodedSize(\"hello\", variableSizeEncoder); // Returns 5.\n * ```\n *\n * @see {@link Encoder}\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/**\n * Creates an `Encoder` by filling in the missing `encode` function using the provided `write` function and\n * either the `fixedSize` property (for {@link FixedSizeEncoder | FixedSizeEncoders}) or\n * the `getSizeFromValue` function (for {@link VariableSizeEncoder | VariableSizeEncoders}).\n *\n * Instead of manually implementing `encode`, this utility leverages the existing `write` function\n * and the size helpers to generate a complete encoder. The provided `encode` method will allocate\n * a new `Uint8Array` of the correct size and use `write` to populate it.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size encoders).\n *\n * @param encoder - An encoder object that implements `write`, but not `encode`.\n * - If the encoder has a `fixedSize` property, it is treated as a {@link FixedSizeEncoder}.\n * - Otherwise, it is treated as a {@link VariableSizeEncoder}.\n *\n * @returns A fully functional `Encoder` with both `write` and `encode` methods.\n *\n * @example\n * Creating a custom fixed-size encoder.\n * ```ts\n * const encoder = createEncoder({\n * fixedSize: 4,\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n * ```\n *\n * @example\n * Creating a custom variable-size encoder:\n * ```ts\n * const encoder = createEncoder({\n * getSizeFromValue: (value: string) => value.length,\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = encoder.encode(\"hello\");\n * // 0x68656c6c6f\n * ```\n *\n * @remarks\n * Note that, while `createEncoder` is useful for defining more complex encoders, it is more common to compose\n * encoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createEncoder`.\n *\n * ```ts\n * // Fixed-size encoder for unsigned 32-bit integers.\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n *\n * // Variable-size encoder for 32-bytes prefixed UTF-8 strings.\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * const bytes = encoder.encode(\"hello\");\n * // 0x0500000068656c6c6f\n *\n * // Variable-size encoder for custom objects.\n * type Person = { name: string; age: number };\n * const encoder: Encoder<Person> = getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * const bytes = encoder.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link getStructEncoder}\n * @see {@link getU32Encoder}\n * @see {@link getUtf8Encoder}\n * @see {@link addEncoderSizePrefix}\n */\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/**\n * Creates a `Decoder` by filling in the missing `decode` function using the provided `read` function.\n *\n * Instead of manually implementing `decode`, this utility leverages the existing `read` function\n * and the size properties to generate a complete decoder. The provided `decode` method will read\n * from a `Uint8Array` at the given offset and return the decoded value.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeDecoder} will be created, otherwise\n * a {@link VariableSizeDecoder} will be created.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size decoders).\n *\n * @param decoder - A decoder object that implements `read`, but not `decode`.\n * - If the decoder has a `fixedSize` property, it is treated as a {@link FixedSizeDecoder}.\n * - Otherwise, it is treated as a {@link VariableSizeDecoder}.\n *\n * @returns A fully functional `Decoder` with both `read` and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size decoder.\n * ```ts\n * const decoder = createDecoder({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size decoder:\n * ```ts\n * const decoder = createDecoder({\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([104, 101, 108, 108, 111]));\n * // \"hello\"\n * ```\n *\n * @remarks\n * Note that, while `createDecoder` is useful for defining more complex decoders, it is more common to compose\n * decoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createDecoder`.\n *\n * ```ts\n * // Fixed-size decoder for unsigned 32-bit integers.\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n *\n * // Variable-size decoder for 32-bytes prefixed UTF-8 strings.\n * const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());\n * const value = decoder.decode(new Uint8Array([5, 0, 0, 0, 104, 101, 108, 108, 111]));\n * // \"hello\"\n *\n * // Variable-size decoder for custom objects.\n * type Person = { name: string; age: number };\n * const decoder: Decoder<Person> = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * const value = decoder.decode(new Uint8Array([3, 0, 0, 0, 66, 111, 98, 42, 0, 0, 0]));\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Decoder}\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link getStructDecoder}\n * @see {@link getU32Decoder}\n * @see {@link getUtf8Decoder}\n * @see {@link addDecoderSizePrefix}\n */\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/**\n * Creates a `Codec` by filling in the missing `encode` and `decode` functions using the provided `write` and `read` functions.\n *\n * This utility combines the behavior of {@link createEncoder} and {@link createDecoder} to produce a fully functional `Codec`.\n * The `encode` method is derived from the `write` function, while the `decode` method is derived from the `read` function.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeCodec} will be created, otherwise\n * a {@link VariableSizeCodec} will be created.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).\n *\n * @param codec - A codec object that implements `write` and `read`, but not `encode` or `decode`.\n * - If the codec has a `fixedSize` property, it is treated as a {@link FixedSizeCodec}.\n * - Otherwise, it is treated as a {@link VariableSizeCodec}.\n *\n * @returns A fully functional `Codec` with `write`, `read`, `encode`, and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size codec.\n * ```ts\n * const codec = createCodec({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size codec:\n * ```ts\n * const codec = createCodec({\n * getSizeFromValue: (value: string) => value.length,\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = codec.encode(\"hello\");\n * // 0x68656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n * ```\n *\n * @remarks\n * This function effectively combines the behavior of {@link createEncoder} and {@link createDecoder}.\n * If you only need to encode or decode (but not both), consider using those functions instead.\n *\n * Here are some alternative examples using codec primitives instead of `createCodec`.\n *\n * ```ts\n * // Fixed-size codec for unsigned 32-bit integers.\n * const codec = getU32Codec();\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n *\n * // Variable-size codec for 32-bytes prefixed UTF-8 strings.\n * const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const bytes = codec.encode(\"hello\");\n * // 0x0500000068656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n *\n * // Variable-size codec for custom objects.\n * type Person = { name: string; age: number };\n * const codec: Codec<PersonInput, Person> = getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * const bytes = codec.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * const value = codec.decode(bytes);\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link createEncoder}\n * @see {@link createDecoder}\n * @see {@link getStructCodec}\n * @see {@link getU32Codec}\n * @see {@link getUtf8Codec}\n * @see {@link addCodecSizePrefix}\n */\nexport function createCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number>(\n codec: Omit<FixedSizeCodec<TFrom, TTo, TSize>, 'decode' | 'encode'>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec: Omit<VariableSizeCodec<TFrom, TTo>, 'decode' | 'encode'>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'decode' | 'encode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'decode' | 'encode'>,\n): Codec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'decode' | 'encode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'decode' | 'encode'>,\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\n/**\n * Determines whether the given codec, encoder, or decoder is fixed-size.\n *\n * A fixed-size object is identified by the presence of a `fixedSize` property.\n * If this property exists, the object is considered a {@link FixedSizeCodec},\n * {@link FixedSizeEncoder}, or {@link FixedSizeDecoder}.\n * Otherwise, it is assumed to be a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is fixed-size, `false` otherwise.\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isFixedSize(encoder); // true\n * ```\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isFixedSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is commonly used to distinguish between fixed-size and variable-size objects at runtime.\n * If you need to enforce this distinction with type assertions, consider using {@link assertIsFixedSize}.\n *\n * @see {@link assertIsFixedSize}\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\n/**\n * Asserts that the given codec, encoder, or decoder is fixed-size.\n *\n * If the object is not fixed-size (i.e., it lacks a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not fixed-size.\n *\n * @example\n * Asserting a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsFixedSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsFixedSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isFixedSize}.\n * If you only need to check whether an object is fixed-size without throwing an error, use {@link isFixedSize} instead.\n *\n * @see {@link isFixedSize}\n */\nexport function assertIsFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): asserts encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function assertIsFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\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): asserts codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function assertIsFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);\n }\n}\n\n/**\n * Determines whether the given codec, encoder, or decoder is variable-size.\n *\n * A variable-size object is identified by the absence of a `fixedSize` property.\n * If this property is missing, the object is considered a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is variable-size, `false` otherwise.\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isVariableSize(encoder); // true\n * ```\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isVariableSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is the inverse of {@link isFixedSize}.\n *\n * @see {@link isFixedSize}\n * @see {@link assertIsVariableSize}\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\n/**\n * Asserts that the given codec, encoder, or decoder is variable-size.\n *\n * If the object is not variable-size (i.e., it has a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not variable-size.\n *\n * @example\n * Asserting a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsVariableSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsVariableSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isVariableSize}.\n * If you only need to check whether an object is variable-size without throwing an error, use {@link isVariableSize} instead.\n *\n * Also note that this function is the inverse of {@link assertIsFixedSize}.\n *\n * @see {@link isVariableSize}\n * @see {@link assertIsFixedSize}\n */\nexport function assertIsVariableSize<TFrom>(encoder: Encoder<TFrom>): asserts encoder is VariableSizeEncoder<TFrom>;\nexport function assertIsVariableSize<TTo>(decoder: Decoder<TTo>): asserts decoder is VariableSizeDecoder<TTo>;\nexport function assertIsVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): asserts codec is VariableSizeCodec<TFrom, TTo>;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);\n }\n}\n","import {\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Asserts that a given byte array is not empty (after the optional provided offset).\n *\n * Returns void if the byte array is not empty but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n * If provided, the byte array is considered empty if it has no bytes after the offset.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 1); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 3); // Throws\n * ```\n */\nexport function assertByteArrayIsNotEmptyForCodec(\n codecDescription: string,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n if (bytes.length - offset <= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, {\n codecDescription,\n });\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode\n * (after the optional provided offset).\n *\n * Returns void if the byte array has at least the expected number\n * of bytes but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param expected - The minimum number of bytes expected in the byte array.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 4, bytes); // Throws\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 2, bytes, 1); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes, 1); // Throws\n * ```\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {\n bytesLength,\n codecDescription,\n expected,\n });\n }\n}\n\n/**\n * Asserts that a given offset is within the byte array bounds.\n * This range is between 0 and the byte array length and is inclusive.\n * An offset equals to the byte array length is considered a valid offset\n * as it allows the post-offset of codecs to signal the end of the byte array.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param offset - The offset to check.\n * @param bytesLength - The length of the byte array from which the offset should be within bounds.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 0, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 3, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 4, bytes.length); // Throws\n * ```\n */\nexport function assertByteArrayOffsetIsNotOutOfRange(codecDescription: string, offset: number, bytesLength: number) {\n if (offset < 0 || offset > bytesLength) {\n throw new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, {\n bytesLength,\n codecDescription,\n offset,\n });\n }\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport {\n Codec,\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 './codec';\nimport { combineCodec } from './combine-codec';\n\ntype NumberEncoder = Encoder<bigint | number> | Encoder<number>;\ntype FixedSizeNumberEncoder<TSize extends number = number> =\n | FixedSizeEncoder<bigint | number, TSize>\n | FixedSizeEncoder<number, TSize>;\ntype NumberDecoder = Decoder<bigint> | Decoder<number>;\ntype FixedSizeNumberDecoder<TSize extends number = number> =\n | FixedSizeDecoder<bigint, TSize>\n | FixedSizeDecoder<number, TSize>;\ntype NumberCodec = Codec<bigint | number, bigint> | Codec<number>;\ntype FixedSizeNumberCodec<TSize extends number = number> =\n | FixedSizeCodec<bigint | number, bigint, TSize>\n | FixedSizeCodec<number, number, TSize>;\n\n/**\n * Stores the size of the `encoder` in bytes as a prefix using the `prefix` encoder.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addEncoderSizePrefix<TFrom>(\n encoder: FixedSizeEncoder<TFrom>,\n prefix: FixedSizeNumberEncoder,\n): FixedSizeEncoder<TFrom>;\nexport function addEncoderSizePrefix<TFrom>(encoder: Encoder<TFrom>, prefix: NumberEncoder): VariableSizeEncoder<TFrom>;\nexport function addEncoderSizePrefix<TFrom>(encoder: Encoder<TFrom>, prefix: NumberEncoder): Encoder<TFrom> {\n const write = ((value, bytes, offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function to contain the content of the encoder within its own bounds.\n const encoderBytes = encoder.encode(value);\n offset = prefix.write(encoderBytes.length, bytes, offset);\n bytes.set(encoderBytes, offset);\n return offset + encoderBytes.length;\n }) as Encoder<TFrom>['write'];\n\n if (isFixedSize(prefix) && isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : (encoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;\n\n return createEncoder({\n ...encoder,\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: value => {\n const encoderSize = getEncodedSize(value, encoder);\n return getEncodedSize(encoderSize, prefix) + encoderSize;\n },\n write,\n });\n}\n\n/**\n * Bounds the size of the nested `decoder` by reading its encoded `prefix`.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addDecoderSizePrefix<TTo>(\n decoder: FixedSizeDecoder<TTo>,\n prefix: FixedSizeNumberDecoder,\n): FixedSizeDecoder<TTo>;\nexport function addDecoderSizePrefix<TTo>(decoder: Decoder<TTo>, prefix: NumberDecoder): VariableSizeDecoder<TTo>;\nexport function addDecoderSizePrefix<TTo>(decoder: Decoder<TTo>, prefix: NumberDecoder): Decoder<TTo> {\n const read = ((bytes, offset) => {\n const [bigintSize, decoderOffset] = prefix.read(bytes, offset);\n const size = Number(bigintSize);\n offset = decoderOffset;\n // Slice the byte array to the contained size if necessary.\n if (offset > 0 || bytes.length > size) {\n bytes = bytes.slice(offset, offset + size);\n }\n assertByteArrayHasEnoughBytesForCodec('addDecoderSizePrefix', size, bytes);\n // Here we exceptionally use the `decode` function instead of the `read`\n // function to contain the content of the decoder within its own bounds.\n return [decoder.decode(bytes), offset + size];\n }) as Decoder<TTo>['read'];\n\n if (isFixedSize(prefix) && isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : (decoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;\n return createDecoder({ ...decoder, ...(maxSize !== null ? { maxSize } : {}), read });\n}\n\n/**\n * Stores the byte size of any given codec as an encoded number prefix.\n *\n * This sets a limit on variable-size codecs and tells us when to stop decoding.\n * When encoding, the size of the encoded data is stored before the encoded data itself.\n * When decoding, the size is read first to know how many bytes to read next.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * For example, say we want to bound a variable-size base-58 string using a `u32` size prefix.\n * Here’s how you can use the `addCodecSizePrefix` function to achieve that.\n *\n * ```ts\n * const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec());\n *\n * getU32Base58Codec().encode('hello world');\n * // 0x0b00000068656c6c6f20776f726c64\n * // | └-- Our encoded base-58 string.\n * // └-- Our encoded u32 size prefix.\n * ```\n *\n * @remarks\n * Separate {@link addEncoderSizePrefix} and {@link addDecoderSizePrefix} functions are also available.\n *\n * ```ts\n * const bytes = addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()).encode('hello');\n * const value = addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link addEncoderSizePrefix}\n * @see {@link addDecoderSizePrefix}\n */\nexport function addCodecSizePrefix<TFrom, TTo extends TFrom>(\n codec: FixedSizeCodec<TFrom, TTo>,\n prefix: FixedSizeNumberCodec,\n): FixedSizeCodec<TFrom, TTo>;\nexport function addCodecSizePrefix<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n prefix: NumberCodec,\n): VariableSizeCodec<TFrom, TTo>;\nexport function addCodecSizePrefix<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n prefix: NumberCodec,\n): Codec<TFrom, TTo> {\n return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));\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 * The resulting encoder ensures that encoded values always have the specified number of bytes.\n * If the original encoded value is larger than `fixedBytes`, it is truncated.\n * If it is smaller, it is padded with trailing zeroes.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @returns A `FixedSizeEncoder` that ensures a consistent output size.\n *\n * @example\n * ```ts\n * const encoder = fixEncoderSize(getUtf8Encoder(), 4);\n * encoder.encode(\"Hello\"); // 0x48656c6c (truncated)\n * encoder.encode(\"Hi\"); // 0x48690000 (padded)\n * encoder.encode(\"Hiya\"); // 0x48697961 (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixEncoderSize<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 * The resulting decoder always reads exactly `fixedBytes` bytes from the input.\n * If the nested decoder is also fixed-size, the bytes are truncated or padded as needed.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @returns A `FixedSizeDecoder` that ensures a consistent input size.\n *\n * @example\n * ```ts\n * const decoder = fixDecoderSize(getUtf8Decoder(), 4);\n * decoder.decode(new Uint8Array([72, 101, 108, 108, 111])); // \"Hell\" (truncated)\n * decoder.decode(new Uint8Array([72, 105, 0, 0])); // \"Hi\" (zeroes ignored)\n * decoder.decode(new Uint8Array([72, 105, 121, 97])); // \"Hiya\" (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixEncoderSize}\n */\nexport function fixDecoderSize<TTo, TSize extends number>(\n decoder: Decoder<TTo>,\n fixedBytes: TSize,\n): FixedSizeDecoder<TTo, TSize> {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes, offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodecSize', 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 * The resulting codec ensures that both encoding and decoding operate on a fixed number of bytes.\n * When encoding:\n * - If the encoded value is larger than `fixedBytes`, it is truncated.\n * - If it is smaller, it is padded with trailing zeroes.\n * - If it is exactly `fixedBytes`, it remains unchanged.\n *\n * When decoding:\n * - Exactly `fixedBytes` bytes are read from the input.\n * - If the nested decoder has a smaller fixed size, bytes are truncated or padded as necessary.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\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 * @returns A `FixedSizeCodec` that ensures both encoding and decoding conform to a fixed size.\n *\n * @example\n * ```ts\n * const codec = fixCodecSize(getUtf8Codec(), 4);\n *\n * const bytes1 = codec.encode(\"Hello\"); // 0x48656c6c (truncated)\n * const value1 = codec.decode(bytes1); // \"Hell\"\n *\n * const bytes2 = codec.encode(\"Hi\"); // 0x48690000 (padded)\n * const value2 = codec.decode(bytes2); // \"Hi\"\n *\n * const bytes3 = codec.encode(\"Hiya\"); // 0x48697961 (same length)\n * const value3 = codec.decode(bytes3); // \"Hiya\"\n * ```\n *\n * @remarks\n * If you only need to enforce a fixed size for encoding, use {@link fixEncoderSize}.\n * If you only need to enforce a fixed size for decoding, use {@link fixDecoderSize}.\n *\n * ```ts\n * const bytes = fixEncoderSize(getUtf8Encoder(), 4).encode(\"Hiya\");\n * const value = fixDecoderSize(getUtf8Decoder(), 4).decode(bytes);\n * ```\n *\n * @see {@link fixEncoderSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixCodecSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: Codec<TFrom, TTo>,\n fixedBytes: TSize,\n): FixedSizeCodec<TFrom, TTo, TSize> {\n return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(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';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Transforms an encoder by mapping its input values.\n *\n * This function takes an existing `Encoder<A>` and returns an `Encoder<B>`, allowing values of type `B`\n * to be converted into values of type `A` before encoding. The transformation is applied via the `unmap` function.\n *\n * This is useful for handling type conversions, applying default values, or structuring data before encoding.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldFrom - The original type expected by the encoder.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n *\n * @param encoder - The encoder to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @returns A new encoder that accepts `TNewFrom` values and transforms them before encoding.\n *\n * @example\n * Encoding a string by counting its characters and storing the length as a `u32`.\n * ```ts\n * const encoder = transformEncoder(getU32Encoder(), (value: string) => value.length);\n * encoder.encode(\"hello\"); // 0x05000000 (stores length 5)\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformDecoder}\n */\nexport function transformEncoder<TOldFrom, TNewFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TOldFrom, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder<TNewFrom, TSize>;\nexport function transformEncoder<TOldFrom, TNewFrom>(\n encoder: VariableSizeEncoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder<TNewFrom>;\nexport function transformEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom>;\nexport function transformEncoder<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 * Transforms a decoder by mapping its output values.\n *\n * This function takes an existing `Decoder<A>` and returns a `Decoder<B>`, allowing values of type `A`\n * to be converted into values of type `B` after decoding. The transformation is applied via the `map` function.\n *\n * This is useful for post-processing, type conversions, or enriching decoded data.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldTo - The original type returned by the decoder.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param decoder - The decoder to transform.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding.\n * @returns A new decoder that decodes into `TNewTo`.\n *\n * @example\n * Decoding a stored `u32` length into a string of `'x'` characters.\n * ```ts\n * const decoder = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length));\n * decoder.decode(new Uint8Array([0x05, 0x00, 0x00, 0x00])); // \"xxxxx\"\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformEncoder}\n */\nexport function transformDecoder<TOldTo, TNewTo, TSize extends number>(\n decoder: FixedSizeDecoder<TOldTo, TSize>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder<TNewTo, TSize>;\nexport function transformDecoder<TOldTo, TNewTo>(\n decoder: VariableSizeDecoder<TOldTo>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder<TNewTo>;\nexport function transformDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo>;\nexport function transformDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo> {\n return createDecoder({\n ...decoder,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Transforms a codec by mapping its input and output values.\n *\n * This function takes an existing `Codec<A, B>` and returns a `Codec<C, D>`, allowing:\n * - Values of type `C` to be transformed into `A` before encoding.\n * - Values of type `B` to be transformed into `D` after decoding.\n *\n * This is useful for adapting codecs to work with different representations, handling default values, or\n * converting between primitive and structured types.\n *\n * @typeParam TOldFrom - The original type expected by the codec.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n * @typeParam TOldTo - The original type returned by the codec.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param codec - The codec to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding (optional).\n * @returns A new codec that encodes `TNewFrom` and decodes into `TNewTo`.\n *\n * @example\n * Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters.\n * ```ts\n * const codec = transformCodec(\n * getU32Codec(),\n * (value: string) => value.length, // Encode string length\n * (length) => 'x'.repeat(length) // Decode length into a string of 'x's\n * );\n *\n * const bytes = codec.encode(\"hello\"); // 0x05000000 (stores length 5)\n * const value = codec.decode(bytes); // \"xxxxx\"\n * ```\n *\n * @remarks\n * If only input transformation is needed, use {@link transformEncoder}.\n * If only output transformation is needed, use {@link transformDecoder}.\n *\n * ```ts\n * const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode(\"hello\");\n * const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes);\n * ```\n *\n * @see {@link transformEncoder}\n * @see {@link transformDecoder}\n */\nexport function transformCodec<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 transformCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: VariableSizeCodec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec<TNewFrom, TTo>;\nexport function transformCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: Codec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec<TNewFrom, TTo>;\nexport function transformCodec<\n TOldFrom,\n TNewFrom,\n TOldTo extends TOldFrom,\n TNewTo extends TNewFrom,\n TSize extends number,\n>(\n codec: FixedSizeCodec<TOldFrom, TOldTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec<TNewFrom, TNewTo, TSize>;\nexport function transformCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: VariableSizeCodec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec<TNewFrom, TNewTo>;\nexport function transformCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo>;\nexport function transformCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo> {\n return createCodec({\n ...transformEncoder(codec, unmap),\n read: map ? transformDecoder(codec, map).read : (codec.read as unknown as Decoder<TNewTo>['read']),\n });\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\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 * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder<string>` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\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 * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder<string>` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\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 * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec<string>` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\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 { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder<string>` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder<string>` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec<string>` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Returns an encoder for base-64 strings.\n *\n * This encoder serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeEncoder<string>` for encoding base-64 strings.\n *\n * @example\n * Encoding a base-64 string.\n * ```ts\n * const encoder = getBase64Encoder();\n * const bytes = encoder.encode('hello+world'); // 0x85e965a3ec28ae57\n * ```\n *\n * @see {@link getBase64Codec}\n */\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 {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\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 {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\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 transformEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/**\n * Returns a decoder for base-64 strings.\n *\n * This decoder deserializes base-64 encoded strings from a byte array.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeDecoder<string>` for decoding base-64 strings.\n *\n * @example\n * Decoding a base-64 string.\n * ```ts\n * const decoder = getBase64Decoder();\n * const value = decoder.decode(new Uint8Array([0x85, 0xe9, 0x65, 0xa3, 0xec, 0x28, 0xae, 0x57])); // \"hello+world\"\n * ```\n *\n * @see {@link getBase64Codec}\n */\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 transformDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '='),\n );\n};\n\n/**\n * Returns a codec for encoding and decoding base-64 strings.\n *\n * This codec serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * @returns A `VariableSizeCodec<string>` for encoding and decoding base-64 strings.\n *\n * @example\n * Encoding and decoding a base-64 string.\n * ```ts\n * const codec = getBase64Codec();\n * const bytes = codec.encode('hello+world'); // 0x85e965a3ec28ae57\n * const value = codec.decode(bytes); // \"hello+world\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-64 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase64Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-64 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase64Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase64Encoder} and {@link getBase64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase64Encoder().encode('hello+world');\n * const value = getBase64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase64Encoder}\n * @see {@link getBase64Decoder}\n */\nexport const getBase64Codec = (): VariableSizeCodec<string> => combineCodec(getBase64Encoder(), getBase64Decoder());\n","import type { Decoder, ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SolanaError,\n} from '@solana/errors';\n\nimport type { Account, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\n\n/**\n * Transforms an {@link EncodedAccount} into an {@link Account} (or a {@link MaybeEncodedAccount}\n * into a {@link MaybeAccount}) by decoding the account data using the provided {@link Decoder}\n * instance.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: EncodedAccount<'1234..5678'>;\n * const myDecoder: Decoder<MyAccountData> = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n *\n * const myDecodedAccount = decodeAccount(myAccount, myDecoder);\n * myDecodedAccount satisfies Account<MyAccountData, '1234..5678'>;\n * ```\n */\nexport function decodeAccount<TData extends object, TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>,\n decoder: Decoder<TData>,\n): Account<TData, TAddress>;\nexport function decodeAccount<TData extends object, TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>,\n decoder: Decoder<TData>,\n): MaybeAccount<TData, TAddress>;\nexport function decodeAccount<TData extends object, TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>,\n decoder: Decoder<TData>,\n): Account<TData, TAddress> | MaybeAccount<TData, TAddress> {\n try {\n if ('exists' in encodedAccount && !encodedAccount.exists) {\n return encodedAccount;\n }\n return Object.freeze({ ...encodedAccount, data: decoder.decode(encodedAccount.data) });\n } catch {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT, {\n address: encodedAccount.address,\n });\n }\n}\n\nfunction accountExists<TData extends object>(account: Account<TData> | MaybeAccount<TData>): account is Account<TData> {\n return !('exists' in account) || ('exists' in account && account.exists);\n}\n\n/**\n * Asserts that an account stores decoded data, ie. not a `Uint8Array`.\n *\n * Note that it does not check the shape of the data matches the decoded type, only that it is not a\n * `Uint8Array`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: Account<MyAccountData | Uint8Array, '1234..5678'>;\n * assertAccountDecoded(myAccount);\n *\n * // now the account data can be used as MyAccountData\n * account.data satisfies MyAccountData;\n * ```\n *\n * This is particularly useful for narrowing the result of fetching a JSON parsed account.\n *\n * ```ts\n * const account: MaybeAccount<MockData | Uint8Array> = await fetchJsonParsedAccount<MockData>(\n * rpc,\n * '1234..5678' as Address,\n * );\n *\n * assertAccountDecoded(account);\n * // now we have a MaybeAccount<MockData>\n * account satisfies MaybeAccount<MockData>;\n * ```\n */\nexport function assertAccountDecoded<TData extends object, TAddress extends string = string>(\n account: Account<TData | Uint8Array, TAddress>,\n): asserts account is Account<TData, TAddress>;\nexport function assertAccountDecoded<TData extends object, TAddress extends string = string>(\n account: MaybeAccount<TData | Uint8Array, TAddress>,\n): asserts account is MaybeAccount<TData, TAddress>;\nexport function assertAccountDecoded<TData extends object, TAddress extends string = string>(\n account: Account<TData | Uint8Array, TAddress> | MaybeAccount<TData | Uint8Array, TAddress>,\n): asserts account is Account<TData, TAddress> | MaybeAccount<TData, TAddress> {\n if (accountExists(account) && account.data instanceof Uint8Array) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT, {\n address: account.address,\n });\n }\n}\n\n/**\n * Asserts that all input accounts store decoded data, ie. not a `Uint8Array`.\n *\n * As with {@link assertAccountDecoded} it does not check the shape of the data matches the decoded\n * type, only that it is not a `Uint8Array`.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccounts: Account<MyAccountData | Uint8Array, Address>[];\n * assertAccountsDecoded(myAccounts);\n *\n * // now the account data can be used as MyAccountData\n * for (const a of account) {\n * account.data satisfies MyAccountData;\n * }\n * ```\n */\nexport function assertAccountsDecoded<TData extends object, TAddress extends string = string>(\n accounts: Account<ReadonlyUint8Array | TData, TAddress>[],\n): asserts accounts is Account<TData, TAddress>[];\nexport function assertAccountsDecoded<TData extends object, TAddress extends string = string>(\n accounts: MaybeAccount<ReadonlyUint8Array | TData, TAddress>[],\n): asserts accounts is MaybeAccount<TData, TAddress>[];\nexport function assertAccountsDecoded<TData extends object, TAddress extends string = string>(\n accounts: (Account<ReadonlyUint8Array | TData, TAddress> | MaybeAccount<ReadonlyUint8Array | TData, TAddress>)[],\n): asserts accounts is (Account<TData, TAddress> | MaybeAccount<TData, TAddress>)[] {\n const encoded = accounts.filter(a => accountExists(a) && a.data instanceof Uint8Array);\n if (encoded.length > 0) {\n const encodedAddresses = encoded.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED, {\n addresses: encodedAddresses,\n });\n }\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Encoder, getBase64Encoder } from '@solana/codecs-strings';\nimport type {\n AccountInfoBase,\n AccountInfoWithBase58Bytes,\n AccountInfoWithBase58EncodedData,\n AccountInfoWithBase64EncodedData,\n} from '@solana/rpc-types';\n\nimport type { Account, BaseAccount, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport type { JsonParsedDataResponse } from './rpc-api';\n\ntype Base64EncodedRpcAccount = AccountInfoBase & AccountInfoWithBase64EncodedData;\n\n/**\n * Parses a base64-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base64' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase64RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase64RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base64EncodedRpcAccount,\n): EncodedAccount<TAddress>;\nexport function parseBase64RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base64EncodedRpcAccount | null,\n): MaybeEncodedAccount<TAddress>;\nexport function parseBase64RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base64EncodedRpcAccount | null,\n): EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase64Encoder().encode(rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype Base58EncodedRpcAccount = AccountInfoBase & (AccountInfoWithBase58Bytes | AccountInfoWithBase58EncodedData);\n\n/**\n * Parses a base58-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base58' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase58RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase58RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base58EncodedRpcAccount,\n): EncodedAccount<TAddress>;\nexport function parseBase58RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base58EncodedRpcAccount | null,\n): MaybeEncodedAccount<TAddress>;\nexport function parseBase58RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base58EncodedRpcAccount | null,\n): EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase58Encoder().encode(typeof rpcAccount.data === 'string' ? rpcAccount.data : rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype JsonParsedRpcAccount = AccountInfoBase & { readonly data: JsonParsedDataResponse<unknown> };\n\n/**\n * Parses an arbitrary `jsonParsed` account provided by the RPC client into an {@link Account} type\n * or a {@link MaybeAccount} type if the raw data can be set to `null`.\n *\n * The expected data type should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * const myAccount: Account<MyData> = parseJsonRpcAccount<MyData>(myJsonRpcAccount);\n * ```\n */\nexport function parseJsonRpcAccount<TData extends object, TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: JsonParsedRpcAccount,\n): Account<TData, TAddress>;\nexport function parseJsonRpcAccount<TData extends object, TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: JsonParsedRpcAccount | null,\n): MaybeAccount<TData, TAddress>;\nexport function parseJsonRpcAccount<TData extends object, TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: JsonParsedRpcAccount | null,\n): Account<TData, TAddress> | MaybeAccount<TData, TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = rpcAccount.data.parsed.info as TData;\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\nfunction parseBaseAccount(rpcAccount: AccountInfoBase): BaseAccount {\n return Object.freeze({\n executable: rpcAccount.executable,\n lamports: rpcAccount.lamports,\n programAddress: rpcAccount.owner,\n space: rpcAccount.space,\n });\n}\n","import type { Address } from '@solana/addresses';\nimport type { Rpc } from '@solana/rpc-spec';\nimport type { Commitment, Slot } from '@solana/rpc-types';\n\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport { parseBase64RpcAccount, parseJsonRpcAccount } from './parse-account';\nimport type { GetAccountInfoApi, GetMultipleAccountsApi } from './rpc-api';\n\n/**\n * Optional configuration for fetching a singular account.\n *\n * @interface\n */\nexport type FetchAccountConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the account as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches a {@link MaybeEncodedAccount} from the provided RPC client and address.\n *\n * It uses the {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} RPC method under the hood\n * with base64 encoding and an additional configuration object can be provided to customize the\n * behavior of the RPC call.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress);\n *\n * // With custom configuration.\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccount<TAddress extends string = string>(\n rpc: Rpc<GetAccountInfoApi>,\n address: Address<TAddress>,\n config: FetchAccountConfig = {},\n): Promise<MaybeEncodedAccount<TAddress>> {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: 'base64' }).send({ abortSignal });\n return parseBase64RpcAccount(address, response.value);\n}\n\n/**\n * Fetches a {@link MaybeAccount} from the provided RPC client and address by using\n * {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} under the hood with the `jsonParsed`\n * encoding.\n *\n * It may also return a {@link MaybeEncodedAccount} if the RPC client does not know how to parse the\n * account at the requested address. In any case, the expected data type should be explicitly\n * provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * const myAccount = await fetchJsonParsedAccount<TokenData>(rpc, myAddress);\n * myAccount satisfies MaybeAccount<TokenData> | MaybeEncodedAccount;\n *\n * // With custom configuration.\n * const myAccount = await fetchJsonParsedAccount<TokenData>(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchJsonParsedAccount<TData extends object, TAddress extends string = string>(\n rpc: Rpc<GetAccountInfoApi>,\n address: Address<TAddress>,\n config: FetchAccountConfig = {},\n): Promise<MaybeAccount<TData, TAddress> | MaybeEncodedAccount<TAddress>> {\n const { abortSignal, ...rpcConfig } = config;\n const { value: account } = await rpc\n .getAccountInfo(address, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount<TData, TAddress>(address, account as Parameters<typeof parseJsonRpcAccount>[1])\n : parseBase64RpcAccount<TAddress>(address, account as Parameters<typeof parseBase64RpcAccount>[1]);\n}\n\n/**\n * Optional configuration for fetching multiple accounts.\n *\n * @interface\n */\nexport type FetchAccountsConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the accounts as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches an array of {@link MaybeEncodedAccount | MaybeEncodedAccounts} from the provided RPC\n * client and an array of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with base64 encodings and an additional configuration object can be provided to\n * customize the behavior of the RPC call.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n *\n * @example\n * ```ts\n * const myAddressA = address('1234..5678');\n * const myAddressB = address('8765..4321');\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeEncodedAccount<'1234..5678'>;\n * myAccountB satisfies MaybeEncodedAccount<'8765..4321'>;\n *\n * // With custom configuration.\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB], {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccounts<\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address<TAddresses[P]> } = {\n [P in keyof TAddresses]: Address<TAddresses[P]>;\n },\n>(rpc: Rpc<GetMultipleAccountsApi>, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'base64' })\n .send({ abortSignal });\n return response.value.map((account, index) => parseBase64RpcAccount(addresses[index], account)) as {\n [P in keyof TAddresses]: MaybeEncodedAccount<TAddresses[P]>;\n };\n}\n\n/**\n * Fetches an array of {@link MaybeAccount | MaybeAccounts} from a provided RPC client and an array\n * of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with the `jsonParsed` encoding. It may also return a\n * {@link MaybeEncodedAccount} instead of the expected {@link MaybeAccount} if the RPC client does\n * not know how to parse some of the requested accounts. In any case, the array of expected data\n * types should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n * @typeParam TData - The expected types of these accounts' data.\n \n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * type MintData = { supply: bigint };\n * const [myAccountA, myAccountB] = await fetchJsonParsedAccounts<[TokenData, MintData]>(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeAccount<TokenData> | MaybeEncodedAccount;\n * myAccountB satisfies MaybeAccount<MintData> | MaybeEncodedAccount;\n * ```\n */\nexport async function fetchJsonParsedAccounts<\n TData extends object[],\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address<TAddresses[P]> } = {\n [P in keyof TAddresses]: Address<TAddresses[P]>;\n },\n>(rpc: Rpc<GetMultipleAccountsApi>, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return response.value.map((account, index) => {\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(addresses[index], account as Parameters<typeof parseJsonRpcAccount>[1])\n : parseBase64RpcAccount(addresses[index], account as Parameters<typeof parseBase64RpcAccount>[1]);\n }) as {\n [P in keyof TAddresses]:\n | MaybeAccount<TData[P & keyof TData], TAddresses[P]>\n | MaybeEncodedAccount<TAddresses[P]>;\n } & {\n [P in keyof TData]:\n | MaybeAccount<TData[P], TAddresses[P & keyof TAddresses]>\n | MaybeEncodedAccount<TAddresses[P & keyof TAddresses]>;\n };\n}\n","import { Address } from '@solana/addresses';\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SolanaError,\n} from '@solana/errors';\n\nimport { Account } from './account';\n\n/**\n * Represents an account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type with an additional `exists`\n * attribute set to `true`. When it does not exist, it is represented by an object containing only\n * the address of the account and an `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * // Account exists\n * const myExistingAccount: MaybeAccount<MyAccountData, '1234..5678'> = {\n * exists: true,\n * address: address('1234..5678'),\n * data: { name: 'Alice', age: 30 },\n * // ...\n * };\n *\n * // Account does not exist\n * const myMissingAccount: MaybeAccount<MyAccountData, '8765..4321'> = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeAccount<TData extends Uint8Array | object, TAddress extends string = string> =\n | { readonly address: Address<TAddress>; readonly exists: false }\n | (Account<TData, TAddress> & { readonly exists: true });\n\n/**\n * Represents an encoded account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type having its `TData` type\n * parameter set to `Uint8Array` with an additional `exists` attribute set to `true`. When it does\n * not exist, it is represented by an object containing only the address of the account and an\n * `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * // Encoded account exists\n * const myExistingAccount: MaybeEncodedAccount<'1234..5678'> = {\n * exists: true,\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * // ...\n * };\n *\n * // Encoded account does not exist\n * const myMissingAccount: MaybeEncodedAccount<'8765..4321'> = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeEncodedAccount<TAddress extends string = string> = MaybeAccount<Uint8Array, TAddress>;\n\n/**\n * Given a {@link MaybeAccount}, asserts that the account exists and allows it to be used as an\n * {@link Account} type going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccount: MaybeEncodedAccount<'1234..5678'>;\n * assertAccountExists(myAccount);\n *\n * // Now we can use myAccount as an `EncodedAccount`\n * myAccount satisfies EncodedAccount<'1234..5678'>;\n * ```\n */\nexport function assertAccountExists<TData extends Uint8Array | object, TAddress extends string = string>(\n account: MaybeAccount<TData, TAddress>,\n): asserts account is Account<TData, TAddress> & { exists: true } {\n if (!account.exists) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, { address: account.address });\n }\n}\n\n/**\n * Given an array of {@link MaybeAccount | MaybeAccounts}, asserts that all the accounts exist and\n * allows them to be used as an array of {@link Account | Accounts} going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccounts: MaybeEncodedAccount<Address>[];\n * assertAccountsExist(myAccounts);\n *\n * // Now we can use them as an array of `EncodedAccounts`\n * for (const a of myAccounts) {\n * a satisfies EncodedAccount<Address>;\n * }\n * ```\n */\nexport function assertAccountsExist<TData extends Uint8Array | object, TAddress extends string = string>(\n accounts: MaybeAccount<TData, TAddress>[],\n): asserts accounts is (Account<TData, TAddress> & { exists: true })[] {\n const missingAccounts = accounts.filter(a => !a.exists);\n if (missingAccounts.length > 0) {\n const missingAddresses = missingAccounts.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND, { addresses: missingAddresses });\n }\n}\n","import {\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SolanaError,\n} from '@solana/errors';\n\nfunction assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT);\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 .then(() => {\n resolve((cachedEd25519Decision = true));\n })\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#digest | `crypto.subtle.digest()`} is available in\n * the current JavaScript environment.\n */\nexport function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#generateKey | `crypto.subtle.generateKey()`} is\n * available in the current JavaScript environment and has support for the Ed25519 curve.\n */\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED);\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#exportKey | `crypto.subtle.exportKey()`} is\n * available in the current JavaScript environment.\n */\nexport function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#sign | `crypto.subtle.sign()`} is available in the\n * current JavaScript environment.\n */\nexport function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED);\n }\n}\n/**\n * Throws an exception unless {@link SubtleCrypto#verify | `crypto.subtle.verify()`} is available in\n * the current JavaScript environment.\n */\nexport function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED);\n }\n}\n","import {\n combineCodec,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n transformEncoder,\n} from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\n/**\n * Represents a string that validates as a Solana address. Functions that require well-formed\n * addresses should specify their inputs in terms of this type.\n *\n * Whenever you need to validate an arbitrary string as a base58-encoded address, use the\n * {@link address}, {@link assertIsAddress}, or {@link isAddress} functions in this package.\n */\nexport type Address<TAddress extends string = string> = Brand<EncodedString<TAddress, 'base58'>, 'Address'>;\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\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Address} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAddress } from '@solana/addresses';\n *\n * if (isAddress(ownerAddress)) {\n * // At this point, `ownerAddress` has been refined to a\n * // `Address` that can be used with the RPC.\n * const { value: lamports } = await rpc.getBalance(ownerAddress).send();\n * setBalanceLamports(lamports);\n * } else {\n * setError(`${ownerAddress} is not an address`);\n * }\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 try {\n return base58Encoder.encode(putativeAddress).byteLength === 32;\n } catch {\n return false;\n }\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as an address or public\n * key, from an untrusted network API or user input. Use this function to assert that such an\n * arbitrary string is a base58-encoded address.\n *\n * @example\n * ```ts\n * import { assertIsAddress } from '@solana/addresses';\n *\n * // Imagine a function that fetches an account's balance when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const address: string = accountAddressInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `Address`.\n * assertIsAddress(address);\n * // At this point, `address` is an `Address` that can be used with the RPC.\n * const balanceInLamports = await rpc.getBalance(address).send();\n * } catch (e) {\n * // `address` turned out not to be a base58-encoded address\n * }\n * }\n * ```\n */\nexport function assertIsAddress(putativeAddress: string): asserts 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 throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeAddress.length,\n });\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 SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * Combines _asserting_ that a string is an address with _coercing_ it to the {@link Address} type.\n * It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n *\n * await transfer(address(fromAddress), address(toAddress), lamports(100000n));\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good address as a string, it's more efficient to typecast it rather\n * than to use the {@link address} helper, because the helper unconditionally performs validation on\n * its input.\n * >\n * > ```ts\n * > import { Address } from '@solana/addresses';\n * >\n * > const MEMO_PROGRAM_ADDRESS =\n * > 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' as Address<'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'>;\n * > ```\n */\nexport function address<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address<TAddress>;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded address to a byte array.\n *\n * @example\n * ```ts\n * import { getAddressEncoder } from '@solana/addresses';\n *\n * const address = 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address;\n * const addressEncoder = getAddressEncoder();\n * const addressBytes = addressEncoder.encode(address);\n * // Uint8Array(32) [\n * // 150, 183, 190, 48, 171, 8, 39, 156,\n * // 122, 213, 172, 108, 193, 95, 26, 158,\n * // 149, 243, 115, 254, 20, 200, 36, 30,\n * // 248, 179, 178, 232, 220, 89, 53, 127\n * // ]\n * ```\n */\nexport function getAddressEncoder(): FixedSizeEncoder<Address, 32> {\n return transformEncoder(fixEncoderSize(getMemoizedBase58Encoder(), 32), putativeAddress =>\n address(putativeAddress),\n );\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing an address to the\n * base58-encoded representation of that address.\n *\n * @example\n * ```ts\n * import { getAddressDecoder } from '@solana/addresses';\n *\n * const addressBytes = new Uint8Array([\n * 150, 183, 190, 48, 171, 8, 39, 156,\n * 122, 213, 172, 108, 193, 95, 26, 158,\n * 149, 243, 115, 254, 20, 200, 36, 30,\n * 248, 179, 178, 232, 220, 89, 53, 127\n * ]);\n * const addressDecoder = getAddressDecoder();\n * const address = addressDecoder.decode(addressBytes); // B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka\n * ```\n */\nexport function getAddressDecoder(): FixedSizeDecoder<Address, 32> {\n return fixDecoderSize(getMemoizedBase58Decoder(), 32) as FixedSizeDecoder<Address, 32>;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded address.\n *\n * @see {@link getAddressDecoder}\n * @see {@link getAddressEncoder}\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 { assertKeyExporterIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SolanaError } from '@solana/errors';\n\nimport { Address, getAddressDecoder, getAddressEncoder } from './address';\n\n/**\n * Given a public {@link CryptoKey}, this method will return its associated {@link Address}.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const address = await getAddressFromPublicKey(publicKey);\n * ```\n */\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Address> {\n assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n\n/**\n * Given an {@link Address}, return a {@link CryptoKey} that can be used to verify signatures.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const publicKey = await getPublicKeyFromAddress(address);\n * ```\n */\nexport async function getPublicKeyFromAddress(address: Address) {\n const addressBytes = getAddressEncoder().encode(address);\n return await crypto.subtle.importKey('raw', addressBytes, { name: 'Ed25519' }, true /* extractable */, ['verify']);\n}\n","import { SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\n/**\n * Ensures that a given number falls within a specified range.\n *\n * If the number is outside the allowed range, an error is thrown.\n * This function is primarily used to validate values before encoding them in a codec.\n *\n * @param codecDescription - A string describing the codec that is performing the validation.\n * @param min - The minimum allowed value (inclusive).\n * @param max - The maximum allowed value (inclusive).\n * @param value - The number to validate.\n *\n * @throws {@link SolanaError} if the value is out of range.\n *\n * @example\n * Validating a number within range.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 42); // Passes\n * ```\n *\n * @example\n * Throwing an error for an out-of-range value.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 300); // Throws\n * ```\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: bigint | number,\n max: bigint | number,\n value: bigint | number,\n) {\n if (value < min || value > max) {\n throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {\n codecDescription,\n max,\n min,\n value,\n });\n }\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n createDecoder,\n createEncoder,\n FixedSizeDecoder,\n FixedSizeEncoder,\n Offset,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput<TSize extends number> = {\n config?: NumberCodecConfig;\n name: string;\n size: TSize;\n};\n\ntype NumberFactoryEncoderInput<TFrom, TSize extends number> = NumberFactorySharedInput<TSize> & {\n range?: [bigint | number, bigint | number];\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 bigint | number, 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 bigint | number, 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: ReadonlyUint8Array | 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 {\n combineCodec,\n createDecoder,\n createEncoder,\n Offset,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\n\n/**\n * Returns an encoder for `shortU16` values.\n *\n * This encoder serializes `shortU16` values using **1 to 3 bytes**.\n * Smaller values use fewer bytes, while larger values take up more space.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeEncoder<number | bigint>` for encoding `shortU16` values.\n *\n * @example\n * Encoding a `shortU16` value.\n * ```ts\n * const encoder = getShortU16Encoder();\n * encoder.encode(42); // 0x2a\n * encoder.encode(128); // 0x8001\n * encoder.encode(16384); // 0x808001\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Encoder = (): VariableSizeEncoder<bigint | number> =>\n createEncoder({\n getSizeFromValue: (value: bigint | number): number => {\n if (value <= 0b01111111) return 1;\n if (value <= 0b0011111111111111) return 2;\n return 3;\n },\n maxSize: 3,\n write: (value: bigint | number, bytes: Uint8Array, offset: Offset): Offset => {\n assertNumberIsBetweenForCodec('shortU16', 0, 65535, value);\n const shortU16Bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = Number(value) >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n shortU16Bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n shortU16Bytes[ii - 1] |= 0b10000000;\n }\n }\n bytes.set(shortU16Bytes, offset);\n return offset + shortU16Bytes.length;\n },\n });\n\n/**\n * Returns a decoder for `shortU16` values.\n *\n * This decoder deserializes `shortU16` values from **1 to 3 bytes**.\n * The number of bytes used depends on the encoded value.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeDecoder<number>` for decoding `shortU16` values.\n *\n * @example\n * Decoding a `shortU16` value.\n * ```ts\n * const decoder = getShortU16Decoder();\n * decoder.decode(new Uint8Array([0x2a])); // 42\n * decoder.decode(new Uint8Array([0x80, 0x01])); // 128\n * decoder.decode(new Uint8Array([0x80, 0x80, 0x01])); // 16384\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Decoder = (): VariableSizeDecoder<number> =>\n createDecoder({\n maxSize: 3,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset): [number, 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 = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding `shortU16` values.\n *\n * It serializes unsigned integers using **1 to 3 bytes** based on the encoded value.\n * The larger the value, the more bytes it uses.\n *\n * - If the value is `<= 0x7f` (127), it is stored in a **single byte**\n * and the first bit is set to `0` to indicate the end of the value.\n * - Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern.\n * - This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value.\n *\n * In other words, the encoding scheme follows this structure:\n *\n * ```txt\n * 0XXXXXXX <- Values 0 to 127 (1 byte)\n * 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes)\n * 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes)\n * ```\n *\n * @returns A `VariableSizeCodec<number | bigint, number>` for encoding and decoding `shortU16` values.\n *\n * @example\n * Encoding and decoding `shortU16` values.\n * ```ts\n * const codec = getShortU16Codec();\n * const bytes1 = codec.encode(42); // 0x2a\n * const bytes2 = codec.encode(128); // 0x8001\n * const bytes3 = codec.encode(16384); // 0x808001\n *\n * codec.decode(bytes1); // 42\n * codec.decode(bytes2); // 128\n * codec.decode(bytes3); // 16384\n * ```\n *\n * @remarks\n * This codec efficiently stores small numbers, making it useful for transactions and compact representations.\n *\n * If you need a fixed-size `u16` codec, consider using {@link getU16Codec}.\n *\n * Separate {@link getShortU16Encoder} and {@link getShortU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getShortU16Encoder().encode(42);\n * const value = getShortU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getShortU16Encoder}\n * @see {@link getShortU16Decoder}\n */\nexport const getShortU16Codec = (): VariableSizeCodec<bigint | number, number> =>\n combineCodec(getShortU16Encoder(), getShortU16Decoder());\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 16-bit unsigned integers (`u16`).\n *\n * This encoder serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder<number | bigint, 2>` for encoding `u16` values.\n *\n * @example\n * Encoding a `u16` value.\n * ```ts\n * const encoder = getU16Encoder();\n * const bytes = encoder.encode(42); // 0x2a00\n * ```\n *\n * @see {@link getU16Codec}\n */\nexport const getU16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<bigint | number, 2> =>\n numberEncoderFactory({\n config,\n name: 'u16',\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, Number(value), le),\n size: 2,\n });\n\n/**\n * Returns a decoder for 16-bit unsigned integers (`u16`).\n *\n * This decoder deserializes `u16` values from two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder<number, 2>` for decoding `u16` values.\n *\n * @example\n * Decoding a `u16` value.\n * ```ts\n * const decoder = getU16Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @see {@link getU16Codec}\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\n/**\n * Returns a codec for encoding and decoding 16-bit unsigned integers (`u16`).\n *\n * This codec serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec<number | bigint, number, 2>` for encoding and decoding `u16` values.\n *\n * @example\n * Encoding and decoding a `u16` value.\n * ```ts\n * const codec = getU16Codec();\n * const bytes = codec.encode(42); // 0x2a00 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU16Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^16 - 1`.\n * If you need a larger range, consider using {@link getU32Codec} or {@link getU64Codec}.\n * For signed integers, use {@link getI16Codec}.\n *\n * Separate {@link getU16Encoder} and {@link getU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU16Encoder().encode(42);\n * const value = getU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU16Encoder}\n * @see {@link getU16Decoder}\n */\nexport const getU16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec<bigint | number, number, 2> =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit unsigned integers (`u32`).\n *\n * This encoder serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder<bigint | number, 4>` for encoding `u32` values.\n *\n * @example\n * Encoding a `u32` value.\n * ```ts\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42); // 0x2a000000\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<bigint | number, 4> =>\n numberEncoderFactory({\n config,\n name: 'u32',\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit unsigned integers (`u32`).\n *\n * This decoder deserializes `u32` values from four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder<number, 4>` for decoding `u32` values.\n *\n * @example\n * Decoding a `u32` value.\n * ```ts\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder<number, 4> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit unsigned integers (`u32`).\n *\n * This codec serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec<bigint | number, number, 4>` for encoding and decoding `u32` values.\n *\n * @example\n * Encoding and decoding a `u32` value.\n * ```ts\n * const codec = getU32Codec();\n * const bytes = codec.encode(42); // 0x2a000000 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x0000002a\n * ```\n *\n * @remarks\n * This codec only supports values between `0` and `2^32 - 1`.\n * If you need a larger range, consider using {@link getU64Codec} or {@link getU128Codec}.\n * For signed integers, use {@link getI32Codec}.\n *\n * Separate {@link getU32Encoder} and {@link getU32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU32Encoder().encode(42);\n * const value = getU32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU32Encoder}\n * @see {@link getU32Decoder}\n */\nexport const getU32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec<bigint | number, number, 4> =>\n combineCodec(getU32Encoder(config), getU32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit unsigned integers (`u64`).\n *\n * This encoder serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder<number | bigint, 8>` for encoding `u64` values.\n *\n * @example\n * Encoding a `u64` value.\n * ```ts\n * const encoder = getU64Encoder();\n * const bytes = encoder.encode(42); // 0x2a00000000000000\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<bigint | number, 8> =>\n numberEncoderFactory({\n config,\n name: 'u64',\n range: [0n, BigInt('0xffffffffffffffff')],\n set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit unsigned integers (`u64`).\n *\n * This decoder deserializes `u64` values from 8 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder<bigint, 8>` for decoding `u64` values.\n *\n * @example\n * Decoding a `u64` value.\n * ```ts\n * const decoder = getU64Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder<bigint, 8> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigUint64(0, le),\n name: 'u64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit unsigned integers (`u64`).\n *\n * This codec serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec<number | bigint, bigint, 8>` for encoding and decoding `u64` values.\n *\n * @example\n * Encoding and decoding a `u64` value.\n * ```ts\n * const codec = getU64Codec();\n * const bytes = codec.encode(42); // 0x2a00000000000000\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getU64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x000000000000002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^64 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller unsigned integer, consider using {@link getU32Codec} or {@link getU16Codec}.\n * - If you need a larger unsigned integer, consider using {@link getU128Codec}.\n * - If you need signed integers, consider using {@link getI64Codec}.\n *\n * Separate {@link getU64Encoder} and {@link getU64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU64Encoder().encode(42);\n * const value = getU64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU64Encoder}\n * @see {@link getU64Decoder}\n */\nexport const getU64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec<bigint | number, bigint, 8> =>\n combineCodec(getU64Encoder(config), getU64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 8-bit unsigned integers (`u8`).\n *\n * This encoder serializes `u8` values using a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeEncoder<number | bigint, 1>` for encoding `u8` values.\n *\n * @example\n * Encoding a `u8` value.\n * ```ts\n * const encoder = getU8Encoder();\n * const bytes = encoder.encode(42); // 0x2a\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Encoder = (): FixedSizeEncoder<bigint | number, 1> =>\n numberEncoderFactory({\n name: 'u8',\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n size: 1,\n });\n\n/**\n * Returns a decoder for 8-bit unsigned integers (`u8`).\n *\n * This decoder deserializes `u8` values from a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeDecoder<number, 1>` for decoding `u8` values.\n *\n * @example\n * Decoding a `u8` value.\n * ```ts\n * const decoder = getU8Decoder();\n * const value = decoder.decode(new Uint8Array([0xff])); // 255\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Decoder = (): FixedSizeDecoder<number, 1> =>\n numberDecoderFactory({\n get: view => view.getUint8(0),\n name: 'u8',\n size: 1,\n });\n\n/**\n * Returns a codec for encoding and decoding 8-bit unsigned integers (`u8`).\n *\n * This codec serializes `u8` values using a single byte.\n *\n * @returns A `FixedSizeCodec<number | bigint, number, 1>` for encoding and decoding `u8` values.\n *\n * @example\n * Encoding and decoding a `u8` value.\n * ```ts\n * const codec = getU8Codec();\n * const bytes = codec.encode(255); // 0xff\n * const value = codec.decode(bytes); // 255\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^8 - 1` (0 to 255).\n * If you need larger integers, consider using {@link getU16Codec}, {@link getU32Codec}, or {@link getU64Codec}.\n * For signed integers, use {@link getI8Codec}.\n *\n * Separate {@link getU8Encoder} and {@link getU8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU8Encoder().encode(42);\n * const value = getU8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU8Encoder}\n * @see {@link getU8Decoder}\n */\nexport const getU8Codec = (): FixedSizeCodec<bigint | number, number, 1> =>\n combineCodec(getU8Encoder(), getU8Decoder());\n","import { SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, SolanaError } from '@solana/errors';\n\n/** Checks the number of items in an array-like structure is expected. */\nexport function assertValidNumberOfItemsForCodec(\n codecDescription: string,\n expected: bigint | number,\n actual: bigint | number,\n) {\n if (expected !== actual) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, {\n actual,\n codecDescription,\n expected,\n });\n }\n}\n","import { isFixedSize } from '@solana/codecs-core';\n\n/**\n * Functionally, this type helper is equivalent to the identity type — i.e. `type Identity<T> = T`.\n * However, wrapping generic object mappings in this type significantly reduces the number\n * of instantiation expressions processed, which increases TypeScript performance and\n * prevents \"Type instantiation is excessively deep and possibly infinite\" errors.\n *\n * This works because TypeScript doesn't create a new level of nesting when encountering conditional generic types.\n * @see https://github.com/microsoft/TypeScript/issues/34933\n * @see https://github.com/kysely-org/kysely/pull/483\n */\nexport type DrainOuterGeneric<T> = [T] extends [unknown] ? T : never;\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 Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\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 * Defines the possible size strategies for array-like codecs (`array`, `map`, and `set`).\n *\n * The size of the collection can be determined using one of the following approaches:\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} to store a size prefix.\n * - A fixed `number` of items, enforcing an exact length.\n * - The string `\"remainder\"`, which infers the number of items by consuming the rest of the available bytes.\n * This option is only available when encoding fixed-size items.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayLikeCodecSize<TPrefix extends NumberCodec | NumberDecoder | NumberEncoder> =\n | TPrefix\n | number\n | 'remainder';\n\n/**\n * Defines the configuration options for array codecs.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayCodecConfig<TPrefix extends NumberCodec | NumberDecoder | NumberEncoder> = {\n /**\n * Specifies how the size of the array is determined.\n *\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} stores a size prefix before encoding the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length (only for fixed-size items).\n *\n * @defaultValue A `u32` size prefix.\n */\n size?: ArrayLikeCodecSize<TPrefix>;\n};\n\n/**\n * Returns an encoder for arrays of values.\n *\n * This encoder serializes arrays by encoding each element using the provided item encoder.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TFrom - The type of the elements in the array.\n *\n * @param item - The encoder for each item in the array.\n * @param config - Optional configuration for the size encoding strategy.\n * @returns A `VariableSizeEncoder<TFrom[]>` for encoding arrays.\n *\n * @example\n * Encoding an array of `u8` numbers.\n * ```ts\n * const encoder = getArrayEncoder(getU8Encoder());\n * const bytes = encoder.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\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: Encoder<TFrom>,\n config?: ArrayCodecConfig<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 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 * Returns a decoder for arrays of values.\n *\n * This decoder deserializes arrays by decoding each element using the provided item decoder.\n * By default, a `u32` size prefix is expected to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TTo - The type of the decoded elements in the array.\n *\n * @param item - The decoder for each item in the array.\n * @param config - Optional configuration for the size decoding strategy.\n * @returns A `VariableSizeDecoder<TTo[]>` for decoding arrays.\n *\n * @example\n * Decoding an array of `u8` numbers.\n * ```ts\n * const decoder = getArrayDecoder(getU8Decoder());\n * const array = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03]));\n * // [1, 2, 3]\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\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: Decoder<TTo>,\n config?: ArrayCodecConfig<NumberDecoder>,\n): VariableSizeDecoder<TTo[]>;\nexport function getArrayDecoder<TTo>(item: Decoder<TTo>, config: ArrayCodecConfig<NumberDecoder> = {}): Decoder<TTo[]> {\n const size = config.size ?? getU32Decoder();\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: ReadonlyUint8Array | Uint8Array, offset) => {\n const array: TTo[] = [];\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [array, offset];\n }\n\n if (size === 'remainder') {\n while (offset < bytes.length) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, offset];\n }\n\n const [resolvedSize, newOffset] = typeof size === 'number' ? [size, offset] : size.read(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 * Returns a codec for encoding and decoding arrays of values.\n *\n * This codec serializes arrays by encoding each element using the provided item codec.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * @typeParam TFrom - The type of the elements to encode.\n * @typeParam TTo - The type of the decoded elements.\n *\n * @param item - The codec for each item in the array.\n * @param config - Optional configuration for the size encoding/decoding strategy.\n * @returns A `VariableSizeCodec<TFrom[], TTo[]>` for encoding and decoding arrays.\n *\n * @example\n * Encoding and decoding an array of `u8` numbers.\n * ```ts\n * const codec = getArrayCodec(getU8Codec());\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n *\n * const array = codec.decode(bytes);\n * // [1, 2, 3]\n * ```\n *\n * @example\n * Using a `u16` size prefix instead of `u32`.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x0300010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 2-byte prefix telling us to read 3 items.\n * ```\n *\n * @example\n * Using a fixed-size array of 3 items.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 3 });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. There must always be 3 items in the array.\n * ```\n *\n * @example\n * Using the `\"remainder\"` size strategy.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 'remainder' });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes.\n * ```\n *\n * @remarks\n * The size of the array can be controlled using the `size` option:\n * - A `Codec<number>` (e.g. `getU16Codec()`) stores a size prefix before the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length.\n *\n * Separate {@link getArrayEncoder} and {@link getArrayDecoder} functions are available.\n *\n * ```ts\n * const bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]);\n * const array = getArrayDecoder(getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getArrayEncoder}\n * @see {@link getArrayDecoder}\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: Codec<TFrom, TTo>,\n config?: ArrayCodecConfig<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 computeArrayLikeCodecSize(size: number | object | '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 {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\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\n/**\n * Defines the configuration options for boolean codecs.\n *\n * A boolean codec encodes `true` as `1` and `false` as `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * @typeParam TSize - A number codec, encoder, or decoder used for boolean representation.\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\n * @see {@link getBooleanCodec}\n */\nexport type BooleanCodecConfig<TSize extends NumberCodec | NumberDecoder | NumberEncoder> = {\n /**\n * The number codec used to store boolean values.\n *\n * - By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * - A custom number codec can be provided to change the storage size.\n *\n * @defaultValue `u8`\n */\n size?: TSize;\n};\n\n/**\n * Returns an encoder for boolean values.\n *\n * This encoder converts `true` into `1` and `false` into `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for encoding booleans.\n * @returns A `FixedSizeEncoder<boolean, N>` where `N` is the size of the number codec.\n *\n * @example\n * Encoding booleans.\n * ```ts\n * const encoder = getBooleanEncoder();\n *\n * encoder.encode(false); // 0x00\n * encoder.encode(true); // 0x01\n * ```\n *\n * @see {@link getBooleanCodec}\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>): VariableSizeEncoder<boolean>;\nexport function getBooleanEncoder(config: BooleanCodecConfig<NumberEncoder> = {}): Encoder<boolean> {\n return transformEncoder(config.size ?? getU8Encoder(), (value: boolean) => (value ? 1 : 0));\n}\n\n/**\n * Returns a decoder for boolean values.\n *\n * This decoder reads a number and interprets `1` as `true` and `0` as `false`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for decoding booleans.\n * @returns A `FixedSizeDecoder<boolean, N>` where `N` is the size of the number codec.\n *\n * @example\n * Decoding booleans.\n * ```ts\n * const decoder = getBooleanDecoder();\n *\n * decoder.decode(new Uint8Array([0x00])); // false\n * decoder.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @see {@link getBooleanCodec}\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>): VariableSizeDecoder<boolean>;\nexport function getBooleanDecoder(config: BooleanCodecConfig<NumberDecoder> = {}): Decoder<boolean> {\n return transformDecoder(config.size ?? getU8Decoder(), (value: bigint | number): boolean => Number(value) === 1);\n}\n\n/**\n * Returns a codec for encoding and decoding boolean values.\n *\n * By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * The `size` option allows customizing the number codec used for storage.\n *\n * @param config - Configuration options for encoding and decoding booleans.\n * @returns A `FixedSizeCodec<boolean, boolean, N>` where `N` is the size of the number codec.\n *\n * @example\n * Encoding and decoding booleans using a `u8` (default).\n * ```ts\n * const codec = getBooleanCodec();\n *\n * codec.encode(false); // 0x00\n * codec.encode(true); // 0x01\n *\n * codec.decode(new Uint8Array([0x00])); // false\n * codec.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @example\n * Encoding and decoding booleans using a custom number codec.\n * ```ts\n * const codec = getBooleanCodec({ size: getU16Codec() });\n *\n * codec.encode(false); // 0x0000\n * codec.encode(true); // 0x0100\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // false\n * codec.decode(new Uint8Array([0x01, 0x00])); // true\n * ```\n *\n * @remarks\n * Separate {@link getBooleanEncoder} and {@link getBooleanDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBooleanEncoder().encode(true);\n * const value = getBooleanDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\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>): VariableSizeCodec<boolean>;\nexport function getBooleanCodec(config: BooleanCodecConfig<NumberCodec> = {}): Codec<boolean> {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for raw byte arrays.\n *\n * This encoder writes byte arrays exactly as provided without modification.\n *\n * The size of the encoded byte array is determined by the length of the input.\n * - To enforce a fixed size, consider using {@link fixEncoderSize}.\n * - To add a size prefix, use {@link addEncoderSizePrefix}.\n * - To add a sentinel value, use {@link addEncoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeEncoder<ReadonlyUint8Array | Uint8Array>`.\n *\n * @example\n * Encoding a byte array as-is.\n * ```ts\n * const encoder = getBytesEncoder();\n *\n * encoder.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * encoder.encode(new Uint8Array([255, 0, 127])); // 0xff007f\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesEncoder(): VariableSizeEncoder<ReadonlyUint8Array | Uint8Array> {\n return createEncoder({\n getSizeFromValue: value => value.length,\n write: (value, bytes, offset) => {\n bytes.set(value, offset);\n return offset + value.length;\n },\n });\n}\n\n/**\n * Returns a decoder for raw byte arrays.\n *\n * This decoder reads byte arrays exactly as provided without modification.\n *\n * The decoded byte array extends from the provided offset to the end of the input.\n * - To enforce a fixed size, consider using {@link fixDecoderSize}.\n * - To add a size prefix, use {@link addDecoderSizePrefix}.\n * - To add a sentinel value, use {@link addDecoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeDecoder<ReadonlyUint8Array>`.\n *\n * @example\n * Decoding a byte array as-is.\n * ```ts\n * const decoder = getBytesDecoder();\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Uint8Array([1, 2, 3])\n * decoder.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesDecoder(): VariableSizeDecoder<ReadonlyUint8Array> {\n return createDecoder({\n read: (bytes, offset) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding raw byte arrays.\n *\n * This codec serializes and deserializes byte arrays without modification.\n *\n * The size of the encoded and decoded byte array is determined dynamically.\n * This means, when reading, the codec will consume all remaining bytes in the input.\n * - To enforce a fixed size, consider using {@link fixCodecSize}.\n * - To add a size prefix, use {@link addCodecSizePrefix}.\n * - To add a sentinel value, use {@link addCodecSentinel}.\n *\n * @returns A `VariableSizeCodec<ReadonlyUint8Array | Uint8Array, ReadonlyUint8Array>`.\n *\n * @example\n * Encoding and decoding a byte array.\n * ```ts\n * const codec = getBytesCodec();\n *\n * codec.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * codec.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @remarks\n * Separate {@link getBytesEncoder} and {@link getBytesDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBytesEncoder().encode(new Uint8Array([1, 2, 3]));\n * const value = getBytesDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBytesEncoder}\n * @see {@link getBytesDecoder}\n */\nexport function getBytesCodec(): VariableSizeCodec<ReadonlyUint8Array | Uint8Array, ReadonlyUint8Array> {\n return combineCodec(getBytesEncoder(), getBytesDecoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nconst enum HexC {\n ZERO = 48, // 0\n NINE = 57, // 9\n A_UP = 65, // A\n F_UP = 70, // F\n A_LO = 97, // a\n F_LO = 102, // f\n}\n\nconst INVALID_STRING_ERROR_BASE_CONFIG = {\n alphabet: '0123456789abcdef',\n base: 16,\n} as const;\n\nfunction charCodeToBase16(char: number) {\n if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;\n if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);\n if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);\n}\n\n/**\n * Returns an encoder for base-16 (hexadecimal) strings.\n *\n * This encoder serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeEncoder<string>` for encoding base-16 strings.\n *\n * @example\n * Encoding a base-16 string.\n * ```ts\n * const encoder = getBase16Encoder();\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Encoder = (): VariableSizeEncoder<string> =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const len = value.length;\n const al = len / 2;\n if (len === 1) {\n const c = value.charCodeAt(0);\n const n = charCodeToBase16(c);\n if (n === undefined) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n bytes.set([n], offset);\n return 1 + offset;\n }\n const hexBytes = new Uint8Array(al);\n for (let i = 0, j = 0; i < al; i++) {\n const c1 = value.charCodeAt(j++);\n const c2 = value.charCodeAt(j++);\n\n const n1 = charCodeToBase16(c1);\n const n2 = charCodeToBase16(c2);\n if (n1 === undefined || (n2 === undefined && !Number.isNaN(c2))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n hexBytes[i] = !Number.isNaN(c2) ? (n1 << 4) | (n2 ?? 0) : n1;\n }\n\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-16 (hexadecimal) strings.\n *\n * This decoder deserializes base-16 encoded strings from a byte array.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeDecoder<string>` for decoding base-16 strings.\n *\n * @example\n * Decoding a base-16 string.\n * ```ts\n * const decoder = getBase16Decoder();\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBase16Codec}\n */\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/**\n * Returns a codec for encoding and decoding base-16 (hexadecimal) strings.\n *\n * This codec serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * @returns A `VariableSizeCodec<string>` for encoding and decoding base-16 strings.\n *\n * @example\n * Encoding and decoding a base-16 string.\n * ```ts\n * const codec = getBase16Codec();\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-16 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase16Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-16 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase16Encoder} and {@link getBase16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase16Encoder().encode('deadface');\n * const value = getBase16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase16Encoder}\n * @see {@link getBase16Decoder}\n */\nexport const getBase16Codec = (): VariableSizeCodec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import {\n combineCodec,\n containsBytes,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { getBase16Decoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__CODECS__INVALID_CONSTANT, SolanaError } from '@solana/errors';\n\n/**\n * Returns an encoder that always writes a predefined constant byte sequence.\n *\n * This encoder ensures that encoding always produces the specified byte array,\n * ignoring any input values.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence that will be written during encoding.\n *\n * @param constant - The predefined byte array to encode.\n * @returns A `FixedSizeEncoder<void, N>` where `N` is the length of the constant.\n *\n * @example\n * Encoding a constant magic number.\n * ```ts\n * const encoder = getConstantEncoder(new Uint8Array([1, 2, 3, 4]));\n *\n * const bytes = encoder.encode();\n * // 0x01020304\n * // └──────┘ The predefined 4-byte constant.\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantEncoder<TConstant extends ReadonlyUint8Array>(\n constant: TConstant,\n): FixedSizeEncoder<void, TConstant['length']> {\n return createEncoder({\n fixedSize: constant.length,\n write: (_, bytes, offset) => {\n bytes.set(constant, offset);\n return offset + constant.length;\n },\n });\n}\n\n/**\n * Returns a decoder that verifies a predefined constant byte sequence.\n *\n * This decoder reads the next bytes and checks that they match the provided constant.\n * If the bytes differ, it throws an error.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence expected during decoding.\n *\n * @param constant - The predefined byte array to verify.\n * @returns A `FixedSizeDecoder<void, N>` where `N` is the length of the constant.\n *\n * @example\n * Decoding a constant magic number.\n * ```ts\n * const decoder = getConstantDecoder(new Uint8Array([1, 2, 3]));\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Passes\n * decoder.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantDecoder<TConstant extends ReadonlyUint8Array>(\n constant: TConstant,\n): FixedSizeDecoder<void, TConstant['length']> {\n return createDecoder({\n fixedSize: constant.length,\n read: (bytes, offset) => {\n const base16 = getBase16Decoder();\n if (!containsBytes(bytes, constant, offset)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_CONSTANT, {\n constant,\n data: bytes,\n hexConstant: base16.decode(constant),\n hexData: base16.decode(bytes),\n offset,\n });\n }\n return [undefined, offset + constant.length];\n },\n });\n}\n\n/**\n * Returns a codec that encodes and decodes a predefined constant byte sequence.\n *\n * - **Encoding:** Always writes the specified byte array.\n * - **Decoding:** Asserts that the next bytes match the constant, throwing an error if they do not.\n *\n * This is useful for encoding fixed byte patterns required in a binary format or to use in\n * conjunction with other codecs such as {@link getHiddenPrefixCodec} or {@link getHiddenSuffixCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence to encode and verify during decoding.\n *\n * @param constant - The predefined byte array to encode and assert during decoding.\n * @returns A `FixedSizeCodec<void, void, N>` where `N` is the length of the constant.\n *\n * @example\n * Encoding and decoding a constant magic number.\n * ```ts\n * const codec = getConstantCodec(new Uint8Array([1, 2, 3]));\n *\n * codec.encode(); // 0x010203\n * codec.decode(new Uint8Array([1, 2, 3])); // Passes\n * codec.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @remarks\n * Separate {@link getConstantEncoder} and {@link getConstantDecoder} functions are available.\n *\n * ```ts\n * const bytes = getConstantEncoder(new Uint8Array([1, 2, 3])).encode();\n * getConstantDecoder(new Uint8Array([1, 2, 3])).decode(bytes);\n * ```\n *\n * @see {@link getConstantEncoder}\n * @see {@link getConstantDecoder}\n */\nexport function getConstantCodec<TConstant extends ReadonlyUint8Array>(\n constant: TConstant,\n): FixedSizeCodec<void, void, TConstant['length']> {\n return combineCodec(getConstantEncoder(constant), getConstantDecoder(constant));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for a tuple that can be encoded using a tuple codec.\n *\n * This type maps each provided item encoder to its corresponding value type.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n */\ntype GetEncoderTypeFromItems<TItems extends readonly Encoder<any>[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Encoder<infer TFrom> ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for a tuple that can be decoded using a tuple codec.\n *\n * This type maps each provided item decoder to its corresponding value type.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n */\ntype GetDecoderTypeFromItems<TItems extends readonly Decoder<any>[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Decoder<infer TTo> ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for tuples.\n *\n * This encoder serializes a fixed-size array (tuple) by encoding its items\n * sequentially using the provided item encoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n *\n * @param items - The encoders for each item in the tuple.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding tuples.\n *\n * @example\n * Encoding a tuple with 2 items.\n * ```ts\n * const encoder = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()]);\n *\n * const bytes = encoder.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleEncoder<const TItems extends readonly FixedSizeEncoder<any>[]>(\n items: TItems,\n): FixedSizeEncoder<GetEncoderTypeFromItems<TItems>>;\nexport function getTupleEncoder<const TItems extends readonly Encoder<any>[]>(\n items: TItems,\n): VariableSizeEncoder<GetEncoderTypeFromItems<TItems>>;\nexport function getTupleEncoder<const TItems extends readonly Encoder<any>[]>(\n items: TItems,\n): Encoder<GetEncoderTypeFromItems<TItems>> {\n type TFrom = GetEncoderTypeFromItems<TItems>;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n items.map((item, index) => getEncodedSize(value[index], item)).reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (value: TFrom, bytes, offset) => {\n assertValidNumberOfItemsForCodec('tuple', items.length, value.length);\n items.forEach((item, index) => {\n offset = item.write(value[index], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for tuples.\n *\n * This decoder deserializes a fixed-size array (tuple) by decoding its items\n * sequentially using the provided item decoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n *\n * @param items - The decoders for each item in the tuple.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding tuples.\n *\n * @example\n * Decoding a tuple with 2 items.\n * ```ts\n * const decoder = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()]);\n *\n * const tuple = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // ['Alice', 42]\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleDecoder<const TItems extends readonly FixedSizeDecoder<any>[]>(\n items: TItems,\n): FixedSizeDecoder<GetDecoderTypeFromItems<TItems>>;\nexport function getTupleDecoder<const TItems extends readonly Decoder<any>[]>(\n items: TItems,\n): VariableSizeDecoder<GetDecoderTypeFromItems<TItems>>;\nexport function getTupleDecoder<const TItems extends readonly Decoder<any>[]>(\n items: TItems,\n): Decoder<GetDecoderTypeFromItems<TItems>> {\n type TTo = GetDecoderTypeFromItems<TItems>;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const values = [] as Array<any> & TTo;\n items.forEach(item => {\n const [newValue, newOffset] = item.read(bytes, offset);\n values.push(newValue);\n offset = newOffset;\n });\n return [values, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding tuples.\n *\n * This codec serializes tuples by encoding and decoding each item sequentially.\n *\n * Unlike the {@link getArrayCodec} codec, each item in the tuple has its own codec\n * and, therefore, can be of a different type.\n *\n * @typeParam TItems - An array of codecs, each corresponding to a tuple element.\n *\n * @param items - The codecs for each item in the tuple.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding tuples.\n *\n * @example\n * Encoding and decoding a tuple with 2 items.\n * ```ts\n * const codec = getTupleCodec([fixCodecSize(getUtf8Codec(), 5), getU8Codec()]);\n *\n * const bytes = codec.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n *\n * const tuple = codec.decode(bytes);\n * // ['Alice', 42]\n * ```\n *\n * @remarks\n * Separate {@link getTupleEncoder} and {@link getTupleDecoder} functions are available.\n *\n * ```ts\n * const bytes = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()])\n * .encode(['Alice', 42]);\n *\n * const tuple = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()])\n * .decode(bytes);\n * ```\n *\n * @see {@link getTupleEncoder}\n * @see {@link getTupleDecoder}\n */\nexport function getTupleCodec<const TItems extends readonly FixedSizeCodec<any>[]>(\n items: TItems,\n): FixedSizeCodec<GetEncoderTypeFromItems<TItems>, GetDecoderTypeFromItems<TItems> & GetEncoderTypeFromItems<TItems>>;\nexport function getTupleCodec<const TItems extends readonly Codec<any>[]>(\n items: TItems,\n): VariableSizeCodec<\n GetEncoderTypeFromItems<TItems>,\n GetDecoderTypeFromItems<TItems> & GetEncoderTypeFromItems<TItems>\n>;\nexport function getTupleCodec<const TItems extends readonly Codec<any>[]>(\n items: TItems,\n): Codec<GetEncoderTypeFromItems<TItems>, GetDecoderTypeFromItems<TItems> & GetEncoderTypeFromItems<TItems>> {\n return combineCodec(\n getTupleEncoder(items),\n getTupleDecoder(items) as Decoder<GetDecoderTypeFromItems<TItems> & GetEncoderTypeFromItems<TItems>>,\n );\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n Offset,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\nimport { DrainOuterGeneric, getMaxSize, maxCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for values that can be encoded using a union codec.\n *\n * This type maps the provided variant encoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n */\ntype GetEncoderTypeFromVariants<TVariants extends readonly Encoder<any>[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Encoder<infer TFrom> ? TFrom : never;\n}>[number];\n\n/**\n * Infers the TypeScript type for values that can be decoded using a union codec.\n *\n * This type maps the provided variant decoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n */\ntype GetDecoderTypeFromVariants<TVariants extends readonly Decoder<any>[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Decoder<infer TFrom> ? TFrom : never;\n}>[number];\n\ntype UnionEncoder<TVariants extends readonly Encoder<unknown>[]> = TVariants extends readonly FixedSizeEncoder<any>[]\n ? FixedSizeEncoder<GetEncoderTypeFromVariants<TVariants>>\n : Encoder<GetEncoderTypeFromVariants<TVariants>>;\n\ntype UnionDecoder<TVariants extends readonly Decoder<unknown>[]> = TVariants extends readonly FixedSizeDecoder<any>[]\n ? FixedSizeDecoder<GetDecoderTypeFromVariants<TVariants>>\n : Decoder<GetDecoderTypeFromVariants<TVariants>>;\n\ntype UnionCodec<TVariants extends readonly Codec<unknown>[]> = TVariants extends readonly FixedSizeCodec<any>[]\n ? FixedSizeCodec<\n GetEncoderTypeFromVariants<TVariants>,\n GetDecoderTypeFromVariants<TVariants> & GetEncoderTypeFromVariants<TVariants>\n >\n : Codec<\n GetEncoderTypeFromVariants<TVariants>,\n GetDecoderTypeFromVariants<TVariants> & GetEncoderTypeFromVariants<TVariants>\n >;\n\n/**\n * Returns an encoder for union types.\n *\n * This encoder serializes values by selecting the correct variant encoder\n * based on the `getIndexFromValue` function.\n *\n * Unlike other codecs, this encoder does not store the variant index.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n *\n * @param variants - The encoders for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @returns An `Encoder` for encoding union values.\n *\n * @example\n * Encoding a union of numbers and booleans.\n * ```ts\n * const encoder = getUnionEncoder(\n * [getU16Encoder(), getBooleanEncoder()],\n * value => (typeof value === 'number' ? 0 : 1)\n * );\n *\n * encoder.encode(42);\n * // 0x2a00\n * // └── Encoded number (42) as `u16`\n *\n * encoder.encode(true);\n * // 0x01\n * // └── Encoded boolean (`true`) as `u8`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionEncoder<const TVariants extends readonly Encoder<any>[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants<TVariants>) => number,\n): UnionEncoder<TVariants> {\n type TFrom = GetEncoderTypeFromVariants<TVariants>;\n const fixedSize = getUnionFixedSize(variants);\n const write: Encoder<TFrom>['write'] = (variant, bytes, offset) => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return variants[index].write(variant, bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createEncoder({ fixedSize, write }) as UnionEncoder<TVariants>;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createEncoder({\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: variant => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return getEncodedSize(variant, variants[index]);\n },\n write,\n }) as UnionEncoder<TVariants>;\n}\n\n/**\n * Returns a decoder for union types.\n *\n * This decoder deserializes values by selecting the correct variant decoder\n * based on the `getIndexFromBytes` function.\n *\n * Unlike other codecs, this decoder does not assume a stored discriminator.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n *\n * @param variants - The decoders for each variant of the union.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Decoder` for decoding union values.\n *\n * @example\n * Decoding a union of numbers and booleans.\n * ```ts\n * const decoder = getUnionDecoder(\n * [getU16Decoder(), getBooleanDecoder()],\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * decoder.decode(new Uint8Array([0x01])); // true\n * // Type is inferred as `number | boolean`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionDecoder<const TVariants extends readonly Decoder<any>[]>(\n variants: TVariants,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionDecoder<TVariants> {\n type TTo = GetDecoderTypeFromVariants<TVariants>;\n const fixedSize = getUnionFixedSize(variants);\n const read: Decoder<TTo>['read'] = (bytes, offset) => {\n const index = getIndexFromBytes(bytes, offset);\n assertValidVariantIndex(variants, index);\n return variants[index].read(bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createDecoder({ fixedSize, read }) as UnionDecoder<TVariants>;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createDecoder({ ...(maxSize !== null ? { maxSize } : {}), read }) as UnionDecoder<TVariants>;\n}\n\n/**\n * Returns a codec for encoding and decoding union types.\n *\n * This codec serializes and deserializes union values by selecting the correct variant\n * based on the provided index functions.\n *\n * Unlike the {@link getDiscriminatedUnionCodec}, this codec does not assume a stored\n * discriminator and must be used with an explicit mechanism for managing discriminators.\n *\n * @typeParam TVariants - An array of codecs, each corresponding to a union variant.\n *\n * @param variants - The codecs for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Codec` for encoding and decoding union values.\n *\n * @example\n * Encoding and decoding a union of numbers and booleans.\n * ```ts\n * const codec = getUnionCodec(\n * [getU16Codec(), getBooleanCodec()],\n * value => (typeof value === 'number' ? 0 : 1),\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * const bytes1 = codec.encode(42); // 0x2a00\n * const value1: number | boolean = codec.decode(bytes1); // 42\n *\n * const bytes2 = codec.encode(true); // 0x01\n * const value2: number | boolean = codec.decode(bytes2); // true\n * ```\n *\n * @remarks\n * If you need a codec that includes a stored discriminator,\n * consider using {@link getDiscriminatedUnionCodec}.\n *\n * Separate {@link getUnionEncoder} and {@link getUnionDecoder} functions are also available.\n *\n * ```ts\n * const bytes = getUnionEncoder(variantEncoders, getIndexFromValue).encode(42);\n * const value = getUnionDecoder(variantDecoders, getIndexFromBytes).decode(bytes);\n * ```\n *\n * @see {@link getUnionEncoder}\n * @see {@link getUnionDecoder}\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getUnionCodec<const TVariants extends readonly Codec<any>[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants<TVariants>) => number,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionCodec<TVariants> {\n return combineCodec(\n getUnionEncoder(variants, getIndexFromValue),\n getUnionDecoder(variants as readonly Decoder<any>[], getIndexFromBytes) as Decoder<\n GetDecoderTypeFromVariants<TVariants> & GetEncoderTypeFromVariants<TVariants>\n >,\n ) as UnionCodec<TVariants>;\n}\n\nfunction assertValidVariantIndex(variants: readonly unknown[], index: number) {\n if (typeof variants[index] === 'undefined') {\n throw new SolanaError(SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, {\n maxRange: variants.length - 1,\n minRange: 0,\n variant: index,\n });\n }\n}\n\nfunction getUnionFixedSize<const TVariants extends readonly (Decoder<any> | Encoder<any>)[]>(variants: TVariants) {\n if (variants.length === 0) return 0;\n if (!isFixedSize(variants[0])) return null;\n const variantSize = variants[0].fixedSize;\n const sameSizedVariants = variants.every(variant => isFixedSize(variant) && variant.fixedSize === variantSize);\n return sameSizedVariants ? variantSize : null;\n}\n\nfunction getUnionMaxSize<const TVariants extends readonly (Decoder<any> | Encoder<any>)[]>(variants: TVariants) {\n return maxCodecSizes(variants.map(variant => getMaxSize(variant)));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for `void` values.\n *\n * This encoder writes nothing to the byte array and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op encoder,\n * such as empty variants in {@link getDiscriminatedUnionEncoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeEncoder<void, 0>`, representing an empty encoder.\n *\n * @example\n * Encoding a `void` value.\n * ```ts\n * getUnitEncoder().encode(undefined); // Produces an empty byte array.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitEncoder(): FixedSizeEncoder<void, 0> {\n return createEncoder({\n fixedSize: 0,\n write: (_value, _bytes, offset) => offset,\n });\n}\n\n/**\n * Returns a decoder for `void` values.\n *\n * This decoder always returns `undefined` and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op decoder,\n * such as empty variants in {@link getDiscriminatedUnionDecoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeDecoder<void, 0>`, representing an empty decoder.\n *\n * @example\n * Decoding a `void` value.\n * ```ts\n * getUnitDecoder().decode(anyBytes); // Returns `undefined`.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitDecoder(): FixedSizeDecoder<void, 0> {\n return createDecoder({\n fixedSize: 0,\n read: (_bytes: ReadonlyUint8Array | Uint8Array, offset) => [undefined, offset],\n });\n}\n\n/**\n * Returns a codec for `void` values.\n *\n * This codec does nothing when encoding or decoding and has a fixed size of 0 bytes.\n * Namely, it always returns `undefined` when decoding and produces an empty byte array when encoding.\n *\n * This can be useful when working with structures that require a no-op codec,\n * such as empty variants in {@link getDiscriminatedUnionCodec}.\n *\n * @returns A `FixedSizeCodec<void, void, 0>`, representing an empty codec.\n *\n * @example\n * Encoding and decoding a `void` value.\n * ```ts\n * const codec = getUnitCodec();\n *\n * codec.encode(undefined); // Produces an empty byte array.\n * codec.decode(new Uint8Array([])); // Returns `undefined`.\n * ```\n *\n * @example\n * Using unit codecs as empty variants in a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Enter' }\n * | { __kind: 'Leave' }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * const messageCodec = getDiscriminatedUnionCodec([\n * ['Enter', getUnitCodec()], // <- No-op codec for empty data\n * ['Leave', getUnitCodec()], // <- No-op codec for empty data\n * ['Move', getStructCodec([...])]\n * ]);\n * ```\n *\n * @remarks\n * Separate {@link getUnitEncoder} and {@link getUnitDecoder} functions are available.\n *\n * ```ts\n * const bytes = getUnitEncoder().encode();\n * const value = getUnitDecoder().decode(bytes);\n * ```\n *\n * @see {@link getUnitEncoder}\n * @see {@link getUnitDecoder}\n */\nexport function getUnitCodec(): FixedSizeCodec<void, void, 0> {\n return combineCodec(getUnitEncoder(), getUnitDecoder());\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Represents a collection of named fields used in struct codecs.\n *\n * Each field is defined as a tuple containing:\n * - A string key representing the field name.\n * - A codec used to encode and decode the field's value.\n *\n * @typeParam T - The codec type used for each field.\n */\ntype Fields<T> = readonly (readonly [string, T])[];\n\ntype ArrayIndices<T extends readonly unknown[]> = Exclude<Partial<T>['length'], T['length']> & number;\n\n/**\n * Infers the TypeScript type for an object that can be encoded using a struct codec.\n *\n * This type maps the provided field encoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n */\ntype GetEncoderTypeFromFields<TFields extends Fields<Encoder<any>>> = DrainOuterGeneric<{\n [I in ArrayIndices<TFields> as TFields[I][0]]: TFields[I][1] extends Encoder<infer TFrom> ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for an object that can be decoded using a struct codec.\n *\n * This type maps the provided field decoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n */\ntype GetDecoderTypeFromFields<TFields extends Fields<Decoder<any>>> = DrainOuterGeneric<{\n [I in ArrayIndices<TFields> as TFields[I][0]]: TFields[I][1] extends Decoder<infer TTo> ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for custom objects.\n *\n * This encoder serializes an object by encoding its fields sequentially,\n * using the provided field encoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n *\n * @param fields - The name and encoder of each field.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding custom objects.\n *\n * @example\n * Encoding a custom struct.\n * ```ts\n * const encoder = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]);\n *\n * const bytes = encoder.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructEncoder<const TFields extends Fields<FixedSizeEncoder<any>>>(\n fields: TFields,\n): FixedSizeEncoder<GetEncoderTypeFromFields<TFields>>;\nexport function getStructEncoder<const TFields extends Fields<Encoder<any>>>(\n fields: TFields,\n): VariableSizeEncoder<GetEncoderTypeFromFields<TFields>>;\nexport function getStructEncoder<const TFields extends Fields<Encoder<any>>>(\n fields: TFields,\n): Encoder<GetEncoderTypeFromFields<TFields>> {\n type TFrom = GetEncoderTypeFromFields<TFields>;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n fields\n .map(([key, codec]) => getEncodedSize(value[key as keyof TFrom], codec))\n .reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (struct: TFrom, bytes, offset) => {\n fields.forEach(([key, codec]) => {\n offset = codec.write(struct[key as keyof TFrom], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for custom objects.\n *\n * This decoder deserializes an object by decoding its fields sequentially,\n * using the provided field decoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n *\n * @param fields - The name and decoder of each field.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding custom objects.\n *\n * @example\n * Decoding a custom struct.\n * ```ts\n * const decoder = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]);\n *\n * const struct = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructDecoder<const TFields extends Fields<FixedSizeDecoder<any>>>(\n fields: TFields,\n): FixedSizeDecoder<GetDecoderTypeFromFields<TFields>>;\nexport function getStructDecoder<const TFields extends Fields<Decoder<any>>>(\n fields: TFields,\n): VariableSizeDecoder<GetDecoderTypeFromFields<TFields>>;\nexport function getStructDecoder<const TFields extends Fields<Decoder<any>>>(\n fields: TFields,\n): Decoder<GetDecoderTypeFromFields<TFields>> {\n type TTo = GetDecoderTypeFromFields<TFields>;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const struct = {} as TTo;\n fields.forEach(([key, codec]) => {\n const [value, newOffset] = codec.read(bytes, offset);\n offset = newOffset;\n struct[key as keyof TTo] = value;\n });\n return [struct, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding custom objects.\n *\n * This codec serializes objects by encoding and decoding each field sequentially.\n *\n * @typeParam TFields - The fields of the struct, each paired with a codec.\n *\n * @param fields - The name and codec of each field.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding custom objects.\n *\n * @example\n * Encoding and decoding a custom struct.\n * ```ts\n * const codec = getStructCodec([\n * ['name', fixCodecSize(getUtf8Codec(), 5)],\n * ['age', getU8Codec()]\n * ]);\n *\n * const bytes = codec.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n *\n * const struct = codec.decode(bytes);\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @remarks\n * Separate {@link getStructEncoder} and {@link getStructDecoder} functions are available.\n *\n * ```ts\n * const bytes = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]).encode({ name: 'Alice', age: 42 });\n *\n * const struct = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getStructEncoder}\n * @see {@link getStructDecoder}\n */\nexport function getStructCodec<const TFields extends Fields<FixedSizeCodec<any>>>(\n fields: TFields,\n): FixedSizeCodec<\n GetEncoderTypeFromFields<TFields>,\n GetDecoderTypeFromFields<TFields> & GetEncoderTypeFromFields<TFields>\n>;\nexport function getStructCodec<const TFields extends Fields<Codec<any>>>(\n fields: TFields,\n): VariableSizeCodec<\n GetEncoderTypeFromFields<TFields>,\n GetDecoderTypeFromFields<TFields> & GetEncoderTypeFromFields<TFields>\n>;\nexport function getStructCodec<const TFields extends Fields<Codec<any>>>(\n fields: TFields,\n): Codec<GetEncoderTypeFromFields<TFields>, GetDecoderTypeFromFields<TFields> & GetEncoderTypeFromFields<TFields>> {\n return combineCodec(\n getStructEncoder(fields),\n getStructDecoder(fields) as Decoder<GetDecoderTypeFromFields<TFields> & GetEncoderTypeFromFields<TFields>>,\n );\n}\n","/**\n * An implementation of the Rust `Option<T>` type in JavaScript.\n *\n * In Rust, optional values are represented using `Option<T>`, which can be either:\n * - `Some(T)`, indicating a present value.\n * - `None`, indicating the absence of a value.\n *\n * In JavaScript, this is typically represented as `T | null`. However, this approach fails with nested options.\n * For example, `Option<Option<T>>` in Rust would translate to `T | null | null` in JavaScript, which is equivalent to `T | null`.\n * This means there is no way to differentiate between `Some(None)` and `None`, making nested options impossible.\n *\n * This `Option` type helps solve this by mirroring Rust’s `Option<T>` type.\n *\n * ```ts\n * type Option<T> = Some<T> | None;\n * type Some<T> = { __option: 'Some'; value: T };\n * type None = { __option: 'None' };\n * ```\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Here's how you can create `Option` values.\n *\n * To improve developer experience, helper functions are available.\n * TypeScript can infer the type of `T` or it can be explicitly provided.\n *\n * ```ts\n * // Create an option with a value.\n * some('Hello World');\n * some<number | string>(123);\n *\n * // Create an empty option.\n * none();\n * none<number | string>();\n * ```\n *\n * @see {@link Some}\n * @see {@link None}\n * @see {@link some}\n * @see {@link none}\n */\nexport type Option<T> = None | Some<T>;\n\n/**\n * A flexible type that allows working with {@link Option} values or nullable values.\n *\n * It defines a looser type that can be used when encoding {@link Option | Options}.\n * This allows us to pass `null` or the nested value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Accepting both `Option<T>` and `T | null` as input.\n * ```ts\n * function double(value: OptionOrNullable<number>) {\n * const option = isOption(value) ? value : wrapNullable(value);\n * return isSome(option) ? option.value * 2 : 'No value';\n * }\n *\n * double(42); // 84\n * double(some(21)); // 42\n * double(none()); // \"No value\"\n * double(null); // \"No value\"\n * ```\n *\n * @see {@link Option}\n * @see {@link isOption}\n * @see {@link wrapNullable}\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an {@link Option} that contains a value.\n *\n * This type mirrors Rust’s `Some(T)`, indicating that a value is present.\n *\n * For more details, see {@link Option}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Creating a `Some` value.\n * ```ts\n * const value = some(42);\n * isSome(value); // true\n * isNone(value); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link some}\n * @see {@link isSome}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an {@link Option} that contains no value.\n *\n * This type mirrors Rust’s `None`, indicating the absence of a value.\n *\n * For more details, see {@link Option}.\n *\n * @example\n * Creating a `None` value.\n * ```ts\n * const empty = none();\n * isNone(empty); // true\n * isSome(empty); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link none}\n * @see {@link isNone}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} that contains a value.\n *\n * This function explicitly wraps a value in an {@link Option} type.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param value - The value to wrap in an {@link Option}.\n * @returns An {@link Option} containing the provided value.\n *\n * @example\n * Wrapping a value in an `Option`.\n * ```ts\n * const option = some('Hello');\n * option.value; // \"Hello\"\n * isOption(option); // true\n * isSome(option); // true\n * isNone(option); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} that contains no value.\n *\n * This function explicitly represents an absent value.\n *\n * @typeParam T - The type of the expected absent value.\n *\n * @returns An {@link Option} containing no value.\n *\n * @example\n * Creating an empty `Option`.\n * ```ts\n * const empty = none<number>();\n * isOption(empty); // true\n * isSome(empty); // false\n * isNone(empty); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Checks whether the given value is an {@link Option}.\n *\n * This function determines whether an input follows the `Option<T>` structure.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param input - The value to check.\n * @returns `true` if the value is an {@link Option}, `false` otherwise.\n *\n * @example\n * Checking for `Option` values.\n * ```ts\n * isOption(some(42)); // true\n * isOption(none()); // true\n * isOption(42); // false\n * isOption(null); // false\n * isOption(\"anything else\"); // false\n * ```\n *\n * @see {@link Option}\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Checks whether the given {@link Option} contains a value.\n *\n * This function acts as a type guard, ensuring the value is a {@link Some}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link Some}, `false` otherwise.\n *\n * @example\n * Checking for `Some` values.\n * ```ts\n * isSome(some(42)); // true\n * isSome(none()); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Checks whether the given {@link Option} contains no value.\n *\n * This function acts as a type guard, ensuring the value is a {@link None}.\n *\n * @typeParam T - The type of the expected value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link None}, `false` otherwise.\n *\n * @example\n * Checking for `None` values.\n * ```ts\n * isNone(some(42)); // false\n * isNone(none()); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n containsBytes,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getBooleanDecoder,\n getBooleanEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getTupleDecoder,\n getTupleEncoder,\n getUnionDecoder,\n getUnionEncoder,\n getUnitDecoder,\n getUnitEncoder,\n} from '@solana/codecs-data-structures';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { isOption, isSome, None, none, Option, OptionOrNullable, Some, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/**\n * Defines the configuration options for {@link Option} codecs.\n *\n * The `getOptionCodec` function behaves similarly to {@link getNullableCodec}\n * but encodes `Option<T>` types instead of `T | null` types.\n *\n * This configuration controls how {@link None} values are encoded and how presence\n * is determined when decoding.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used as the presence prefix.\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n * @see {@link getOptionCodec}\n */\nexport type OptionCodecConfig<TPrefix extends NumberCodec | NumberDecoder | NumberEncoder> = {\n /**\n * Specifies how {@link None} values are represented in the encoded data.\n *\n * - By default, {@link None} values are omitted from encoding.\n * - `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec for the item.\n * - Custom byte array: {@link None} values are replaced with a predefined byte sequence. This results in a variable-size codec.\n *\n * @defaultValue No explicit `noneValue` is used; {@link None} values are omitted.\n */\n noneValue?: ReadonlyUint8Array | 'zeroes';\n\n /**\n * The presence prefix used to distinguish between {@link None} and present values.\n *\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - Custom number codec: Allows defining a different number size for the prefix.\n * - `null`: No prefix is used; `noneValue` (if provided) determines {@link None}.\n * If no `noneValue` is set, {@link None} is identified by the absence of bytes.\n *\n * @defaultValue `u8` prefix.\n */\n prefix?: TPrefix | null;\n};\n\n/**\n * Returns an encoder for optional values using the {@link Option} type.\n *\n * This encoder serializes an {@link OptionOrNullable} value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, {@link None} values are encoded as zeroes.\n * - If `noneValue` is a byte array, {@link None} values are replaced with the provided constant.\n *\n * Unlike {@link getNullableEncoder}, this encoder accepts both {@link Option} and {@link Nullable} values.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param item - The encoder for the value that may be present.\n * @param config - Configuration options for encoding optional values.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding option values.\n *\n * @example\n * Encoding an optional string.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const encoder = getOptionEncoder(stringCodec);\n *\n * encoder.encode(some('Hi'));\n * encoder.encode('Hi');\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * encoder.encode(none());\n * encoder.encode(null);\n * // 0x00\n * // └-- 1-byte prefix (None).\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionEncoder<TFrom, TSize extends number>(\n item: FixedSizeEncoder<TFrom, TSize>,\n config: OptionCodecConfig<NumberEncoder> & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeEncoder<OptionOrNullable<TFrom>, TSize>;\nexport function getOptionEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: OptionCodecConfig<FixedSizeNumberEncoder> & { noneValue: 'zeroes' },\n): FixedSizeEncoder<OptionOrNullable<TFrom>>;\nexport function getOptionEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: OptionCodecConfig<NumberEncoder> & { noneValue: 'zeroes' },\n): VariableSizeEncoder<OptionOrNullable<TFrom>>;\nexport function getOptionEncoder<TFrom>(\n item: Encoder<TFrom>,\n config?: OptionCodecConfig<NumberEncoder> & { noneValue?: ReadonlyUint8Array },\n): VariableSizeEncoder<OptionOrNullable<TFrom>>;\nexport function getOptionEncoder<TFrom>(\n item: Encoder<TFrom>,\n config: OptionCodecConfig<NumberEncoder> = {},\n): Encoder<OptionOrNullable<TFrom>> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformEncoder(getUnitEncoder(), (_boolean: boolean) => undefined);\n }\n return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixEncoderSize(getUnitEncoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitEncoder();\n }\n return getConstantEncoder(config.noneValue);\n })();\n\n return getUnionEncoder(\n [\n transformEncoder(getTupleEncoder([prefix, noneValue]), (_value: None | null): [boolean, void] => [\n false,\n undefined,\n ]),\n transformEncoder(getTupleEncoder([prefix, item]), (value: Some<TFrom> | TFrom): [boolean, TFrom] => [\n true,\n isOption(value) && isSome(value) ? value.value : value,\n ]),\n ],\n variant => {\n const option = isOption<TFrom>(variant) ? variant : wrapNullable(variant);\n return Number(isSome(option));\n },\n );\n}\n\n/**\n * Returns a decoder for optional values using the {@link Option} type.\n *\n * This decoder deserializes an `Option<T>` value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `None` values are identified by zeroes.\n * - If `noneValue` is a byte array, `None` values match the provided constant.\n *\n * Unlike {@link getNullableDecoder}, this decoder always outputs an {@link Option} type.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The decoder for the value that may be present.\n * @param config - Configuration options for decoding optional values.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding option values.\n *\n * @example\n * Decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const decoder = getOptionDecoder(stringCodec);\n *\n * decoder.decode(new Uint8Array([0x01, 0x02, 0x00, 0x00, 0x00, 0x48, 0x69]));\n * // some('Hi')\n *\n * decoder.decode(new Uint8Array([0x00]));\n * // none()\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionDecoder<TTo, TSize extends number>(\n item: FixedSizeDecoder<TTo, TSize>,\n config: OptionCodecConfig<NumberDecoder> & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeDecoder<Option<TTo>, TSize>;\nexport function getOptionDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: OptionCodecConfig<FixedSizeNumberDecoder> & { noneValue: 'zeroes' },\n): FixedSizeDecoder<Option<TTo>>;\nexport function getOptionDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: OptionCodecConfig<NumberDecoder> & { noneValue: 'zeroes' },\n): VariableSizeDecoder<Option<TTo>>;\nexport function getOptionDecoder<TTo>(\n item: Decoder<TTo>,\n config?: OptionCodecConfig<NumberDecoder> & { noneValue?: ReadonlyUint8Array },\n): VariableSizeDecoder<Option<TTo>>;\nexport function getOptionDecoder<TTo>(\n item: Decoder<TTo>,\n config: OptionCodecConfig<NumberDecoder> = {},\n): Decoder<Option<TTo>> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformDecoder(getUnitDecoder(), () => false);\n }\n return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixDecoderSize(getUnitDecoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitDecoder();\n }\n return getConstantDecoder(config.noneValue);\n })();\n\n return getUnionDecoder(\n [\n transformDecoder(getTupleDecoder([prefix, noneValue]), () => none<TTo>()),\n transformDecoder(getTupleDecoder([prefix, item]), ([, value]) => some(value)),\n ],\n (bytes, offset) => {\n if (config.prefix === null && !config.noneValue) {\n return Number(offset < bytes.length);\n }\n if (config.prefix === null && config.noneValue != null) {\n const zeroValue =\n config.noneValue === 'zeroes' ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;\n return containsBytes(bytes, zeroValue, offset) ? 0 : 1;\n }\n return Number(prefix.read(bytes, offset)[0]);\n },\n );\n}\n\n/**\n * Returns a codec for encoding and decoding optional values using the {@link Option} type.\n *\n * This codec serializes and deserializes `Option<T>` values using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - If `noneValue: 'zeroes'` is set, `None` values are encoded/decoded as zeroes.\n * - If `noneValue` is a byte array, `None` values are represented by the provided constant.\n * - If `prefix: null` is set, the codec determines `None` values solely from `noneValue` or the presence of bytes.\n *\n * For more details on the configuration options, see {@link OptionCodecConfig}.\n *\n * Note that this behaves similarly to {@link getNullableCodec}, except it\n * encodes {@link OptionOrNullable} values and decodes {@link Option} values.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The codec for the value that may be present.\n * @param config - Configuration options for encoding and decoding option values.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding option values.\n *\n * @example\n * Encoding and decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode(some('Hi'));\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * const noneBytes = codec.encode(none());\n * // 0x00\n * // └-- 1-byte prefix (None).\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding nullable values.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode('Hi'); // 0x01020000004869\n * const noneBytes = codec.encode(null); // 0x00\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding an optional number with a fixed size.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { noneValue: 'zeroes' });\n *\n * const someBytes = codec.encode(some(42)); // 0x012a00\n * const noneBytes = codec.encode(none()); // 0x000000\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding {@link None} values with a custom byte sequence and no prefix.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), {\n * noneValue: new Uint8Array([0xff, 0xff]),\n * prefix: null,\n * });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // 0xffff\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Identifying {@link None} values by the absence of bytes.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { prefix: null });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // new Uint8Array(0)\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @remarks\n * Separate {@link getOptionEncoder} and {@link getOptionDecoder} functions are available.\n *\n * ```ts\n * const bytes = getOptionEncoder(getU32Encoder()).encode(some(42));\n * const value = getOptionDecoder(getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n */\nexport function getOptionCodec<TFrom, TTo extends TFrom, TSize extends number>(\n item: FixedSizeCodec<TFrom, TTo, TSize>,\n config: OptionCodecConfig<NumberCodec> & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeCodec<OptionOrNullable<TFrom>, Option<TTo>, TSize>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: OptionCodecConfig<FixedSizeNumberCodec> & { noneValue: 'zeroes' },\n): FixedSizeCodec<OptionOrNullable<TFrom>, Option<TTo>>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: OptionCodecConfig<NumberCodec> & { noneValue: 'zeroes' },\n): VariableSizeCodec<OptionOrNullable<TFrom>, Option<TTo>>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config?: OptionCodecConfig<NumberCodec> & { noneValue?: ReadonlyUint8Array },\n): VariableSizeCodec<OptionOrNullable<TFrom>, Option<TTo>>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: OptionCodecConfig<NumberCodec> = {},\n): Codec<OptionOrNullable<TFrom>, Option<TTo>> {\n type ConfigCast = OptionCodecConfig<NumberCodec> & { noneValue?: ReadonlyUint8Array };\n return combineCodec(\n getOptionEncoder<TFrom>(item, config as ConfigCast),\n getOptionDecoder<TTo>(item, config as ConfigCast),\n );\n}\n","/**\n * A pipeline is a solution that allows you to perform successive transforms of a value using functions. This is useful when building up a transaction message.\n *\n * Until the [pipeline operator](https://github.com/tc39/proposal-pipeline-operator) becomes part of JavaScript you can use this utility to create pipelines.\n *\n * Following common implementations of pipe functions that use TypeScript, this function supports a maximum arity of 10 for type safety.\n *\n * Note you can use nested pipes to extend this limitation, like so:\n * ```ts\n * const myValue = pipe(\n * pipe(\n * 1,\n * (x) => x + 1,\n * (x) => x * 2,\n * (x) => x - 1,\n * ),\n * (y) => y / 3,\n * (y) => y + 1,\n * );\n * ```\n *\n * @see https://github.com/ramda/ramda/blob/master/source/pipe.js\n * @see https://github.com/darky/rocket-pipes/blob/master/index.ts\n *\n * @example Basic\n * ```ts\n * const add = (a, b) => a + b;\n * const add10 = x => add(x, 10);\n * const add100 = x => add(x, 100);\n * const sum = pipe(1, add10, add100);\n * sum === 111; // true\n * ```\n *\n * @example Building a Solana transaction message\n * ```ts\n * const transferTransactionMessage = pipe(\n * // The result of the first expression...\n * createTransactionMessage({ version: 0 }),\n * // ...gets passed as the sole argument to the next function in the pipeline.\n * tx => setTransactionMessageFeePayer(myAddress, tx),\n * // The return value of that function gets passed to the next...\n * tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n * // ...and so on.\n * tx => appendTransactionMessageInstruction(createTransferInstruction(myAddress, toAddress, amountInLamports), tx),\n * );\n * ```\n *\n * @returns The initial value\n */\nexport function pipe<TInitial>(\n /** The initial value */\n init: TInitial,\n): TInitial;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n): R1;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1, R2>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n): R2;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1, R2, R3>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n): R3;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1, R2, R3, R4>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n): R4;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1, R2, R3, R4, R5>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n): R5;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n): R6;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n): R7;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n): R8;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n): R9;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe<TInitial, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10>(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n /** The function with which to transform the return value of the prior function */\n r9_r10: (r9: R9) => R10,\n): R10;\nexport function pipe<TInitial>(init: TInitial, ...fns: CallableFunction[]) {\n return fns.reduce((acc, fn) => fn(acc), init);\n}\n","/**\n * Describes the purpose for which an account participates in a transaction.\n *\n * Every account that participates in a transaction can be read from, but only ones that you mark as\n * writable may be written to, and only ones that you indicate must sign the transaction will gain\n * the privileges associated with signers at runtime.\n *\n * | | `isSigner` | `isWritable` |\n * | ----------------------------- | ---------- | ------------ |\n * | `AccountRole.READONLY` | ❌ | ❌ |\n * | `AccountRole.WRITABLE` | ❌ | ✅ |\n * | `AccountRole.READONLY_SIGNER` | ✅ | ❌ |\n * | `AccountRole.WRITABLE_SIGNER` | ✅ | ✅ |\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\n// Quick primer on bitwise operations: https://stackoverflow.com/a/1436448/802047\nconst IS_SIGNER_BITMASK = 0b10;\nconst IS_WRITABLE_BITMASK = 0b01;\n\n/**\n * @returns An {@link AccountRole} representing the non-signer variant of the supplied role.\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\n/**\n * @returns An {@link AccountRole} representing the read-only variant of the supplied role.\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\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a signer. Also refines the\n * TypeScript type of the supplied role.\n */\nexport function isSignerRole(role: AccountRole): role is AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER {\n return role >= AccountRole.READONLY_SIGNER;\n}\n\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a writable account. Also\n * refines the TypeScript type of the supplied role.\n */\nexport function isWritableRole(role: AccountRole): role is AccountRole.WRITABLE | AccountRole.WRITABLE_SIGNER {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\n\n/**\n * Given two {@link AccountRole | AccountRoles}, will return the {@link AccountRole} that grants the\n * highest privileges of both.\n *\n * @example\n * ```ts\n * // Returns `AccountRole.WRITABLE_SIGNER`\n * mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE);\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\n/**\n * @returns An {@link AccountRole} representing the signer variant of the supplied role.\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\n/**\n * @returns An {@link AccountRole} representing the writable variant of the supplied role.\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 { Address, assertIsAddress, getAddressDecoder, getAddressEncoder, isAddress } from '@solana/addresses';\nimport { combineCodec, createEncoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nexport type Blockhash = Brand<EncodedString<string, 'base58'>, 'Blockhash'>;\n\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Blockhash} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isBlockhash } from '@solana/rpc-types';\n *\n * if (isBlockhash(blockhash)) {\n * // At this point, `blockhash` has been refined to a\n * // `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsFresh(isValid);\n * } else {\n * setError(`${blockhash} is not a blockhash`);\n * }\n * ```\n */\nexport function isBlockhash(putativeBlockhash: string): putativeBlockhash is Blockhash {\n return isAddress(putativeBlockhash);\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as a blockhash, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string is\n * a base58-encoded blockhash.\n *\n * @example\n * ```ts\n * import { assertIsBlockhash } from '@solana/rpc-types';\n *\n * // Imagine a function that determines whether a blockhash is fresh when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const blockhash: string = blockhashInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `blockhash` to `Blockhash`.\n * assertIsBlockhash(blockhash);\n * // At this point, `blockhash` is a `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `blockhash` turned out not to be a base58-encoded blockhash\n * }\n * }\n * ```\n */\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n try {\n assertIsAddress(putativeBlockhash);\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {\n throw new SolanaError(SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, error.context);\n }\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {\n throw new SolanaError(SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, error.context);\n }\n throw error;\n }\n}\n\n/**\n * Combines _asserting_ that a string is a blockhash with _coercing_ it to the {@link Blockhash}\n * type. It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { blockhash } from '@solana/rpc-types';\n *\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash(blockhashFromUserInput)).send();\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good blockhash as a string, it's more efficient to typecast it\n * rather than to use the {@link blockhash} helper, because the helper unconditionally performs\n * validation on its input.\n * >\n * > ```ts\n * > import { Blockhash } from '@solana/rpc-types';\n * >\n * > const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * > ```\n */\nexport function blockhash(putativeBlockhash: string): Blockhash {\n assertIsBlockhash(putativeBlockhash);\n return putativeBlockhash;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded blockhash to a byte array.\n *\n * @example\n * ```ts\n * import { getBlockhashEncoder } from '@solana/rpc-types';\n *\n * const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * const blockhashEncoder = getBlockhashEncoder();\n * const blockhashBytes = blockhashEncoder.encode(blockhash);\n * // Uint8Array(32) [\n * // 136, 123, 44, 249, 43, 19, 60, 14,\n * // 144, 16, 168, 241, 121, 111, 70, 232,\n * // 186, 26, 140, 202, 213, 64, 231, 82,\n * // 179, 66, 103, 237, 52, 117, 217, 93\n * // ]\n * ```\n */\nexport function getBlockhashEncoder(): FixedSizeEncoder<Blockhash, 32> {\n const addressEncoder = getAddressEncoder();\n return createEncoder({\n fixedSize: 32,\n write: (value: string, bytes, offset) => {\n assertIsBlockhash(value);\n return addressEncoder.write(value as string as Address, bytes, offset);\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing a blockhash to\n * the base58-encoded representation of that blockhash.\n *\n * @example\n * ```ts\n * import { getBlockhashDecoder } from '@solana/rpc-types';\n *\n * const blockhashBytes = new Uint8Array([\n * 136, 123, 44, 249, 43, 19, 60, 14,\n * 144, 16, 168, 241, 121, 111, 70, 232,\n * 186, 26, 140, 202, 213, 64, 231, 82,\n * 179, 66, 103, 237, 52, 117, 217, 93\n * ]);\n * const blockhashDecoder = getBlockhashDecoder();\n * const blockhash = blockhashDecoder.decode(blockhashBytes); // ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48\n * ```\n */\nexport function getBlockhashDecoder(): FixedSizeDecoder<Blockhash, 32> {\n return getAddressDecoder() as FixedSizeDecoder<string, 32> as FixedSizeDecoder<Blockhash, 32>;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded blockhash.\n *\n * @see {@link getBlockhashDecoder}\n * @see {@link getBlockhashEncoder}\n */\nexport function getBlockhashCodec(): FixedSizeCodec<Blockhash, Blockhash, 32> {\n return combineCodec(getBlockhashEncoder(), getBlockhashDecoder());\n}\n\nexport function getBlockhashComparator(): (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 { SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME, SolanaError } from '@solana/errors';\nimport { type Blockhash, isBlockhash } from '@solana/rpc-types';\n\nimport { ExcludeTransactionMessageLifetime, TransactionMessageWithLifetime } from './lifetime';\nimport { BaseTransactionMessage } from './transaction-message';\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network. The transaction message will continue to be eligible to land\n * until the network considers the `blockhash` to be expired.\n *\n * This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash\n * is considered valid, or when the network switches to a fork where that blockhash is not present.\n */\ntype BlockhashLifetimeConstraint = Readonly<{\n /**\n * A recent blockhash observed by the transaction proposer.\n *\n * The transaction message will be considered eligible to land until the network determines this\n * blockhash to be too old, or has switched to a fork where it is not present.\n */\n blockhash: Blockhash;\n /**\n * This is the block height beyond which the network will consider the blockhash to be too old\n * to make a transaction message eligible to land.\n */\n lastValidBlockHeight: bigint;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the age of the blockhash it\n * includes.\n *\n * Such a transaction can only be landed on the network if the current block height of the network\n * is less than or equal to the value of\n * `TransactionMessageWithBlockhashLifetime['lifetimeConstraint']['lastValidBlockHeight']`.\n */\nexport interface TransactionMessageWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithBlockhashLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * if (isTransactionMessageWithBlockhashLifetime(message)) {\n * // At this point, `message` has been refined to a `TransactionMessageWithBlockhashLifetime`.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsValid(blockhashIsValid);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithBlockhashLifetime(\n transactionMessage: BaseTransactionMessage | (BaseTransactionMessage & TransactionMessageWithBlockhashLifetime),\n): transactionMessage is BaseTransactionMessage & TransactionMessageWithBlockhashLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.blockhash === 'string' &&\n typeof transactionMessage.lifetimeConstraint.lastValidBlockHeight === 'bigint' &&\n isBlockhash(transactionMessage.lifetimeConstraint.blockhash)\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * blockhash-based lifetime, from an untrusted network API or user input. Use this function to\n * assert that such a transaction message actually has a blockhash-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithBlockhashLifetime`.\n * assertIsTransactionMessageWithBlockhashLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithBlockhashLifetime` that can be used\n * // with the RPC.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `message` turned out not to have a blockhash-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithBlockhashLifetime(\n transactionMessage: BaseTransactionMessage | (BaseTransactionMessage & TransactionMessageWithBlockhashLifetime),\n): asserts transactionMessage is BaseTransactionMessage & TransactionMessageWithBlockhashLifetime {\n if (!isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);\n }\n}\n\n/**\n * Given a blockhash and the last block height at which that blockhash is considered usable to land\n * transactions, this method will return a new transaction message having the same type as the one\n * supplied plus the `TransactionMessageWithBlockhashLifetime` type.\n *\n * @example\n * ```ts\n * import { setTransactionMessageLifetimeUsingBlockhash } from '@solana/transaction-messages';\n *\n * const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n * const txMessageWithBlockhashLifetime = setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, txMessage);\n * ```\n */\nexport function setTransactionMessageLifetimeUsingBlockhash<\n TTransactionMessage extends BaseTransactionMessage & Partial<TransactionMessageWithLifetime>,\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageLifetime<TTransactionMessage> & TransactionMessageWithBlockhashLifetime {\n type ReturnType = ExcludeTransactionMessageLifetime<TTransactionMessage> & TransactionMessageWithBlockhashLifetime;\n\n if (\n 'lifetimeConstraint' in transactionMessage &&\n transactionMessage.lifetimeConstraint &&\n 'blockhash' in transactionMessage.lifetimeConstraint &&\n transactionMessage.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transactionMessage.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transactionMessage as ReturnType;\n }\n\n return Object.freeze({\n ...transactionMessage,\n lifetimeConstraint: Object.freeze(blockhashLifetimeConstraint),\n }) as ReturnType;\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\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 * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder<string>` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\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 * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder<string>` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\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 * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec<string>` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\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 { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder<string>` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder<string>` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec<string>` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\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 const indexEncoder = getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() }) as Encoder<\n readonly number[]\n >;\n memoizedAddressTableLookupEncoder = getStructEncoder([\n ['lookupTableAddress', getAddressEncoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\n ]);\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: VariableSizeDecoder<AddressTableLookup> | undefined;\nexport function getAddressTableLookupDecoder(): VariableSizeDecoder<AddressTableLookup> {\n if (!memoizedAddressTableLookupDecoder) {\n const indexEncoder = getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() });\n memoizedAddressTableLookupDecoder = getStructDecoder([\n ['lookupTableAddress', getAddressDecoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\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 addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n transformDecoder,\n transformEncoder,\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 = transformEncoder<Required<Instruction>, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder()],\n ['accountIndices', getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],\n ['data', addEncoderSizePrefix(getBytesEncoder(), 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 = transformDecoder<Required<Instruction>, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder()],\n ['accountIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n [\n 'data',\n addDecoderSizePrefix(getBytesDecoder(), getShortU16Decoder()) as VariableSizeDecoder<Uint8Array>,\n ],\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 { AccountMeta, Instruction } from '@solana/instructions';\n\nexport type BaseTransactionMessage<\n TVersion extends TransactionVersion = TransactionVersion,\n TInstruction extends Instruction = Instruction,\n> = Readonly<{\n instructions: readonly TInstruction[];\n version: TVersion;\n}>;\n\nexport const MAX_SUPPORTED_TRANSACTION_VERSION = 0;\n\ntype LegacyInstruction<TProgramAddress extends string = string> = Instruction<TProgramAddress, readonly AccountMeta[]>;\ntype LegacyTransactionMessage = BaseTransactionMessage<'legacy', LegacyInstruction>;\ntype V0TransactionMessage = BaseTransactionMessage<0, Instruction>;\n\nexport type TransactionMessage = LegacyTransactionMessage | V0TransactionMessage;\nexport type TransactionVersion = 'legacy' | 0;\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { MAX_SUPPORTED_TRANSACTION_VERSION, TransactionVersion } from '../transaction-message';\n\nconst VERSION_FLAG_MASK = 0x80;\n\n/**\n * Returns an encoder that you can use to encode a {@link TransactionVersion} to a byte array.\n *\n * Legacy messages will produce an empty array and will not advance the offset. Versioned messages\n * will produce an array with a single byte.\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 throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, {\n actualVersion: value,\n });\n }\n\n if (value > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: value,\n });\n }\n bytes.set([value | VERSION_FLAG_MASK], offset);\n return offset + 1;\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link TransactionVersion}.\n *\n * When the byte at the current offset is determined to represent a legacy transaction, this decoder\n * will return `'legacy'` and will not advance the offset.\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;\n if (version > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n return [version as TransactionVersion, offset + 1];\n }\n },\n });\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link TransactionVersion}\n *\n * @see {@link getTransactionVersionDecoder}\n * @see {@link getTransactionVersionEncoder}\n */\nexport function getTransactionVersionCodec(): VariableSizeCodec<TransactionVersion> {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n createEncoder,\n Decoder,\n fixDecoderSize,\n fixEncoderSize,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getConstantEncoder,\n getStructDecoder,\n getStructEncoder,\n getUnionEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile/address-table-lookups';\nimport { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from '../compile/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<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return getStructEncoder(getPreludeStructEncoderTuple()) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >;\n}\n\nfunction getCompiledMessageVersionedEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return transformEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ]) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >,\n value => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n };\n },\n );\n}\n\nfunction getPreludeStructEncoderTuple() {\n const lifetimeTokenEncoder = getUnionEncoder(\n [\n // Use a 32-byte constant encoder for a missing lifetime token (index 0).\n getConstantEncoder(new Uint8Array(32)),\n // Use a 32-byte base58 encoder for a valid lifetime token (index 1).\n fixEncoderSize(getBase58Encoder(), 32),\n ],\n value => (value === undefined ? 0 : 1),\n );\n\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n ['staticAccounts', getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],\n ['lifetimeToken', lifetimeTokenEncoder],\n ['instructions', getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })],\n ] as const;\n}\n\nfunction getPreludeStructDecoderTuple() {\n return [\n ['version', getTransactionVersionDecoder() as Decoder<number>],\n ['header', getMessageHeaderDecoder()],\n ['staticAccounts', getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],\n ['lifetimeToken', fixDecoderSize(getBase58Decoder(), 32)],\n ['instructions', getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ] as const;\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });\n}\n\n/**\n * Returns an encoder that you can use to encode a {@link CompiledTransactionMessage} to a byte\n * array.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. The byte array produced by this encoder is the message part.\n */\nexport function getCompiledTransactionMessageEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\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}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link CompiledTransactionMessage}.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. You can use this decoder to decode the message part.\n */\nexport function getCompiledTransactionMessageDecoder(): VariableSizeDecoder<\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return transformDecoder(\n getStructDecoder(getPreludeStructDecoderTuple()) as VariableSizeDecoder<\n CompiledTransactionMessage &\n CompiledTransactionMessageWithLifetime & {\n addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups>;\n }\n >,\n ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups };\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link CompiledTransactionMessage}\n *\n * @see {@link getCompiledTransactionMessageDecoder}\n * @see {@link getCompiledTransactionMessageEncoder}\n */\nexport function getCompiledTransactionMessageCodec(): VariableSizeCodec<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime),\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return combineCodec(getCompiledTransactionMessageEncoder(), getCompiledTransactionMessageDecoder());\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SolanaError,\n} from '@solana/errors';\nimport {\n AccountLookupMeta,\n AccountMeta,\n AccountRole,\n Instruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\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 = Brand<(AccountLookupMeta | AccountMeta)[], 'OrderedAccounts'>;\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 | Record<never, never> | StaticAccountEntry,\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 Instruction[]): 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 throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, {\n programAddress: instruction.programAddress,\n });\n default:\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, {\n programAddress: instruction.programAddress,\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;\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;\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 throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n {\n programAddress: account.address,\n },\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry;\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;\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: (AccountLookupMeta | AccountMeta)[] = 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 '../compile/accounts';\n\ntype AddressTableLookup = Readonly<{\n /** The address of the address lookup table account. */\n lookupTableAddress: Address;\n /** Indexes of accounts in a lookup table to load as read-only. */\n readonlyIndexes: readonly number[];\n /** Indexes of accounts in a lookup table to load as writable. */\n writableIndexes: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Address,\n Readonly<{\n [K in keyof Omit<AddressTableLookup, 'lookupTableAddress'>]: number[];\n }>\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readonlyIndexes: [],\n writableIndexes: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndexes.push(account.addressIndex);\n } else {\n entry.readonlyIndexes.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 '../compile/accounts';\n\ntype MessageHeader = Readonly<{\n /**\n * The number of accounts in the static accounts list that are neither writable nor\n * signers.\n *\n * Adding this number to `numSignerAccounts` yields the index of the first read-only non-signer\n * account in the static accounts list.\n */\n numReadonlyNonSignerAccounts: number;\n /**\n * The number of read-only accounts in the static accounts list that must sign this\n * transaction.\n *\n * Subtracting this number from `numSignerAccounts` yields the index of the first read-only\n * signer account in the static accounts list.\n */\n numReadonlySignerAccounts: number;\n /**\n * The number of accounts in the static accounts list that must sign this transaction.\n *\n * Subtracting `numReadonlySignerAccounts` from this number yields the number of\n * writable signer accounts in the static accounts list. Writable signer accounts always\n * begin at index zero in the static accounts list.\n *\n * This number itself is the index of the first non-signer account in the static\n * accounts list.\n */\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 { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { Instruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n /**\n * An ordered list of indices that indicate which accounts in the transaction message's\n * accounts list are loaded by this instruction.\n */\n accountIndices?: number[];\n /** The input to the invoked program */\n data?: ReadonlyUint8Array;\n /**\n * The index of the address in the transaction message's accounts list associated with the\n * program to invoke.\n */\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 Instruction[],\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 { TransactionMessageWithBlockhashLifetime, TransactionMessageWithDurableNonceLifetime } from '../index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (\n | TransactionMessageWithBlockhashLifetime\n | TransactionMessageWithDurableNonceLifetime\n )['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 { TransactionMessageWithFeePayer } from '../fee-payer';\nimport { TransactionMessageWithLifetime } from '../lifetime';\nimport { BaseTransactionMessage } from '../transaction-message';\nimport { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { getCompiledAddressTableLookups } from './address-table-lookups';\nimport { getCompiledMessageHeader } from './header';\nimport { getCompiledInstructions } from './instructions';\nimport { getCompiledLifetimeToken } from './lifetime-token';\nimport { getCompiledStaticAccounts } from './static-accounts';\n\ntype BaseCompiledTransactionMessage = Readonly<{\n /**\n * Information about the version of the transaction message and the role of the accounts it\n * loads.\n */\n header: ReturnType<typeof getCompiledMessageHeader>;\n instructions: ReturnType<typeof getCompiledInstructions>;\n /** A list of addresses indicating which accounts to load */\n staticAccounts: ReturnType<typeof getCompiledStaticAccounts>;\n}>;\n\n/**\n * A transaction message in a form suitable for encoding for execution on the network.\n *\n * You can not fully reconstruct a source message from a compiled message without extra information.\n * In particular, supporting details about the lifetime constraint and the concrete addresses of\n * accounts sourced from account lookup tables are lost to compilation.\n */\nexport type CompiledTransactionMessage = LegacyCompiledTransactionMessage | VersionedCompiledTransactionMessage;\n\nexport type CompiledTransactionMessageWithLifetime = Readonly<{\n /**\n * 32 bytes of data observed by the transaction proposed that makes a transaction eligible to\n * land on the network.\n *\n * In the case of a transaction message with a nonce lifetime constraint, this will be the value\n * of the nonce itself. In all other cases this will be a recent blockhash.\n */\n lifetimeToken: ReturnType<typeof getCompiledLifetimeToken>;\n}>;\n\ntype LegacyCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n /** A list of address tables and the accounts that this transaction loads from them */\n addressTableLookups?: ReturnType<typeof getCompiledAddressTableLookups>;\n version: 0;\n }>;\n\n/**\n * Converts the type of transaction message data structure that you create in your application to\n * the type of transaction message data structure that can be encoded for execution on the network.\n *\n * This is a lossy process; you can not fully reconstruct a source message from a compiled message\n * without extra information. In particular, supporting details about the lifetime constraint and\n * the concrete addresses of accounts sourced from account lookup tables will be lost to\n * compilation.\n *\n * @see {@link decompileTransactionMessage}\n */\nexport function compileTransactionMessage<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): CompiledTransactionMessageFromTransactionMessage<TTransactionMessage> {\n type ReturnType = CompiledTransactionMessageFromTransactionMessage<TTransactionMessage>;\n\n const addressMap = getAddressMapFromInstructions(\n transactionMessage.feePayer.address,\n transactionMessage.instructions,\n );\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n const lifetimeConstraint = (transactionMessage as Partial<TransactionMessageWithLifetime>).lifetimeConstraint;\n\n return {\n ...(transactionMessage.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n ...(lifetimeConstraint ? { lifetimeToken: getCompiledLifetimeToken(lifetimeConstraint) } : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transactionMessage.instructions, orderedAccounts),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transactionMessage.version,\n } as ReturnType;\n}\n\ntype CompiledTransactionMessageFromTransactionMessage<TTransactionMessage extends BaseTransactionMessage> =\n ForwardTransactionMessageLifetime<ForwardTransactionMessageVersion<TTransactionMessage>, TTransactionMessage>;\n\ntype ForwardTransactionMessageVersion<TTransactionMessage extends BaseTransactionMessage> =\n TTransactionMessage extends Readonly<{ version: 'legacy' }>\n ? LegacyCompiledTransactionMessage\n : VersionedCompiledTransactionMessage;\n\ntype ForwardTransactionMessageLifetime<\n TCompiledTransactionMessage extends CompiledTransactionMessage,\n TTransactionMessage extends BaseTransactionMessage,\n> = TTransactionMessage extends TransactionMessageWithLifetime\n ? CompiledTransactionMessageWithLifetime & TCompiledTransactionMessage\n : TCompiledTransactionMessage;\n","import { Address } from '@solana/addresses';\nimport { AccountLookupMeta, AccountMeta, AccountRole, Instruction, isSignerRole } from '@solana/instructions';\n\nimport { AddressesByLookupTableAddress } from './addresses-by-lookup-table-address';\nimport { BaseTransactionMessage, TransactionMessage } from './transaction-message';\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\n// Look up the address in lookup tables, return a lookup meta if it is found in any of them\nfunction findAddressInLookupTables(\n address: Address,\n role: AccountRole.READONLY | AccountRole.WRITABLE,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): AccountLookupMeta | undefined {\n for (const [lookupTableAddress, addresses] of Object.entries(addressesByLookupTableAddress)) {\n for (let i = 0; i < addresses.length; i++) {\n if (address === addresses[i]) {\n return {\n address,\n addressIndex: i,\n lookupTableAddress: lookupTableAddress as Address,\n role,\n };\n }\n }\n }\n}\n\ntype TransactionMessageNotLegacy = Exclude<TransactionMessage, { version: 'legacy' }>;\n\n// Each account can be AccountLookupMeta | AccountMeta\ntype WidenInstructionAccounts<TInstruction extends Instruction> =\n TInstruction extends Instruction<infer TProgramAddress, infer TAccounts>\n ? Instruction<\n TProgramAddress,\n {\n [K in keyof TAccounts]: TAccounts[K] extends AccountMeta<infer TAddress>\n ? AccountLookupMeta<TAddress> | AccountMeta<TAddress>\n : TAccounts[K];\n }\n >\n : TInstruction;\n\ntype ExtractAdditionalProps<T, U> = Omit<T, keyof U>;\n\ntype WidenTransactionMessageInstructions<TTransactionMessage extends TransactionMessage> =\n TTransactionMessage extends BaseTransactionMessage<infer TVersion, infer TInstruction>\n ? BaseTransactionMessage<TVersion, WidenInstructionAccounts<TInstruction>> &\n ExtractAdditionalProps<\n TTransactionMessage,\n BaseTransactionMessage<TVersion, WidenInstructionAccounts<TInstruction>>\n >\n : TTransactionMessage;\n\n/**\n * Given a transaction message and a mapping of lookup tables to the addresses stored in them, this\n * function will return a new transaction message with the same instructions but with all non-signer\n * accounts that are found in the given lookup tables represented by an {@link AccountLookupMeta}\n * instead of an {@link AccountMeta}.\n *\n * This means that these accounts will take up less space in the compiled transaction message. This\n * size reduction is most significant when the transaction includes many accounts from the same\n * lookup table.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import {\n * AddressesByLookupTableAddress,\n * compressTransactionMessageUsingAddressLookupTables,\n * } from '@solana/transaction-messages';\n * import { fetchAddressLookupTable } from '@solana-program/address-lookup-table';\n *\n * const lookupTableAddress = address('4QwSwNriKPrz8DLW4ju5uxC2TN5cksJx6tPUPj7DGLAW');\n * const {\n * data: { addresses },\n * } = await fetchAddressLookupTable(rpc, lookupTableAddress);\n * const addressesByAddressLookupTable: AddressesByLookupTableAddress = {\n * [lookupTableAddress]: addresses,\n * };\n *\n * const compressedTransactionMessage = compressTransactionMessageUsingAddressLookupTables(\n * transactionMessage,\n * addressesByAddressLookupTable,\n * );\n * ```\n */\nexport function compressTransactionMessageUsingAddressLookupTables<\n TTransactionMessage extends TransactionMessageNotLegacy = TransactionMessageNotLegacy,\n>(\n transactionMessage: TTransactionMessage,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): TTransactionMessage | WidenTransactionMessageInstructions<TTransactionMessage> {\n const programAddresses = new Set(transactionMessage.instructions.map(ix => ix.programAddress));\n const eligibleLookupAddresses = new Set(\n Object.values(addressesByLookupTableAddress)\n .flatMap(a => a)\n .filter(address => !programAddresses.has(address)),\n );\n const newInstructions: Instruction[] = [];\n let updatedAnyInstructions = false;\n for (const instruction of transactionMessage.instructions) {\n if (!instruction.accounts) {\n newInstructions.push(instruction);\n continue;\n }\n\n const newAccounts: Mutable<NonNullable<Instruction['accounts']>> = [];\n let updatedAnyAccounts = false;\n for (const account of instruction.accounts) {\n // If the address is already a lookup, is not in any lookup tables, or is a signer role, return as-is\n if (\n 'lookupTableAddress' in account ||\n !eligibleLookupAddresses.has(account.address) ||\n isSignerRole(account.role)\n ) {\n newAccounts.push(account);\n continue;\n }\n\n // We already checked it's in one of the lookup tables\n const lookupMetaAccount = findAddressInLookupTables(\n account.address,\n account.role,\n addressesByLookupTableAddress,\n )!;\n newAccounts.push(Object.freeze(lookupMetaAccount));\n updatedAnyAccounts = true;\n updatedAnyInstructions = true;\n }\n\n newInstructions.push(\n Object.freeze(updatedAnyAccounts ? { ...instruction, accounts: newAccounts } : instruction),\n );\n }\n\n return Object.freeze(\n updatedAnyInstructions ? { ...transactionMessage, instructions: newInstructions } : transactionMessage,\n );\n}\n","import { TransactionMessage, TransactionVersion } from './transaction-message';\nimport { TransactionMessageWithinSizeLimit } from './transaction-message-size';\n\ntype TransactionConfig<TVersion extends TransactionVersion> = Readonly<{\n version: TVersion;\n}>;\n\ntype EmptyTransactionMessage<TVersion extends TransactionVersion> = Omit<\n Extract<TransactionMessage, { version: TVersion }>,\n 'instructions'\n> &\n TransactionMessageWithinSizeLimit & { instructions: readonly [] };\n\n/**\n * Given a {@link TransactionVersion} this method will return an empty transaction having the\n * capabilities of that version.\n *\n * @example\n * ```ts\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const message = createTransactionMessage({ version: 0 });\n * ```\n */\nexport function createTransactionMessage<TVersion extends TransactionVersion>(\n config: TransactionConfig<TVersion>,\n): EmptyTransactionMessage<TVersion> {\n return Object.freeze({\n instructions: Object.freeze([]),\n version: config.version,\n }) as EmptyTransactionMessage<TVersion>;\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n AccountRole,\n Instruction,\n InstructionWithAccounts,\n InstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nexport type AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n> = Instruction<'11111111111111111111111111111111'> &\n InstructionWithAccounts<\n readonly [\n WritableAccount<TNonceAccountAddress>,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount<TNonceAuthorityAddress> | WritableSignerAccount<TNonceAuthorityAddress>,\n ]\n > &\n InstructionWithData<AdvanceNonceAccountInstructionData>;\n\ntype AdvanceNonceAccountInstructionData = Brand<Uint8Array, 'AdvanceNonceAccountInstructionData'>;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Address<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\n/**\n * Creates an instruction for the System program to advance a nonce.\n *\n * This instruction is a prerequisite for a transaction with a nonce-based lifetime to be landed on\n * the network. In order to be considered valid, the transaction must meet all of these criteria.\n *\n * 1. Its lifetime constraint must be a {@link NonceLifetimeConstraint}.\n * 2. The value contained in the on-chain account at the address `nonceAccountAddress` must be equal\n * to {@link NonceLifetimeConstraint.nonce} at the time the transaction is landed.\n * 3. The first instruction in that transaction message must be the one returned by this function.\n *\n * You could also use the `getAdvanceNonceAccountInstruction` method of `@solana-program/system`.\n */\nexport function 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\n/**\n * A type guard that returns `true` if the instruction conforms to the\n * {@link AdvanceNonceAccountInstruction} type, and refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAdvanceNonceAccountInstruction } from '@solana/transaction-messages';\n *\n * if (isAdvanceNonceAccountInstruction(message.instructions[0])) {\n * // At this point, the first instruction in the message has been refined to a\n * // `AdvanceNonceAccountInstruction`.\n * setNonceAccountAddress(message.instructions[0].accounts[0].address);\n * } else {\n * setError('The first instruction is not an `AdvanceNonce` instruction');\n * }\n * ```\n */\nexport function isAdvanceNonceAccountInstruction(\n instruction: Instruction,\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: ReadonlyUint8Array): 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","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME, SolanaError } from '@solana/errors';\nimport { Instruction } from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nimport {\n AdvanceNonceAccountInstruction,\n createAdvanceNonceAccountInstruction,\n isAdvanceNonceAccountInstruction,\n} from './durable-nonce-instruction';\nimport { ExcludeTransactionMessageLifetime } from './lifetime';\nimport { BaseTransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\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}>;\n\n/** Represents a string that is particularly known to be the base58-encoded value of a nonce. */\nexport type Nonce<TNonceValue extends string = string> = Brand<TNonceValue, 'Nonce'>;\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network.\n *\n * The transaction message will continue to be eligible to land until the network considers the\n * `nonce` to have advanced. This can happen when the nonce account in which this nonce is found is\n * destroyed, or the nonce value within changes.\n */\ntype NonceLifetimeConstraint<TNonceValue extends string = string> = Readonly<{\n /**\n * A value contained in the related nonce account at the time the transaction was prepared.\n *\n * The transaction will be considered eligible to land until the nonce account ceases to exist\n * or contain this value.\n */\n nonce: Nonce<TNonceValue>;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the value of a nonce it includes.\n *\n * Such a transaction can only be landed on the network if the nonce is known to the network and has\n * not already been used to land a different transaction.\n */\nexport interface TransactionMessageWithDurableNonceLifetime<\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 ...Instruction[],\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint<TNonceValue>;\n}\n\n/**\n * A helper type to exclude the durable nonce lifetime constraint from a transaction message.\n */\nexport type ExcludeTransactionMessageDurableNonceLifetime<TTransactionMessage extends BaseTransactionMessage> =\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? ExcludeTransactionMessageLifetime<TTransactionMessage>\n : TTransactionMessage;\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithDurableNonceLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n * import { fetchNonce } from \"@solana-program/system\";\n *\n * if (isTransactionMessageWithDurableNonceLifetime(message)) {\n * // At this point, `message` has been refined to a\n * // `TransactionMessageWithDurableNonceLifetime`.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * setNonceIsValid(nonce === actualNonce);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithDurableNonceLifetime(\n transactionMessage: BaseTransactionMessage | (BaseTransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): transactionMessage is BaseTransactionMessage & TransactionMessageWithDurableNonceLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.nonce === 'string' &&\n transactionMessage.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transactionMessage.instructions[0])\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * nonce-based lifetime, from an untrusted network API or user input. Use this function to assert\n * that such a transaction message actually has a nonce-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithDurableNonceLifetime`.\n * assertIsTransactionMessageWithDurableNonceLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithDurableNonceLifetime` that can be used\n * // with the RPC.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * } catch (e) {\n * // `message` turned out not to have a nonce-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithDurableNonceLifetime(\n transactionMessage: BaseTransactionMessage | (BaseTransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): asserts transactionMessage is BaseTransactionMessage & TransactionMessageWithDurableNonceLifetime {\n if (!isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);\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\n/**\n * Given a nonce, the account where the value of the nonce is stored, and the address of the account\n * authorized to consume that nonce, this method will return a new transaction having the same type\n * as the one supplied plus the {@link TransactionMessageWithDurableNonceLifetime} type.\n *\n * In particular, this method _prepends_ an instruction to the transaction message designed to\n * consume (or 'advance') the nonce in the same transaction whose lifetime is defined by it.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from '@solana/transaction-messages';\n * import { fetchNonce } from '@solana-program/system';\n *\n * const nonceAccountAddress = address('EGtMh4yvXswwHhwVhyPxGrVV2TkLTgUqGodbATEPvojZ');\n * const nonceAuthorityAddress = address('4KD1Rdrd89NG7XbzW3xsX9Aqnx2EExJvExiNme6g9iAT');\n *\n * const {\n * data: { blockhash },\n * } = await fetchNonce(rpc, nonceAccountAddress);\n * const nonce = blockhash as string as Nonce;\n *\n * const durableNonceTransactionMessage = setTransactionMessageLifetimeUsingDurableNonce(\n * { nonce, nonceAccountAddress, nonceAuthorityAddress },\n * tx,\n * );\n * ```\n */\nexport function setTransactionMessageLifetimeUsingDurableNonce<\n TTransactionMessage extends BaseTransactionMessage,\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 transactionMessage: TTransactionMessage,\n): SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n> {\n type ReturnType = SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n >;\n\n let newInstructions: [\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...Instruction[],\n ];\n\n const firstInstruction = transactionMessage.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (\n isTransactionMessageWithDurableNonceLifetime(transactionMessage) &&\n transactionMessage.lifetimeConstraint.nonce === nonce\n ) {\n return transactionMessage as unknown as ReturnType;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transactionMessage.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.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 Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.instructions,\n ];\n }\n\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze(newInstructions),\n lifetimeConstraint: Object.freeze({ nonce }),\n }) as unknown as ReturnType;\n}\n\n/**\n * Helper type that transforms a given transaction message type into a new one that has the\n * `AdvanceNonceAccount` instruction as the first instruction and a lifetime constraint\n * representing the nonce value.\n */\ntype SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage extends BaseTransactionMessage,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> = Omit<\n // 1. The transaction message only grows in size if it currently has a different (or no) lifetime.\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? TTransactionMessage\n : ExcludeTransactionMessageWithinSizeLimit<TTransactionMessage>,\n // 2. Remove the instructions array as we are going to replace it with a new one.\n 'instructions'\n> & {\n // 3. Replace or prepend the first instruction with the advance nonce account instruction.\n readonly instructions: TTransactionMessage['instructions'] extends readonly [\n AdvanceNonceAccountInstruction,\n ...infer TTail extends readonly Instruction[],\n ]\n ? readonly [AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>, ...TTail]\n : readonly [\n AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>,\n ...TTransactionMessage['instructions'],\n ];\n // 4. Set the lifetime constraint to the nonce value.\n readonly lifetimeConstraint: NonceLifetimeConstraint<TNonceValue>;\n};\n","import { Instruction } from '@solana/instructions';\n\nimport { ExcludeTransactionMessageDurableNonceLifetime } from './durable-nonce';\nimport { BaseTransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\n\n/**\n * A helper type to append instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype AppendTransactionMessageInstructions<\n TTransactionMessage extends BaseTransactionMessage,\n TInstructions extends readonly Instruction[],\n> = Omit<ExcludeTransactionMessageWithinSizeLimit<TTransactionMessage>, 'instructions'> & {\n readonly instructions: readonly [...TTransactionMessage['instructions'], ...TInstructions];\n};\n\n/**\n * A helper type to prepend instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype PrependTransactionMessageInstructions<\n TTransactionMessage extends BaseTransactionMessage,\n TInstructions extends readonly Instruction[],\n> = Omit<\n ExcludeTransactionMessageWithinSizeLimit<ExcludeTransactionMessageDurableNonceLifetime<TTransactionMessage>>,\n 'instructions'\n> & {\n readonly instructions: readonly [...TInstructions, ...TTransactionMessage['instructions']];\n};\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstructions} if you need to append multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { appendTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransactionMessage = appendTransactionMessageInstruction(\n * {\n * data: getUtf8Encoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * transactionMessage,\n * );\n * ```\n */\nexport function appendTransactionMessageInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions<TTransactionMessage, [TInstruction]> {\n return appendTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstruction} if you only need to append one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { appendTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = appendTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function appendTransactionMessageInstructions<\n TTransactionMessage extends BaseTransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions<TTransactionMessage, TInstructions> {\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze([\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ...instructions,\n ] as readonly [...TTransactionMessage['instructions'], ...TInstructions]),\n });\n}\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstructions} if you need to prepend multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstruction(\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions<TTransactionMessage, [TInstruction]> {\n return prependTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstruction} if you only need to prepend one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstructions<\n TTransactionMessage extends BaseTransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions<TTransactionMessage, TInstructions> {\n return Object.freeze({\n ...(transactionMessage as ExcludeTransactionMessageDurableNonceLifetime<TTransactionMessage>),\n instructions: Object.freeze([\n ...instructions,\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ] as readonly [...TInstructions, ...TTransactionMessage['instructions']]),\n });\n}\n","export const ED25519_ALGORITHM_IDENTIFIER =\n // Resist the temptation to convert this to a simple string; As of version 133.0.3, Firefox\n // requires the object form of `AlgorithmIdentifier` and will throw a `DOMException` otherwise.\n Object.freeze({ name: 'Ed25519' });\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder, ReadonlyUint8Array } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\n\n/**\n * A 64-byte Ed25519 signature as a base58-encoded string.\n */\nexport type Signature = Brand<EncodedString<string, 'base58'>, 'Signature'>;\n/**\n * A 64-byte Ed25519 signature.\n *\n * Whenever you need to verify that a particular signature is, in fact, the one that would have been\n * produced by signing some known bytes using the private key associated with some known public key,\n * use the {@link verifySignature} function in this package.\n */\nexport type SignatureBytes = Brand<Uint8Array, 'SignatureBytes'>;\n\nlet base58Encoder: Encoder<string> | undefined;\n\n/**\n * Asserts that an arbitrary string is a base58-encoded Ed25519 signature.\n *\n * Useful when you receive a string from user input or an untrusted network API that you expect to\n * represent an Ed25519 signature (eg. of a transaction).\n *\n * @example\n * ```ts\n * import { assertIsSignature } from '@solana/keys';\n *\n * // Imagine a function that asserts whether a user-supplied signature is valid or not.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const signature: string = signatureInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signature` to `Signature`.\n * assertIsSignature(signature);\n * // At this point, `signature` is a `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * } catch (e) {\n * // `signature` turned out not to be a base58-encoded signature\n * }\n * }\n * ```\n */\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\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 SolanaError(SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeSignature.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n assertIsSignatureBytes(bytes);\n}\n\n/**\n * Asserts that an arbitrary `ReadonlyUint8Array` is an Ed25519 signature.\n *\n * Useful when you receive a `ReadonlyUint8Array` from an external interface (like the browser wallets' `signMessage` API) that you expect to\n * represent an Ed25519 signature.\n *\n * @example\n * ```ts\n * import { assertIsSignatureBytes } from '@solana/keys';\n *\n * // Imagine a function that verifies a signature.\n * function verifySignature() {\n * // We know only that the input conforms to the `ReadonlyUint8Array` type.\n * const signatureBytes: ReadonlyUint8Array = signatureBytesInput;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signatureBytes` to `SignatureBytes`.\n * assertIsSignatureBytes(signatureBytes);\n * // At this point, `signatureBytes` is a `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } catch (e) {\n * // `signatureBytes` turned out not to be a 64-byte Ed25519 signature\n * }\n * }\n * ```\n */\nexport function assertIsSignatureBytes(\n putativeSignatureBytes: ReadonlyUint8Array,\n): asserts putativeSignatureBytes is SignatureBytes {\n const numBytes = putativeSignatureBytes.byteLength;\n if (numBytes !== 64) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * A type guard that accepts a string as input. It will both return `true` if the string conforms to\n * the {@link Signature} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignature } from '@solana/keys';\n *\n * if (isSignature(signature)) {\n * // At this point, `signature` has been refined to a\n * // `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * setSignatureStatus(status);\n * } else {\n * setError(`${signature} is not a transaction signature`);\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 return isSignatureBytes(bytes);\n}\n\n/**\n * A type guard that accepts a `ReadonlyUint8Array` as input. It will both return `true` if the `ReadonlyUint8Array` conforms to\n * the {@link SignatureBytes} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignatureBytes } from '@solana/keys';\n *\n * if (isSignatureBytes(signatureBytes)) {\n * // At this point, `signatureBytes` has been refined to a\n * // `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } else {\n * setError(`${signatureBytes} is not a 64-byte Ed25519 signature`);\n * }\n * ```\n */\nexport function isSignatureBytes(putativeSignatureBytes: ReadonlyUint8Array): putativeSignatureBytes is SignatureBytes {\n return putativeSignatureBytes.byteLength === 64;\n}\n\n/**\n * Given a private [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and a\n * `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a\n * `Uint8Array`.\n *\n * @example\n * ```ts\n * import { signBytes } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * const signature = await signBytes(privateKey, data);\n * ```\n */\nexport async function signBytes(key: CryptoKey, data: ReadonlyUint8Array): Promise<SignatureBytes> {\n assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign(ED25519_ALGORITHM_IDENTIFIER, key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\n/**\n * This helper combines _asserting_ that a string is an Ed25519 signature with _coercing_ it to the\n * {@link Signature} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signature } from '@solana/keys';\n *\n * const signature = signature(userSuppliedSignature);\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * ```\n */\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\n/**\n * This helper combines _asserting_ that a `ReadonlyUint8Array` is an Ed25519 signature with _coercing_ it to the\n * {@link SignatureBytes} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signatureBytes } from '@solana/keys';\n *\n * const signature = signatureBytes(userSuppliedSignatureBytes);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport function signatureBytes(putativeSignatureBytes: ReadonlyUint8Array): SignatureBytes {\n assertIsSignatureBytes(putativeSignatureBytes);\n return putativeSignatureBytes;\n}\n\n/**\n * Given a public [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey), some\n * {@link SignatureBytes}, and a `Uint8Array` of data, this method will return `true` if the\n * signature was produced by signing the data using the private key associated with the public key,\n * and `false` otherwise.\n *\n * @example\n * ```ts\n * import { verifySignature } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport async function verifySignature(\n key: CryptoKey,\n signature: SignatureBytes,\n data: ReadonlyUint8Array,\n): Promise<boolean> {\n assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify(ED25519_ALGORITHM_IDENTIFIER, key, signature, data);\n}\n","import { fixEncoderSize, transformEncoder, VariableSizeEncoder } from '@solana/codecs-core';\nimport { getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { SignaturesMap } from '../transaction';\n\nfunction getSignaturesToEncode(signaturesMap: SignaturesMap): SignatureBytes[] {\n const signatures = Object.values(signaturesMap);\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES);\n }\n\n return signatures.map(signature => {\n if (!signature) {\n return new Uint8Array(64).fill(0) as SignatureBytes;\n }\n return signature;\n });\n}\n\nexport function getSignaturesEncoder(): VariableSizeEncoder<SignaturesMap> {\n return transformEncoder(\n getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getShortU16Encoder() }),\n getSignaturesToEncode,\n );\n}\n","import { getAddressDecoder } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n padRightDecoder,\n ReadonlyUint8Array,\n transformDecoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getTupleDecoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getU8Decoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { getTransactionVersionDecoder } from '@solana/transaction-messages';\n\nimport { SignaturesMap, Transaction, TransactionMessageBytes } from '../transaction';\nimport { getSignaturesEncoder } from './signatures-encoder';\n\n/**\n * Returns an encoder that you can use to encode a {@link Transaction} to a byte array in a wire\n * format appropriate for sending to the Solana network for execution.\n */\nexport function getTransactionEncoder(): VariableSizeEncoder<Transaction> {\n return getStructEncoder([\n ['signatures', getSignaturesEncoder()],\n ['messageBytes', getBytesEncoder()],\n ]);\n}\n\n/**\n * Returns a decoder that you can use to convert a byte array in the Solana transaction wire format\n * to a {@link Transaction} object.\n *\n * @example\n * ```ts\n * import { getTransactionDecoder } from '@solana/transactions';\n *\n * const transactionDecoder = getTransactionDecoder();\n * const transaction = transactionDecoder.decode(wireTransactionBytes);\n * for (const [address, signature] in Object.entries(transaction.signatures)) {\n * console.log(`Signature by ${address}`, signature);\n * }\n * ```\n */\n\nexport function getTransactionDecoder(): VariableSizeDecoder<Transaction> {\n return transformDecoder(\n getStructDecoder([\n ['signatures', getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getShortU16Decoder() })],\n ['messageBytes', getBytesDecoder()],\n ]),\n decodePartiallyDecodedTransaction,\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a {@link Transaction}\n *\n * @see {@link getTransactionDecoder}\n * @see {@link getTransactionEncoder}\n */\nexport function getTransactionCodec(): VariableSizeCodec<Transaction> {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder());\n}\n\ntype PartiallyDecodedTransaction = {\n messageBytes: ReadonlyUint8Array;\n signatures: ReadonlyUint8Array[];\n};\n\nfunction decodePartiallyDecodedTransaction(transaction: PartiallyDecodedTransaction): Transaction {\n const { messageBytes, signatures } = transaction;\n\n /*\n Relevant message structure is at the start:\n - transaction version (0 bytes for legacy transactions, 1 byte for versioned transactions)\n - `numRequiredSignatures` (1 byte, we verify this matches the length of signatures)\n - `numReadOnlySignedAccounts` (1 byte, not used here)\n - `numReadOnlyUnsignedAccounts` (1 byte, not used here)\n - static addresses, with signers first. This is an array of addresses, prefixed with a short-u16 length\n */\n\n const signerAddressesDecoder = getTupleDecoder([\n // read transaction version\n getTransactionVersionDecoder(),\n // read first byte of header, `numSignerAccounts`\n // padRight to skip the next 2 bytes, `numReadOnlySignedAccounts` and `numReadOnlyUnsignedAccounts` which we don't need\n padRightDecoder(getU8Decoder(), 2),\n // read static addresses\n getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() }),\n ]);\n const [_txVersion, numRequiredSignatures, staticAddresses] = signerAddressesDecoder.decode(messageBytes);\n\n const signerAddresses = staticAddresses.slice(0, numRequiredSignatures);\n\n // signer addresses and signatures must be the same length\n // we encode an all-zero signature when the signature is missing\n if (signerAddresses.length !== signatures.length) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, {\n numRequiredSignatures,\n signaturesLength: signatures.length,\n signerAddresses,\n });\n }\n\n // combine the signer addresses + signatures into the signatures map\n const signaturesMap: SignaturesMap = {};\n signerAddresses.forEach((address, index) => {\n const signatureForAddress = signatures[index];\n if (signatureForAddress.every(b => b === 0)) {\n signaturesMap[address] = null;\n } else {\n signaturesMap[address] = signatureForAddress as SignatureBytes;\n }\n });\n\n return {\n messageBytes: messageBytes as TransactionMessageBytes,\n signatures: Object.freeze(signaturesMap),\n };\n}\n","import {\n BaseTransactionMessage,\n compileTransactionMessage,\n getCompiledTransactionMessageEncoder,\n isTransactionMessageWithBlockhashLifetime,\n isTransactionMessageWithDurableNonceLifetime,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\n\nimport type { TransactionWithLifetime } from './lifetime';\nimport type { SignaturesMap, TransactionFromTransactionMessage, TransactionMessageBytes } from './transaction';\n\n/**\n * Returns a {@link Transaction} object for a given {@link TransactionMessage}.\n *\n * This includes the compiled bytes of the transaction message, and a map of signatures. This map\n * will have a key for each address that is required to sign the transaction. The transaction will\n * not yet have signatures for any of these addresses.\n *\n * Whether a transaction message is ready to be compiled or not is enforced for you at the type\n * level. In order to be signable, a transaction message must:\n *\n * - have a version and a list of zero or more instructions (ie. conform to\n * {@link BaseTransactionMessage})\n * - have a fee payer set (ie. conform to {@link TransactionMessageWithFeePayer})\n * - have a lifetime specified (ie. conform to {@link TransactionMessageWithBlockhashLifetime} or\n * {@link TransactionMessageWithDurableNonceLifetime})\n */\nexport function compileTransaction<TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer>(\n transactionMessage: TTransactionMessage,\n): Readonly<TransactionFromTransactionMessage<TTransactionMessage>> {\n type ReturnType = Readonly<TransactionFromTransactionMessage<TTransactionMessage>>;\n\n const compiledMessage = compileTransactionMessage(transactionMessage);\n const messageBytes = getCompiledTransactionMessageEncoder().encode(compiledMessage) as TransactionMessageBytes;\n\n const transactionSigners = compiledMessage.staticAccounts.slice(0, compiledMessage.header.numSignerAccounts);\n const signatures: SignaturesMap = {};\n for (const signerAddress of transactionSigners) {\n signatures[signerAddress] = null;\n }\n\n let lifetimeConstraint: TransactionWithLifetime['lifetimeConstraint'] | undefined;\n if (isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n lifetimeConstraint = {\n blockhash: transactionMessage.lifetimeConstraint.blockhash,\n lastValidBlockHeight: transactionMessage.lifetimeConstraint.lastValidBlockHeight,\n };\n } else if (isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n lifetimeConstraint = {\n nonce: transactionMessage.lifetimeConstraint.nonce,\n nonceAccountAddress: transactionMessage.instructions[0].accounts[0].address,\n };\n }\n\n return Object.freeze({\n ...(lifetimeConstraint ? { lifetimeConstraint } : undefined),\n messageBytes: messageBytes,\n signatures: Object.freeze(signatures),\n }) as ReturnType;\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { Decoder } from '@solana/codecs-core';\nimport { getBase58Decoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { Signature, SignatureBytes, signBytes } from '@solana/keys';\nimport { NominalType } from '@solana/nominal-types';\n\nimport { TransactionWithLifetime } from './lifetime';\nimport { Transaction } from './transaction';\n\n/**\n * Represents a transaction that is signed by all of its required signers. Being fully signed is a\n * prerequisite of functions designed to land transactions on the network.\n */\nexport type FullySignedTransaction = NominalType<'transactionSignedness', 'fullySigned'>;\n\nlet base58Decoder: Decoder<string> | undefined;\n\n/**\n * Given a transaction signed by its fee payer, this method will return the {@link Signature} that\n * uniquely identifies it. This string can be used to look up transactions at a later date, for\n * example on a Solana block explorer.\n *\n * @example\n * ```ts\n * import { getSignatureFromTransaction } from '@solana/transactions';\n *\n * const signature = getSignatureFromTransaction(tx);\n * console.debug(`Inspect this transaction at https://explorer.solana.com/tx/${signature}`);\n * ```\n */\nexport function getSignatureFromTransaction(transaction: Transaction): Signature {\n if (!base58Decoder) base58Decoder = getBase58Decoder();\n\n // We have ordered signatures from the compiled message accounts\n // first signature is the fee payer\n const signatureBytes = Object.values(transaction.signatures)[0];\n if (!signatureBytes) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING);\n }\n const transactionSignature = base58Decoder.decode(signatureBytes);\n return transactionSignature as Signature;\n}\n\nfunction uint8ArraysEqual(arr1: Uint8Array, arr2: Uint8Array) {\n return arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link Transaction}.\n *\n * Though the resulting transaction might have every signature it needs to land on the network, this\n * function will not assert that it does. A partially signed transaction cannot be landed on the\n * network, but can be serialized and deserialized.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { partiallySignTransaction } from '@solana/transactions';\n *\n * const partiallySignedTransaction = await partiallySignTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link signTransaction} if you want to assert that the transaction has all of its required\n * signatures after signing.\n */\nexport async function partiallySignTransaction<TTransaction extends Transaction & TransactionWithLifetime>(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise<TTransaction> {\n let newSignatures: Record<Address, SignatureBytes> | undefined;\n let unexpectedSigners: Set<Address> | undefined;\n\n await Promise.all(\n keyPairs.map(async keyPair => {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const existingSignature = transaction.signatures[address];\n\n // Check if the address is expected to sign the transaction\n if (existingSignature === undefined) {\n // address is not an expected signer for this transaction\n unexpectedSigners ||= new Set();\n unexpectedSigners.add(address);\n return;\n }\n\n // Return if there are any unexpected signers already since we won't be using signatures\n if (unexpectedSigners) {\n return;\n }\n\n const newSignature = await signBytes(keyPair.privateKey, transaction.messageBytes);\n\n if (existingSignature !== null && uint8ArraysEqual(newSignature, existingSignature)) {\n // already have the same signature set\n return;\n }\n\n newSignatures ||= {};\n newSignatures[address] = newSignature;\n }),\n );\n\n if (unexpectedSigners && unexpectedSigners.size > 0) {\n const expectedSigners = Object.keys(transaction.signatures);\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, {\n expectedAddresses: expectedSigners,\n unexpectedAddresses: [...unexpectedSigners],\n });\n }\n\n if (!newSignatures) {\n return transaction;\n }\n\n return Object.freeze({\n ...transaction,\n signatures: Object.freeze({\n ...transaction.signatures,\n ...newSignatures,\n }),\n });\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link FullySignedTransaction}.\n *\n * This function will throw unless the resulting transaction is fully signed.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { signTransaction } from '@solana/transactions';\n *\n * const signedTransaction = await signTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link partiallySignTransaction} if you want to sign the transaction without asserting that\n * the resulting transaction is fully signed.\n */\nexport async function signTransaction<TTransaction extends Transaction & TransactionWithLifetime>(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise<FullySignedTransaction & TTransaction> {\n const out = await partiallySignTransaction(keyPairs, transaction);\n assertIsFullySignedTransaction(out);\n Object.freeze(out);\n return out;\n}\n\n/**\n * Checks whether a given {@link Transaction} is fully signed.\n *\n * @example\n * ```ts\n * import { isFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * if (isFullySignedTransaction(transaction)) {\n * // At this point we know that the transaction is signed and can be sent to the network.\n * }\n * ```\n */\nexport function isFullySignedTransaction<TTransaction extends Transaction>(\n transaction: TTransaction,\n): transaction is FullySignedTransaction & TTransaction {\n return Object.entries(transaction.signatures).every(([_, signatureBytes]) => !!signatureBytes);\n}\n\n/**\n * From time to time you might acquire a {@link Transaction}, that you expect to be fully signed,\n * from an untrusted network API or user input. Use this function to assert that such a transaction\n * is fully signed.\n *\n * @example\n * ```ts\n * import { assertIsFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast `transaction`\n * // to `FullySignedTransaction`.\n * assertIsFullySignedTransaction(transaction);\n * // At this point we know that the transaction is signed and can be sent to the network.\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * }\n * throw;\n * }\n * ```\n */\nexport function assertIsFullySignedTransaction<TTransaction extends Transaction>(\n transaction: TTransaction,\n): asserts transaction is FullySignedTransaction & TTransaction {\n const missingSigs: Address[] = [];\n Object.entries(transaction.signatures).forEach(([address, signatureBytes]) => {\n if (!signatureBytes) {\n missingSigs.push(address as Address);\n }\n });\n\n if (missingSigs.length > 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, {\n addresses: missingSigs,\n });\n }\n}\n","import { getBase64Decoder } from '@solana/codecs-strings';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { getTransactionEncoder } from './codecs';\nimport { Transaction } from './transaction';\n\n/** Represents the wire format of a transaction as a base64-encoded string. */\nexport type Base64EncodedWireTransaction = Brand<EncodedString<string, 'base64'>, 'Base64EncodedWireTransaction'>;\n\n/**\n * Given a signed transaction, this method returns the transaction as a string that conforms to the\n * {@link Base64EncodedWireTransaction} type.\n *\n * @example\n * ```ts\n * import { getBase64EncodedWireTransaction, signTransaction } from '@solana/transactions';\n *\n * const serializedTransaction = getBase64EncodedWireTransaction(signedTransaction);\n * const signature = await rpc.sendTransaction(serializedTransaction, { encoding: 'base64' }).send();\n * ```\n */\nexport function getBase64EncodedWireTransaction(transaction: Transaction): Base64EncodedWireTransaction {\n const wireTransactionBytes = getTransactionEncoder().encode(transaction);\n return getBase64Decoder().decode(wireTransactionBytes) as Base64EncodedWireTransaction;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, SolanaError } from '@solana/errors';\n\nimport { MessageSigner } from './message-signer';\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Removes all duplicated {@link MessageSigner | MessageSigners} and\n * {@link TransactionSigner | TransactionSigners} from a provided array\n * by comparing their {@link Address | addresses}.\n *\n * @internal\n */\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 throw new SolanaError(SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, {\n address: signer.address,\n });\n }\n });\n return Object.values(deduplicated);\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionModifyingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that potentially modifies the provided {@link Transaction | Transactions}\n * before signing them.\n *\n * For instance, this enables wallets to inject additional instructions into the\n * transaction before signing them. For each transaction, instead of returning a\n * {@link SignatureDictionary}, its\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} function\n * returns an updated {@link Transaction} with a potentially modified set of instructions and\n * signature dictionary. The returned transaction must be within the transaction size limit,\n * and include a `lifetimeConstraint`.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionModifyingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * modifyAndSignTransactions: async (\n * transactions: Transaction[]\n * ): Promise<(Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[]> => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Sequential**. Contrary to partial signers, these cannot be executed in\n * parallel as each call can modify the provided transactions.\n * - **First signers**. For a given transaction, a modifying signer must always\n * be used before a partial signer as the former will likely modify the\n * transaction and thus impact the outcome of the latter.\n * - **Potential conflicts**. If more than one modifying signer is provided,\n * the second signer may invalidate the signature of the first one. However,\n * modifying signers may decide not to modify a transaction based on the\n * existence of signatures for that transaction.\n *\n * @see {@link isTransactionModifyingSigner}\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport type TransactionModifyingSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n modifyAndSignTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionModifyingSignerConfig,\n ): Promise<readonly (Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[]>;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionModifyingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport function isTransactionModifyingSigner<TAddress extends string>(value: {\n [key: string]: unknown;\n address: Address<TAddress>;\n}): value is TransactionModifyingSigner<TAddress> {\n return 'modifyAndSignTransactions' in value && typeof value.modifyAndSignTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionModifyingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionModifyingSigner}\n */\nexport function assertIsTransactionModifyingSigner<TAddress extends string>(value: {\n [key: string]: unknown;\n address: Address<TAddress>;\n}): asserts value is TransactionModifyingSigner<TAddress> {\n if (!isTransactionModifyingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig, SignatureDictionary } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionPartialSigner#signTransactions | signTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionPartialSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs an array of {@link Transaction | Transactions}\n * without modifying their content. It defines a\n * {@link TransactionPartialSigner#signTransactions | signTransactions}\n * function that returns a {@link SignatureDictionary} for each provided transaction.\n *\n * Such signature dictionaries are expected to be merged with the existing ones if any.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionPartialSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signTransactions: async (\n * transactions: Transaction[]\n * ): Promise<SignatureDictionary[]> => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Parallel**. It returns a signature dictionary for each provided\n * transaction without modifying them, making it possible for multiple\n * partial signers to sign the same transaction in parallel.\n * - **Flexible order**. The order in which we use these signers for\n * a given transaction doesn’t matter.\n *\n * @see {@link isTransactionPartialSigner}\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport type TransactionPartialSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n signTransactions(\n transactions: readonly (Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[],\n config?: TransactionPartialSignerConfig,\n ): Promise<readonly SignatureDictionary[]>;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionPartialSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionPartialSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport function isTransactionPartialSigner<TAddress extends string>(value: {\n [key: string]: unknown;\n address: Address<TAddress>;\n}): value is TransactionPartialSigner<TAddress> {\n return 'signTransactions' in value && typeof value.signTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionPartialSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionPartialSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionPartialSigner}\n */\nexport function assertIsTransactionPartialSigner<TAddress extends string>(value: {\n [key: string]: unknown;\n address: Address<TAddress>;\n}): asserts value is TransactionPartialSigner<TAddress> {\n if (!isTransactionPartialSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { Transaction, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionSendingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs one or multiple transactions\n * before sending them immediately to the blockchain.\n *\n * It defines a {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions}\n * function that returns the transaction signature (i.e. its identifier) for each provided\n * {@link Transaction}.\n *\n * This interface is required for PDA wallets and other types of wallets that don't provide an\n * interface for signing transactions without sending them.\n *\n * Note that it is also possible for such signers to modify the provided transactions\n * before signing and sending them. This enables use cases where the modified transactions\n * cannot be shared with the app and thus must be sent directly.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const myTransactionSendingSigner: TransactionSendingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signAndSendTransactions: async (transactions: Transaction[]): Promise<SignatureBytes[]> => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Single signer**. Since this signer also sends the provided transactions,\n * we can only use a single {@link TransactionSendingSigner} for a given set of transactions.\n * - **Last signer**. Trivially, that signer must also be the last one used.\n * - **Potential conflicts**. Since signers may decide to modify the given\n * transactions before sending them, they may invalidate previous signatures.\n * However, signers may decide not to modify a transaction based\n * on the existence of signatures for that transaction.\n * - **Potential confirmation**. Whilst this is not required by this interface,\n * it is also worth noting that most wallets will also wait for the transaction\n * to be confirmed (typically with a `confirmed` commitment)\n * before notifying the app that they are done.\n *\n * @see {@link isTransactionSendingSigner}\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport type TransactionSendingSigner<TAddress extends string = string> = Readonly<{\n address: Address<TAddress>;\n signAndSendTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionSendingSignerConfig,\n ): Promise<readonly SignatureBytes[]>;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSendingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport function isTransactionSendingSigner<TAddress extends string>(value: {\n [key: string]: unknown;\n address: Address<TAddress>;\n}): value is TransactionSendingSigner<TAddress> {\n return 'signAndSendTransactions' in value && typeof value.signAndSendTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSendingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSendingSigner}\n */\nexport function assertIsTransactionSendingSigner<TAddress extends string>(value: {\n [key: string]: unknown;\n address: Address<TAddress>;\n}): asserts value is TransactionSendingSigner<TAddress> {\n if (!isTransactionSendingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, SolanaError } from '@solana/errors';\n\nimport { isTransactionModifyingSigner, TransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner, TransactionSendingSigner } from './transaction-sending-signer';\n\n/**\n * Defines a signer capable of signing transactions.\n *\n * @see {@link TransactionModifyingSigner} For signers that can modify transactions before signing them.\n * @see {@link TransactionPartialSigner} For signers that can be used in parallel.\n * @see {@link TransactionSendingSigner} For signers that send transactions after signing them.\n * @see {@link isTransactionSigner}\n * @see {@link assertIsTransactionSigner}\n */\nexport type TransactionSigner<TAddress extends string = string> =\n | TransactionModifyingSigner<TAddress>\n | TransactionPartialSigner<TAddress>\n | TransactionSendingSigner<TAddress>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSigner}\n */\nexport function isTransactionSigner<TAddress extends string>(value: {\n [key: string]: unknown;\n address: Address<TAddress>;\n}): value is TransactionSigner<TAddress> {\n return (\n isTransactionPartialSigner(value) || isTransactionModifyingSigner(value) || isTransactionSendingSigner(value)\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSigner}\n */\nexport function assertIsTransactionSigner<TAddress extends string>(value: {\n [key: string]: unknown;\n address: Address<TAddress>;\n}): asserts value is TransactionSigner<TAddress> {\n if (!isTransactionSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { AccountLookupMeta, AccountMeta, AccountRole, Instruction } from '@solana/instructions';\nimport {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionVersion,\n} from '@solana/transaction-messages';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { TransactionMessageWithFeePayerSigner } from './fee-payer-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\n\n/**\n * An extension of the {@link AccountMeta} type that allows us to store {@link TransactionSigner | TransactionSigners} inside it.\n *\n * Note that, because this type represents a signer, it must use one the following two roles:\n * - {@link AccountRole.READONLY_SIGNER}\n * - {@link AccountRole.WRITABLE_SIGNER}\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner} to use within the account meta.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole } from '@solana/instructions';\n * import { generateKeyPairSigner, AccountSignerMeta } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const account: AccountSignerMeta = {\n * address: signer.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer,\n * };\n * ```\n */\nexport interface AccountSignerMeta<\n TAddress extends string = string,\n TSigner extends TransactionSigner<TAddress> = TransactionSigner<TAddress>,\n> extends AccountMeta<TAddress> {\n readonly role: AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER;\n readonly signer: TSigner;\n}\n\n/**\n * A union type that supports base account metas as well as {@link AccountSignerMeta | signer account metas}.\n */\ntype AccountMetaWithSigner<TSigner extends TransactionSigner = TransactionSigner> =\n | AccountLookupMeta\n | AccountMeta\n | AccountSignerMeta<string, TSigner>;\n\n/**\n * Composable type that allows {@link AccountSignerMeta | AccountSignerMetas} to be used inside the instruction's `accounts` array\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { generateKeyPairSigner, InstructionWithSigners } from '@solana/signers';\n *\n * const [authority, buffer] = await Promise.all([\n * generateKeyPairSigner(),\n * generateKeyPairSigner(),\n * ]);\n * const instruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [\n * // The authority is a signer account.\n * {\n * address: authority.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer: authority,\n * },\n * // The buffer is a writable account.\n * { address: buffer.address, role: AccountRole.WRITABLE },\n * ],\n * };\n * ```\n */\nexport type InstructionWithSigners<\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly AccountMetaWithSigner<TSigner>[] = readonly AccountMetaWithSigner<TSigner>[],\n> = Pick<Instruction<string, TAccounts>, 'accounts'>;\n\n/**\n * A {@link BaseTransactionMessage} type extension that accept {@link TransactionSigner | TransactionSigners}.\n *\n * Namely, it allows:\n * - a {@link TransactionSigner} to be used as the fee payer and\n * - {@link InstructionWithSigners} to be used in its instructions.\n *\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, InstructionWithSigners, TransactionMessageWithSigners } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const firstInstruction: Instruction = { ... };\n * const secondInstruction: InstructionWithSigners = { ... };\n * const transactionMessage: BaseTransactionMessage & TransactionMessageWithSigners = {\n * feePayer: signer,\n * instructions: [firstInstruction, secondInstruction],\n * }\n * ```\n */\nexport type TransactionMessageWithSigners<\n TAddress extends string = string,\n TSigner extends TransactionSigner<TAddress> = TransactionSigner<TAddress>,\n TAccounts extends readonly AccountMetaWithSigner<TSigner>[] = readonly AccountMetaWithSigner<TSigner>[],\n> = Partial<TransactionMessageWithFeePayer<TAddress> | TransactionMessageWithFeePayerSigner<TAddress, TSigner>> &\n Pick<\n BaseTransactionMessage<TransactionVersion, Instruction & InstructionWithSigners<TSigner, TAccounts>>,\n 'instructions'\n >;\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside the account metas of an {@link InstructionWithSigners | instruction}.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n *\n * @example\n * ```ts\n * import { InstructionWithSigners, getSignersFromInstruction } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const instructionWithSigners: InstructionWithSigners = {\n * accounts: [\n * { address: signerA.address, signer: signerA, ... },\n * { address: signerB.address, signer: signerB, ... },\n * { address: signerA.address, signer: signerA, ... },\n * ],\n * };\n *\n * const instructionSigners = getSignersFromInstruction(instructionWithSigners);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromInstruction<TSigner extends TransactionSigner = TransactionSigner>(\n instruction: InstructionWithSigners<TSigner>,\n): readonly TSigner[] {\n return deduplicateSigners(\n (instruction.accounts ?? []).flatMap(account => ('signer' in account ? account.signer : [])),\n );\n}\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside a given {@link TransactionMessageWithSigners | transaction message}.\n *\n * This includes any {@link TransactionSigner | TransactionSigners} stored\n * as the fee payer or in the instructions of the transaction message.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { InstructionWithSigners, TransactionMessageWithSigners, getSignersFromTransactionMessage } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const firstInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerA.address, signer: signerA, ... }],\n * };\n * const secondInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerB.address, signer: signerB, ... }],\n * };\n * const transactionMessage: TransactionMessageWithSigners = {\n * feePayer: signerA,\n * instructions: [firstInstruction, secondInstruction],\n * }\n *\n * const transactionSigners = getSignersFromTransactionMessage(transactionMessage);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromTransactionMessage<\n TAddress extends string = string,\n TSigner extends TransactionSigner<TAddress> = TransactionSigner<TAddress>,\n TTransactionMessage extends TransactionMessageWithSigners<TAddress, TSigner> = TransactionMessageWithSigners<\n TAddress,\n TSigner\n >,\n>(transaction: TTransactionMessage): readonly TSigner[] {\n return deduplicateSigners([\n ...(transaction.feePayer && isTransactionSigner(transaction.feePayer) ? [transaction.feePayer as TSigner] : []),\n ...transaction.instructions.flatMap(getSignersFromInstruction),\n ]);\n}\n","import { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Alternative to {@link TransactionMessageWithFeePayer} that uses a {@link TransactionSigner} for the fee payer.\n *\n * @typeParam TAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner}.\n *\n * @example\n * ```ts\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, TransactionMessageWithFeePayerSigner } from '@solana/signers';\n *\n * const transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayerSigner = {\n * feePayer: await generateKeyPairSigner(),\n * instructions: [],\n * version: 0,\n * };\n * ```\n */\nexport interface TransactionMessageWithFeePayerSigner<\n TAddress extends string = string,\n TSigner extends TransactionSigner<TAddress> = TransactionSigner<TAddress>,\n> {\n readonly feePayer: TSigner;\n}\n\n/**\n * Sets the fee payer of a {@link BaseTransactionMessage | transaction message}\n * using a {@link TransactionSigner}.\n *\n * @typeParam TFeePayerAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { pipe } from '@solana/functional';\n * import { generateKeyPairSigner, setTransactionMessageFeePayerSigner } from '@solana/signers';\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const feePayer = await generateKeyPairSigner();\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * message => setTransactionMessageFeePayerSigner(signer, message),\n * );\n * ```\n */\nexport function setTransactionMessageFeePayerSigner<\n TFeePayerAddress extends string,\n TTransactionMessage extends BaseTransactionMessage &\n Partial<TransactionMessageWithFeePayer | TransactionMessageWithFeePayerSigner>,\n>(\n feePayer: TransactionSigner<TFeePayerAddress>,\n transactionMessage: TTransactionMessage,\n): Omit<TTransactionMessage, 'feePayer'> & TransactionMessageWithFeePayerSigner<TFeePayerAddress> {\n Object.freeze(feePayer);\n const out = { ...transactionMessage, feePayer };\n Object.freeze(out);\n return out;\n}\n","import { SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport {\n assertIsFullySignedTransaction,\n compileTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithinSizeLimit,\n TransactionWithLifetime,\n} from '@solana/transactions';\n\nimport { getSignersFromTransactionMessage, TransactionMessageWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport {\n isTransactionModifyingSigner,\n TransactionModifyingSigner,\n TransactionModifyingSignerConfig,\n} from './transaction-modifying-signer';\nimport {\n isTransactionPartialSigner,\n TransactionPartialSigner,\n TransactionPartialSignerConfig,\n} from './transaction-partial-signer';\nimport {\n isTransactionSendingSigner,\n TransactionSendingSigner,\n TransactionSendingSignerConfig,\n} from './transaction-sending-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\nimport { assertIsTransactionMessageWithSingleSendingSigner } from './transaction-with-single-sending-signer';\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction.\n *\n * It first uses all {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before\n * using all {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n *\n * If a composite signer implements both interfaces, it will be used as a\n * {@link TransactionModifyingSigner} if no other signer implements that interface.\n * Otherwise, it will be used as a {@link TransactionPartialSigner}.\n *\n * @example\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage);\n * ```\n *\n * It also accepts an optional {@link AbortSignal} that will be propagated to all signers.\n *\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Finally, note that this function ignores {@link TransactionSendingSigner | TransactionSendingSigners}\n * as it does not send the transaction. Check out the {@link signAndSendTransactionMessageWithSigners}\n * function for more details on how to use sending signers.\n *\n * @see {@link signTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function partiallySignTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise<Transaction & TransactionWithinSizeLimit & TransactionWithLifetime> {\n const { partialSigners, modifyingSigners } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transactionMessage).filter(isTransactionSigner)),\n { identifySendingSigner: false },\n );\n\n return await signModifyingAndPartialTransactionSigners(\n transactionMessage,\n modifyingSigners,\n partialSigners,\n config,\n );\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction before asserting\n * that all signatures required by the transaction are present.\n *\n * This function delegates to the {@link partiallySignTransactionMessageWithSigners} function\n * in order to extract signers from the transaction message and sign the transaction.\n *\n * @example\n * ```ts\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage);\n *\n * // With additional config.\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n *\n * // We now know the transaction is fully signed.\n * mySignedTransaction satisfies FullySignedTransaction;\n * ```\n *\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function signTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise<SendableTransaction & Transaction & TransactionWithLifetime> {\n const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, config);\n assertIsFullySignedTransaction(signedTransaction);\n return signedTransaction;\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to sign it before sending it immediately to the blockchain.\n *\n * It returns the signature of the sent transaction (i.e. its identifier) as bytes.\n *\n * @example\n * ```ts\n * import { signAndSendTransactionMessageWithSigners } from '@solana/signers';\n *\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n *\n * // With additional config.\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Similarly to the {@link partiallySignTransactionMessageWithSigners} function, it first uses all\n * {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before using all\n * {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n * It then sends the transaction using the {@link TransactionSendingSigner} it identified.\n *\n * Composite transaction signers are treated such that at least one sending signer is used if any.\n * When a {@link TransactionSigner} implements more than one interface, we use it as a:\n *\n * - {@link TransactionSendingSigner}, if no other {@link TransactionSendingSigner} exists.\n * - {@link TransactionModifyingSigner}, if no other {@link TransactionModifyingSigner} exists.\n * - {@link TransactionPartialSigner}, otherwise.\n *\n * The provided transaction must contain exactly one {@link TransactionSendingSigner} inside its account metas.\n * If more than one composite signers implement the {@link TransactionSendingSigner} interface,\n * one of them will be selected as the sending signer. Otherwise, if multiple\n * {@link TransactionSendingSigner | TransactionSendingSigners} must be selected, the function will throw an error.\n *\n * If you'd like to assert that a transaction makes use of exactly one {@link TransactionSendingSigner}\n * _before_ calling this function, you may use the {@link assertIsTransactionMessageWithSingleSendingSigner} function.\n *\n * Alternatively, you may use the {@link isTransactionMessageWithSingleSendingSigner} function to provide a\n * fallback in case the transaction does not contain any sending signer.\n *\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signTransactionMessageWithSigners}\n *\n */\nexport async function signAndSendTransactionMessageWithSigners(\n transaction: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionSendingSignerConfig,\n): Promise<SignatureBytes> {\n assertIsTransactionMessageWithSingleSendingSigner(transaction);\n\n const abortSignal = config?.abortSignal;\n const { partialSigners, modifyingSigners, sendingSigner } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transaction).filter(isTransactionSigner)),\n );\n\n abortSignal?.throwIfAborted();\n const signedTransaction = await signModifyingAndPartialTransactionSigners(\n transaction,\n modifyingSigners,\n partialSigners,\n config,\n );\n\n if (!sendingSigner) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);\n }\n\n abortSignal?.throwIfAborted();\n const [signature] = await sendingSigner.signAndSendTransactions([signedTransaction], config);\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 transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n modifyingSigners: readonly TransactionModifyingSigner[] = [],\n partialSigners: readonly TransactionPartialSigner[] = [],\n config?: TransactionModifyingSignerConfig,\n): Promise<Transaction & TransactionWithinSizeLimit & TransactionWithLifetime> {\n // serialize the transaction\n const transaction = compileTransaction(transactionMessage);\n\n // Handle modifying signers sequentially.\n const modifiedTransaction = (await modifyingSigners.reduce(\n async (transaction, modifyingSigner) => {\n config?.abortSignal?.throwIfAborted();\n const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction], config);\n return Object.freeze(tx);\n },\n Promise.resolve(transaction) as Promise<Readonly<Transaction & TransactionWithLifetime>>,\n )) as Transaction & TransactionWithinSizeLimit & TransactionWithLifetime;\n\n // Handle partial signers in parallel.\n config?.abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signTransactions([modifiedTransaction], config);\n return signatures;\n }),\n );\n\n return Object.freeze({\n ...modifiedTransaction,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedTransaction.signatures ?? {}),\n ),\n });\n}\n","import {\n assertAccountsDecoded,\n assertAccountsExist,\n type FetchAccountsConfig,\n fetchJsonParsedAccounts,\n} from '@solana/accounts';\nimport type { Address } from '@solana/addresses';\nimport type { GetMultipleAccountsApi, Rpc } from '@solana/rpc';\nimport { type AddressesByLookupTableAddress } from '@solana/transaction-messages';\n\ntype FetchedAddressLookup = {\n addresses: Address[];\n};\n\n/**\n * Given a list of addresses belonging to address lookup tables, returns a map of lookup table\n * addresses to an ordered array of the addresses they contain.\n *\n * @param rpc An object that supports the {@link GetMultipleAccountsApi} of the Solana RPC API\n * @param config\n */\nexport async function fetchAddressesForLookupTables(\n lookupTableAddresses: Address[],\n rpc: Rpc<GetMultipleAccountsApi>,\n config?: FetchAccountsConfig,\n): Promise<AddressesByLookupTableAddress> {\n if (lookupTableAddresses.length === 0) {\n return {};\n }\n\n const fetchedLookupTables = await fetchJsonParsedAccounts<FetchedAddressLookup[]>(\n rpc,\n lookupTableAddresses,\n config,\n );\n\n assertAccountsDecoded(fetchedLookupTables);\n assertAccountsExist(fetchedLookupTables);\n\n return fetchedLookupTables.reduce<AddressesByLookupTableAddress>((acc, lookup) => {\n return {\n ...acc,\n [lookup.address]: lookup.data.addresses,\n };\n }, {});\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedRequestHeapFrameInstruction,\n type ParsedRequestUnitsInstruction,\n type ParsedSetComputeUnitLimitInstruction,\n type ParsedSetComputeUnitPriceInstruction,\n type ParsedSetLoadedAccountsDataSizeLimitInstruction,\n} from '../instructions';\n\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS =\n 'ComputeBudget111111111111111111111111111111' as Address<'ComputeBudget111111111111111111111111111111'>;\n\nexport enum ComputeBudgetInstruction {\n RequestUnits,\n RequestHeapFrame,\n SetComputeUnitLimit,\n SetComputeUnitPrice,\n SetLoadedAccountsDataSizeLimit,\n}\n\nexport function identifyComputeBudgetInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): ComputeBudgetInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return ComputeBudgetInstruction.RequestUnits;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return ComputeBudgetInstruction.RequestHeapFrame;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitLimit;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitPrice;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n }\n throw new Error(\n 'The provided instruction could not be identified as a computeBudget instruction.'\n );\n}\n\nexport type ParsedComputeBudgetInstruction<\n TProgram extends string = 'ComputeBudget111111111111111111111111111111',\n> =\n | ({\n instructionType: ComputeBudgetInstruction.RequestUnits;\n } & ParsedRequestUnitsInstruction<TProgram>)\n | ({\n instructionType: ComputeBudgetInstruction.RequestHeapFrame;\n } & ParsedRequestHeapFrameInstruction<TProgram>)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitLimit;\n } & ParsedSetComputeUnitLimitInstruction<TProgram>)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitPrice;\n } & ParsedSetComputeUnitPriceInstruction<TProgram>)\n | ({\n instructionType: ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n } & ParsedSetLoadedAccountsDataSizeLimitInstruction<TProgram>);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR = 2;\n\nexport function getSetComputeUnitLimitDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<TRemainingAccounts>;\n\nexport type SetComputeUnitLimitInstructionData = {\n discriminator: number;\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport type SetComputeUnitLimitInstructionDataArgs = {\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport function getSetComputeUnitLimitInstructionDataEncoder(): FixedSizeEncoder<SetComputeUnitLimitInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['units', getU32Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitLimitInstructionDataDecoder(): FixedSizeDecoder<SetComputeUnitLimitInstructionData> {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['units', getU32Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitLimitInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitLimitInstructionDataArgs,\n SetComputeUnitLimitInstructionData\n> {\n return combineCodec(\n getSetComputeUnitLimitInstructionDataEncoder(),\n getSetComputeUnitLimitInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitLimitInput = {\n units: SetComputeUnitLimitInstructionDataArgs['units'];\n};\n\nexport function getSetComputeUnitLimitInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitLimitInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitLimitInstruction<TProgramAddress> {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitLimitInstructionDataEncoder().encode(\n args as SetComputeUnitLimitInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitLimitInstruction<TProgramAddress>);\n}\n\nexport type ParsedSetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address<TProgram>;\n data: SetComputeUnitLimitInstructionData;\n};\n\nexport function parseSetComputeUnitLimitInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedSetComputeUnitLimitInstruction<TProgram> {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitLimitInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR = 3;\n\nexport function getSetComputeUnitPriceDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<TRemainingAccounts>;\n\nexport type SetComputeUnitPriceInstructionData = {\n discriminator: number;\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: bigint;\n};\n\nexport type SetComputeUnitPriceInstructionDataArgs = {\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: number | bigint;\n};\n\nexport function getSetComputeUnitPriceInstructionDataEncoder(): FixedSizeEncoder<SetComputeUnitPriceInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['microLamports', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitPriceInstructionDataDecoder(): FixedSizeDecoder<SetComputeUnitPriceInstructionData> {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['microLamports', getU64Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitPriceInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitPriceInstructionDataArgs,\n SetComputeUnitPriceInstructionData\n> {\n return combineCodec(\n getSetComputeUnitPriceInstructionDataEncoder(),\n getSetComputeUnitPriceInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitPriceInput = {\n microLamports: SetComputeUnitPriceInstructionDataArgs['microLamports'];\n};\n\nexport function getSetComputeUnitPriceInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitPriceInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitPriceInstruction<TProgramAddress> {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitPriceInstructionDataEncoder().encode(\n args as SetComputeUnitPriceInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitPriceInstruction<TProgramAddress>);\n}\n\nexport type ParsedSetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address<TProgram>;\n data: SetComputeUnitPriceInstructionData;\n};\n\nexport function parseSetComputeUnitPriceInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedSetComputeUnitPriceInstruction<TProgram> {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitPriceInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","import type {} from \"@solana/kit\";\nimport {\n getBase58Encoder,\n getPublicKeyFromAddress,\n verifySignature,\n type Address,\n type ReadonlyUint8Array,\n type Signature,\n type SignatureBytes,\n} from \"@solana/kit\";\n\n/**\n * Verifies a Solana Address had signed the given message.\n *\n * @param address - The Solana address expected to have signed the message\n * @param signature - The signature to verify\n * @param signedMessage - The original message that was signed\n * @returns Promise that resolves to `true` if the signature is valid, `false` otherwise\n *\n * @example\n * ```typescript\n * const isValid = await verifySignatureForAddress(\n * \"GC5AFcYqshWUnNK23MbWTXPix3FUagZt4fjUAt88FT59\" as Address,\n * \"jrZaHRqiRojydQMxHqqe7FEkfeyw64KfPdF2ww1mm3hpVtGyxBvEU5NmHdZFoawYnYu62ujgqw3gcL2XHYbxd9K\",\n * \"Hello, Solana!!\"\n * );\n * console.log(isValid); // true or false\n * ```\n */\nexport async function verifySignatureForAddress(\n address: Address,\n signature: string | Signature | SignatureBytes | Uint8Array | ReadonlyUint8Array,\n message: string | Uint8Array,\n): Promise<boolean> {\n const publicKey = await getPublicKeyFromAddress(address);\n if (typeof message === \"string\") {\n message = new TextEncoder().encode(message);\n }\n // massage the signature into the branded type for `SignatureBytes`\n if (typeof signature === \"string\") {\n signature = getBase58Encoder().encode(signature);\n }\n return verifySignature(publicKey, signature as SignatureBytes, message);\n}\n","export const REVIBASE_AUTH_URL = \"https://auth.revibase.com\";\n\nexport const REVIBASE_RP_ID = \"revibase.com\";\n\nexport const REVIBASE_API_ENDPOINT = \"https://api.revibase.com\";\n\nexport const REVIBASE_LOOKUP_TABLE_ADDRESS =\n \"2c1LgZfCun82niPCgfg2cTMZmAiahraTjY4KNb1BSU4Z\";\n\nexport const DEFAULT_JITO_BLOCK_ENGINE_SEND_BUNDLE_URL =\n \"https://mainnet.block-engine.jito.wtf/api/v1/bundles\";\n\nexport const DEFAULT_JITO_TIPS_URL =\n \"https://bundles.jito.wtf/api/v1/bundles/tip_floor\";\n","/** Base error. Use instanceof or .code for handling. */\nexport class RevibaseError extends Error {\n readonly code: string;\n\n constructor(message: string, code: string) {\n super(message);\n this.name = \"RevibaseError\";\n this.code = code;\n Object.setPrototypeOf(this, RevibaseError.prototype);\n }\n}\n\n/** Auth popup blocked. */\nexport class RevibasePopupBlockedError extends RevibaseError {\n constructor(message = \"Popup blocked. Please enable popups.\") {\n super(message, \"POPUP_BLOCKED\");\n this.name = \"RevibasePopupBlockedError\";\n Object.setPrototypeOf(this, RevibasePopupBlockedError.prototype);\n }\n}\n\n/** User closed popup before auth. */\nexport class RevibasePopupClosedError extends RevibaseError {\n constructor(message = \"Popup was closed by the user\") {\n super(message, \"POPUP_CLOSED\");\n this.name = \"RevibasePopupClosedError\";\n Object.setPrototypeOf(this, RevibasePopupClosedError.prototype);\n }\n}\n\n/** Authorization flow timed out. */\nexport class RevibaseTimeoutError extends RevibaseError {\n constructor(message = \"Authentication timed out\") {\n super(message, \"TIMEOUT\");\n this.name = \"RevibaseTimeoutError\";\n Object.setPrototypeOf(this, RevibaseTimeoutError.prototype);\n }\n}\n\n/** Flow already in progress. */\nexport class RevibaseFlowInProgressError extends RevibaseError {\n constructor(message = \"An authorization flow is already in progress\") {\n super(message, \"FLOW_IN_PROGRESS\");\n this.name = \"RevibaseFlowInProgressError\";\n Object.setPrototypeOf(this, RevibaseFlowInProgressError.prototype);\n }\n}\n\n/** Flow aborted (e.g. AbortSignal). */\nexport class RevibaseAbortedError extends RevibaseError {\n constructor(message = \"Aborted\") {\n super(message, \"ABORTED\");\n this.name = \"RevibaseAbortedError\";\n Object.setPrototypeOf(this, RevibaseAbortedError.prototype);\n }\n}\n\n/** Popup not open. */\nexport class RevibasePopupNotOpenError extends RevibaseError {\n constructor(message = \"Popup is not open. Call startRequest first.\") {\n super(message, \"POPUP_NOT_OPEN\");\n this.name = \"RevibasePopupNotOpenError\";\n Object.setPrototypeOf(this, RevibasePopupNotOpenError.prototype);\n }\n}\n\n/** Backend authorization failed. */\nexport class RevibaseAuthError extends RevibaseError {\n constructor(message: string) {\n super(message, \"AUTH_FAILED\");\n this.name = \"RevibaseAuthError\";\n Object.setPrototypeOf(this, RevibaseAuthError.prototype);\n }\n}\n\n/** Backend authorization failed. */\nexport class RevibaseApiError extends RevibaseError {\n constructor(message: string) {\n super(message, \"API_FAILED\");\n this.name = \"RevibaseApiError\";\n Object.setPrototypeOf(this, RevibaseApiError.prototype);\n }\n}\n\n/** Used outside browser. */\nexport class RevibaseEnvironmentError extends RevibaseError {\n constructor(message = \"Provider can only be used in a browser environment\") {\n super(message, \"ENVIRONMENT\");\n this.name = \"RevibaseEnvironmentError\";\n Object.setPrototypeOf(this, RevibaseEnvironmentError.prototype);\n }\n}\n","import type {\n CompleteMessageRequest,\n CompleteTransactionRequest,\n UserInfo,\n} from \"@revibase/core\";\nimport {\n RevibaseApiError,\n RevibaseAuthError,\n type ClientAuthorizationCallback,\n type OnConnectedCallback,\n type OnSuccessCallback,\n} from \"../utils\";\n\nexport const DEFAULT_TIMEOUT = 3 * 60 * 1000;\nexport const HEARTBEAT_INTERVAL = 2000;\nexport const CONNECT_TIMEOUT = 20000;\n\nexport type PopupPortMessage =\n | { type: \"pong\" }\n | {\n type: \"popup-complete\";\n payload: CompleteTransactionRequest | CompleteMessageRequest;\n }\n | { type: \"popup-rejected\"; rid: string }\n | { type: \"popup-error\"; error: string }\n | { type: \"popup-closed\" };\n\nexport type PopupConnectMessage = {\n type: \"popup-connect\";\n rid: string;\n};\n\nexport type Pending = {\n rid: string;\n clientOrigin: string;\n onConnectedCallback: OnConnectedCallback;\n onSuccessCallback: OnSuccessCallback;\n signal?: AbortSignal;\n resolve: (v: { user: UserInfo } | { user: UserInfo; txSig: string }) => void;\n reject: (e: Error) => void;\n};\n\n/** RevibaseProvider options. rpcEndpoint required for executeTransaction. */\nexport type RevibaseProviderOptions = {\n rpcEndpoint: string;\n providerOrigin?: string;\n rpId?: string;\n /** UI mode for same-device authorization. Default: \"iframe\". */\n ui?: {\n mode?: \"popup\" | \"iframe\";\n /**\n * Optional advanced hook to fully control how the provider UI is rendered.\n * Return a target window (popup or iframe.contentWindow) for postMessage transport,\n * and a close() function for cleanup. If you can, also provide isClosed() so the\n * SDK can detect user-dismissal.\n */\n render?: (url: string) => {\n targetWindow: Window;\n close: () => void;\n isClosed?: () => boolean;\n };\n };\n onClientAuthorizationCallback?: ClientAuthorizationCallback;\n onEstimateJitoTipsCallback?: () => Promise<number>;\n onSendJitoBundleCallback?: (request: string[]) => Promise<string>;\n};\n\nexport const defaultSendJitoBundleCallback: (\n serializedTransactions: string[],\n) => Promise<string> = async (request) => {\n const res = await fetch(\"/api/sendJitoBundle\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(request),\n });\n\n const data = await res.json();\n if (!res.ok) {\n throw new RevibaseApiError(\n (data as { error?: string }).error ?? \"Send jito bundle failed\",\n );\n }\n\n return data;\n};\n\nexport const defaultEstimateJitoTipsCallback: () => Promise<number> =\n async () => {\n const res = await fetch(\"/api/estimateJitoTips\");\n\n const data = await res.json();\n if (!res.ok) {\n throw new RevibaseApiError(\n (data as { error?: string }).error ?? \"Estimate jito tips failed\",\n );\n }\n\n return data;\n };\n\nexport const defaultClientAuthorizationCallback: ClientAuthorizationCallback =\n async (request) => {\n const res = await fetch(\"/api/clientAuthorization\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(request),\n });\n\n const data = await res.json();\n if (!res.ok) {\n throw new RevibaseAuthError(\n (data as { error?: string }).error ?? \"Authorization failed\",\n );\n }\n\n return data;\n };\n\nexport function createPopUp(url: string): Window | null {\n if (typeof window === \"undefined\") {\n throw new Error(\"Function can only be called in a browser environment\");\n }\n\n const availW = window.innerWidth || window.screen.availWidth;\n const availH = window.innerHeight || window.screen.availHeight;\n const isMobile = availW <= 768;\n\n let width: number;\n let height: number;\n let top: number;\n let left: number;\n\n if (isMobile) {\n width = availW;\n height = availH;\n top = 0;\n left = 0;\n } else {\n const screenLeft = window.screenLeft ?? window.screenX ?? 0;\n const screenTop = window.screenTop ?? window.screenY ?? 0;\n\n const viewportW =\n window.innerWidth ??\n document.documentElement.clientWidth ??\n window.screen.width;\n\n const viewportH =\n window.innerHeight ??\n document.documentElement.clientHeight ??\n window.screen.height;\n\n width = 500;\n height = 600;\n left = Math.round(screenLeft + (viewportW - width) / 2);\n top = Math.round(screenTop + (viewportH - height) / 2);\n }\n\n const features = [\n \"popup=yes\",\n `width=${width}`,\n `height=${height}`,\n `top=${top}`,\n `left=${left}`,\n \"toolbar=no\",\n \"location=no\",\n \"status=no\",\n \"menubar=no\",\n \"scrollbars=yes\",\n \"resizable=yes\",\n ].join(\",\");\n\n return window.open(url, \"_blank\", features);\n}\nexport interface ProviderFrame {\n iframe: HTMLIFrameElement;\n close: () => void;\n}\n\nexport function createProviderFrame(\n url: string,\n signal?: AbortSignal,\n onDismiss?: () => void,\n): ProviderFrame {\n if (typeof window === \"undefined\") {\n throw new Error(\"Function can only be called in a browser environment\");\n }\n\n const isMobile = window.matchMedia(\"(max-width: 768px)\").matches;\n\n // ----------------------------------------\n // Scroll lock (iOS-safe)\n // ----------------------------------------\n\n const scrollY = window.scrollY;\n\n const previousBodyStyles = {\n overflow: document.body.style.overflow,\n position: document.body.style.position,\n top: document.body.style.top,\n left: document.body.style.left,\n right: document.body.style.right,\n width: document.body.style.width,\n };\n\n const lockScroll = () => {\n document.body.style.overflow = \"hidden\";\n document.body.style.position = \"fixed\";\n document.body.style.top = `-${scrollY}px`;\n document.body.style.left = \"0\";\n document.body.style.right = \"0\";\n document.body.style.width = \"100%\";\n };\n\n const unlockScroll = () => {\n document.body.style.overflow = previousBodyStyles.overflow;\n document.body.style.position = previousBodyStyles.position;\n document.body.style.top = previousBodyStyles.top;\n document.body.style.left = previousBodyStyles.left;\n document.body.style.right = previousBodyStyles.right;\n document.body.style.width = previousBodyStyles.width;\n\n window.scrollTo(0, scrollY);\n };\n\n lockScroll();\n\n // ----------------------------------------\n // Shadow DOM host\n // ----------------------------------------\n\n const host = document.createElement(\"div\");\n\n host.setAttribute(\"data-provider-frame-root\", \"true\");\n\n Object.assign(host.style, {\n position: \"fixed\",\n inset: \"0\",\n zIndex: \"2147483647\",\n pointerEvents: \"none\",\n contain: \"layout style paint\",\n });\n\n document.body.appendChild(host);\n\n const shadow = host.attachShadow({ mode: \"closed\" });\n\n // ----------------------------------------\n // Overlay\n // ----------------------------------------\n\n const overlay = document.createElement(\"div\");\n\n Object.assign(overlay.style, {\n all: \"initial\",\n\n position: \"fixed\",\n inset: \"0\",\n\n display: \"flex\",\n alignItems: isMobile ? \"flex-end\" : \"center\",\n justifyContent: \"center\",\n\n background: \"rgba(0,0,0,0.45)\",\n\n zIndex: \"2147483647\",\n\n pointerEvents: \"auto\",\n\n overscrollBehavior: \"contain\",\n touchAction: \"none\",\n\n WebkitTapHighlightColor: \"transparent\",\n\n paddingBottom: \"env(safe-area-inset-bottom)\",\n\n fontFamily:\n 'Inter, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif',\n });\n\n shadow.appendChild(overlay);\n\n // ----------------------------------------\n // Frame wrapper\n // ----------------------------------------\n\n const frameWrapper = document.createElement(\"div\");\n\n Object.assign(frameWrapper.style, {\n all: \"initial\",\n\n position: \"relative\",\n\n display: \"flex\",\n\n width: isMobile ? \"100%\" : \"500px\",\n\n height: isMobile ? \"90dvh\" : \"600px\",\n\n maxWidth: \"100vw\",\n maxHeight: \"100dvh\",\n\n borderRadius: isMobile ? \"16px 16px 0 0\" : \"16px\",\n\n overflow: \"hidden\",\n\n boxShadow: \"0 24px 80px rgba(0,0,0,0.35)\",\n\n background: \"#fff\",\n\n pointerEvents: \"auto\",\n });\n\n overlay.appendChild(frameWrapper);\n\n // ----------------------------------------\n // iframe\n // ----------------------------------------\n\n const iframe = document.createElement(\"iframe\");\n\n iframe.src = url;\n\n iframe.title = \"Authorization\";\n\n iframe.setAttribute(\"tabindex\", \"0\");\n\n iframe.allow = [`publickey-credentials-get ${new URL(url).origin}`].join(\n \"; \",\n );\n\n iframe.sandbox = [\"allow-scripts\", \"allow-same-origin\"].join(\" \");\n\n Object.assign(iframe.style, {\n width: \"100%\",\n height: \"100%\",\n\n border: \"0\",\n\n background: \"#fff\",\n\n display: \"block\",\n });\n\n frameWrapper.appendChild(iframe);\n\n // ----------------------------------------\n // Close button\n // ----------------------------------------\n\n const closeBtn = document.createElement(\"button\");\n\n closeBtn.type = \"button\";\n\n closeBtn.setAttribute(\"aria-label\", \"Close\");\n\n closeBtn.innerHTML = \"×\";\n\n Object.assign(closeBtn.style, {\n all: \"initial\",\n\n position: \"absolute\",\n\n top: isMobile ? \"12px\" : \"14px\",\n right: isMobile ? \"12px\" : \"14px\",\n\n width: \"44px\",\n height: \"44px\",\n\n display: \"grid\",\n placeItems: \"center\",\n\n borderRadius: \"9999px\",\n\n background: \"rgba(255,255,255,0.96)\",\n\n color: \"#111\",\n\n fontSize: \"28px\",\n\n lineHeight: \"1\",\n\n cursor: \"pointer\",\n\n boxShadow: \"0 8px 24px rgba(0,0,0,0.25)\",\n\n zIndex: \"2\",\n\n userSelect: \"none\",\n WebkitUserSelect: \"none\",\n });\n\n frameWrapper.appendChild(closeBtn);\n\n // ----------------------------------------\n // Focus iframe\n // ----------------------------------------\n\n requestAnimationFrame(() => {\n try {\n iframe.focus();\n } catch {}\n });\n\n // ----------------------------------------\n // Escape key\n // ----------------------------------------\n\n const keyHandler = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n dismiss();\n }\n };\n\n document.addEventListener(\"keydown\", keyHandler);\n\n // ----------------------------------------\n // Close logic\n // ----------------------------------------\n\n let closed = false;\n\n const close = () => {\n if (closed) return;\n\n closed = true;\n\n try {\n signal?.removeEventListener(\"abort\", abortHandler);\n } catch {}\n\n try {\n document.removeEventListener(\"keydown\", keyHandler);\n } catch {}\n\n try {\n iframe.src = \"about:blank\";\n iframe.removeAttribute(\"src\");\n } catch {}\n\n try {\n host.remove();\n } catch {}\n\n unlockScroll();\n };\n\n // ----------------------------------------\n // Dismiss\n // ----------------------------------------\n\n const dismiss = () => {\n onDismiss?.();\n close();\n };\n\n closeBtn.addEventListener(\"click\", (e) => {\n e.preventDefault();\n e.stopPropagation();\n\n dismiss();\n });\n\n overlay.addEventListener(\"click\", (e) => {\n if (e.target === overlay) {\n dismiss();\n }\n });\n\n // ----------------------------------------\n // Abort signal\n // ----------------------------------------\n\n const abortHandler = () => {\n dismiss();\n };\n\n if (signal) {\n if (signal.aborted) {\n abortHandler();\n } else {\n signal.addEventListener(\"abort\", abortHandler, {\n once: true,\n });\n }\n }\n\n return {\n iframe,\n close,\n };\n}\n","import type {\n CompleteMessageRequest,\n CompleteTransactionRequest,\n UserInfo,\n} from \"@revibase/core\";\nimport { initialize } from \"@revibase/core\";\nimport { getBase64Decoder } from \"gill\";\nimport type {\n ClientAuthorizationCallback,\n OnConnectedCallback,\n OnSuccessCallback,\n} from \"../utils\";\nimport { REVIBASE_AUTH_URL, REVIBASE_RP_ID } from \"../utils/consts\";\nimport {\n RevibaseAbortedError,\n RevibaseAuthError,\n RevibaseEnvironmentError,\n RevibaseFlowInProgressError,\n RevibasePopupBlockedError,\n RevibasePopupClosedError,\n RevibaseTimeoutError,\n} from \"../utils/errors\";\nimport {\n CONNECT_TIMEOUT,\n createPopUp,\n createProviderFrame,\n defaultClientAuthorizationCallback,\n defaultEstimateJitoTipsCallback,\n defaultSendJitoBundleCallback,\n HEARTBEAT_INTERVAL,\n type Pending,\n type PopupConnectMessage,\n type PopupPortMessage,\n type RevibaseProviderOptions,\n} from \"./utils\";\n\n/** Provider: popup or channel auth. Default callback: POST /api/clientAuthorization. */\nexport class RevibaseProvider {\n public onClientAuthorizationCallback: ClientAuthorizationCallback;\n public onSendJitoBundleCallback: (request: string[]) => Promise<string>;\n public onEstimateJitoTipsCallback: () => Promise<number>;\n public providerOrigin: string;\n public rpId: string;\n private uiMode: \"popup\" | \"iframe\";\n private render?: NonNullable<RevibaseProviderOptions[\"ui\"]>[\"render\"];\n private popUp: Window | null = null;\n private frame: ReturnType<typeof createProviderFrame> | null = null;\n private rendered:\n | { targetWindow: Window; close: () => void; isClosed?: () => boolean }\n | null = null;\n\n constructor(options: RevibaseProviderOptions) {\n const {\n rpId,\n rpcEndpoint,\n providerOrigin,\n ui,\n onClientAuthorizationCallback,\n onSendJitoBundleCallback,\n onEstimateJitoTipsCallback,\n } = options;\n\n initialize({ rpcEndpoint });\n this.onClientAuthorizationCallback =\n onClientAuthorizationCallback ?? defaultClientAuthorizationCallback;\n this.onSendJitoBundleCallback =\n onSendJitoBundleCallback ?? defaultSendJitoBundleCallback;\n this.onEstimateJitoTipsCallback =\n onEstimateJitoTipsCallback ?? defaultEstimateJitoTipsCallback;\n this.providerOrigin = providerOrigin ?? REVIBASE_AUTH_URL;\n this.rpId = rpId ?? REVIBASE_RP_ID;\n this.uiMode = ui?.mode ?? \"iframe\";\n this.render = ui?.render;\n }\n\n async sendRequestToPopupProvider({\n onConnectedCallback,\n onSuccessCallback,\n signal,\n }: {\n onConnectedCallback: OnConnectedCallback;\n onSuccessCallback: OnSuccessCallback;\n signal?: AbortSignal;\n }) {\n if (typeof window === \"undefined\") {\n throw new RevibaseEnvironmentError();\n }\n\n if (this.popUp || this.frame || this.rendered) {\n throw new RevibaseFlowInProgressError();\n }\n\n const rid = getBase64Decoder().decode(\n crypto.getRandomValues(new Uint8Array(16)),\n );\n const clientOrigin = window.location.origin;\n const popupUrl = `${this.providerOrigin}?clientOrigin=${encodeURIComponent(clientOrigin)}&rid=${encodeURIComponent(rid)}`;\n\n let detachForwardAbort: (() => void) | undefined;\n\n if (this.render) {\n this.rendered = this.render(popupUrl);\n } else if (this.uiMode === \"iframe\") {\n // We need a controller here so backdrop-dismiss can \"abort\" the flow.\n const flowAbortController = new AbortController();\n const forwardAbort = () => flowAbortController.abort();\n const originalSignal = signal;\n if (originalSignal) {\n if (originalSignal.aborted) {\n flowAbortController.abort();\n } else {\n originalSignal.addEventListener(\"abort\", forwardAbort, { once: true });\n detachForwardAbort = () =>\n originalSignal.removeEventListener(\"abort\", forwardAbort);\n }\n }\n\n this.frame = createProviderFrame(\n popupUrl,\n flowAbortController.signal,\n () => flowAbortController.abort(),\n );\n\n // Replace the provided signal so transport + cleanup treat backdrop-dismiss as abort.\n signal = flowAbortController.signal;\n } else {\n this.popUp = createPopUp(popupUrl);\n if (!this.popUp) {\n throw new RevibasePopupBlockedError();\n }\n }\n\n return new Promise<{ user: UserInfo } | { txSig: string; user: UserInfo }>(\n (resolve, reject) => {\n setTimeout(() => {\n this.attachTransport({\n rid,\n clientOrigin,\n onConnectedCallback,\n onSuccessCallback,\n signal,\n resolve,\n reject,\n });\n }, 0);\n },\n ).finally(() => {\n try {\n detachForwardAbort?.();\n } catch {\n // ignore\n }\n });\n }\n\n private attachTransport(params: Pending) {\n const {\n rid,\n clientOrigin,\n onConnectedCallback,\n onSuccessCallback,\n signal,\n reject,\n resolve,\n } = params;\n\n const abortHandler = () => {\n fail(new RevibaseAbortedError());\n };\n signal?.addEventListener(\"abort\", abortHandler, { once: true });\n\n let port: MessagePort | null = null;\n let finished = false;\n\n let heartbeatInterval: ReturnType<typeof setInterval> | null = null;\n let connectTimeoutId: ReturnType<typeof setTimeout> | null = null;\n let requestTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = (): void => {\n // Remove all event listeners\n window.removeEventListener(\"message\", onConnect);\n signal?.removeEventListener(\"abort\", abortHandler);\n\n // Clear all timers\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = null;\n }\n if (connectTimeoutId) {\n clearTimeout(connectTimeoutId);\n connectTimeoutId = null;\n }\n if (requestTimeoutId) {\n clearTimeout(requestTimeoutId);\n requestTimeoutId = null;\n }\n\n // Close message port\n try {\n port?.close();\n } catch (err) {\n // Ignore close errors\n }\n port = null;\n\n // Close UI\n try {\n if (this.popUp && !this.popUp.closed) {\n this.popUp.close();\n }\n } catch (err) {\n // Ignore close errors\n }\n\n try {\n this.frame?.close();\n } catch (err) {\n // Ignore close errors\n }\n\n try {\n this.rendered?.close();\n } catch (err) {\n // Ignore close errors\n }\n\n this.popUp = null;\n this.frame = null;\n this.rendered = null;\n };\n\n const fail = (err: Error): void => {\n if (finished) return;\n finished = true;\n cleanup();\n reject(err);\n };\n\n const succeed = (\n value: CompleteMessageRequest | CompleteTransactionRequest,\n ): void => {\n if (finished) return;\n finished = true;\n cleanup();\n onSuccessCallback(value as any)\n .then((result) => {\n resolve(result);\n })\n .catch((err) => {\n reject(err);\n });\n };\n\n // Connection timeout - handles popup closed before connection\n connectTimeoutId = setTimeout(() => {\n fail(new RevibaseTimeoutError(\"Popup connection timed out after 20s\"));\n }, CONNECT_TIMEOUT);\n\n const onConnect = (event: MessageEvent) => {\n // Prevent race condition - only process once\n if (finished || port) return;\n\n // Validate message origin\n if (event.origin !== this.providerOrigin) return;\n\n const data = event.data as PopupConnectMessage;\n\n // Validate message structure\n if (!data || data.type !== \"popup-connect\") return;\n if (data.rid !== rid) return;\n\n // Clear connection timeout\n if (connectTimeoutId) {\n clearTimeout(connectTimeoutId);\n connectTimeoutId = null;\n }\n\n // Create MessageChannel for bidirectional communication\n const channel = new MessageChannel();\n port = channel.port1;\n port.start();\n\n let lastPong = Date.now();\n\n // Start heartbeat ONLY AFTER connection established\n heartbeatInterval = setInterval(() => {\n if (finished) {\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = null;\n }\n return;\n }\n\n if (this.rendered?.isClosed) {\n if (this.rendered.isClosed()) {\n fail(new RevibasePopupClosedError(\"Provider UI was closed\"));\n return;\n }\n } else if (this.rendered) {\n // If consumer didn't provide isClosed, we can't reliably detect.\n } else if (this.uiMode === \"iframe\") {\n // If the iframe is removed, treat as closed\n if (!this.frame?.iframe.isConnected) {\n fail(new RevibasePopupClosedError(\"Provider iframe was closed\"));\n return;\n }\n } else {\n if (this.popUp?.closed) {\n fail(new RevibasePopupClosedError(\"Popup was closed\"));\n return;\n }\n }\n\n // Check if port is still available\n if (!port) {\n fail(new RevibasePopupClosedError(\"Message channel lost\"));\n return;\n }\n\n const now = Date.now();\n\n // Check if we've lost connection (no pong in 2x heartbeat interval)\n if (now - lastPong > HEARTBEAT_INTERVAL * 2) {\n fail(\n new RevibasePopupClosedError(\n \"Lost connection to popup (heartbeat timeout)\",\n ),\n );\n return;\n }\n\n // Send ping\n try {\n port.postMessage({ type: \"ping\" });\n } catch (err) {\n fail(new RevibasePopupClosedError(\"Failed to send heartbeat\"));\n }\n }, HEARTBEAT_INTERVAL);\n\n // Handle messages from popup\n port.onmessage = (ev: MessageEvent<PopupPortMessage>): void => {\n if (finished) return;\n const msg = ev.data;\n\n switch (msg.type) {\n case \"pong\":\n lastPong = Date.now();\n break;\n\n case \"popup-complete\":\n if (msg.payload) {\n succeed(msg.payload);\n } else {\n fail(new RevibaseAuthError(\"Invalid completion payload\"));\n }\n break;\n\n case \"popup-rejected\":\n fail(new RevibaseAuthError(\"User rejected the operation\"));\n break;\n\n case \"popup-error\":\n fail(new RevibaseAuthError(msg.error || \"Unknown popup error\"));\n break;\n\n case \"popup-closed\":\n fail(new RevibasePopupClosedError(\"User closed popup\"));\n break;\n\n default:\n console.warn(\"Unknown message type from popup:\", msg);\n }\n };\n\n // Handle port errors\n port.onmessageerror = () => {\n fail(new RevibaseAuthError(\"Message deserialization error\"));\n };\n\n // Send init message to popup with port2\n try {\n if (this.rendered) {\n this.rendered.targetWindow.postMessage(\n {\n type: \"popup-init\",\n rid,\n },\n this.providerOrigin,\n [channel.port2],\n );\n } else if (this.uiMode === \"iframe\") {\n this.frame?.iframe.contentWindow?.postMessage(\n {\n type: \"popup-init\",\n rid,\n },\n this.providerOrigin,\n [channel.port2],\n );\n } else {\n this.popUp?.postMessage(\n {\n type: \"popup-init\",\n rid,\n },\n this.providerOrigin,\n [channel.port2],\n );\n }\n } catch (err) {\n fail(new RevibaseAuthError(`Failed to initialize popup: ${err}`));\n return;\n }\n\n // Call the callback to get the request\n onConnectedCallback(rid, clientOrigin)\n .then((result) => {\n // Verify we're still active\n if (finished || !port) {\n return;\n }\n if (this.rendered?.isClosed) {\n if (this.rendered.isClosed()) return;\n } else if (this.uiMode === \"iframe\") {\n if (!this.frame?.iframe.isConnected) return;\n } else {\n if (this.popUp?.closed) return;\n }\n\n // Send the request to popup\n try {\n port.postMessage({\n type: \"popup-start\",\n payload: result,\n });\n } catch (err) {\n fail(\n new RevibaseAuthError(`Failed to send request to popup: ${err}`),\n );\n return;\n }\n\n // Clear any existing request timeout\n if (requestTimeoutId) {\n clearTimeout(requestTimeoutId);\n requestTimeoutId = null;\n }\n\n // Calculate TTL and set new timeout\n const timeoutDuration = Math.max(\n 0,\n result.request.validTill - Date.now(),\n );\n\n requestTimeoutId = setTimeout(() => {\n fail(new RevibaseTimeoutError(\"Request expired\"));\n }, timeoutDuration);\n })\n .catch((err) => {\n fail(err);\n });\n };\n\n // Attach connect listener\n window.addEventListener(\"message\", onConnect);\n }\n}\n","/** Sign-in message text (domain + nonce). */\nexport function createSignInMessageText(input: {\n domain?: string;\n nonce: string;\n}): string {\n const message = input.domain\n ? `${input.domain} wants you to sign in with your account.`\n : \"Sign in with your account.\";\n\n const fields: string[] = [];\n\n if (input.nonce) {\n fields.push(`Nonce: ${input.nonce}`);\n }\n\n return fields.length > 0 ? `${message}\\n\\n${fields.join(\"\\n\")}` : message;\n}\n","/**\n * Checks if an error is network-related (e.g., load failed, network errors)\n */\nfunction isNetworkError(err: Error): boolean {\n const msg = err?.message || \"\";\n return (\n msg === \"Failed to fetch\" ||\n msg.includes(\"Load failed\") ||\n msg.includes(\"NetworkError\") ||\n msg.includes(\"ERR_NETWORK\")\n );\n}\n\n/**\n * Retries a function with exponential backoff on network errors only.\n * @param fn - The async function to retry\n * @param maxAttempts - Maximum number of attempts (default: 3)\n * @param initialDelay - Initial delay in ms (default: 100)\n * @param maxDelay - Maximum delay in ms (default: 5000)\n */\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n maxAttempts = 3,\n initialDelay = 500,\n maxDelay = 5000,\n): Promise<T> {\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Only retry on network errors\n if (!isNetworkError(lastError)) {\n throw lastError;\n }\n\n // Don't retry on the last attempt\n if (attempt === maxAttempts - 1) {\n break;\n }\n\n // Calculate exponential backoff delay\n const delay = Math.min(initialDelay * Math.pow(2, attempt), maxDelay);\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw lastError;\n}\n","import type { CompleteMessageRequest } from \"@revibase/core\";\nimport type { SignInAuthorizationFlowOptions } from \"../types\";\n\nexport async function fetchSignatureFromTransactionManager({\n data,\n url,\n options,\n}: {\n data: {\n publicKey: string;\n payload: CompleteMessageRequest;\n };\n url: string;\n options?: SignInAuthorizationFlowOptions;\n}) {\n const maxAttempts = 10;\n const retryDelayMs = 400;\n const wsUrl = toWebSocketUrl(url);\n const { pendingApprovalsCallback, signal } = options ?? {};\n\n for (let i = 0; i < maxAttempts; i++) {\n if (signal?.aborted) throw Error(\"Aborted\");\n let signatures: string[] | undefined;\n let ws: WebSocket | undefined;\n try {\n ws = await openWebSocket(wsUrl, signal);\n ws.send(JSON.stringify({ type: \"message\", data }));\n await readWebSocketJsonEvents(\n ws,\n (event, data) => {\n if (event === \"error\") {\n const err =\n data &&\n typeof data === \"object\" &&\n typeof (data as { error?: string }).error === \"string\"\n ? (data as { error: string }).error\n : \"Unknown error\";\n const e = new Error(err) as Error & { noRetry: true };\n e.noRetry = true;\n throw e;\n }\n if (event === \"signatures\") {\n signatures = (data as { signatures?: string[] }).signatures;\n return true;\n }\n if (event === \"pending_transaction_approval\") {\n pendingApprovalsCallback?.onPendingApprovalsCallback?.(\n (data as { validTill: number }).validTill,\n );\n } else if (event === \"transaction_approved\") {\n pendingApprovalsCallback?.onPendingApprovalsSuccess?.();\n }\n return false;\n },\n signal,\n );\n } catch (e: unknown) {\n if (e && typeof e === \"object\" && (e as { noRetry?: true }).noRetry) {\n throw new Error(`${(e as Error).message}`);\n }\n if (\n e &&\n typeof e === \"object\" &&\n (e as { name?: string }).name === \"AbortError\"\n )\n throw e;\n } finally {\n try {\n ws?.close();\n } catch {\n /* ignore */\n }\n }\n if (signatures?.length) {\n return signatures[0];\n }\n if (i < maxAttempts - 1)\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n }\n throw new Error(\"Transaction manager: missing signatures\");\n}\n\nfunction toWebSocketUrl(httpUrl: string): string {\n const u = new URL(httpUrl);\n if (u.protocol === \"https:\") u.protocol = \"wss:\";\n else if (u.protocol === \"http:\") u.protocol = \"ws:\";\n return u.toString();\n}\n\nfunction openWebSocket(url: string, signal?: AbortSignal): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(url);\n\n const onAbort = () => {\n try {\n ws.close();\n } catch {\n /* ignore */\n }\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n ws.onopen = () => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(ws);\n };\n ws.onerror = () => {\n signal?.removeEventListener(\"abort\", onAbort);\n reject(new Error(\"WebSocket connection failed\"));\n };\n });\n}\n\nasync function readWebSocketJsonEvents(\n ws: WebSocket,\n onEvent: (event: string, data: any) => boolean,\n signal?: AbortSignal,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let settled = false;\n\n const cleanup = () => {\n signal?.removeEventListener(\"abort\", onAbort);\n ws.removeEventListener(\"message\", onMessage);\n ws.removeEventListener(\"error\", onError);\n ws.removeEventListener(\"close\", onClose);\n };\n\n const finish = (fn: () => void) => {\n if (settled) return;\n settled = true;\n cleanup();\n fn();\n };\n\n const onAbort = () => {\n try {\n ws.close();\n } catch {\n /* ignore */\n }\n };\n signal?.addEventListener(\"abort\", onAbort);\n\n const onMessage = (ev: MessageEvent) => {\n if (typeof ev.data !== \"string\") return;\n let parsed: { event?: string; data?: unknown };\n try {\n parsed = JSON.parse(ev.data);\n } catch {\n return;\n }\n const event = typeof parsed.event === \"string\" ? parsed.event : \"message\";\n const data = parsed.data;\n try {\n if (onEvent(event, data)) {\n finish(() => resolve());\n }\n } catch (e) {\n finish(() => reject(e));\n }\n };\n\n const onError = () => {\n finish(() => reject(new Error(\"Transaction manager request failed\")));\n };\n\n const onClose = () => {\n finish(() => resolve());\n };\n\n ws.addEventListener(\"message\", onMessage);\n ws.addEventListener(\"error\", onError);\n ws.addEventListener(\"close\", onClose);\n });\n}\n","import type { UserInfo } from \"@revibase/core\";\nimport {\n convertMemberKeyToString,\n fetchSettings,\n fetchUser,\n getSettingsFromIndex,\n getSolanaRpc,\n getUserAddress,\n UserRole,\n type CompleteMessageRequest,\n} from \"@revibase/core\";\nimport { address } from \"gill\";\nimport { withRetry } from \"../retry\";\nimport type { SignInAuthorizationFlowOptions } from \"../types\";\nimport { fetchSignatureFromTransactionManager } from \"./fetchSIgnatureFromTransactionManager\";\n\nexport async function send2FARequestIfNeeded(\n user: UserInfo,\n request: CompleteMessageRequest,\n options?: SignInAuthorizationFlowOptions,\n): Promise<{ publicKey: string; signature: string } | null> {\n const { startRequest } = request.data.payload;\n\n if (!startRequest.data.requireTwoFactorAuthentication) {\n return null;\n }\n\n const settingsData = (\n await withRetry(async () =>\n fetchSettings(\n getSolanaRpc(),\n await getSettingsFromIndex(user.settingsIndexWithAddress.index),\n ),\n )\n ).data;\n const transactionManager = settingsData.members.find(\n (x) => x.role === UserRole.TransactionManager,\n );\n if (!transactionManager) {\n throw new Error(\"No transaction manager found.\");\n }\n const publicKey = convertMemberKeyToString(transactionManager.pubkey);\n const userAccountData = (\n await withRetry(async () =>\n fetchUser(getSolanaRpc(), await getUserAddress(address(publicKey))),\n )\n ).data;\n if (userAccountData.transactionManagerUrl.__option === \"None\") {\n throw new Error(\"No transaction manager url found.\");\n }\n const signature = await fetchSignatureFromTransactionManager({\n data: {\n publicKey,\n payload: request,\n },\n url: userAccountData.transactionManagerUrl.value,\n options,\n });\n\n return { publicKey, signature };\n}\n","import {\n UserInfoSchema,\n type CompleteMessageRequest,\n type UserInfo,\n} from \"@revibase/core\";\nimport { getBase64Decoder } from \"gill\";\nimport { RevibaseProvider } from \"../provider/main\";\nimport { createSignInMessageText } from \"../utils/internal\";\nimport { send2FARequestIfNeeded } from \"../utils/message\";\nimport { withRetry } from \"../utils/retry\";\nimport type { SignInAuthorizationFlowOptions } from \"../utils/types\";\n\n/** Opens auth popup (or channel when options.channelId). Returns user after passkey auth. Options: signal?, channelId?. */\nexport async function signIn(\n provider: RevibaseProvider,\n options?: SignInAuthorizationFlowOptions,\n): Promise<{ user: UserInfo }> {\n const onConnectedCallback = async (rid: string, clientOrigin: string) => {\n const payload = {\n phase: \"start\" as const,\n rid,\n providerOrigin: provider.providerOrigin,\n rpId: provider.rpId,\n data: {\n type: \"message\" as const,\n payload: createSignInMessageText({\n domain: clientOrigin,\n nonce: getBase64Decoder().decode(\n crypto.getRandomValues(new Uint8Array(16)),\n ),\n }),\n requireTwoFactorAuthentication:\n options?.requireTwoFactorAuthentication ?? false,\n },\n clientOrigin,\n };\n\n const { signature, validTill } = await withRetry(() =>\n provider.onClientAuthorizationCallback(payload),\n );\n return { request: { ...payload, rid, validTill }, signature };\n };\n\n const onSuccessCallback = async (\n result: CompleteMessageRequest,\n ): Promise<{ user: UserInfo }> => {\n const user = UserInfoSchema.parse(result.data.payload.additionalInfo);\n const transactionManager = await send2FARequestIfNeeded(\n user,\n result,\n options,\n );\n await provider.onClientAuthorizationCallback(\n !transactionManager\n ? result\n : {\n ...result,\n data: {\n ...result.data,\n payload: { ...result.data.payload, transactionManager },\n },\n },\n );\n return { user };\n };\n\n return provider.sendRequestToPopupProvider({\n onConnectedCallback,\n onSuccessCallback,\n signal: options?.signal,\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU32Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAdvanceNonceAccountInstruction,\n type ParsedAllocateInstruction,\n type ParsedAllocateWithSeedInstruction,\n type ParsedAssignInstruction,\n type ParsedAssignWithSeedInstruction,\n type ParsedAuthorizeNonceAccountInstruction,\n type ParsedCreateAccountInstruction,\n type ParsedCreateAccountWithSeedInstruction,\n type ParsedInitializeNonceAccountInstruction,\n type ParsedTransferSolInstruction,\n type ParsedTransferSolWithSeedInstruction,\n type ParsedUpgradeNonceAccountInstruction,\n type ParsedWithdrawNonceAccountInstruction,\n} from '../instructions';\n\nexport const SYSTEM_PROGRAM_ADDRESS =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\nexport enum SystemAccount {\n Nonce,\n}\n\nexport enum SystemInstruction {\n CreateAccount,\n Assign,\n TransferSol,\n CreateAccountWithSeed,\n AdvanceNonceAccount,\n WithdrawNonceAccount,\n InitializeNonceAccount,\n AuthorizeNonceAccount,\n Allocate,\n AllocateWithSeed,\n AssignWithSeed,\n TransferSolWithSeed,\n UpgradeNonceAccount,\n}\n\nexport function identifySystemInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): SystemInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU32Encoder().encode(0), 0)) {\n return SystemInstruction.CreateAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(1), 0)) {\n return SystemInstruction.Assign;\n }\n if (containsBytes(data, getU32Encoder().encode(2), 0)) {\n return SystemInstruction.TransferSol;\n }\n if (containsBytes(data, getU32Encoder().encode(3), 0)) {\n return SystemInstruction.CreateAccountWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(4), 0)) {\n return SystemInstruction.AdvanceNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(5), 0)) {\n return SystemInstruction.WithdrawNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(6), 0)) {\n return SystemInstruction.InitializeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(7), 0)) {\n return SystemInstruction.AuthorizeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(8), 0)) {\n return SystemInstruction.Allocate;\n }\n if (containsBytes(data, getU32Encoder().encode(9), 0)) {\n return SystemInstruction.AllocateWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(10), 0)) {\n return SystemInstruction.AssignWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(11), 0)) {\n return SystemInstruction.TransferSolWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(12), 0)) {\n return SystemInstruction.UpgradeNonceAccount;\n }\n throw new Error(\n 'The provided instruction could not be identified as a system instruction.'\n );\n}\n\nexport type ParsedSystemInstruction<\n TProgram extends string = '11111111111111111111111111111111',\n> =\n | ({\n instructionType: SystemInstruction.CreateAccount;\n } & ParsedCreateAccountInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.Assign;\n } & ParsedAssignInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.TransferSol;\n } & ParsedTransferSolInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.CreateAccountWithSeed;\n } & ParsedCreateAccountWithSeedInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.AdvanceNonceAccount;\n } & ParsedAdvanceNonceAccountInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.WithdrawNonceAccount;\n } & ParsedWithdrawNonceAccountInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.InitializeNonceAccount;\n } & ParsedInitializeNonceAccountInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.AuthorizeNonceAccount;\n } & ParsedAuthorizeNonceAccountInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.Allocate;\n } & ParsedAllocateInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.AllocateWithSeed;\n } & ParsedAllocateWithSeedInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.AssignWithSeed;\n } & ParsedAssignWithSeedInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.TransferSolWithSeed;\n } & ParsedTransferSolWithSeedInstruction<TProgram>)\n | ({\n instructionType: SystemInstruction.UpgradeNonceAccount;\n } & ParsedUpgradeNonceAccountInstruction<TProgram>);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { SYSTEM_PROGRAM_ADDRESS } from '../programs';\n\n/** AccountAlreadyInUse: an account with the same address already exists */\nexport const SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE = 0x0; // 0\n/** ResultWithNegativeLamports: account does not have enough SOL to perform the operation */\nexport const SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS = 0x1; // 1\n/** InvalidProgramId: cannot assign account to this program id */\nexport const SYSTEM_ERROR__INVALID_PROGRAM_ID = 0x2; // 2\n/** InvalidAccountDataLength: cannot allocate account data of this length */\nexport const SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH = 0x3; // 3\n/** MaxSeedLengthExceeded: length of requested seed is too long */\nexport const SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED = 0x4; // 4\n/** AddressWithSeedMismatch: provided address does not match addressed derived from seed */\nexport const SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH = 0x5; // 5\n/** NonceNoRecentBlockhashes: advancing stored nonce requires a populated RecentBlockhashes sysvar */\nexport const SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES = 0x6; // 6\n/** NonceBlockhashNotExpired: stored nonce is still in recent_blockhashes */\nexport const SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED = 0x7; // 7\n/** NonceUnexpectedBlockhashValue: specified nonce does not match stored nonce */\nexport const SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE = 0x8; // 8\n\nexport type SystemError =\n | typeof SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE\n | typeof SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH\n | typeof SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH\n | typeof SYSTEM_ERROR__INVALID_PROGRAM_ID\n | typeof SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED\n | typeof SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES\n | typeof SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE\n | typeof SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS;\n\nlet systemErrorMessages: Record<SystemError, string> | undefined;\nif (process.env.NODE_ENV !== 'production') {\n systemErrorMessages = {\n [SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE]: `an account with the same address already exists`,\n [SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH]: `provided address does not match addressed derived from seed`,\n [SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH]: `cannot allocate account data of this length`,\n [SYSTEM_ERROR__INVALID_PROGRAM_ID]: `cannot assign account to this program id`,\n [SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED]: `length of requested seed is too long`,\n [SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED]: `stored nonce is still in recent_blockhashes`,\n [SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES]: `advancing stored nonce requires a populated RecentBlockhashes sysvar`,\n [SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE]: `specified nonce does not match stored nonce`,\n [SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS]: `account does not have enough SOL to perform the operation`,\n };\n}\n\nexport function getSystemErrorMessage(code: SystemError): string {\n if (process.env.NODE_ENV !== 'production') {\n return (systemErrorMessages as Record<SystemError, string>)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isSystemError<TProgramErrorCode extends SystemError>(\n error: unknown,\n transactionMessage: {\n instructions: Record<number, { programAddress: Address }>;\n },\n code?: TProgramErrorCode\n): error is SolanaError<typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM> &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError<TProgramErrorCode>(\n error,\n transactionMessage,\n SYSTEM_PROGRAM_ADDRESS,\n code\n );\n}\n","import { findAssociatedTokenPda, TOKEN_2022_PROGRAM_ADDRESS } from \"@solana-program/token-2022\";\nimport { isAddress, type Address, type TransactionSigner } from \"@solana/kit\";\nimport { checkedAddress } from \"../../core/utils\";\n\nexport type LegacyTokenProgramMonikers = \"legacy\" | \"token\";\n\nexport type TokenExtensionProgramMonikers = \"token22\" | \"tokenExtension\" | \"tokenExtensions\" | \"token2022\";\n\nexport type TokenProgramMonikers = LegacyTokenProgramMonikers | TokenExtensionProgramMonikers;\n\nexport const TOKEN_PROGRAM_ADDRESS =\n \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\" as Address<\"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\">;\n\n/**\n * Derive the associated token account (ata) address for an owner and mint/tokenProgram\n *\n * @argument `mint` - the token mint itself\n * @argument `owner` - destination wallet address to own tokens from `mint`\n * @argument `tokenProgram` - token program that the token `mint` was created with\n *\n * - (default) {@link TOKEN_PROGRAM_ADDRESS} - the original SPL Token Program\n * - {@link TOKEN_2022_PROGRAM_ADDRESS} - the SPL Token Extensions Program (aka Token22)\n */\nexport async function getAssociatedTokenAccountAddress(\n mint: Address | TransactionSigner,\n owner: Address | TransactionSigner,\n tokenProgram?: Address,\n): Promise<Address> {\n return (\n await findAssociatedTokenPda({\n mint: checkedAddress(mint),\n owner: checkedAddress(owner),\n tokenProgram: checkedTokenProgramAddress(tokenProgram),\n })\n )[0];\n}\n\nexport function parseTokenProgramAddressOrMoniker(tokenProgram: Address | TokenProgramMonikers): Address {\n if (!isAddress(tokenProgram)) {\n tokenProgram = tokenProgram.toLowerCase() as TokenProgramMonikers;\n }\n switch (tokenProgram) {\n case \"legacy\":\n case \"token\":\n case TOKEN_PROGRAM_ADDRESS: {\n return TOKEN_PROGRAM_ADDRESS;\n }\n case \"token22\":\n case \"token2022\":\n case \"tokenextension\":\n case \"tokenextensions\":\n case TOKEN_2022_PROGRAM_ADDRESS: {\n return TOKEN_2022_PROGRAM_ADDRESS;\n }\n default:\n throw Error(\"Unsupported token program. Try 'TOKEN_PROGRAM_ADDRESS' or 'TOKEN_2022_PROGRAM_ADDRESS'\");\n }\n}\n\nexport function assertIsSupportedTokenProgram(\n tokenProgram: Address,\n): asserts tokenProgram is Address<typeof tokenProgram> {\n if (tokenProgram !== TOKEN_PROGRAM_ADDRESS && tokenProgram !== TOKEN_2022_PROGRAM_ADDRESS) {\n throw Error(\"Unsupported token program. Try 'TOKEN_PROGRAM_ADDRESS' or 'TOKEN_2022_PROGRAM_ADDRESS'\");\n }\n}\n\n/**\n * Check the provided program is one of the supported token programs.\n * Including setting the default to {@link TOKEN_PROGRAM_ADDRESS} (the original SPL token program)\n *\n * @example\n * ```\n * args.tokenProgram = checkedTokenProgramAddress(args.tokenProgram);\n * ```\n */\nexport function checkedTokenProgramAddress(tokenProgram?: Address | TokenProgramMonikers): Address {\n if (!tokenProgram) return TOKEN_PROGRAM_ADDRESS;\n tokenProgram = parseTokenProgramAddressOrMoniker(tokenProgram);\n assertIsSupportedTokenProgram(tokenProgram);\n return tokenProgram;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport { AddressLookupTableSeeds, findAddressLookupTablePda } from '../pdas';\n\nexport const ADDRESS_LOOKUP_TABLE_DISCRIMINATOR = 1;\n\nexport function getAddressLookupTableDiscriminatorBytes() {\n return getU32Encoder().encode(ADDRESS_LOOKUP_TABLE_DISCRIMINATOR);\n}\n\nexport type AddressLookupTable = {\n discriminator: number;\n deactivationSlot: bigint;\n lastExtendedSlot: bigint;\n lastExtendedSlotStartIndex: number;\n authority: Option<Address>;\n padding: number;\n addresses: Array<Address>;\n};\n\nexport type AddressLookupTableArgs = {\n deactivationSlot: number | bigint;\n lastExtendedSlot: number | bigint;\n lastExtendedSlotStartIndex: number;\n authority: OptionOrNullable<Address>;\n addresses: Array<Address>;\n};\n\nexport function getAddressLookupTableEncoder(): Encoder<AddressLookupTableArgs> {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU32Encoder()],\n ['deactivationSlot', getU64Encoder()],\n ['lastExtendedSlot', getU64Encoder()],\n ['lastExtendedSlotStartIndex', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), { noneValue: 'zeroes' }),\n ],\n ['padding', getU16Encoder()],\n [\n 'addresses',\n getArrayEncoder(getAddressEncoder(), { size: 'remainder' }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: ADDRESS_LOOKUP_TABLE_DISCRIMINATOR,\n padding: 0,\n })\n );\n}\n\nexport function getAddressLookupTableDecoder(): Decoder<AddressLookupTable> {\n return getStructDecoder([\n ['discriminator', getU32Decoder()],\n ['deactivationSlot', getU64Decoder()],\n ['lastExtendedSlot', getU64Decoder()],\n ['lastExtendedSlotStartIndex', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), { noneValue: 'zeroes' }),\n ],\n ['padding', getU16Decoder()],\n ['addresses', getArrayDecoder(getAddressDecoder(), { size: 'remainder' })],\n ]);\n}\n\nexport function getAddressLookupTableCodec(): Codec<\n AddressLookupTableArgs,\n AddressLookupTable\n> {\n return combineCodec(\n getAddressLookupTableEncoder(),\n getAddressLookupTableDecoder()\n );\n}\n\nexport function decodeAddressLookupTable<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<AddressLookupTable, TAddress>;\nexport function decodeAddressLookupTable<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<AddressLookupTable, TAddress>;\nexport function decodeAddressLookupTable<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n):\n | Account<AddressLookupTable, TAddress>\n | MaybeAccount<AddressLookupTable, TAddress> {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount<TAddress>,\n getAddressLookupTableDecoder()\n );\n}\n\nexport async function fetchAddressLookupTable<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<AddressLookupTable, TAddress>> {\n const maybeAccount = await fetchMaybeAddressLookupTable(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeAddressLookupTable<\n TAddress extends string = string,\n>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<AddressLookupTable, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeAddressLookupTable(maybeAccount);\n}\n\nexport async function fetchAllAddressLookupTable(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<AddressLookupTable>[]> {\n const maybeAccounts = await fetchAllMaybeAddressLookupTable(\n rpc,\n addresses,\n config\n );\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeAddressLookupTable(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<AddressLookupTable>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) =>\n decodeAddressLookupTable(maybeAccount)\n );\n}\n\nexport async function fetchAddressLookupTableFromSeeds(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n seeds: AddressLookupTableSeeds,\n config: FetchAccountConfig & { programAddress?: Address } = {}\n): Promise<Account<AddressLookupTable>> {\n const maybeAccount = await fetchMaybeAddressLookupTableFromSeeds(\n rpc,\n seeds,\n config\n );\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeAddressLookupTableFromSeeds(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n seeds: AddressLookupTableSeeds,\n config: FetchAccountConfig & { programAddress?: Address } = {}\n): Promise<MaybeAccount<AddressLookupTable>> {\n const { programAddress, ...fetchConfig } = config;\n const [address] = await findAddressLookupTablePda(seeds, { programAddress });\n return await fetchMaybeAddressLookupTable(rpc, address, fetchConfig);\n}\n","import {\n getSolanaRpc,\n getSolanaRpcEndpoint,\n type TransactionDetails,\n} from \"@revibase/core\";\nimport {\n AccountRole,\n appendTransactionMessageInstructions,\n compileTransaction,\n compressTransactionMessageUsingAddressLookupTables,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n getBlockhashDecoder,\n getSignatureFromTransaction,\n pipe,\n prependTransactionMessageInstructions,\n setTransactionMessageFeePayerSigner,\n setTransactionMessageLifetimeUsingBlockhash,\n signTransactionMessageWithSigners,\n type AccountMeta,\n type Rpc,\n type SolanaRpcApi,\n} from \"gill\";\nimport {\n getSetComputeUnitLimitInstruction,\n getSetComputeUnitPriceInstruction,\n} from \"gill/programs\";\nimport type { RevibaseProvider } from \"../../provider\";\nimport { withRetry } from \"../retry\";\n\nexport async function signAndSendTransaction({\n instructions,\n payer,\n addressesByLookupTableAddress,\n}: TransactionDetails): Promise<string> {\n const latestBlockHash = await withRetry(() =>\n getSolanaRpc().getLatestBlockhash().send(),\n );\n const tx = await pipe(\n createTransactionMessage({ version: 0 }),\n (tx) => appendTransactionMessageInstructions(instructions, tx),\n (tx) => setTransactionMessageFeePayerSigner(payer, tx),\n (tx) =>\n setTransactionMessageLifetimeUsingBlockhash(latestBlockHash.value, tx),\n (tx) =>\n addressesByLookupTableAddress\n ? compressTransactionMessageUsingAddressLookupTables(\n tx,\n addressesByLookupTableAddress,\n )\n : tx,\n async (tx) => {\n const [unitsConsumed, priorityFees] = await Promise.all([\n getComputeUnitsEstimate(tx),\n getMedianPriorityFees(\n getSolanaRpc(),\n tx.instructions.flatMap((x) => x.accounts ?? []),\n ),\n ]);\n const computeUnits = Math.ceil((Number(unitsConsumed) ?? 0) * 1.1);\n return prependTransactionMessageInstructions(\n [\n ...(computeUnits > 200_000\n ? [\n getSetComputeUnitLimitInstruction({\n units: computeUnits,\n }),\n ]\n : []),\n ...(priorityFees > 0\n ? [\n getSetComputeUnitPriceInstruction({\n microLamports: priorityFees,\n }),\n ]\n : []),\n ],\n tx,\n );\n },\n async (tx) =>\n await withRetry(async () => signTransactionMessageWithSigners(await tx)),\n );\n await withRetry(() =>\n getSolanaRpc()\n .sendTransaction(getBase64EncodedWireTransaction(tx), {\n skipPreflight: true,\n encoding: \"base64\",\n })\n .send(),\n );\n\n return getSignatureFromTransaction(tx);\n}\n\nexport async function signAndSendBundledTransactions(\n provider: RevibaseProvider,\n bundle: TransactionDetails[],\n): Promise<string> {\n const simulationBundle = await createEncodedBundle(bundle, true);\n const computeUnits = await simulateBundle(\n simulationBundle.map(getBase64EncodedWireTransaction),\n getSolanaRpcEndpoint(),\n );\n const encodedBundle = await createEncodedBundle(\n bundle.map((x, index) => ({\n ...x,\n unitsConsumed: computeUnits[index],\n })),\n );\n await withRetry(() =>\n provider.onSendJitoBundleCallback(\n encodedBundle.map(getBase64EncodedWireTransaction),\n ),\n );\n return getSignatureFromTransaction(encodedBundle[encodedBundle.length - 1]);\n}\n\nexport async function simulateBundle(\n bundle: string[],\n connectionUrl: string,\n): Promise<number[]> {\n const response = await withRetry(() =>\n fetch(connectionUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"2\",\n method: \"simulateBundle\",\n params: [\n {\n encodedTransactions: bundle,\n },\n {\n skipSigVerify: true,\n replaceRecentBlockhash: true,\n preExecutionAccountsConfigs: bundle.map(() => ({\n encoding: \"base64\",\n addresses: [],\n })),\n postExecutionAccountsConfigs: bundle.map(() => ({\n encoding: \"base64\",\n addresses: [],\n })),\n },\n ],\n }),\n }),\n );\n\n const data = (await response.json()) as {\n result?: {\n value: {\n transactionResults: { unitsConsumed: number }[];\n summary:\n | string\n | {\n failed?: {\n error: {\n TransactionFailure: [unknown, string];\n };\n };\n };\n };\n };\n error?: unknown;\n };\n\n if (!data.result || data.error) {\n throw new Error(\n `Unable to simulate bundle: ${JSON.stringify(data.error ?? data.result)}`,\n );\n }\n\n if (\n typeof data.result.value.summary !== \"string\" &&\n data.result.value.summary.failed\n ) {\n const { TransactionFailure } = data.result.value.summary.failed.error;\n const [, programError] = TransactionFailure;\n throw new Error(`Simulation failed: ${programError}`);\n }\n\n return data.result.value.transactionResults.map((x) => x.unitsConsumed);\n}\n\nasync function createEncodedBundle(\n bundle: (TransactionDetails & { unitsConsumed?: number })[],\n isSimulate = false,\n) {\n const latestBlockHash = isSimulate\n ? {\n blockhash: getBlockhashDecoder().decode(\n crypto.getRandomValues(new Uint8Array(32)),\n ),\n lastValidBlockHeight: BigInt(Number.MAX_SAFE_INTEGER),\n }\n : (await withRetry(() => getSolanaRpc().getLatestBlockhash().send())).value;\n return await Promise.all(\n bundle.map(async (x) => {\n const tx = await pipe(\n createTransactionMessage({ version: 0 }),\n (tx) => appendTransactionMessageInstructions(x.instructions, tx),\n (tx) => setTransactionMessageFeePayerSigner(x.payer, tx),\n (tx) =>\n setTransactionMessageLifetimeUsingBlockhash(latestBlockHash, tx),\n (tx) =>\n x.addressesByLookupTableAddress\n ? compressTransactionMessageUsingAddressLookupTables(\n tx,\n x.addressesByLookupTableAddress,\n )\n : tx,\n (tx) => {\n const computeUnits = Math.ceil((x.unitsConsumed ?? 0) * 1.1);\n return computeUnits > 200_000\n ? prependTransactionMessageInstructions(\n [\n getSetComputeUnitLimitInstruction({\n units: computeUnits,\n }),\n ],\n tx,\n )\n : tx;\n },\n async (tx) =>\n isSimulate\n ? compileTransaction(tx)\n : await withRetry(() => signTransactionMessageWithSigners(tx)),\n );\n return tx;\n }),\n );\n}\n\nasync function getComputeUnitsEstimate(\n transactionMessage: Parameters<typeof compileTransaction>[0],\n) {\n const transactionMessageWithComputeUnitAndPriorityFees =\n prependTransactionMessageInstructions(\n [\n getSetComputeUnitLimitInstruction({ units: 800_000 }),\n getSetComputeUnitPriceInstruction({ microLamports: 10_000 }),\n ],\n transactionMessage,\n );\n const transaction = compileTransaction(\n transactionMessageWithComputeUnitAndPriorityFees,\n );\n const simulatedTransaction = await withRetry(() =>\n getSolanaRpc()\n .simulateTransaction(getBase64EncodedWireTransaction(transaction), {\n encoding: \"base64\",\n })\n .send(),\n );\n if (simulatedTransaction.value.err) {\n if (simulatedTransaction.value.logs) {\n const errorMessage = [\n \"Transaction simulation failed:\",\n \"\",\n ...simulatedTransaction.value.logs,\n ].join(\"\\n\");\n throw new Error(errorMessage);\n }\n const errorMessage = [\n \"Transaction simulation failed:\",\n \"\",\n simulatedTransaction.value.err.toString(),\n ].join(\"\\n\");\n throw new Error(errorMessage);\n }\n return simulatedTransaction.value.unitsConsumed;\n}\n\nexport async function getMedianPriorityFees(\n connection: Rpc<SolanaRpcApi>,\n accounts: AccountMeta[],\n): Promise<number> {\n const recentFees = await withRetry(() =>\n connection\n .getRecentPrioritizationFees(\n accounts\n .filter(\n (x) =>\n x.role === AccountRole.WRITABLE ||\n x.role === AccountRole.WRITABLE_SIGNER,\n )\n .map((x) => x.address),\n )\n .send(),\n );\n const fees = recentFees.map((f) => Number(f.prioritizationFee));\n fees.sort((a, b) => a - b);\n const mid = Math.floor(fees.length / 2);\n\n if (fees.length % 2 === 0) {\n return Math.round((fees[mid - 1] + fees[mid]) / 2);\n } else {\n return fees[mid];\n }\n}\n","import {\n createTransactionManagerSigner,\n fetchUser,\n getSolanaRpc,\n getUserAddress,\n type TransactionAuthDetails,\n} from \"@revibase/core\";\nimport {\n address,\n fetchAddressesForLookupTables,\n getBase58Encoder,\n getBase64Decoder,\n getTransactionEncoder,\n type Address,\n type AddressesByLookupTableAddress,\n type ReadonlyUint8Array,\n type SignatureBytes,\n type TransactionSigner,\n} from \"gill\";\nimport { fetchMaybeAddressLookupTable } from \"gill/programs\";\nimport {\n REVIBASE_API_ENDPOINT,\n REVIBASE_LOOKUP_TABLE_ADDRESS,\n} from \"../consts\";\nimport { withRetry } from \"../retry\";\n\nconst payerCache = new Map<string, TransactionSigner>();\n\nexport async function getRandomPayer(): Promise<TransactionSigner> {\n const cached = payerCache.get(REVIBASE_API_ENDPOINT);\n if (cached) return cached;\n\n const response = await withRetry(() =>\n fetch(`${REVIBASE_API_ENDPOINT}/getRandomPayer`),\n );\n\n if (!response.ok) {\n throw new Error(`Failed to get random payer: ${response.statusText}`);\n }\n\n const { randomPayer } = (await response.json()) as { randomPayer: string };\n const payer = createTransactionSigner(\n address(randomPayer),\n `${REVIBASE_API_ENDPOINT}/sign`,\n );\n payerCache.set(REVIBASE_API_ENDPOINT, payer);\n return payer;\n}\n\nfunction createTransactionSigner(\n publicKey: Address,\n url: string,\n): TransactionSigner {\n const payer: TransactionSigner = {\n address: publicKey,\n async signTransactions(transactions) {\n const payload = {\n publicKey: publicKey,\n transactions: transactions.map((tx) =>\n getBase64Decoder().decode(getTransactionEncoder().encode(tx)),\n ),\n };\n\n const signResponse = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n if (!signResponse.ok) {\n throw new Error(\n `Failed to sign transactions: ${signResponse.statusText}`,\n );\n }\n\n const data = (await signResponse.json()) as\n | { signatures: string[] }\n | { error: string };\n\n if (\"error\" in data) {\n throw new Error(data.error);\n }\n\n return data.signatures.map((sig) => ({\n [publicKey]: getBase58Encoder().encode(sig) as SignatureBytes,\n }));\n },\n };\n\n return payer;\n}\n\nexport async function getTransactionManagerSigner(args: {\n transactionManagerAddress: Address | undefined;\n authResponses?: TransactionAuthDetails[];\n transactionMessageBytes?: ReadonlyUint8Array;\n onPendingApprovalsCallback?: (validTill: number) => void;\n onPendingApprovalsSuccess?: () => void;\n abortController?: AbortController;\n abortSignal?: AbortSignal;\n}) {\n const {\n transactionManagerAddress,\n transactionMessageBytes,\n authResponses,\n onPendingApprovalsCallback,\n onPendingApprovalsSuccess,\n abortController: abortControllerArg,\n abortSignal,\n } = args;\n\n let abortController = abortControllerArg;\n if (abortSignal && !abortController) {\n const ac = new AbortController();\n if (abortSignal.aborted) {\n ac.abort();\n } else {\n abortSignal.addEventListener(\"abort\", () => ac.abort(), { once: true });\n }\n abortController = ac;\n }\n let url;\n if (transactionManagerAddress) {\n const txManagerUrl = (\n await withRetry(async () =>\n fetchUser(\n getSolanaRpc(),\n await getUserAddress(transactionManagerAddress),\n ),\n )\n ).data.transactionManagerUrl;\n url = txManagerUrl.__option === \"Some\" ? txManagerUrl.value : null;\n }\n\n const transactionManagerSigner =\n transactionManagerAddress && url\n ? createTransactionManagerSigner({\n address: transactionManagerAddress,\n url,\n authResponses,\n transactionMessageBytes,\n onPendingApprovalsCallback,\n onPendingApprovalsSuccess,\n abortController,\n })\n : null;\n\n return transactionManagerSigner;\n}\n\nexport async function fetchAdditionalLoopUpTableIfNecessary(\n addressesByLookupTableAddress?: AddressesByLookupTableAddress,\n) {\n if (!addressesByLookupTableAddress) {\n return await withRetry(() =>\n fetchAddressesForLookupTables(\n [address(REVIBASE_LOOKUP_TABLE_ADDRESS)],\n getSolanaRpc(),\n ),\n );\n }\n\n if (REVIBASE_LOOKUP_TABLE_ADDRESS in addressesByLookupTableAddress) {\n return addressesByLookupTableAddress;\n }\n\n const fetched = await withRetry(() =>\n fetchMaybeAddressLookupTable(\n getSolanaRpc(),\n address(REVIBASE_LOOKUP_TABLE_ADDRESS),\n ),\n );\n\n if (fetched.exists) {\n return {\n ...addressesByLookupTableAddress,\n [fetched.address]: fetched.data.addresses,\n };\n }\n\n return addressesByLookupTableAddress;\n}\n","import {\n fetchSettings,\n getSignedSecp256r1Key,\n getSolanaRpc,\n prepareTransactionBundle,\n retrieveTransactionManager,\n type TransactionAuthenticationResponse,\n} from \"@revibase/core\";\nimport { getBase64Encoder, type Address, type TransactionSigner } from \"gill\";\nimport type { RevibaseProvider } from \"../../provider\";\nimport { withRetry } from \"../retry\";\nimport type { TransactionAuthorizationFlowOptions } from \"../types\";\nimport { signAndSendBundledTransactions } from \"./solana-send\";\nimport {\n fetchAdditionalLoopUpTableIfNecessary,\n getRandomPayer,\n getTransactionManagerSigner,\n} from \"./utils\";\n\nexport async function processBundledTransaction(\n provider: RevibaseProvider,\n params: {\n authResponse: TransactionAuthenticationResponse;\n settings: Address;\n payer?: TransactionSigner;\n additionalSigners?: TransactionSigner[];\n options?: TransactionAuthorizationFlowOptions;\n },\n): Promise<string> {\n const { authResponse, settings, additionalSigners, options, payer } = params;\n const { startRequest, signer } = authResponse;\n if (startRequest.data.type !== \"transaction\")\n throw new Error(\"Invalid request type.\");\n\n const { transactionActionType, transactionMessageBytes } =\n startRequest.data.payload;\n\n if (\n transactionActionType !== \"execute\" &&\n transactionActionType !== \"create_with_preauthorized_execution\"\n ) {\n throw new Error(\n \"Transaction action type must be 'execute' or 'create_with_preauthorized_execution'\",\n );\n }\n\n const [feePayer, settingsData, signedSigner] = await Promise.all([\n payer ?? getRandomPayer(),\n (await withRetry(() => fetchSettings(getSolanaRpc(), settings))).data,\n getSignedSecp256r1Key(authResponse),\n ]);\n\n const tm = retrieveTransactionManager(signer, settingsData);\n\n const [transactionManagerSigner, jitoBundlesTipAmount] = await Promise.all([\n getTransactionManagerSigner({\n authResponses: [authResponse],\n transactionManagerAddress: tm?.transactionManagerAddress,\n transactionMessageBytes: getBase64Encoder().encode(\n transactionMessageBytes,\n ),\n onPendingApprovalsCallback:\n options?.pendingApprovalsCallback?.onPendingApprovalsCallback,\n onPendingApprovalsSuccess:\n options?.pendingApprovalsCallback?.onPendingApprovalsSuccess,\n abortSignal: options?.signal,\n }),\n withRetry(() => provider.onEstimateJitoTipsCallback()),\n ]);\n\n const bundle = await prepareTransactionBundle({\n settings,\n transactionMessageBytes: getBase64Encoder().encode(\n transactionMessageBytes,\n ) as Uint8Array<ArrayBuffer>,\n creator: transactionManagerSigner ?? signedSigner,\n executor: transactionManagerSigner ? signedSigner : undefined,\n jitoBundlesTipAmount,\n additionalSigners,\n payer: feePayer,\n });\n\n const bundlesWithLookupTables = await Promise.all(\n bundle.map(async (x) => ({\n ...x,\n addressesByLookupTableAddress:\n await fetchAdditionalLoopUpTableIfNecessary(\n x.addressesByLookupTableAddress,\n ),\n })),\n );\n\n return signAndSendBundledTransactions(provider, bundlesWithLookupTables);\n}\n","import {\n fetchSettings,\n getSignedSecp256r1Key,\n getSolanaRpc,\n prepareTransactionSync,\n retrieveTransactionManager,\n type TransactionAuthenticationResponse,\n} from \"@revibase/core\";\nimport { getBase64Encoder, type Address, type TransactionSigner } from \"gill\";\nimport { withRetry } from \"../retry\";\nimport type { TransactionAuthorizationFlowOptions } from \"../types\";\nimport { signAndSendTransaction } from \"./solana-send\";\nimport {\n fetchAdditionalLoopUpTableIfNecessary,\n getRandomPayer,\n getTransactionManagerSigner,\n} from \"./utils\";\n\nexport async function processSyncTransaction(params: {\n authResponse: TransactionAuthenticationResponse;\n settings: Address;\n payer?: TransactionSigner;\n additionalSigners?: TransactionSigner[];\n options?: TransactionAuthorizationFlowOptions;\n}): Promise<string> {\n const { authResponse, settings, payer, additionalSigners, options } = params;\n const { startRequest, signer } = authResponse;\n if (startRequest.data.type !== \"transaction\")\n throw new Error(\"Invalid request type.\");\n\n const { transactionActionType, transactionMessageBytes } =\n startRequest.data.payload;\n\n if (transactionActionType !== \"sync\") {\n throw new Error(\"Transaction action type must be 'sync'\");\n }\n\n const [feePayer, settingsData, signedSigner] = await Promise.all([\n payer ?? getRandomPayer(),\n (await withRetry(() => fetchSettings(getSolanaRpc(), settings))).data,\n getSignedSecp256r1Key(authResponse),\n ]);\n\n const tm = retrieveTransactionManager(signer, settingsData);\n\n const transactionManagerSigner = await getTransactionManagerSigner({\n authResponses: [authResponse],\n transactionManagerAddress: tm?.transactionManagerAddress,\n transactionMessageBytes: getBase64Encoder().encode(transactionMessageBytes),\n onPendingApprovalsCallback:\n options?.pendingApprovalsCallback?.onPendingApprovalsCallback,\n onPendingApprovalsSuccess:\n options?.pendingApprovalsCallback?.onPendingApprovalsSuccess,\n abortSignal: options?.signal,\n });\n\n const signers = transactionManagerSigner\n ? [signedSigner, transactionManagerSigner]\n : [signedSigner];\n\n const { instructions, addressesByLookupTableAddress } =\n await prepareTransactionSync({\n signers,\n payer: feePayer,\n transactionMessageBytes: getBase64Encoder().encode(\n transactionMessageBytes,\n ),\n settings,\n additionalSigners,\n });\n\n return signAndSendTransaction({\n instructions,\n payer: feePayer,\n addressesByLookupTableAddress: await fetchAdditionalLoopUpTableIfNecessary(\n addressesByLookupTableAddress,\n ),\n });\n}\n","import {\n fetchSettings,\n getSignedSecp256r1Key,\n getSolanaRpc,\n nativeTransferIntent,\n retrieveTransactionManager,\n tokenTransferIntent,\n type TransactionAuthenticationResponse,\n} from \"@revibase/core\";\nimport {\n address,\n getAddressDecoder,\n getBase64Encoder,\n getU64Decoder,\n type Address,\n type AddressesByLookupTableAddress,\n type TransactionSigner,\n} from \"gill\";\nimport { SYSTEM_PROGRAM_ADDRESS } from \"gill/programs\";\nimport { withRetry } from \"../retry\";\nimport type { TransactionAuthorizationFlowOptions } from \"../types\";\nimport { signAndSendTransaction } from \"./solana-send\";\nimport {\n fetchAdditionalLoopUpTableIfNecessary,\n getRandomPayer,\n getTransactionManagerSigner,\n} from \"./utils\";\n\nexport async function processTokenTransfer(params: {\n authResponse: TransactionAuthenticationResponse;\n settings: Address;\n payer?: TransactionSigner;\n options?: TransactionAuthorizationFlowOptions;\n addressesByLookupTableAddress?: AddressesByLookupTableAddress;\n}): Promise<string> {\n const {\n authResponse,\n settings,\n options,\n payer,\n addressesByLookupTableAddress,\n } = params;\n const { startRequest, signer } = authResponse;\n if (startRequest.data.type !== \"transaction\")\n throw new Error(\"Invalid request type.\");\n\n const { transactionActionType, transactionAddress, transactionMessageBytes } =\n startRequest.data.payload;\n\n if (transactionActionType !== \"transfer_intent\") {\n throw new Error(\"Transaction action type must be 'transfer_intent'\");\n }\n\n const message = getBase64Encoder().encode(transactionMessageBytes);\n const amount = getU64Decoder().decode(message.slice(0, 8));\n const destination = getAddressDecoder().decode(message.slice(8, 40));\n const mint = getAddressDecoder().decode(message.slice(40, 72));\n\n const [feePayer, settingsData, signedSigner] = await Promise.all([\n payer ?? getRandomPayer(),\n (await withRetry(() => fetchSettings(getSolanaRpc(), settings))).data,\n getSignedSecp256r1Key(authResponse),\n ]);\n\n const tm = retrieveTransactionManager(signer, settingsData);\n\n const transactionManagerSigner = await getTransactionManagerSigner({\n authResponses: [authResponse],\n transactionManagerAddress: tm?.transactionManagerAddress,\n transactionMessageBytes: getBase64Encoder().encode(transactionMessageBytes),\n onPendingApprovalsCallback:\n options?.pendingApprovalsCallback?.onPendingApprovalsCallback,\n onPendingApprovalsSuccess:\n options?.pendingApprovalsCallback?.onPendingApprovalsSuccess,\n abortSignal: options?.signal,\n });\n\n const signers = transactionManagerSigner\n ? [signedSigner, transactionManagerSigner]\n : [signedSigner];\n\n const instructions =\n mint !== SYSTEM_PROGRAM_ADDRESS\n ? await tokenTransferIntent({\n payer: feePayer,\n settings,\n amount,\n signers,\n destination,\n mint,\n tokenProgram: address(transactionAddress),\n })\n : await nativeTransferIntent({\n settings,\n amount,\n signers,\n destination,\n });\n\n return signAndSendTransaction({\n instructions,\n payer: feePayer,\n addressesByLookupTableAddress: await fetchAdditionalLoopUpTableIfNecessary(\n addressesByLookupTableAddress,\n ),\n });\n}\n","import { getSolanaRpc } from \"@revibase/core\";\nimport type { Signature } from \"gill\";\nimport { withRetry } from \"../retry\";\n\nexport async function pollTransactionConfirmation(\n txSig: string,\n maxRetries = 30,\n delayMs = 2000,\n): Promise<string> {\n for (let i = 0; i < maxRetries; i++) {\n const status = await withRetry(() =>\n getSolanaRpc()\n .getSignatureStatuses([txSig as Signature])\n .send(),\n );\n\n const confirmation = status.value[0];\n\n if (\n confirmation?.confirmationStatus === \"confirmed\" ||\n confirmation?.confirmationStatus === \"finalized\"\n ) {\n return txSig;\n }\n\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n\n throw new Error(\"Transaction confirmation timeout\");\n}\n","import type { UserInfo } from \"@revibase/core\";\nimport {\n getSettingsFromIndex,\n type CompleteTransactionRequest,\n} from \"@revibase/core\";\nimport {\n address,\n type AddressesByLookupTableAddress,\n type TransactionSigner,\n} from \"gill\";\nimport type { RevibaseProvider } from \"../../provider\";\nimport type { TransactionAuthorizationFlowOptions } from \"../../utils\";\nimport { processBundledTransaction } from \"../../utils/transactions/processBundledTransaction\";\nimport { processSyncTransaction } from \"../../utils/transactions/processSyncTransaction\";\nimport { processTokenTransfer } from \"../../utils/transactions/processTokenTransfer\";\nimport { pollTransactionConfirmation } from \"./pollTransactionConfirmation\";\n\nexport async function sendTransaction(\n provider: RevibaseProvider,\n params: {\n user: UserInfo;\n request: CompleteTransactionRequest;\n additionalSigners?: TransactionSigner[];\n options?: TransactionAuthorizationFlowOptions;\n payer?: TransactionSigner;\n addressesByLookupTableAddress?: AddressesByLookupTableAddress;\n },\n): Promise<string> {\n const {\n user,\n request,\n additionalSigners,\n options,\n payer,\n addressesByLookupTableAddress,\n } = params;\n const { confirmTransaction = true } = options ?? {};\n\n const settings =\n request.data.type === \"transaction\" &&\n request.data.payload.startRequest.data.payload.transactionActionType !==\n \"transfer_intent\"\n ? request.data.payload.startRequest.data.payload.transactionAddress\n : user.settingsIndexWithAddress?.index\n ? await getSettingsFromIndex(user.settingsIndexWithAddress.index)\n : null;\n\n if (!settings) {\n throw Error(\"User is not delegated to any wallet\");\n }\n let txSig: string;\n switch (\n request.data.payload.startRequest.data.payload.transactionActionType\n ) {\n case \"transfer_intent\":\n txSig = await processTokenTransfer({\n authResponse: request.data.payload,\n settings: address(settings),\n options,\n payer,\n addressesByLookupTableAddress,\n });\n break;\n case \"execute\":\n case \"create_with_preauthorized_execution\":\n txSig = await processBundledTransaction(provider, {\n authResponse: request.data.payload,\n settings: address(settings),\n additionalSigners,\n options,\n payer,\n });\n break;\n case \"sync\":\n txSig = await processSyncTransaction({\n authResponse: request.data.payload,\n settings: address(settings),\n additionalSigners,\n options,\n payer,\n });\n break;\n default:\n throw Error(\"Invalid Transaction Action Type for send tx payload.\");\n }\n\n if (confirmTransaction) {\n await pollTransactionConfirmation(txSig);\n }\n\n return txSig;\n}\n","import type {\n CompleteTransactionRequest,\n TransactionPayloadWithBase64MessageBytes,\n UserInfo,\n} from \"@revibase/core\";\nimport {\n fetchSettings,\n getSettingsFromIndex,\n getSolanaRpc,\n prepareTransactionMessage,\n UserInfoSchema,\n UserRole,\n} from \"@revibase/core\";\nimport {\n address,\n getBase64Decoder,\n type AddressesByLookupTableAddress,\n type Instruction,\n type TransactionSigner,\n} from \"gill\";\nimport type { RevibaseProvider } from \"../provider/main\";\nimport { withRetry } from \"../utils/retry\";\nimport { sendTransaction } from \"../utils/transactions\";\nimport type { TransactionAuthorizationFlowOptions } from \"../utils/types\";\n\n/** Custom transaction. Action from wallet settings (TransactionManager). Provider needs rpcEndpoint. Options: signal?, channelId?. */\nexport async function executeTransaction(\n provider: RevibaseProvider,\n args: {\n instructions: Instruction[];\n signer: UserInfo;\n payer?: TransactionSigner;\n settingsIndexWithAddress?: {\n index: number | bigint;\n };\n additionalSigners?: TransactionSigner[];\n addressesByLookupTableAddress?: AddressesByLookupTableAddress;\n },\n options?: TransactionAuthorizationFlowOptions,\n): Promise<{ txSig?: string; user: UserInfo }> {\n const {\n instructions,\n signer,\n addressesByLookupTableAddress,\n settingsIndexWithAddress,\n additionalSigners,\n payer,\n } = args;\n\n const onConnectedCallback = async (rid: string, clientOrigin: string) => {\n const transactionMessageBytes = prepareTransactionMessage({\n payer: address(signer.walletAddress),\n instructions,\n addressesByLookupTableAddress,\n });\n const settingsArgs =\n settingsIndexWithAddress ?? signer.settingsIndexWithAddress;\n const settings = await getSettingsFromIndex(settingsArgs.index);\n const settingsData = (\n await withRetry(() => fetchSettings(getSolanaRpc(), settings))\n ).data;\n const hasTxManager = settingsData.members.some(\n (x) => x.role === UserRole.TransactionManager,\n );\n const transactionPayload: TransactionPayloadWithBase64MessageBytes = {\n transactionMessageBytes: getBase64Decoder().decode(\n transactionMessageBytes,\n ),\n transactionAddress: settings,\n transactionActionType: hasTxManager\n ? \"execute\"\n : \"create_with_preauthorized_execution\",\n };\n\n const payload = {\n phase: \"start\" as const,\n rid,\n providerOrigin: provider.providerOrigin,\n rpId: provider.rpId,\n data: {\n type: \"transaction\" as const,\n payload: transactionPayload,\n },\n clientOrigin,\n signer: signer.publicKey,\n };\n const { signature, validTill } = await withRetry(() =>\n provider.onClientAuthorizationCallback(payload),\n );\n return { request: { ...payload, rid, validTill }, signature };\n };\n\n const onSuccessCallback = async (\n result: CompleteTransactionRequest,\n ): Promise<{ txSig: string; user: UserInfo }> => {\n const { signature } = await provider.onClientAuthorizationCallback(result);\n const user = UserInfoSchema.parse(result.data.payload.additionalInfo);\n const txSig = await sendTransaction(provider, {\n user,\n request: {\n ...result,\n data: {\n ...result.data,\n payload: {\n ...result.data.payload,\n client: { ...result.data.payload.client, jws: signature },\n },\n },\n },\n options,\n additionalSigners,\n addressesByLookupTableAddress,\n payer,\n });\n\n return { user, txSig };\n };\n\n return provider.sendRequestToPopupProvider({\n onConnectedCallback,\n onSuccessCallback,\n signal: options?.signal,\n });\n}\n","import {\n UserInfoSchema,\n type CompleteTransactionRequest,\n type TransactionPayloadWithBase64MessageBytes,\n type UserInfo,\n} from \"@revibase/core\";\nimport {\n address,\n getAddressEncoder,\n getBase64Decoder,\n getU64Encoder,\n type AddressesByLookupTableAddress,\n type TransactionSigner,\n} from \"gill\";\nimport { SYSTEM_PROGRAM_ADDRESS, TOKEN_PROGRAM_ADDRESS } from \"gill/programs\";\nimport type { RevibaseProvider } from \"../provider/main\";\nimport { withRetry } from \"../utils/retry\";\nimport { sendTransaction } from \"../utils/transactions/sendTransaction\";\nimport type { TransactionAuthorizationFlowOptions } from \"../utils/types\";\n\n/** Transfers SOL or SPL (set mint for SPL). amount > 0, destination required */\nexport async function transferTokens(\n provider: RevibaseProvider,\n args: {\n amount: number | bigint;\n destination: string;\n signer?: UserInfo;\n mint?: string;\n tokenProgram?: string;\n payer?: TransactionSigner;\n addressesByLookupTableAddress?: AddressesByLookupTableAddress;\n },\n options?: TransactionAuthorizationFlowOptions,\n): Promise<{ txSig?: string; user: UserInfo }> {\n if (args.amount <= 0) {\n throw new Error(\"Transfer amount must be greater than 0\");\n }\n\n if (!args.destination || typeof args.destination !== \"string\") {\n throw new Error(\"Destination address is required\");\n }\n\n const {\n mint,\n tokenProgram = TOKEN_PROGRAM_ADDRESS,\n amount,\n destination,\n signer,\n payer,\n addressesByLookupTableAddress,\n } = args;\n\n const onConnectedCallback = async (rid: string, clientOrigin: string) => {\n const transactionPayload: TransactionPayloadWithBase64MessageBytes = {\n transactionActionType: \"transfer_intent\",\n transactionAddress: mint ? tokenProgram : SYSTEM_PROGRAM_ADDRESS,\n transactionMessageBytes: getBase64Decoder().decode(\n new Uint8Array([\n ...getU64Encoder().encode(amount),\n ...getAddressEncoder().encode(address(destination)),\n ...getAddressEncoder().encode(\n address(mint ?? SYSTEM_PROGRAM_ADDRESS),\n ),\n ]),\n ),\n };\n\n const payload = {\n phase: \"start\" as const,\n rid,\n providerOrigin: provider.providerOrigin,\n rpId: provider.rpId,\n data: {\n type: \"transaction\" as const,\n payload: transactionPayload,\n },\n clientOrigin,\n signer: signer?.publicKey,\n };\n const { signature, validTill } = await withRetry(() =>\n provider.onClientAuthorizationCallback(payload),\n );\n return { request: { ...payload, rid, validTill }, signature };\n };\n\n const onSuccessCallback = async (\n result: CompleteTransactionRequest,\n ): Promise<{ txSig: string; user: UserInfo }> => {\n const { signature } = await provider.onClientAuthorizationCallback(result);\n const user = UserInfoSchema.parse(result.data.payload.additionalInfo);\n const txSig = await sendTransaction(provider, {\n user,\n request: {\n ...result,\n data: {\n ...result.data,\n payload: {\n ...result.data.payload,\n client: { ...result.data.payload.client, jws: signature },\n },\n },\n },\n options,\n addressesByLookupTableAddress,\n payer,\n });\n\n return { txSig, user };\n };\n\n return provider.sendRequestToPopupProvider({\n onConnectedCallback,\n onSuccessCallback,\n signal: options?.signal,\n });\n}\n","import {\n convertBase64StringToJWK,\n createClientAuthorizationStartRequestChallenge,\n type StartMessageRequest,\n type StartTransactionRequest,\n} from \"@revibase/core\";\nimport { CompactSign } from \"jose\";\nimport { DEFAULT_TIMEOUT } from \"../provider/utils\";\n\nexport async function startRequest(\n request:\n | Omit<StartMessageRequest, \"validTill\">\n | Omit<StartTransactionRequest, \"validTill\">,\n allowedClientOrigins: string[],\n privateKey: string,\n) {\n if (!allowedClientOrigins.includes(request.clientOrigin)) {\n throw new Error(\"Invalid client origin\");\n }\n const validTill = Date.now() + DEFAULT_TIMEOUT;\n const pKey = convertBase64StringToJWK(privateKey);\n if (!pKey.alg) throw new Error(\"Property alg in JWK is missing.\");\n const signature = await new CompactSign(\n createClientAuthorizationStartRequestChallenge({\n ...request,\n validTill,\n }),\n )\n .setProtectedHeader({\n alg: pKey.alg,\n })\n .sign(pKey);\n return { ok: true, signature, validTill };\n}\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type CHash = {\n (message: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array) => Uint8Array;\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// Used in weierstrass, der\nfunction abignumber(n: number | bigint) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new Error('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\nexport function asafenumber(value: number, title: string = ''): void {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len) throw new Error('number too large');\n return res;\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, message: Uint8Array) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n const u8n = (len: number): Uint8Array => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...msgs: Uint8Array[]) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed: Uint8Array = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\nexport function validateObject(\n object: Record<string, any>,\n fields: Record<string, string> = {},\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n\nexport interface CryptoKeys {\n lengths: { seed?: number; public?: number; secret?: number };\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","import { equalBytes } from \"@noble/curves/utils.js\";\nimport type { CompleteMessageRequest } from \"@revibase/core\";\nimport {\n bufferToBase64URLString,\n convertBase64StringToJWK,\n convertMemberKeyToString,\n convertPubkeyCompressedToCose,\n createClientAuthorizationStartRequestChallenge,\n createMessageChallenge,\n fetchSettings,\n fetchUserAccountByFilters,\n getDeviceMessageHash,\n getDomainConfigAddress,\n getSettingsFromIndex,\n getSolanaRpc,\n UserRole,\n} from \"@revibase/core\";\nimport { verifyAuthenticationResponse } from \"@simplewebauthn/server\";\nimport { address, verifySignatureForAddress } from \"gill\";\nimport { compactVerify, importJWK } from \"jose\";\n\n/** Verifies WebAuthn message, returns user. */\nexport async function verifyMessage(\n request: CompleteMessageRequest,\n expectedClientJwk: string,\n allowedClientOrigins: string[],\n requireTwoFactorAuthentication: boolean,\n) {\n const { payload } = request.data;\n if (payload.startRequest.data.type !== \"message\")\n throw new Error(\"Invalid request type.\");\n if (Date.now() > payload.startRequest.validTill) {\n throw new Error(\"Request expired.\");\n }\n if (\n !allowedClientOrigins.includes(payload.startRequest.clientOrigin) ||\n !allowedClientOrigins.includes(payload.client.clientOrigin) ||\n payload.startRequest.clientOrigin !== payload.client.clientOrigin\n ) {\n throw new Error(\"Invalid client origin\");\n }\n\n {\n const key = await importJWK(convertBase64StringToJWK(expectedClientJwk));\n const result = await compactVerify(request.data.payload.client.jws, key);\n if (\n !equalBytes(\n result.payload,\n createClientAuthorizationStartRequestChallenge(\n request.data.payload.startRequest,\n ),\n )\n ) {\n throw new Error(\"Invalid client signature\");\n }\n }\n\n {\n if (payload.device.jwk !== payload.device.deviceProfile.devicePublicKey) {\n throw new Error(\"Device publickey mismatch\");\n }\n const key = await importJWK(convertBase64StringToJWK(payload.device.jwk));\n const result = await compactVerify(payload.device.jws, key);\n if (\n !equalBytes(\n result.payload,\n getDeviceMessageHash(\n payload.authResponse,\n payload.device.deviceProfile,\n ),\n )\n ) {\n throw new Error(\"Invalid device signature\");\n }\n }\n\n const expectedChallenge = createMessageChallenge(\n payload.startRequest.data.payload,\n payload.startRequest.clientOrigin,\n payload.device.jwk,\n payload.startRequest.rid,\n );\n const { verified } = await verifyAuthenticationResponse({\n response: payload.authResponse,\n expectedChallenge: bufferToBase64URLString(expectedChallenge),\n expectedRPID: payload.startRequest.rpId,\n expectedOrigin: payload.startRequest.providerOrigin,\n requireUserVerification: false,\n credential: {\n counter: 0,\n id: payload.authResponse.id,\n publicKey: convertPubkeyCompressedToCose(payload.signer),\n },\n });\n\n if (!verified) {\n throw new Error(\"Invalid user siganture\");\n }\n\n if (requireTwoFactorAuthentication) {\n if (!payload.startRequest.data.requireTwoFactorAuthentication) {\n throw new Error(\"Two factor authentication is required.\");\n }\n if (!payload.transactionManager) {\n throw new Error(\"Missing signature from transaction manager.\");\n }\n\n const user = await fetchUserAccountByFilters(\n await getDomainConfigAddress({ rpId: payload.startRequest.rpId }),\n { credentialId: payload.authResponse.id },\n );\n const delegateTo = user?.wallets.find((x) => x.isDelegate);\n if (!delegateTo) {\n throw new Error(\"User does not have a delegated wallet\");\n }\n const settingsData = (\n await fetchSettings(\n getSolanaRpc(),\n await getSettingsFromIndex(delegateTo.index),\n )\n ).data;\n const transactionManager = settingsData.members.find(\n (x) => x.role === UserRole.TransactionManager,\n );\n if (!transactionManager) {\n throw new Error(\"No transaction manager found.\");\n }\n if (\n payload.transactionManager.publicKey !==\n convertMemberKeyToString(transactionManager.pubkey)\n ) {\n throw new Error(\"Transaction manager mismatch.\");\n }\n if (\n !(await verifySignatureForAddress(\n address(payload.transactionManager.publicKey),\n payload.transactionManager.signature,\n expectedChallenge,\n ))\n ) {\n throw new Error(\"Invalid transaction manager signature.\");\n }\n }\n\n return {\n ok: true,\n };\n}\n","import { equalBytes } from \"@noble/curves/utils.js\";\nimport type { CompleteTransactionRequest } from \"@revibase/core\";\nimport {\n bufferToBase64URLString,\n convertBase64StringToJWK,\n convertPubkeyCompressedToCose,\n createClientAuthorizationCompleteRequestChallenge,\n createClientAuthorizationStartRequestChallenge,\n createTransactionChallenge,\n getDeviceMessageHash,\n} from \"@revibase/core\";\nimport { verifyAuthenticationResponse } from \"@simplewebauthn/server\";\nimport { CompactSign, compactVerify, importJWK } from \"jose\";\n\n/** Verifies WebAuthn message, returns signature. */\nexport async function verifyTransaction(\n request: CompleteTransactionRequest,\n expectedClientJwk: string,\n allowedClientOrigins: string[],\n privateKey: string,\n) {\n const { payload } = request.data;\n if (payload.startRequest.data.type !== \"transaction\")\n throw new Error(\"Invalid request type.\");\n if (\n Date.now() >\n Math.min(payload.startRequest.validTill, payload.estimatedSlotHashExpiry)\n ) {\n throw new Error(\"Request expired.\");\n }\n if (\n !allowedClientOrigins.includes(payload.startRequest.clientOrigin) ||\n !allowedClientOrigins.includes(payload.client.clientOrigin) ||\n payload.startRequest.clientOrigin !== payload.client.clientOrigin\n ) {\n throw new Error(\"Invalid client origin\");\n }\n\n {\n const key = await importJWK(convertBase64StringToJWK(expectedClientJwk));\n const result = await compactVerify(request.data.payload.client.jws, key);\n if (\n !equalBytes(\n result.payload,\n createClientAuthorizationStartRequestChallenge(\n request.data.payload.startRequest,\n ),\n )\n ) {\n throw new Error(\"Invalid client signature\");\n }\n }\n\n {\n if (payload.device.jwk !== payload.device.deviceProfile.devicePublicKey) {\n throw new Error(\"Device publickey mismatch\");\n }\n const key = await importJWK(convertBase64StringToJWK(payload.device.jwk));\n const result = await compactVerify(payload.device.jws, key);\n if (\n !equalBytes(\n result.payload,\n getDeviceMessageHash(\n payload.authResponse,\n payload.device.deviceProfile,\n ),\n )\n ) {\n throw new Error(\"Invalid device signature\");\n }\n }\n {\n const { challenge: expectedChallenge } = await createTransactionChallenge(\n payload.startRequest.data.payload,\n payload.startRequest.clientOrigin,\n payload.device.jwk,\n payload.startRequest.rid,\n payload.slotHash,\n payload.slotNumber,\n payload.estimatedSlotHashExpiry,\n );\n const { verified } = await verifyAuthenticationResponse({\n response: payload.authResponse,\n expectedChallenge: bufferToBase64URLString(expectedChallenge),\n expectedRPID: payload.startRequest.rpId,\n expectedOrigin: payload.startRequest.providerOrigin,\n requireUserVerification: false,\n credential: {\n counter: 0,\n id: payload.authResponse.id,\n publicKey: convertPubkeyCompressedToCose(payload.signer),\n },\n });\n\n if (!verified) {\n throw new Error(\"Invalid user siganture\");\n }\n }\n\n const pKey = convertBase64StringToJWK(privateKey);\n if (!pKey.alg) throw new Error(\"Property alg in JWK is missing.\");\n const signature = await new CompactSign(\n createClientAuthorizationCompleteRequestChallenge(request),\n )\n .setProtectedHeader({\n alg: pKey.alg,\n })\n .sign(pKey);\n\n return { ok: true, signature };\n}\n","import {\n initialize,\n type CompleteMessageRequest,\n type CompleteTransactionRequest,\n type StartMessageRequest,\n type StartTransactionRequest,\n} from \"@revibase/core\";\nimport { startRequest } from \"./startRequest\";\nimport { verifyMessage } from \"./verifyMessage\";\nimport { verifyTransaction } from \"./verifyTransaction\";\n\nlet initialized = false;\nfunction ensureInitialize(rpcEndpoint?: string) {\n if (initialized) return;\n if (rpcEndpoint) {\n initialize({ rpcEndpoint });\n initialized = true;\n }\n}\n/** Validates start request, calls Revibase start + getResult, returns user or tx. Pass req.signal for cancel on disconnect. */\nexport async function processClientAuthCallback({\n request,\n publicKey,\n allowedClientOrigins,\n privateKey,\n requireTwoFactorAuthentication,\n}: {\n request:\n | Omit<StartMessageRequest, \"validTill\">\n | Omit<StartTransactionRequest, \"validTill\">\n | CompleteMessageRequest\n | CompleteTransactionRequest;\n allowedClientOrigins: string[];\n publicKey: string;\n privateKey: string;\n requireTwoFactorAuthentication?: {\n rpcEndpoint: string;\n };\n}) {\n ensureInitialize(requireTwoFactorAuthentication?.rpcEndpoint);\n\n if (request.phase === \"start\") {\n if (\n request.data.type === \"message\" &&\n !!requireTwoFactorAuthentication !==\n request.data.requireTwoFactorAuthentication\n ) {\n throw new Error(\"Require 2fa check mismatch\");\n }\n return await startRequest(request, allowedClientOrigins, privateKey);\n } else if (request.phase === \"complete\") {\n if (request.data.type === \"message\") {\n return await verifyMessage(\n request as CompleteMessageRequest,\n publicKey,\n allowedClientOrigins,\n !!requireTwoFactorAuthentication,\n );\n } else if (request.data.type === \"transaction\") {\n return await verifyTransaction(\n request as CompleteTransactionRequest,\n publicKey,\n allowedClientOrigins,\n privateKey,\n );\n } else {\n throw new Error(\"Invalid request type\");\n }\n } else {\n throw new Error(\"Invalid request phase\");\n }\n}\n","import { DEFAULT_JITO_TIPS_URL } from \"../utils/consts\";\n\nexport async function processEstimateJitoTipsCallback(\n priority = \"landed_tips_75th_percentile\",\n url = DEFAULT_JITO_TIPS_URL,\n) {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Jito tips: ${response.status} ${response.statusText}`,\n );\n }\n\n const result = await response.json();\n if (\n !Array.isArray(result) ||\n !result[0] ||\n typeof result[0][priority] !== \"number\"\n ) {\n throw new Error(\"Invalid Jito tips response format\");\n }\n\n const LAMPORTS_PER_SOL = 1_000_000_000;\n return Math.round(result[0][priority] * LAMPORTS_PER_SOL);\n}\n","import { DEFAULT_JITO_BLOCK_ENGINE_SEND_BUNDLE_URL } from \"../utils/consts\";\n\nexport async function processSendJitoBundleCallback(\n serializedTransactions: string[],\n jitoUUID?: string,\n url = DEFAULT_JITO_BLOCK_ENGINE_SEND_BUNDLE_URL,\n): Promise<string> {\n const maxRetries = 5;\n const baseBackoffMs = 250;\n\n const body = JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"sendBundle\",\n params: [\n serializedTransactions,\n {\n encoding: \"base64\",\n },\n ],\n });\n\n let response: Response | null = null;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(jitoUUID ? { \"x-jito-auth\": jitoUUID } : {}),\n },\n body,\n });\n\n if (response.status !== 429) break;\n if (attempt === maxRetries) break;\n\n const backoffMs = Math.min(10_000, baseBackoffMs * 2 ** attempt);\n await sleep(backoffMs);\n }\n\n if (!response) {\n throw new Error(\"Failed to send bundles: no response\");\n }\n\n const data = (await response.json()) as { result?: string; error?: unknown };\n\n if (data.error) {\n throw new Error(\n `Error sending bundles: ${JSON.stringify(data.error, null, 2)}`,\n );\n }\n\n if (!data.result) {\n throw new Error(\"No bundle ID returned from Jito\");\n }\n\n return data.result;\n}\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/consts.ts","../src/utils/errors.ts","../src/provider/utils.ts","../src/provider/main.ts","../src/utils/internal.ts","../src/utils/retry.ts","../src/utils/message/fetchSIgnatureFromTransactionManager.ts","../src/utils/message/index.ts","../src/client/signIn.ts","../src/utils/transactions/solana-send.ts","../src/utils/transactions/utils.ts","../src/utils/transactions/processBundledTransaction.ts","../src/utils/transactions/processSyncTransaction.ts","../src/utils/transactions/processTokenTransfer.ts","../src/utils/transactions/pollTransactionConfirmation.ts","../src/utils/transactions/sendTransaction.ts","../src/client/transactions.ts","../src/client/transfer.ts","../src/server/startRequest.ts","../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/utils.ts","../src/server/verifyMessage.ts","../src/server/verifyTransaction.ts","../src/server/processClientAuthCallback.ts","../src/server/processEstimateJitoTipsCallback.ts","../src/server/processSendJitoBundleCallback.ts"],"names":["REVIBASE_AUTH_URL","REVIBASE_RP_ID","REVIBASE_API_ENDPOINT","REVIBASE_LOOKUP_TABLE_ADDRESS","DEFAULT_JITO_BLOCK_ENGINE_SEND_BUNDLE_URL","DEFAULT_JITO_TIPS_URL","RevibaseError","_RevibaseError","message","code","RevibasePopupBlockedError","_RevibasePopupBlockedError","RevibasePopupClosedError","_RevibasePopupClosedError","RevibaseTimeoutError","_RevibaseTimeoutError","RevibaseFlowInProgressError","_RevibaseFlowInProgressError","RevibaseAbortedError","_RevibaseAbortedError","RevibasePopupNotOpenError","_RevibasePopupNotOpenError","RevibaseAuthError","_RevibaseAuthError","RevibaseApiError","_RevibaseApiError","RevibaseEnvironmentError","_RevibaseEnvironmentError","DEFAULT_TIMEOUT","HEARTBEAT_INTERVAL","CONNECT_TIMEOUT","defaultSendJitoBundleCallback","request","res","data","defaultEstimateJitoTipsCallback","defaultClientAuthorizationCallback","createPopUp","url","availW","availH","isMobile","width","height","top","left","screenLeft","screenTop","viewportW","viewportH","features","createProviderFrame","signal","onDismiss","scrollY","previousBodyStyles","lockScroll","unlockScroll","host","shadow","overlay","frameWrapper","iframe","closeBtn","keyHandler","e","dismiss","closed","close","abortHandler","RevibaseProvider","options","rpId","rpcEndpoint","providerOrigin","ui","onClientAuthorizationCallback","onSendJitoBundleCallback","onEstimateJitoTipsCallback","initialize","onConnectedCallback","onSuccessCallback","rid","getBase64Decoder","clientOrigin","popupUrl","detachForwardAbort","flowAbortController","forwardAbort","originalSignal","resolve","reject","params","fail","port","finished","heartbeatInterval","connectTimeoutId","requestTimeoutId","cleanup","onConnect","err","succeed","value","result","event","channel","lastPong","ev","msg","timeoutDuration","createSignInMessageText","input","fields","isNetworkError","withRetry","fn","maxAttempts","initialDelay","maxDelay","lastError","attempt","error","delay","fetchSignatureFromTransactionManager","wsUrl","toWebSocketUrl","pendingApprovalsCallback","signatures","ws","openWebSocket","readWebSocketJsonEvents","httpUrl","u","onAbort","onEvent","settled","onMessage","onError","onClose","finish","parsed","send2FARequestIfNeeded","startRequest","transactionManager","fetchSettings","getSolanaRpc","getSettingsFromIndex","x","UserRole","publicKey","convertMemberKeyToString","userAccountData","fetchUser","getUserAddress","address","signature","signIn","provider","payload","validTill","signAndSendTransaction","instructions","payer","addressesByLookupTableAddress","unitsConsumed","latestBlockHash","tx","pipe","createTransactionMessage","appendTransactionMessageInstructions","setTransactionMessageFeePayerSigner","setTransactionMessageLifetimeUsingBlockhash","compressTransactionMessageUsingAddressLookupTables","priorityFees","getMedianPriorityFees","computeUnits","prependTransactionMessageInstructions","getSetComputeUnitLimitInstruction","getSetComputeUnitPriceInstruction","signTransactionMessageWithSigners","getBase64EncodedWireTransaction","getSignatureFromTransaction","signAndSendBundledTransactions","bundle","encodedBundle","createEncodedBundle","connection","accounts","fees","AccountRole","f","a","b","mid","payerCache","getRandomPayer","cached","response","randomPayer","createTransactionSigner","transactions","getTransactionEncoder","signResponse","sig","getBase58Encoder","getTransactionManagerSigner","args","transactionManagerAddress","transactionMessageBytes","authResponses","onPendingApprovalsCallback","onPendingApprovalsSuccess","abortControllerArg","abortSignal","abortController","ac","txManagerUrl","createTransactionManagerSigner","fetchAdditionalLoopUpTableIfNecessary","fetchAddressesForLookupTables","fetched","fetchMaybeAddressLookupTable","processBundledTransaction","authResponse","settings","additionalSigners","additionalVoters","transactionActionType","signedSigner","getSignedSecp256r1Key","transactionManagerSigner","jitoBundlesTipAmount","getBase64Encoder","prepareTransactionBundle","bundlesWithLookupTables","index","processSyncTransaction","signers","prepareTransactionSync","processTokenTransfer","transactionAddress","amount","getU64Decoder","destination","getAddressDecoder","mint","SYSTEM_PROGRAM_ADDRESS","tokenTransferIntent","nativeTransferIntent","pollTransactionConfirmation","txSig","maxRetries","delayMs","i","confirmation","sendTransaction","confirmTransaction","executeTransaction","signer","settingsIndexWithAddress","prepareTransactionMessage","settingsArgs","transactionPayload","SignedSecp256r1Key","KeyType","transferTokens","tokenProgram","TOKEN_PROGRAM_ADDRESS","getU64Encoder","getAddressEncoder","allowedClientOrigins","privateKey","pKey","convertBase64StringToJWK","CompactSign","createClientAuthorizationStartRequestChallenge","equalBytes","diff","verifyMessage","expectedClientJwk","requireTwoFactorAuthentication","key","importJWK","compactVerify","getDeviceMessageHash","expectedChallenge","createMessageChallenge","verified","verifyAuthenticationResponse","bufferToBase64URLString","convertPubkeyCompressedToCose","delegateTo","fetchUserAccountByFilters","getDomainConfigAddress","verifySignature","getPublicKeyFromAddress","signatureBytes","verifyTransaction","createTransactionChallenge","createClientAuthorizationCompleteRequestChallenge","initialized","ensureInitialize","processClientAuthCallback","processEstimateJitoTipsCallback","priority","processSendJitoBundleCallback","serializedTransactions","jitoUUID","body","backoffMs","sleep","ms","r"],"mappings":"ooDAAO,IAAMA,CAAAA,CAAoB,2BAAA,CAEpBC,CAAAA,CAAiB,cAAA,CAEjBC,CAAAA,CAAwB,0BAAA,CAExBC,CAAAA,CACX,8CAAA,CAEWC,CAAAA,CACX,sDAAA,CAEWC,CAAAA,CACX,mDAAA,CCZK,IAAMC,CAAAA,CAAN,MAAMC,CAAAA,SAAsB,KAAM,CAC9B,IAAA,CAET,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAc,CACzC,KAAA,CAAMD,CAAO,CAAA,CACb,IAAA,CAAK,IAAA,CAAO,eAAA,CACZ,IAAA,CAAK,IAAA,CAAOC,CAAAA,CACZ,MAAA,CAAO,cAAA,CAAe,IAAA,CAAMF,CAAAA,CAAc,SAAS,EACrD,CACF,CAAA,CAGaG,CAAAA,CAAN,MAAMC,CAAAA,SAAkCL,CAAc,CAC3D,YAAYE,CAAAA,CAAU,sCAAA,CAAwC,CAC5D,KAAA,CAAMA,CAAAA,CAAS,eAAe,CAAA,CAC9B,IAAA,CAAK,IAAA,CAAO,2BAAA,CACZ,MAAA,CAAO,cAAA,CAAe,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AAAA,CAAK,MAAA,CACR,MAAM,IAAI,KAAA,CAAM,iCAAiC,CAAA,CAGnD,OAAOA,CAAAA,CAAK,MACd,CAEA,IAAMqR,EAAAA,CAASC,CAAAA,EAAe,IAAI,OAAA,CAAeC,CAAAA,EAAM,UAAA,CAAWA,CAAAA,CAAGD,CAAE,CAAC,CAAA","file":"index.js","sourcesContent":["export const REVIBASE_AUTH_URL = \"https://auth.revibase.com\";\n\nexport const REVIBASE_RP_ID = \"revibase.com\";\n\nexport const REVIBASE_API_ENDPOINT = \"https://api.revibase.com\";\n\nexport const REVIBASE_LOOKUP_TABLE_ADDRESS =\n \"2c1LgZfCun82niPCgfg2cTMZmAiahraTjY4KNb1BSU4Z\";\n\nexport const DEFAULT_JITO_BLOCK_ENGINE_SEND_BUNDLE_URL =\n \"https://mainnet.block-engine.jito.wtf/api/v1/bundles\";\n\nexport const DEFAULT_JITO_TIPS_URL =\n \"https://bundles.jito.wtf/api/v1/bundles/tip_floor\";\n","/** Base error. Use instanceof or .code for handling. */\nexport class RevibaseError extends Error {\n readonly code: string;\n\n constructor(message: string, code: string) {\n super(message);\n this.name = \"RevibaseError\";\n this.code = code;\n Object.setPrototypeOf(this, RevibaseError.prototype);\n }\n}\n\n/** Auth popup blocked. */\nexport class RevibasePopupBlockedError extends RevibaseError {\n constructor(message = \"Popup blocked. Please enable popups.\") {\n super(message, \"POPUP_BLOCKED\");\n this.name = \"RevibasePopupBlockedError\";\n Object.setPrototypeOf(this, RevibasePopupBlockedError.prototype);\n }\n}\n\n/** User closed popup before auth. */\nexport class RevibasePopupClosedError extends RevibaseError {\n constructor(message = \"Popup was closed by the user\") {\n super(message, \"POPUP_CLOSED\");\n this.name = \"RevibasePopupClosedError\";\n Object.setPrototypeOf(this, RevibasePopupClosedError.prototype);\n }\n}\n\n/** Authorization flow timed out. */\nexport class RevibaseTimeoutError extends RevibaseError {\n constructor(message = \"Authentication timed out\") {\n super(message, \"TIMEOUT\");\n this.name = \"RevibaseTimeoutError\";\n Object.setPrototypeOf(this, RevibaseTimeoutError.prototype);\n }\n}\n\n/** Flow already in progress. */\nexport class RevibaseFlowInProgressError extends RevibaseError {\n constructor(message = \"An authorization flow is already in progress\") {\n super(message, \"FLOW_IN_PROGRESS\");\n this.name = \"RevibaseFlowInProgressError\";\n Object.setPrototypeOf(this, RevibaseFlowInProgressError.prototype);\n }\n}\n\n/** Flow aborted (e.g. AbortSignal). */\nexport class RevibaseAbortedError extends RevibaseError {\n constructor(message = \"Aborted\") {\n super(message, \"ABORTED\");\n this.name = \"RevibaseAbortedError\";\n Object.setPrototypeOf(this, RevibaseAbortedError.prototype);\n }\n}\n\n/** Popup not open. */\nexport class RevibasePopupNotOpenError extends RevibaseError {\n constructor(message = \"Popup is not open. Call startRequest first.\") {\n super(message, \"POPUP_NOT_OPEN\");\n this.name = \"RevibasePopupNotOpenError\";\n Object.setPrototypeOf(this, RevibasePopupNotOpenError.prototype);\n }\n}\n\n/** Backend authorization failed. */\nexport class RevibaseAuthError extends RevibaseError {\n constructor(message: string) {\n super(message, \"AUTH_FAILED\");\n this.name = \"RevibaseAuthError\";\n Object.setPrototypeOf(this, RevibaseAuthError.prototype);\n }\n}\n\n/** Backend authorization failed. */\nexport class RevibaseApiError extends RevibaseError {\n constructor(message: string) {\n super(message, \"API_FAILED\");\n this.name = \"RevibaseApiError\";\n Object.setPrototypeOf(this, RevibaseApiError.prototype);\n }\n}\n\n/** Used outside browser. */\nexport class RevibaseEnvironmentError extends RevibaseError {\n constructor(message = \"Provider can only be used in a browser environment\") {\n super(message, \"ENVIRONMENT\");\n this.name = \"RevibaseEnvironmentError\";\n Object.setPrototypeOf(this, RevibaseEnvironmentError.prototype);\n }\n}\n","import type {\n CompleteMessageRequest,\n CompleteTransactionRequest,\n UserInfo,\n} from \"@revibase/core\";\nimport {\n RevibaseApiError,\n RevibaseAuthError,\n type ClientAuthorizationCallback,\n type OnConnectedCallback,\n type OnSuccessCallback,\n} from \"../utils\";\n\nexport const DEFAULT_TIMEOUT = 3 * 60 * 1000;\nexport const HEARTBEAT_INTERVAL = 2000;\nexport const CONNECT_TIMEOUT = 20000;\n\nexport type PopupPortMessage =\n | { type: \"pong\" }\n | {\n type: \"popup-complete\";\n payload: CompleteTransactionRequest | CompleteMessageRequest;\n }\n | { type: \"popup-rejected\"; rid: string }\n | { type: \"popup-error\"; error: string }\n | { type: \"popup-closed\" };\n\nexport type PopupConnectMessage = {\n type: \"popup-connect\";\n rid: string;\n};\n\nexport type Pending = {\n rid: string;\n clientOrigin: string;\n onConnectedCallback: OnConnectedCallback;\n onSuccessCallback: OnSuccessCallback;\n signal?: AbortSignal;\n resolve: (v: { user: UserInfo } | { user: UserInfo; txSig: string }) => void;\n reject: (e: Error) => void;\n};\n\n/** RevibaseProvider options. rpcEndpoint required for executeTransaction. */\nexport type RevibaseProviderOptions = {\n rpcEndpoint: string;\n providerOrigin?: string;\n rpId?: string;\n /** UI mode for same-device authorization. Default: \"iframe\". */\n ui?: {\n mode?: \"popup\" | \"iframe\";\n /**\n * Optional advanced hook to fully control how the provider UI is rendered.\n * Return a target window (popup or iframe.contentWindow) for postMessage transport,\n * and a close() function for cleanup. If you can, also provide isClosed() so the\n * SDK can detect user-dismissal.\n */\n render?: (url: string) => {\n targetWindow: Window;\n close: () => void;\n isClosed?: () => boolean;\n };\n };\n onClientAuthorizationCallback?: ClientAuthorizationCallback;\n onEstimateJitoTipsCallback?: () => Promise<number>;\n onSendJitoBundleCallback?: (request: string[]) => Promise<string>;\n};\n\nexport const defaultSendJitoBundleCallback: (\n serializedTransactions: string[],\n) => Promise<string> = async (request) => {\n const res = await fetch(\"/api/sendJitoBundle\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(request),\n });\n\n const data = await res.json();\n if (!res.ok) {\n throw new RevibaseApiError(\n (data as { error?: string }).error ?? \"Send jito bundle failed\",\n );\n }\n\n return data;\n};\n\nexport const defaultEstimateJitoTipsCallback: () => Promise<number> =\n async () => {\n const res = await fetch(\"/api/estimateJitoTips\");\n\n const data = await res.json();\n if (!res.ok) {\n throw new RevibaseApiError(\n (data as { error?: string }).error ?? \"Estimate jito tips failed\",\n );\n }\n\n return data;\n };\n\nexport const defaultClientAuthorizationCallback: ClientAuthorizationCallback =\n async (request) => {\n const res = await fetch(\"/api/clientAuthorization\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(request),\n });\n\n const data = await res.json();\n if (!res.ok) {\n throw new RevibaseAuthError(\n (data as { error?: string }).error ?? \"Authorization failed\",\n );\n }\n\n return data;\n };\n\nexport function createPopUp(url: string): Window | null {\n if (typeof window === \"undefined\") {\n throw new Error(\"Function can only be called in a browser environment\");\n }\n\n const availW = window.innerWidth || window.screen.availWidth;\n const availH = window.innerHeight || window.screen.availHeight;\n const isMobile = availW <= 768;\n\n let width: number;\n let height: number;\n let top: number;\n let left: number;\n\n if (isMobile) {\n width = availW;\n height = availH;\n top = 0;\n left = 0;\n } else {\n const screenLeft = window.screenLeft ?? window.screenX ?? 0;\n const screenTop = window.screenTop ?? window.screenY ?? 0;\n\n const viewportW =\n window.innerWidth ??\n document.documentElement.clientWidth ??\n window.screen.width;\n\n const viewportH =\n window.innerHeight ??\n document.documentElement.clientHeight ??\n window.screen.height;\n\n width = 500;\n height = 600;\n left = Math.round(screenLeft + (viewportW - width) / 2);\n top = Math.round(screenTop + (viewportH - height) / 2);\n }\n\n const features = [\n \"popup=yes\",\n `width=${width}`,\n `height=${height}`,\n `top=${top}`,\n `left=${left}`,\n \"toolbar=no\",\n \"location=no\",\n \"status=no\",\n \"menubar=no\",\n \"scrollbars=yes\",\n \"resizable=yes\",\n ].join(\",\");\n\n return window.open(url, \"_blank\", features);\n}\nexport interface ProviderFrame {\n iframe: HTMLIFrameElement;\n close: () => void;\n}\n\nexport function createProviderFrame(\n url: string,\n signal?: AbortSignal,\n onDismiss?: () => void,\n): ProviderFrame {\n if (typeof window === \"undefined\") {\n throw new Error(\"Function can only be called in a browser environment\");\n }\n\n const isMobile = window.matchMedia(\"(max-width: 768px)\").matches;\n\n // ----------------------------------------\n // Scroll lock (iOS-safe)\n // ----------------------------------------\n\n const scrollY = window.scrollY;\n\n const previousBodyStyles = {\n overflow: document.body.style.overflow,\n position: document.body.style.position,\n top: document.body.style.top,\n left: document.body.style.left,\n right: document.body.style.right,\n width: document.body.style.width,\n };\n\n const lockScroll = () => {\n document.body.style.overflow = \"hidden\";\n document.body.style.position = \"fixed\";\n document.body.style.top = `-${scrollY}px`;\n document.body.style.left = \"0\";\n document.body.style.right = \"0\";\n document.body.style.width = \"100%\";\n };\n\n const unlockScroll = () => {\n document.body.style.overflow = previousBodyStyles.overflow;\n document.body.style.position = previousBodyStyles.position;\n document.body.style.top = previousBodyStyles.top;\n document.body.style.left = previousBodyStyles.left;\n document.body.style.right = previousBodyStyles.right;\n document.body.style.width = previousBodyStyles.width;\n\n window.scrollTo(0, scrollY);\n };\n\n lockScroll();\n\n // ----------------------------------------\n // Shadow DOM host\n // ----------------------------------------\n\n const host = document.createElement(\"div\");\n\n host.setAttribute(\"data-provider-frame-root\", \"true\");\n\n Object.assign(host.style, {\n position: \"fixed\",\n inset: \"0\",\n zIndex: \"2147483647\",\n pointerEvents: \"none\",\n contain: \"layout style paint\",\n });\n\n document.body.appendChild(host);\n\n const shadow = host.attachShadow({ mode: \"closed\" });\n\n // ----------------------------------------\n // Overlay\n // ----------------------------------------\n\n const overlay = document.createElement(\"div\");\n\n Object.assign(overlay.style, {\n all: \"initial\",\n\n position: \"fixed\",\n inset: \"0\",\n\n display: \"flex\",\n alignItems: isMobile ? \"flex-end\" : \"center\",\n justifyContent: \"center\",\n\n background: \"rgba(0,0,0,0.45)\",\n\n zIndex: \"2147483647\",\n\n pointerEvents: \"auto\",\n\n overscrollBehavior: \"contain\",\n touchAction: \"none\",\n\n WebkitTapHighlightColor: \"transparent\",\n\n paddingBottom: \"env(safe-area-inset-bottom)\",\n\n fontFamily:\n 'Inter, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif',\n });\n\n shadow.appendChild(overlay);\n\n // ----------------------------------------\n // Frame wrapper\n // ----------------------------------------\n\n const frameWrapper = document.createElement(\"div\");\n\n Object.assign(frameWrapper.style, {\n all: \"initial\",\n\n position: \"relative\",\n\n display: \"flex\",\n\n width: isMobile ? \"100%\" : \"500px\",\n\n height: isMobile ? \"90dvh\" : \"600px\",\n\n maxWidth: \"100vw\",\n maxHeight: \"100dvh\",\n\n borderRadius: isMobile ? \"16px 16px 0 0\" : \"16px\",\n\n overflow: \"hidden\",\n\n boxShadow: \"0 24px 80px rgba(0,0,0,0.35)\",\n\n background: \"#fff\",\n\n pointerEvents: \"auto\",\n });\n\n overlay.appendChild(frameWrapper);\n\n // ----------------------------------------\n // iframe\n // ----------------------------------------\n\n const iframe = document.createElement(\"iframe\");\n\n iframe.src = url;\n\n iframe.title = \"Authorization\";\n\n iframe.setAttribute(\"tabindex\", \"0\");\n\n iframe.allow = [`publickey-credentials-get ${new URL(url).origin}`].join(\n \"; \",\n );\n\n iframe.sandbox = [\"allow-scripts\", \"allow-same-origin\"].join(\" \");\n\n Object.assign(iframe.style, {\n width: \"100%\",\n height: \"100%\",\n\n border: \"0\",\n\n background: \"#fff\",\n\n display: \"block\",\n });\n\n frameWrapper.appendChild(iframe);\n\n // ----------------------------------------\n // Close button\n // ----------------------------------------\n\n const closeBtn = document.createElement(\"button\");\n\n closeBtn.type = \"button\";\n\n closeBtn.setAttribute(\"aria-label\", \"Close\");\n\n closeBtn.innerHTML = \"×\";\n\n Object.assign(closeBtn.style, {\n all: \"initial\",\n\n position: \"absolute\",\n\n top: isMobile ? \"12px\" : \"14px\",\n right: isMobile ? \"12px\" : \"14px\",\n\n width: \"44px\",\n height: \"44px\",\n\n display: \"grid\",\n placeItems: \"center\",\n\n borderRadius: \"9999px\",\n\n background: \"rgba(255,255,255,0.96)\",\n\n color: \"#111\",\n\n fontSize: \"28px\",\n\n lineHeight: \"1\",\n\n cursor: \"pointer\",\n\n boxShadow: \"0 8px 24px rgba(0,0,0,0.25)\",\n\n zIndex: \"2\",\n\n userSelect: \"none\",\n WebkitUserSelect: \"none\",\n });\n\n frameWrapper.appendChild(closeBtn);\n\n // ----------------------------------------\n // Focus iframe\n // ----------------------------------------\n\n requestAnimationFrame(() => {\n try {\n iframe.focus();\n } catch {}\n });\n\n // ----------------------------------------\n // Escape key\n // ----------------------------------------\n\n const keyHandler = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n dismiss();\n }\n };\n\n document.addEventListener(\"keydown\", keyHandler);\n\n // ----------------------------------------\n // Close logic\n // ----------------------------------------\n\n let closed = false;\n\n const close = () => {\n if (closed) return;\n\n closed = true;\n\n try {\n signal?.removeEventListener(\"abort\", abortHandler);\n } catch {}\n\n try {\n document.removeEventListener(\"keydown\", keyHandler);\n } catch {}\n\n try {\n iframe.src = \"about:blank\";\n iframe.removeAttribute(\"src\");\n } catch {}\n\n try {\n host.remove();\n } catch {}\n\n unlockScroll();\n };\n\n // ----------------------------------------\n // Dismiss\n // ----------------------------------------\n\n const dismiss = () => {\n onDismiss?.();\n close();\n };\n\n closeBtn.addEventListener(\"click\", (e) => {\n e.preventDefault();\n e.stopPropagation();\n\n dismiss();\n });\n\n overlay.addEventListener(\"click\", (e) => {\n if (e.target === overlay) {\n dismiss();\n }\n });\n\n // ----------------------------------------\n // Abort signal\n // ----------------------------------------\n\n const abortHandler = () => {\n dismiss();\n };\n\n if (signal) {\n if (signal.aborted) {\n abortHandler();\n } else {\n signal.addEventListener(\"abort\", abortHandler, {\n once: true,\n });\n }\n }\n\n return {\n iframe,\n close,\n };\n}\n","import type {\n CompleteMessageRequest,\n CompleteTransactionRequest,\n UserInfo,\n} from \"@revibase/core\";\nimport { initialize } from \"@revibase/core\";\nimport { getBase64Decoder } from \"@solana/kit\";\nimport type {\n ClientAuthorizationCallback,\n OnConnectedCallback,\n OnSuccessCallback,\n} from \"../utils\";\nimport { REVIBASE_AUTH_URL, REVIBASE_RP_ID } from \"../utils/consts\";\nimport {\n RevibaseAbortedError,\n RevibaseAuthError,\n RevibaseEnvironmentError,\n RevibaseFlowInProgressError,\n RevibasePopupBlockedError,\n RevibasePopupClosedError,\n RevibaseTimeoutError,\n} from \"../utils/errors\";\nimport {\n CONNECT_TIMEOUT,\n createPopUp,\n createProviderFrame,\n defaultClientAuthorizationCallback,\n defaultEstimateJitoTipsCallback,\n defaultSendJitoBundleCallback,\n HEARTBEAT_INTERVAL,\n type Pending,\n type PopupConnectMessage,\n type PopupPortMessage,\n type RevibaseProviderOptions,\n} from \"./utils\";\n\n/** Provider: popup or channel auth. Default callback: POST /api/clientAuthorization. */\nexport class RevibaseProvider {\n public onClientAuthorizationCallback: ClientAuthorizationCallback;\n public onSendJitoBundleCallback: (request: string[]) => Promise<string>;\n public onEstimateJitoTipsCallback: () => Promise<number>;\n public providerOrigin: string;\n public rpId: string;\n private uiMode: \"popup\" | \"iframe\";\n private render?: NonNullable<RevibaseProviderOptions[\"ui\"]>[\"render\"];\n private popUp: Window | null = null;\n private frame: ReturnType<typeof createProviderFrame> | null = null;\n private rendered: {\n targetWindow: Window;\n close: () => void;\n isClosed?: () => boolean;\n } | null = null;\n\n constructor(options: RevibaseProviderOptions) {\n const {\n rpId,\n rpcEndpoint,\n providerOrigin,\n ui,\n onClientAuthorizationCallback,\n onSendJitoBundleCallback,\n onEstimateJitoTipsCallback,\n } = options;\n\n initialize({ rpcEndpoint });\n this.onClientAuthorizationCallback =\n onClientAuthorizationCallback ?? defaultClientAuthorizationCallback;\n this.onSendJitoBundleCallback =\n onSendJitoBundleCallback ?? defaultSendJitoBundleCallback;\n this.onEstimateJitoTipsCallback =\n onEstimateJitoTipsCallback ?? defaultEstimateJitoTipsCallback;\n this.providerOrigin = providerOrigin ?? REVIBASE_AUTH_URL;\n this.rpId = rpId ?? REVIBASE_RP_ID;\n this.uiMode = ui?.mode ?? \"iframe\";\n this.render = ui?.render;\n }\n\n async sendRequestToPopupProvider({\n onConnectedCallback,\n onSuccessCallback,\n signal,\n }: {\n onConnectedCallback: OnConnectedCallback;\n onSuccessCallback: OnSuccessCallback;\n signal?: AbortSignal;\n }) {\n if (typeof window === \"undefined\") {\n throw new RevibaseEnvironmentError();\n }\n\n if (this.popUp || this.frame || this.rendered) {\n throw new RevibaseFlowInProgressError();\n }\n\n const rid = getBase64Decoder().decode(\n crypto.getRandomValues(new Uint8Array(16)),\n );\n const clientOrigin = window.location.origin;\n const popupUrl = `${this.providerOrigin}?clientOrigin=${encodeURIComponent(clientOrigin)}&rid=${encodeURIComponent(rid)}`;\n\n let detachForwardAbort: (() => void) | undefined;\n\n if (this.render) {\n this.rendered = this.render(popupUrl);\n } else if (this.uiMode === \"iframe\") {\n // We need a controller here so backdrop-dismiss can \"abort\" the flow.\n const flowAbortController = new AbortController();\n const forwardAbort = () => flowAbortController.abort();\n const originalSignal = signal;\n if (originalSignal) {\n if (originalSignal.aborted) {\n flowAbortController.abort();\n } else {\n originalSignal.addEventListener(\"abort\", forwardAbort, {\n once: true,\n });\n detachForwardAbort = () =>\n originalSignal.removeEventListener(\"abort\", forwardAbort);\n }\n }\n\n this.frame = createProviderFrame(\n popupUrl,\n flowAbortController.signal,\n () => flowAbortController.abort(),\n );\n\n // Replace the provided signal so transport + cleanup treat backdrop-dismiss as abort.\n signal = flowAbortController.signal;\n } else {\n this.popUp = createPopUp(popupUrl);\n if (!this.popUp) {\n throw new RevibasePopupBlockedError();\n }\n }\n\n return new Promise<{ user: UserInfo } | { txSig: string; user: UserInfo }>(\n (resolve, reject) => {\n setTimeout(() => {\n this.attachTransport({\n rid,\n clientOrigin,\n onConnectedCallback,\n onSuccessCallback,\n signal,\n resolve,\n reject,\n });\n }, 0);\n },\n ).finally(() => {\n try {\n detachForwardAbort?.();\n } catch {\n // ignore\n }\n });\n }\n\n private attachTransport(params: Pending) {\n const {\n rid,\n clientOrigin,\n onConnectedCallback,\n onSuccessCallback,\n signal,\n reject,\n resolve,\n } = params;\n\n const abortHandler = () => {\n fail(new RevibaseAbortedError());\n };\n signal?.addEventListener(\"abort\", abortHandler, { once: true });\n\n let port: MessagePort | null = null;\n let finished = false;\n\n let heartbeatInterval: ReturnType<typeof setInterval> | null = null;\n let connectTimeoutId: ReturnType<typeof setTimeout> | null = null;\n let requestTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = (): void => {\n // Remove all event listeners\n window.removeEventListener(\"message\", onConnect);\n signal?.removeEventListener(\"abort\", abortHandler);\n\n // Clear all timers\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = null;\n }\n if (connectTimeoutId) {\n clearTimeout(connectTimeoutId);\n connectTimeoutId = null;\n }\n if (requestTimeoutId) {\n clearTimeout(requestTimeoutId);\n requestTimeoutId = null;\n }\n\n // Close message port\n try {\n port?.close();\n } catch (err) {\n // Ignore close errors\n }\n port = null;\n\n // Close UI\n try {\n if (this.popUp && !this.popUp.closed) {\n this.popUp.close();\n }\n } catch (err) {\n // Ignore close errors\n }\n\n try {\n this.frame?.close();\n } catch (err) {\n // Ignore close errors\n }\n\n try {\n this.rendered?.close();\n } catch (err) {\n // Ignore close errors\n }\n\n this.popUp = null;\n this.frame = null;\n this.rendered = null;\n };\n\n const fail = (err: Error): void => {\n if (finished) return;\n finished = true;\n cleanup();\n reject(err);\n };\n\n const succeed = (\n value: CompleteMessageRequest | CompleteTransactionRequest,\n ): void => {\n if (finished) return;\n finished = true;\n cleanup();\n onSuccessCallback(value as any)\n .then((result) => {\n resolve(result);\n })\n .catch((err) => {\n reject(err);\n });\n };\n\n // Connection timeout - handles popup closed before connection\n connectTimeoutId = setTimeout(() => {\n fail(new RevibaseTimeoutError(\"Popup connection timed out after 20s\"));\n }, CONNECT_TIMEOUT);\n\n const onConnect = (event: MessageEvent) => {\n // Prevent race condition - only process once\n if (finished || port) return;\n\n // Validate message origin\n if (event.origin !== this.providerOrigin) return;\n\n const data = event.data as PopupConnectMessage;\n\n // Validate message structure\n if (!data || data.type !== \"popup-connect\") return;\n if (data.rid !== rid) return;\n\n // Clear connection timeout\n if (connectTimeoutId) {\n clearTimeout(connectTimeoutId);\n connectTimeoutId = null;\n }\n\n // Create MessageChannel for bidirectional communication\n const channel = new MessageChannel();\n port = channel.port1;\n port.start();\n\n let lastPong = Date.now();\n\n // Start heartbeat ONLY AFTER connection established\n heartbeatInterval = setInterval(() => {\n if (finished) {\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = null;\n }\n return;\n }\n\n if (this.rendered?.isClosed) {\n if (this.rendered.isClosed()) {\n fail(new RevibasePopupClosedError(\"Provider UI was closed\"));\n return;\n }\n } else if (this.rendered) {\n // If consumer didn't provide isClosed, we can't reliably detect.\n } else if (this.uiMode === \"iframe\") {\n // If the iframe is removed, treat as closed\n if (!this.frame?.iframe.isConnected) {\n fail(new RevibasePopupClosedError(\"Provider iframe was closed\"));\n return;\n }\n } else {\n if (this.popUp?.closed) {\n fail(new RevibasePopupClosedError(\"Popup was closed\"));\n return;\n }\n }\n\n // Check if port is still available\n if (!port) {\n fail(new RevibasePopupClosedError(\"Message channel lost\"));\n return;\n }\n\n const now = Date.now();\n\n // Check if we've lost connection (no pong in 2x heartbeat interval)\n if (now - lastPong > HEARTBEAT_INTERVAL * 2) {\n fail(\n new RevibasePopupClosedError(\n \"Lost connection to popup (heartbeat timeout)\",\n ),\n );\n return;\n }\n\n // Send ping\n try {\n port.postMessage({ type: \"ping\" });\n } catch (err) {\n fail(new RevibasePopupClosedError(\"Failed to send heartbeat\"));\n }\n }, HEARTBEAT_INTERVAL);\n\n // Handle messages from popup\n port.onmessage = (ev: MessageEvent<PopupPortMessage>): void => {\n if (finished) return;\n const msg = ev.data;\n\n switch (msg.type) {\n case \"pong\":\n lastPong = Date.now();\n break;\n\n case \"popup-complete\":\n if (msg.payload) {\n succeed(msg.payload);\n } else {\n fail(new RevibaseAuthError(\"Invalid completion payload\"));\n }\n break;\n\n case \"popup-rejected\":\n fail(new RevibaseAuthError(\"User rejected the operation\"));\n break;\n\n case \"popup-error\":\n fail(new RevibaseAuthError(msg.error || \"Unknown popup error\"));\n break;\n\n case \"popup-closed\":\n fail(new RevibasePopupClosedError(\"User closed popup\"));\n break;\n\n default:\n console.warn(\"Unknown message type from popup:\", msg);\n }\n };\n\n // Handle port errors\n port.onmessageerror = () => {\n fail(new RevibaseAuthError(\"Message deserialization error\"));\n };\n\n // Send init message to popup with port2\n try {\n if (this.rendered) {\n this.rendered.targetWindow.postMessage(\n {\n type: \"popup-init\",\n rid,\n },\n this.providerOrigin,\n [channel.port2],\n );\n } else if (this.uiMode === \"iframe\") {\n this.frame?.iframe.contentWindow?.postMessage(\n {\n type: \"popup-init\",\n rid,\n },\n this.providerOrigin,\n [channel.port2],\n );\n } else {\n this.popUp?.postMessage(\n {\n type: \"popup-init\",\n rid,\n },\n this.providerOrigin,\n [channel.port2],\n );\n }\n } catch (err) {\n fail(new RevibaseAuthError(`Failed to initialize popup: ${err}`));\n return;\n }\n\n // Call the callback to get the request\n onConnectedCallback(rid, clientOrigin)\n .then((result) => {\n // Verify we're still active\n if (finished || !port) {\n return;\n }\n if (this.rendered?.isClosed) {\n if (this.rendered.isClosed()) return;\n } else if (this.uiMode === \"iframe\") {\n if (!this.frame?.iframe.isConnected) return;\n } else {\n if (this.popUp?.closed) return;\n }\n\n // Send the request to popup\n try {\n port.postMessage({\n type: \"popup-start\",\n payload: result,\n });\n } catch (err) {\n fail(\n new RevibaseAuthError(`Failed to send request to popup: ${err}`),\n );\n return;\n }\n\n // Clear any existing request timeout\n if (requestTimeoutId) {\n clearTimeout(requestTimeoutId);\n requestTimeoutId = null;\n }\n\n // Calculate TTL and set new timeout\n const timeoutDuration = Math.max(\n 0,\n result.request.validTill - Date.now(),\n );\n\n requestTimeoutId = setTimeout(() => {\n fail(new RevibaseTimeoutError(\"Request expired\"));\n }, timeoutDuration);\n })\n .catch((err) => {\n fail(err);\n });\n };\n\n // Attach connect listener\n window.addEventListener(\"message\", onConnect);\n }\n}\n","/** Sign-in message text (domain + nonce). */\nexport function createSignInMessageText(input: {\n domain?: string;\n nonce: string;\n}): string {\n const message = input.domain\n ? `${input.domain} wants you to sign in with your account.`\n : \"Sign in with your account.\";\n\n const fields: string[] = [];\n\n if (input.nonce) {\n fields.push(`Nonce: ${input.nonce}`);\n }\n\n return fields.length > 0 ? `${message}\\n\\n${fields.join(\"\\n\")}` : message;\n}\n","/**\n * Checks if an error is network-related (e.g., load failed, network errors)\n */\nfunction isNetworkError(err: Error): boolean {\n const msg = err?.message || \"\";\n return (\n msg === \"Failed to fetch\" ||\n msg.includes(\"Load failed\") ||\n msg.includes(\"NetworkError\") ||\n msg.includes(\"ERR_NETWORK\")\n );\n}\n\n/**\n * Retries a function with exponential backoff on network errors only.\n * @param fn - The async function to retry\n * @param maxAttempts - Maximum number of attempts (default: 3)\n * @param initialDelay - Initial delay in ms (default: 100)\n * @param maxDelay - Maximum delay in ms (default: 5000)\n */\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n maxAttempts = 3,\n initialDelay = 500,\n maxDelay = 5000,\n): Promise<T> {\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Only retry on network errors\n if (!isNetworkError(lastError)) {\n throw lastError;\n }\n\n // Don't retry on the last attempt\n if (attempt === maxAttempts - 1) {\n break;\n }\n\n // Calculate exponential backoff delay\n const delay = Math.min(initialDelay * Math.pow(2, attempt), maxDelay);\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw lastError;\n}\n","import type { CompleteMessageRequest } from \"@revibase/core\";\nimport type { SignInAuthorizationFlowOptions } from \"../types\";\n\nexport async function fetchSignatureFromTransactionManager({\n data,\n url,\n options,\n}: {\n data: {\n publicKey: string;\n payload: CompleteMessageRequest;\n };\n url: string;\n options?: SignInAuthorizationFlowOptions;\n}) {\n const maxAttempts = 10;\n const retryDelayMs = 400;\n const wsUrl = toWebSocketUrl(url);\n const { pendingApprovalsCallback, signal } = options ?? {};\n\n for (let i = 0; i < maxAttempts; i++) {\n if (signal?.aborted) throw Error(\"Aborted\");\n let signatures: string[] | undefined;\n let ws: WebSocket | undefined;\n try {\n ws = await openWebSocket(wsUrl, signal);\n ws.send(JSON.stringify({ type: \"message\", data }));\n await readWebSocketJsonEvents(\n ws,\n (event, data) => {\n if (event === \"error\") {\n const err =\n data &&\n typeof data === \"object\" &&\n typeof (data as { error?: string }).error === \"string\"\n ? (data as { error: string }).error\n : \"Unknown error\";\n const e = new Error(err) as Error & { noRetry: true };\n e.noRetry = true;\n throw e;\n }\n if (event === \"signatures\") {\n signatures = (data as { signatures?: string[] }).signatures;\n return true;\n }\n if (event === \"pending_transaction_approval\") {\n pendingApprovalsCallback?.onPendingApprovalsCallback?.(\n (data as { validTill: number }).validTill,\n );\n } else if (event === \"transaction_approved\") {\n pendingApprovalsCallback?.onPendingApprovalsSuccess?.();\n }\n return false;\n },\n signal,\n );\n } catch (e: unknown) {\n if (e && typeof e === \"object\" && (e as { noRetry?: true }).noRetry) {\n throw new Error(`${(e as Error).message}`);\n }\n if (\n e &&\n typeof e === \"object\" &&\n (e as { name?: string }).name === \"AbortError\"\n )\n throw e;\n } finally {\n try {\n ws?.close();\n } catch {\n /* ignore */\n }\n }\n if (signatures?.length) {\n return signatures[0];\n }\n if (i < maxAttempts - 1)\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n }\n throw new Error(\"Transaction manager: missing signatures\");\n}\n\nfunction toWebSocketUrl(httpUrl: string): string {\n const u = new URL(httpUrl);\n if (u.protocol === \"https:\") u.protocol = \"wss:\";\n else if (u.protocol === \"http:\") u.protocol = \"ws:\";\n return u.toString();\n}\n\nfunction openWebSocket(url: string, signal?: AbortSignal): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(url);\n\n const onAbort = () => {\n try {\n ws.close();\n } catch {\n /* ignore */\n }\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n ws.onopen = () => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(ws);\n };\n ws.onerror = () => {\n signal?.removeEventListener(\"abort\", onAbort);\n reject(new Error(\"WebSocket connection failed\"));\n };\n });\n}\n\nasync function readWebSocketJsonEvents(\n ws: WebSocket,\n onEvent: (event: string, data: any) => boolean,\n signal?: AbortSignal,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let settled = false;\n\n const cleanup = () => {\n signal?.removeEventListener(\"abort\", onAbort);\n ws.removeEventListener(\"message\", onMessage);\n ws.removeEventListener(\"error\", onError);\n ws.removeEventListener(\"close\", onClose);\n };\n\n const finish = (fn: () => void) => {\n if (settled) return;\n settled = true;\n cleanup();\n fn();\n };\n\n const onAbort = () => {\n try {\n ws.close();\n } catch {\n /* ignore */\n }\n };\n signal?.addEventListener(\"abort\", onAbort);\n\n const onMessage = (ev: MessageEvent) => {\n if (typeof ev.data !== \"string\") return;\n let parsed: { event?: string; data?: unknown };\n try {\n parsed = JSON.parse(ev.data);\n } catch {\n return;\n }\n const event = typeof parsed.event === \"string\" ? parsed.event : \"message\";\n const data = parsed.data;\n try {\n if (onEvent(event, data)) {\n finish(() => resolve());\n }\n } catch (e) {\n finish(() => reject(e));\n }\n };\n\n const onError = () => {\n finish(() => reject(new Error(\"Transaction manager request failed\")));\n };\n\n const onClose = () => {\n finish(() => resolve());\n };\n\n ws.addEventListener(\"message\", onMessage);\n ws.addEventListener(\"error\", onError);\n ws.addEventListener(\"close\", onClose);\n });\n}\n","import {\n convertMemberKeyToString,\n fetchSettings,\n fetchUser,\n getSettingsFromIndex,\n getSolanaRpc,\n getUserAddress,\n UserRole,\n type CompleteMessageRequest,\n} from \"@revibase/core\";\nimport { address } from \"@solana/kit\";\nimport { withRetry } from \"../retry\";\nimport type { SignInAuthorizationFlowOptions } from \"../types\";\nimport { fetchSignatureFromTransactionManager } from \"./fetchSIgnatureFromTransactionManager\";\n\nexport async function send2FARequestIfNeeded(\n request: CompleteMessageRequest,\n options?: SignInAuthorizationFlowOptions,\n): Promise<{ publicKey: string; signature: string } | null> {\n const { startRequest } = request.data.payload;\n\n if (!startRequest.data.requireTwoFactorAuthentication) {\n return null;\n }\n\n const settingsData = (\n await withRetry(async () =>\n fetchSettings(\n getSolanaRpc(),\n await getSettingsFromIndex(\n request.data.payload.user.settingsIndexWithAddress.index,\n ),\n ),\n )\n ).data;\n const transactionManager = settingsData.members.find(\n (x) => x.role === UserRole.TransactionManager,\n );\n if (!transactionManager) {\n throw new Error(\"No transaction manager found.\");\n }\n const publicKey = convertMemberKeyToString(transactionManager.pubkey);\n const userAccountData = (\n await withRetry(async () =>\n fetchUser(getSolanaRpc(), await getUserAddress(address(publicKey))),\n )\n ).data;\n if (userAccountData.transactionManagerUrl.__option === \"None\") {\n throw new Error(\"No transaction manager url found.\");\n }\n const signature = await fetchSignatureFromTransactionManager({\n data: {\n publicKey,\n payload: request,\n },\n url: userAccountData.transactionManagerUrl.value,\n options,\n });\n\n return { publicKey, signature };\n}\n","import { type CompleteMessageRequest, type UserInfo } from \"@revibase/core\";\nimport { getBase64Decoder } from \"@solana/kit\";\nimport { RevibaseProvider } from \"../provider/main\";\nimport { createSignInMessageText } from \"../utils/internal\";\nimport { send2FARequestIfNeeded } from \"../utils/message\";\nimport { withRetry } from \"../utils/retry\";\nimport type { SignInAuthorizationFlowOptions } from \"../utils/types\";\n\nexport async function signIn(\n provider: RevibaseProvider,\n options?: SignInAuthorizationFlowOptions,\n): Promise<{ user: UserInfo }> {\n const onConnectedCallback = async (rid: string, clientOrigin: string) => {\n const payload = {\n phase: \"start\" as const,\n rid,\n providerOrigin: provider.providerOrigin,\n rpId: provider.rpId,\n data: {\n type: \"message\" as const,\n payload: createSignInMessageText({\n domain: clientOrigin,\n nonce: getBase64Decoder().decode(\n crypto.getRandomValues(new Uint8Array(16)),\n ),\n }),\n requireTwoFactorAuthentication:\n options?.requireTwoFactorAuthentication ?? false,\n },\n clientOrigin,\n };\n\n const { signature, validTill } = await withRetry(() =>\n provider.onClientAuthorizationCallback(payload),\n );\n return { request: { ...payload, rid, validTill }, signature };\n };\n\n const onSuccessCallback = async (\n result: CompleteMessageRequest,\n ): Promise<{ user: UserInfo }> => {\n const transactionManager = await send2FARequestIfNeeded(result, options);\n await provider.onClientAuthorizationCallback(\n !transactionManager\n ? result\n : {\n ...result,\n data: {\n ...result.data,\n payload: { ...result.data.payload, transactionManager },\n },\n },\n );\n return { user: result.data.payload.user };\n };\n\n return provider.sendRequestToPopupProvider({\n onConnectedCallback,\n onSuccessCallback,\n signal: options?.signal,\n });\n}\n","import { getSolanaRpc, type TransactionDetails } from \"@revibase/core\";\nimport {\n getSetComputeUnitLimitInstruction,\n getSetComputeUnitPriceInstruction,\n} from \"@solana-program/compute-budget\";\nimport {\n AccountRole,\n appendTransactionMessageInstructions,\n compressTransactionMessageUsingAddressLookupTables,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n getSignatureFromTransaction,\n pipe,\n prependTransactionMessageInstructions,\n setTransactionMessageFeePayerSigner,\n setTransactionMessageLifetimeUsingBlockhash,\n signTransactionMessageWithSigners,\n type AccountMeta,\n type Rpc,\n type SolanaRpcApi,\n} from \"@solana/kit\";\nimport type { RevibaseProvider } from \"../../provider\";\nimport { withRetry } from \"../retry\";\n\nexport async function signAndSendTransaction({\n instructions,\n payer,\n addressesByLookupTableAddress,\n unitsConsumed,\n}: TransactionDetails): Promise<string> {\n const latestBlockHash = await withRetry(() =>\n getSolanaRpc().getLatestBlockhash().send(),\n );\n const tx = await pipe(\n createTransactionMessage({ version: 0 }),\n (tx) => appendTransactionMessageInstructions(instructions, tx),\n (tx) => setTransactionMessageFeePayerSigner(payer, tx),\n (tx) =>\n setTransactionMessageLifetimeUsingBlockhash(latestBlockHash.value, tx),\n (tx) =>\n addressesByLookupTableAddress\n ? compressTransactionMessageUsingAddressLookupTables(\n tx,\n addressesByLookupTableAddress,\n )\n : tx,\n async (tx) => {\n const priorityFees = await getMedianPriorityFees(\n getSolanaRpc(),\n tx.instructions.flatMap((x) => x.accounts ?? []),\n );\n\n const computeUnits = Math.ceil((Number(unitsConsumed) ?? 0) * 1.1);\n return prependTransactionMessageInstructions(\n [\n ...(computeUnits > 200_000\n ? [\n getSetComputeUnitLimitInstruction({\n units: computeUnits,\n }),\n ]\n : []),\n ...(priorityFees > 0\n ? [\n getSetComputeUnitPriceInstruction({\n microLamports: priorityFees,\n }),\n ]\n : []),\n ],\n tx,\n );\n },\n async (tx) =>\n await withRetry(async () => signTransactionMessageWithSigners(await tx)),\n );\n await withRetry(() =>\n getSolanaRpc()\n .sendTransaction(getBase64EncodedWireTransaction(tx), {\n skipPreflight: true,\n encoding: \"base64\",\n })\n .send(),\n );\n\n return getSignatureFromTransaction(tx);\n}\n\nexport async function signAndSendBundledTransactions(\n provider: RevibaseProvider,\n bundle: TransactionDetails[],\n): Promise<string> {\n const encodedBundle = await createEncodedBundle(bundle);\n await withRetry(() =>\n provider.onSendJitoBundleCallback(\n encodedBundle.map(getBase64EncodedWireTransaction),\n ),\n );\n return getSignatureFromTransaction(encodedBundle[encodedBundle.length - 1]);\n}\n\nasync function createEncodedBundle(bundle: TransactionDetails[]) {\n const latestBlockHash = (\n await withRetry(() => getSolanaRpc().getLatestBlockhash().send())\n ).value;\n return await Promise.all(\n bundle.map(async (x) => {\n const tx = await pipe(\n createTransactionMessage({ version: 0 }),\n (tx) => appendTransactionMessageInstructions(x.instructions, tx),\n (tx) => setTransactionMessageFeePayerSigner(x.payer, tx),\n (tx) =>\n setTransactionMessageLifetimeUsingBlockhash(latestBlockHash, tx),\n (tx) =>\n x.addressesByLookupTableAddress\n ? compressTransactionMessageUsingAddressLookupTables(\n tx,\n x.addressesByLookupTableAddress,\n )\n : tx,\n (tx) => {\n const computeUnits = Math.ceil(Number(x.unitsConsumed ?? 0) * 1.1);\n return computeUnits > 200_000\n ? prependTransactionMessageInstructions(\n [\n getSetComputeUnitLimitInstruction({\n units: computeUnits,\n }),\n ],\n tx,\n )\n : tx;\n },\n async (tx) =>\n await withRetry(() => signTransactionMessageWithSigners(tx)),\n );\n return tx;\n }),\n );\n}\n\nexport async function getMedianPriorityFees(\n connection: Rpc<SolanaRpcApi>,\n accounts: AccountMeta[],\n): Promise<number> {\n const recentFees = await withRetry(() =>\n connection\n .getRecentPrioritizationFees(\n accounts\n .filter(\n (x) =>\n x.role === AccountRole.WRITABLE ||\n x.role === AccountRole.WRITABLE_SIGNER,\n )\n .map((x) => x.address),\n )\n .send(),\n );\n const fees = recentFees.map((f) => Number(f.prioritizationFee));\n fees.sort((a, b) => a - b);\n const mid = Math.floor(fees.length / 2);\n\n if (fees.length % 2 === 0) {\n return Math.round((fees[mid - 1] + fees[mid]) / 2);\n } else {\n return fees[mid];\n }\n}\n","import {\n createTransactionManagerSigner,\n fetchUser,\n getSolanaRpc,\n getUserAddress,\n type TransactionAuthDetails,\n} from \"@revibase/core\";\nimport {\n address,\n fetchAddressesForLookupTables,\n getBase58Encoder,\n getBase64Decoder,\n getTransactionEncoder,\n type Address,\n type AddressesByLookupTableAddress,\n type ReadonlyUint8Array,\n type SignatureBytes,\n type TransactionSigner,\n} from \"@solana/kit\";\nimport { fetchMaybeAddressLookupTable } from \"@solana-program/address-lookup-table\";\nimport {\n REVIBASE_API_ENDPOINT,\n REVIBASE_LOOKUP_TABLE_ADDRESS,\n} from \"../consts\";\nimport { withRetry } from \"../retry\";\n\nconst payerCache = new Map<string, TransactionSigner>();\n\nexport async function getRandomPayer(): Promise<TransactionSigner> {\n const cached = payerCache.get(REVIBASE_API_ENDPOINT);\n if (cached) return cached;\n\n const response = await withRetry(() =>\n fetch(`${REVIBASE_API_ENDPOINT}/getRandomPayer`),\n );\n\n if (!response.ok) {\n throw new Error(`Failed to get random payer: ${response.statusText}`);\n }\n\n const { randomPayer } = (await response.json()) as { randomPayer: string };\n const payer = createTransactionSigner(\n address(randomPayer),\n `${REVIBASE_API_ENDPOINT}/sign`,\n );\n payerCache.set(REVIBASE_API_ENDPOINT, payer);\n return payer;\n}\n\nfunction createTransactionSigner(\n publicKey: Address,\n url: string,\n): TransactionSigner {\n const payer: TransactionSigner = {\n address: publicKey,\n async signTransactions(transactions) {\n const payload = {\n publicKey: publicKey,\n transactions: transactions.map((tx) =>\n getBase64Decoder().decode(getTransactionEncoder().encode(tx)),\n ),\n };\n\n const signResponse = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n if (!signResponse.ok) {\n throw new Error(\n `Failed to sign transactions: ${signResponse.statusText}`,\n );\n }\n\n const data = (await signResponse.json()) as\n | { signatures: string[] }\n | { error: string };\n\n if (\"error\" in data) {\n throw new Error(data.error);\n }\n\n return data.signatures.map((sig) => ({\n [publicKey]: getBase58Encoder().encode(sig) as SignatureBytes,\n }));\n },\n };\n\n return payer;\n}\n\nexport async function getTransactionManagerSigner(args: {\n transactionManagerAddress: Address | undefined;\n authResponses?: TransactionAuthDetails[];\n transactionMessageBytes?: ReadonlyUint8Array;\n onPendingApprovalsCallback?: (validTill: number) => void;\n onPendingApprovalsSuccess?: () => void;\n abortController?: AbortController;\n abortSignal?: AbortSignal;\n}) {\n const {\n transactionManagerAddress,\n transactionMessageBytes,\n authResponses,\n onPendingApprovalsCallback,\n onPendingApprovalsSuccess,\n abortController: abortControllerArg,\n abortSignal,\n } = args;\n\n let abortController = abortControllerArg;\n if (abortSignal && !abortController) {\n const ac = new AbortController();\n if (abortSignal.aborted) {\n ac.abort();\n } else {\n abortSignal.addEventListener(\"abort\", () => ac.abort(), { once: true });\n }\n abortController = ac;\n }\n let url;\n if (transactionManagerAddress) {\n const txManagerUrl = (\n await withRetry(async () =>\n fetchUser(\n getSolanaRpc(),\n await getUserAddress(transactionManagerAddress),\n ),\n )\n ).data.transactionManagerUrl;\n url = txManagerUrl.__option === \"Some\" ? txManagerUrl.value : null;\n }\n\n const transactionManagerSigner =\n transactionManagerAddress && url\n ? createTransactionManagerSigner({\n address: transactionManagerAddress,\n url,\n authResponses,\n transactionMessageBytes,\n onPendingApprovalsCallback,\n onPendingApprovalsSuccess,\n abortController,\n })\n : null;\n\n return transactionManagerSigner;\n}\n\nexport async function fetchAdditionalLoopUpTableIfNecessary(\n addressesByLookupTableAddress?: AddressesByLookupTableAddress,\n) {\n if (!addressesByLookupTableAddress) {\n return await withRetry(() =>\n fetchAddressesForLookupTables(\n [address(REVIBASE_LOOKUP_TABLE_ADDRESS)],\n getSolanaRpc(),\n ),\n );\n }\n\n if (REVIBASE_LOOKUP_TABLE_ADDRESS in addressesByLookupTableAddress) {\n return addressesByLookupTableAddress;\n }\n\n const fetched = await withRetry(() =>\n fetchMaybeAddressLookupTable(\n getSolanaRpc(),\n address(REVIBASE_LOOKUP_TABLE_ADDRESS),\n ),\n );\n\n if (fetched.exists) {\n return {\n ...addressesByLookupTableAddress,\n [fetched.address]: fetched.data.addresses,\n };\n }\n\n return addressesByLookupTableAddress;\n}\n","import {\n getSignedSecp256r1Key,\n prepareTransactionBundle,\n SignedSecp256r1Key,\n type TransactionAuthenticationResponse,\n} from \"@revibase/core\";\nimport {\n address,\n getBase64Encoder,\n type Address,\n type TransactionSigner,\n} from \"@solana/kit\";\nimport type { RevibaseProvider } from \"../../provider\";\nimport { withRetry } from \"../retry\";\nimport type { TransactionAuthorizationFlowOptions } from \"../types\";\nimport { signAndSendBundledTransactions } from \"./solana-send\";\nimport {\n fetchAdditionalLoopUpTableIfNecessary,\n getTransactionManagerSigner,\n} from \"./utils\";\n\nexport async function processBundledTransaction(\n provider: RevibaseProvider,\n params: {\n authResponse: TransactionAuthenticationResponse;\n settings: Address;\n payer: TransactionSigner;\n additionalVoters?: (TransactionSigner | SignedSecp256r1Key)[];\n additionalSigners?: TransactionSigner[];\n options?: TransactionAuthorizationFlowOptions;\n },\n): Promise<string> {\n const {\n authResponse,\n settings,\n additionalSigners,\n additionalVoters,\n options,\n payer,\n } = params;\n const { startRequest, transactionManagerAddress, unitsConsumed } =\n authResponse;\n if (startRequest.data.type !== \"transaction\")\n throw new Error(\"Invalid request type.\");\n\n const { transactionActionType, transactionMessageBytes } =\n startRequest.data.payload;\n\n if (\n transactionActionType !== \"execute\" &&\n transactionActionType !== \"create_with_preauthorized_execution\"\n ) {\n throw new Error(\n \"Transaction action type must be 'execute' or 'create_with_preauthorized_execution'\",\n );\n }\n\n const signedSigner = await getSignedSecp256r1Key(authResponse);\n\n const [transactionManagerSigner, jitoBundlesTipAmount] = await Promise.all([\n getTransactionManagerSigner({\n authResponses: [authResponse],\n transactionManagerAddress: transactionManagerAddress\n ? address(transactionManagerAddress)\n : undefined,\n transactionMessageBytes: getBase64Encoder().encode(\n transactionMessageBytes,\n ),\n onPendingApprovalsCallback:\n options?.pendingApprovalsCallback?.onPendingApprovalsCallback,\n onPendingApprovalsSuccess:\n options?.pendingApprovalsCallback?.onPendingApprovalsSuccess,\n abortSignal: options?.signal,\n }),\n withRetry(() => provider.onEstimateJitoTipsCallback()),\n ]);\n\n const bundle = await prepareTransactionBundle({\n settings,\n transactionMessageBytes: getBase64Encoder().encode(\n transactionMessageBytes,\n ) as Uint8Array<ArrayBuffer>,\n creator: transactionManagerSigner ?? signedSigner,\n executor: transactionManagerSigner ? signedSigner : undefined,\n jitoBundlesTipAmount,\n additionalVoters,\n additionalSigners,\n payer,\n });\n\n const bundlesWithLookupTables = await Promise.all(\n bundle.map(async (x, index) => ({\n ...x,\n addressesByLookupTableAddress:\n await fetchAdditionalLoopUpTableIfNecessary(\n x.addressesByLookupTableAddress,\n ),\n unitsConsumed: unitsConsumed?.[index],\n })),\n );\n\n return signAndSendBundledTransactions(provider, bundlesWithLookupTables);\n}\n","import {\n getSignedSecp256r1Key,\n prepareTransactionSync,\n SignedSecp256r1Key,\n type TransactionAuthenticationResponse,\n} from \"@revibase/core\";\nimport {\n address,\n getBase64Encoder,\n type Address,\n type TransactionSigner,\n} from \"@solana/kit\";\nimport type { TransactionAuthorizationFlowOptions } from \"../types\";\nimport { signAndSendTransaction } from \"./solana-send\";\nimport {\n fetchAdditionalLoopUpTableIfNecessary,\n getTransactionManagerSigner,\n} from \"./utils\";\n\nexport async function processSyncTransaction(params: {\n authResponse: TransactionAuthenticationResponse;\n settings: Address;\n payer: TransactionSigner;\n additionalVoters?: (TransactionSigner | SignedSecp256r1Key)[];\n additionalSigners?: TransactionSigner[];\n options?: TransactionAuthorizationFlowOptions;\n}): Promise<string> {\n const {\n authResponse,\n settings,\n payer,\n additionalSigners,\n additionalVoters,\n options,\n } = params;\n const { startRequest, transactionManagerAddress, unitsConsumed } =\n authResponse;\n if (startRequest.data.type !== \"transaction\")\n throw new Error(\"Invalid request type.\");\n\n const { transactionActionType, transactionMessageBytes } =\n startRequest.data.payload;\n\n if (transactionActionType !== \"sync\") {\n throw new Error(\"Transaction action type must be 'sync'\");\n }\n\n const signedSigner = await getSignedSecp256r1Key(authResponse);\n\n const transactionManagerSigner = await getTransactionManagerSigner({\n authResponses: [authResponse],\n transactionManagerAddress: transactionManagerAddress\n ? address(transactionManagerAddress)\n : undefined,\n transactionMessageBytes: getBase64Encoder().encode(transactionMessageBytes),\n onPendingApprovalsCallback:\n options?.pendingApprovalsCallback?.onPendingApprovalsCallback,\n onPendingApprovalsSuccess:\n options?.pendingApprovalsCallback?.onPendingApprovalsSuccess,\n abortSignal: options?.signal,\n });\n\n const signers = transactionManagerSigner\n ? [signedSigner, transactionManagerSigner, ...(additionalVoters ?? [])]\n : [signedSigner, ...(additionalVoters ?? [])];\n\n const { instructions, addressesByLookupTableAddress } =\n await prepareTransactionSync({\n signers,\n payer,\n transactionMessageBytes: getBase64Encoder().encode(\n transactionMessageBytes,\n ),\n settings,\n additionalSigners,\n });\n\n return signAndSendTransaction({\n instructions,\n payer,\n addressesByLookupTableAddress: await fetchAdditionalLoopUpTableIfNecessary(\n addressesByLookupTableAddress,\n ),\n unitsConsumed: unitsConsumed?.[0],\n });\n}\n","import {\n getSignedSecp256r1Key,\n nativeTransferIntent,\n SignedSecp256r1Key,\n tokenTransferIntent,\n type TransactionAuthenticationResponse,\n} from \"@revibase/core\";\nimport { SYSTEM_PROGRAM_ADDRESS } from \"@solana-program/system\";\nimport {\n address,\n getAddressDecoder,\n getBase64Encoder,\n getU64Decoder,\n type Address,\n type TransactionSigner,\n} from \"@solana/kit\";\nimport type { TransactionAuthorizationFlowOptions } from \"../types\";\nimport { signAndSendTransaction } from \"./solana-send\";\nimport {\n fetchAdditionalLoopUpTableIfNecessary,\n getTransactionManagerSigner,\n} from \"./utils\";\n\nexport async function processTokenTransfer(params: {\n authResponse: TransactionAuthenticationResponse;\n settings: Address;\n additionalVoters?: (TransactionSigner | SignedSecp256r1Key)[];\n payer: TransactionSigner;\n options?: TransactionAuthorizationFlowOptions;\n}): Promise<string> {\n const { authResponse, settings, options, payer, additionalVoters } = params;\n const { startRequest, transactionManagerAddress, unitsConsumed } =\n authResponse;\n if (startRequest.data.type !== \"transaction\")\n throw new Error(\"Invalid request type.\");\n\n const { transactionActionType, transactionAddress, transactionMessageBytes } =\n startRequest.data.payload;\n\n if (transactionActionType !== \"transfer_intent\") {\n throw new Error(\"Transaction action type must be 'transfer_intent'\");\n }\n\n const message = getBase64Encoder().encode(transactionMessageBytes);\n const amount = getU64Decoder().decode(message.slice(0, 8));\n const destination = getAddressDecoder().decode(message.slice(8, 40));\n const mint = getAddressDecoder().decode(message.slice(40, 72));\n\n const signedSigner = await getSignedSecp256r1Key(authResponse);\n\n const transactionManagerSigner = await getTransactionManagerSigner({\n authResponses: [authResponse],\n transactionManagerAddress: transactionManagerAddress\n ? address(transactionManagerAddress)\n : undefined,\n transactionMessageBytes: getBase64Encoder().encode(transactionMessageBytes),\n onPendingApprovalsCallback:\n options?.pendingApprovalsCallback?.onPendingApprovalsCallback,\n onPendingApprovalsSuccess:\n options?.pendingApprovalsCallback?.onPendingApprovalsSuccess,\n abortSignal: options?.signal,\n });\n\n const signers = transactionManagerSigner\n ? [signedSigner, transactionManagerSigner, ...(additionalVoters ?? [])]\n : [signedSigner, ...(additionalVoters ?? [])];\n\n const instructions =\n mint !== SYSTEM_PROGRAM_ADDRESS\n ? await tokenTransferIntent({\n payer,\n settings,\n amount,\n signers,\n destination,\n mint,\n tokenProgram: address(transactionAddress),\n })\n : await nativeTransferIntent({\n settings,\n amount,\n signers,\n destination,\n });\n\n return signAndSendTransaction({\n instructions,\n payer,\n addressesByLookupTableAddress:\n await fetchAdditionalLoopUpTableIfNecessary(undefined),\n unitsConsumed: unitsConsumed?.[0],\n });\n}\n","import { getSolanaRpc } from \"@revibase/core\";\nimport type { Signature } from \"@solana/kit\";\nimport { withRetry } from \"../retry\";\n\nexport async function pollTransactionConfirmation(\n txSig: string,\n maxRetries = 30,\n delayMs = 2000,\n): Promise<string> {\n for (let i = 0; i < maxRetries; i++) {\n const status = await withRetry(() =>\n getSolanaRpc()\n .getSignatureStatuses([txSig as Signature])\n .send(),\n );\n\n const confirmation = status.value[0];\n\n if (\n confirmation?.confirmationStatus === \"confirmed\" ||\n confirmation?.confirmationStatus === \"finalized\"\n ) {\n return txSig;\n }\n\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n\n throw new Error(\"Transaction confirmation timeout\");\n}\n","import type { SignedSecp256r1Key } from \"@revibase/core\";\nimport {\n getSettingsFromIndex,\n type CompleteTransactionRequest,\n} from \"@revibase/core\";\nimport { address, type TransactionSigner } from \"@solana/kit\";\nimport type { RevibaseProvider } from \"../../provider\";\nimport type { TransactionAuthorizationFlowOptions } from \"../../utils\";\nimport { processBundledTransaction } from \"../../utils/transactions/processBundledTransaction\";\nimport { processSyncTransaction } from \"../../utils/transactions/processSyncTransaction\";\nimport { processTokenTransfer } from \"../../utils/transactions/processTokenTransfer\";\nimport { pollTransactionConfirmation } from \"./pollTransactionConfirmation\";\n\nexport async function sendTransaction(\n provider: RevibaseProvider,\n params: {\n request: CompleteTransactionRequest;\n additionalVoters?: (TransactionSigner | SignedSecp256r1Key)[];\n additionalSigners?: TransactionSigner[];\n options?: TransactionAuthorizationFlowOptions;\n payer: TransactionSigner;\n },\n): Promise<string> {\n const { request, additionalSigners, options, payer, additionalVoters } =\n params;\n const { confirmTransaction = true } = options ?? {};\n\n const settings =\n request.data.type === \"transaction\" &&\n request.data.payload.startRequest.data.payload.transactionActionType !==\n \"transfer_intent\"\n ? request.data.payload.startRequest.data.payload.transactionAddress\n : request.data.payload.user.settingsIndexWithAddress?.index\n ? await getSettingsFromIndex(\n request.data.payload.user.settingsIndexWithAddress.index,\n )\n : null;\n\n if (!settings) {\n throw Error(\"User is not delegated to any wallet\");\n }\n let txSig: string;\n switch (\n request.data.payload.startRequest.data.payload.transactionActionType\n ) {\n case \"transfer_intent\":\n txSig = await processTokenTransfer({\n authResponse: request.data.payload,\n settings: address(settings),\n options,\n payer,\n additionalVoters,\n });\n break;\n case \"execute\":\n case \"create_with_preauthorized_execution\":\n txSig = await processBundledTransaction(provider, {\n authResponse: request.data.payload,\n settings: address(settings),\n additionalSigners,\n additionalVoters,\n options,\n payer,\n });\n break;\n case \"sync\":\n txSig = await processSyncTransaction({\n authResponse: request.data.payload,\n settings: address(settings),\n additionalSigners,\n additionalVoters,\n options,\n payer,\n });\n break;\n default:\n throw Error(\"Invalid Transaction Action Type for send tx payload.\");\n }\n\n if (confirmTransaction) {\n await pollTransactionConfirmation(txSig);\n }\n\n return txSig;\n}\n","import {\n convertMemberKeyToString,\n fetchSettings,\n getSettingsFromIndex,\n getSolanaRpc,\n KeyType,\n prepareTransactionMessage,\n SignedSecp256r1Key,\n UserRole,\n type CompleteTransactionRequest,\n type TransactionPayloadWithBase64MessageBytes,\n type UserInfo,\n} from \"@revibase/core\";\nimport {\n address,\n getBase64Decoder,\n type AddressesByLookupTableAddress,\n type Instruction,\n type TransactionSigner,\n} from \"@solana/kit\";\nimport type { RevibaseProvider } from \"../provider/main\";\nimport { withRetry } from \"../utils/retry\";\nimport { sendTransaction } from \"../utils/transactions\";\nimport { getRandomPayer } from \"../utils/transactions/utils\";\nimport type { TransactionAuthorizationFlowOptions } from \"../utils/types\";\n\n/** Custom transaction. Action from wallet settings (TransactionManager). Provider needs rpcEndpoint. Options: signal?, channelId?. */\nexport async function executeTransaction(\n provider: RevibaseProvider,\n args: {\n instructions: Instruction[];\n signer: UserInfo;\n payer?: TransactionSigner;\n settingsIndexWithAddress?: {\n index: number | bigint;\n };\n additionalSigners?: TransactionSigner[];\n additionalVoters?: (TransactionSigner | SignedSecp256r1Key)[];\n addressesByLookupTableAddress?: AddressesByLookupTableAddress;\n },\n options?: TransactionAuthorizationFlowOptions,\n): Promise<{ txSig?: string; user: UserInfo }> {\n const {\n instructions,\n signer,\n addressesByLookupTableAddress,\n settingsIndexWithAddress,\n additionalSigners,\n additionalVoters,\n payer,\n } = args;\n\n const onConnectedCallback = async (rid: string, clientOrigin: string) => {\n const transactionMessageBytes = prepareTransactionMessage({\n payer: address(signer.walletAddress),\n instructions,\n addressesByLookupTableAddress,\n });\n const settingsArgs =\n settingsIndexWithAddress ?? signer.settingsIndexWithAddress;\n const settings = await getSettingsFromIndex(settingsArgs.index);\n const settingsData = (\n await withRetry(() => fetchSettings(getSolanaRpc(), settings))\n ).data;\n const transactionManagerAddress = settingsData.members.find(\n (x) => x.role === UserRole.TransactionManager,\n )?.pubkey;\n const transactionPayload: TransactionPayloadWithBase64MessageBytes = {\n transactionMessageBytes: getBase64Decoder().decode(\n transactionMessageBytes,\n ),\n transactionAddress: settings,\n transactionActionType: transactionManagerAddress\n ? \"execute\"\n : \"create_with_preauthorized_execution\",\n };\n\n const payload = {\n phase: \"start\" as const,\n rid,\n providerOrigin: provider.providerOrigin,\n rpId: provider.rpId,\n data: {\n type: \"transaction\" as const,\n payload: transactionPayload,\n },\n clientOrigin,\n signer: signer.publicKey,\n };\n const { signature, validTill } = await withRetry(() =>\n provider.onClientAuthorizationCallback(payload),\n );\n return {\n request: { ...payload, rid, validTill },\n signature,\n transactionManagerAddress: transactionManagerAddress\n ? convertMemberKeyToString(transactionManagerAddress)\n : undefined,\n additionalSigners: additionalSigners?.map((x) => x.address.toString()),\n additionalVoters: additionalVoters?.map((x) =>\n x instanceof SignedSecp256r1Key\n ? { keyType: KeyType.Secp256r1, publicKey: x.toString() }\n : { keyType: KeyType.Ed25519, publicKey: x.address.toString() },\n ),\n payer: (payer ?? (await getRandomPayer())).address.toString(),\n };\n };\n\n const onSuccessCallback = async (\n result: CompleteTransactionRequest,\n ): Promise<{ txSig: string; user: UserInfo }> => {\n const { signature } = await provider.onClientAuthorizationCallback(result);\n\n const txSig = await sendTransaction(provider, {\n request: {\n ...result,\n data: {\n ...result.data,\n payload: {\n ...result.data.payload,\n client: { ...result.data.payload.client, jws: signature },\n },\n },\n },\n options,\n additionalSigners,\n additionalVoters,\n payer: payer ?? (await getRandomPayer()),\n });\n\n return { user: result.data.payload.user, txSig };\n };\n\n return provider.sendRequestToPopupProvider({\n onConnectedCallback,\n onSuccessCallback,\n signal: options?.signal,\n });\n}\n","import {\n KeyType,\n SignedSecp256r1Key,\n type CompleteTransactionRequest,\n type TransactionPayloadWithBase64MessageBytes,\n type UserInfo,\n} from \"@revibase/core\";\nimport { SYSTEM_PROGRAM_ADDRESS } from \"@solana-program/system\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport {\n address,\n getAddressEncoder,\n getBase64Decoder,\n getU64Encoder,\n type TransactionSigner,\n} from \"@solana/kit\";\nimport type { RevibaseProvider } from \"../provider/main\";\nimport { withRetry } from \"../utils/retry\";\nimport { sendTransaction } from \"../utils/transactions/sendTransaction\";\nimport { getRandomPayer } from \"../utils/transactions/utils\";\nimport type { TransactionAuthorizationFlowOptions } from \"../utils/types\";\n\n/** Transfers SOL or SPL (set mint for SPL). amount > 0, destination required */\nexport async function transferTokens(\n provider: RevibaseProvider,\n args: {\n amount: number | bigint;\n destination: string;\n signer?: UserInfo;\n mint?: string;\n tokenProgram?: string;\n payer?: TransactionSigner;\n additionalVoters?: (TransactionSigner | SignedSecp256r1Key)[];\n },\n options?: TransactionAuthorizationFlowOptions,\n): Promise<{ txSig?: string; user: UserInfo }> {\n if (args.amount <= 0) {\n throw new Error(\"Transfer amount must be greater than 0\");\n }\n\n if (!args.destination || typeof args.destination !== \"string\") {\n throw new Error(\"Destination address is required\");\n }\n\n const {\n mint,\n tokenProgram = TOKEN_PROGRAM_ADDRESS,\n amount,\n destination,\n signer,\n payer,\n additionalVoters,\n } = args;\n\n const onConnectedCallback = async (rid: string, clientOrigin: string) => {\n const transactionPayload: TransactionPayloadWithBase64MessageBytes = {\n transactionActionType: \"transfer_intent\",\n transactionAddress: mint ? tokenProgram : SYSTEM_PROGRAM_ADDRESS,\n transactionMessageBytes: getBase64Decoder().decode(\n new Uint8Array([\n ...getU64Encoder().encode(amount),\n ...getAddressEncoder().encode(address(destination)),\n ...getAddressEncoder().encode(\n address(mint ?? SYSTEM_PROGRAM_ADDRESS),\n ),\n ]),\n ),\n };\n\n const payload = {\n phase: \"start\" as const,\n rid,\n providerOrigin: provider.providerOrigin,\n rpId: provider.rpId,\n data: {\n type: \"transaction\" as const,\n payload: transactionPayload,\n },\n clientOrigin,\n signer: signer?.publicKey,\n };\n const { signature, validTill } = await withRetry(() =>\n provider.onClientAuthorizationCallback(payload),\n );\n return {\n request: { ...payload, rid, validTill },\n signature,\n additionalVoters: additionalVoters?.map((x) =>\n x instanceof SignedSecp256r1Key\n ? { keyType: KeyType.Secp256r1, publicKey: x.toString() }\n : { keyType: KeyType.Ed25519, publicKey: x.address.toString() },\n ),\n payer: (payer ?? (await getRandomPayer())).address.toString(),\n };\n };\n\n const onSuccessCallback = async (\n result: CompleteTransactionRequest,\n ): Promise<{ txSig: string; user: UserInfo }> => {\n const { signature } = await provider.onClientAuthorizationCallback(result);\n const txSig = await sendTransaction(provider, {\n request: {\n ...result,\n data: {\n ...result.data,\n payload: {\n ...result.data.payload,\n client: { ...result.data.payload.client, jws: signature },\n },\n },\n },\n options,\n additionalVoters,\n payer: payer ?? (await getRandomPayer()),\n });\n\n return { txSig, user: result.data.payload.user };\n };\n\n return provider.sendRequestToPopupProvider({\n onConnectedCallback,\n onSuccessCallback,\n signal: options?.signal,\n });\n}\n","import {\n convertBase64StringToJWK,\n createClientAuthorizationStartRequestChallenge,\n type StartMessageRequest,\n type StartTransactionRequest,\n} from \"@revibase/core\";\nimport { CompactSign } from \"jose\";\nimport { DEFAULT_TIMEOUT } from \"../provider/utils\";\n\nexport async function startRequest(\n request:\n | Omit<StartMessageRequest, \"validTill\">\n | Omit<StartTransactionRequest, \"validTill\">,\n allowedClientOrigins: string[],\n privateKey: string,\n) {\n if (!allowedClientOrigins.includes(request.clientOrigin)) {\n throw new Error(\"Invalid client origin\");\n }\n const validTill = Date.now() + DEFAULT_TIMEOUT;\n const pKey = convertBase64StringToJWK(privateKey);\n if (!pKey.alg) throw new Error(\"Property alg in JWK is missing.\");\n const signature = await new CompactSign(\n createClientAuthorizationStartRequestChallenge({\n ...request,\n validTill,\n }),\n )\n .setProtectedHeader({\n alg: pKey.alg,\n })\n .sign(pKey);\n return { ok: true, signature, validTill };\n}\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type CHash = {\n (message: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array) => Uint8Array;\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// Used in weierstrass, der\nfunction abignumber(n: number | bigint) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new Error('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\nexport function asafenumber(value: number, title: string = ''): void {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len) throw new Error('number too large');\n return res;\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, message: Uint8Array) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n const u8n = (len: number): Uint8Array => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...msgs: Uint8Array[]) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed: Uint8Array = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\nexport function validateObject(\n object: Record<string, any>,\n fields: Record<string, string> = {},\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n\nexport interface CryptoKeys {\n lengths: { seed?: number; public?: number; secret?: number };\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","import { equalBytes } from \"@noble/curves/utils.js\";\nimport type { CompleteMessageRequest } from \"@revibase/core\";\nimport {\n bufferToBase64URLString,\n convertBase64StringToJWK,\n convertMemberKeyToString,\n convertPubkeyCompressedToCose,\n createClientAuthorizationStartRequestChallenge,\n createMessageChallenge,\n fetchSettings,\n fetchUserAccountByFilters,\n getDeviceMessageHash,\n getDomainConfigAddress,\n getSettingsFromIndex,\n getSolanaRpc,\n UserRole,\n} from \"@revibase/core\";\nimport { verifyAuthenticationResponse } from \"@simplewebauthn/server\";\nimport {\n address,\n getBase58Encoder,\n getPublicKeyFromAddress,\n signatureBytes,\n verifySignature,\n} from \"@solana/kit\";\nimport { compactVerify, importJWK } from \"jose\";\n\n/** Verifies WebAuthn message, returns user. */\nexport async function verifyMessage(\n request: CompleteMessageRequest,\n expectedClientJwk: string,\n allowedClientOrigins: string[],\n requireTwoFactorAuthentication: boolean,\n) {\n const { payload } = request.data;\n if (payload.startRequest.data.type !== \"message\")\n throw new Error(\"Invalid request type.\");\n if (Date.now() > payload.startRequest.validTill) {\n throw new Error(\"Request expired.\");\n }\n if (\n !allowedClientOrigins.includes(payload.startRequest.clientOrigin) ||\n !allowedClientOrigins.includes(payload.client.clientOrigin) ||\n payload.startRequest.clientOrigin !== payload.client.clientOrigin\n ) {\n throw new Error(\"Invalid client origin\");\n }\n\n {\n const key = await importJWK(convertBase64StringToJWK(expectedClientJwk));\n const result = await compactVerify(request.data.payload.client.jws, key);\n if (\n !equalBytes(\n result.payload,\n createClientAuthorizationStartRequestChallenge(\n request.data.payload.startRequest,\n ),\n )\n ) {\n throw new Error(\"Invalid client signature\");\n }\n }\n\n {\n if (payload.device.jwk !== payload.device.deviceProfile.devicePublicKey) {\n throw new Error(\"Device publickey mismatch\");\n }\n const key = await importJWK(convertBase64StringToJWK(payload.device.jwk));\n const result = await compactVerify(payload.device.jws, key);\n if (\n !equalBytes(\n result.payload,\n getDeviceMessageHash(\n payload.authResponse,\n payload.device.deviceProfile,\n ),\n )\n ) {\n throw new Error(\"Invalid device signature\");\n }\n }\n\n const expectedChallenge = createMessageChallenge(\n payload.startRequest.data.payload,\n payload.startRequest.clientOrigin,\n payload.device.jwk,\n payload.startRequest.rid,\n );\n const { verified } = await verifyAuthenticationResponse({\n response: payload.authResponse,\n expectedChallenge: bufferToBase64URLString(expectedChallenge),\n expectedRPID: payload.startRequest.rpId,\n expectedOrigin: payload.startRequest.providerOrigin,\n requireUserVerification: false,\n credential: {\n counter: 0,\n id: payload.authResponse.id,\n publicKey: convertPubkeyCompressedToCose(payload.signer),\n },\n });\n\n if (!verified) {\n throw new Error(\"Invalid user siganture\");\n }\n\n if (requireTwoFactorAuthentication) {\n if (!payload.startRequest.data.requireTwoFactorAuthentication) {\n throw new Error(\"Two factor authentication is required.\");\n }\n if (!payload.transactionManager) {\n throw new Error(\"Missing signature from transaction manager.\");\n }\n\n const user = await fetchUserAccountByFilters(\n await getDomainConfigAddress({ rpId: payload.startRequest.rpId }),\n { credentialId: payload.authResponse.id },\n );\n const delegateTo = user?.wallets.find((x) => x.isDelegate);\n if (!delegateTo) {\n throw new Error(\"User does not have a delegated wallet\");\n }\n const settingsData = (\n await fetchSettings(\n getSolanaRpc(),\n await getSettingsFromIndex(delegateTo.index),\n )\n ).data;\n const transactionManager = settingsData.members.find(\n (x) => x.role === UserRole.TransactionManager,\n );\n if (!transactionManager) {\n throw new Error(\"No transaction manager found.\");\n }\n if (\n payload.transactionManager.publicKey !==\n convertMemberKeyToString(transactionManager.pubkey)\n ) {\n throw new Error(\"Transaction manager mismatch.\");\n }\n if (\n !(await verifySignature(\n await getPublicKeyFromAddress(\n address(payload.transactionManager.publicKey),\n ),\n signatureBytes(\n getBase58Encoder().encode(payload.transactionManager.signature),\n ),\n expectedChallenge,\n ))\n ) {\n throw new Error(\"Invalid transaction manager signature.\");\n }\n }\n\n return {\n ok: true,\n };\n}\n","import { equalBytes } from \"@noble/curves/utils.js\";\nimport type { CompleteTransactionRequest } from \"@revibase/core\";\nimport {\n bufferToBase64URLString,\n convertBase64StringToJWK,\n convertPubkeyCompressedToCose,\n createClientAuthorizationCompleteRequestChallenge,\n createClientAuthorizationStartRequestChallenge,\n createTransactionChallenge,\n getDeviceMessageHash,\n} from \"@revibase/core\";\nimport { verifyAuthenticationResponse } from \"@simplewebauthn/server\";\nimport { CompactSign, compactVerify, importJWK } from \"jose\";\n\n/** Verifies WebAuthn message, returns signature. */\nexport async function verifyTransaction(\n request: CompleteTransactionRequest,\n expectedClientJwk: string,\n allowedClientOrigins: string[],\n privateKey: string,\n) {\n const { payload } = request.data;\n if (payload.startRequest.data.type !== \"transaction\")\n throw new Error(\"Invalid request type.\");\n if (\n Date.now() >\n Math.min(payload.startRequest.validTill, payload.estimatedSlotHashExpiry)\n ) {\n throw new Error(\"Request expired.\");\n }\n if (\n !allowedClientOrigins.includes(payload.startRequest.clientOrigin) ||\n !allowedClientOrigins.includes(payload.client.clientOrigin) ||\n payload.startRequest.clientOrigin !== payload.client.clientOrigin\n ) {\n throw new Error(\"Invalid client origin\");\n }\n\n {\n const key = await importJWK(convertBase64StringToJWK(expectedClientJwk));\n const result = await compactVerify(request.data.payload.client.jws, key);\n if (\n !equalBytes(\n result.payload,\n createClientAuthorizationStartRequestChallenge(\n request.data.payload.startRequest,\n ),\n )\n ) {\n throw new Error(\"Invalid client signature\");\n }\n }\n\n {\n if (payload.device.jwk !== payload.device.deviceProfile.devicePublicKey) {\n throw new Error(\"Device publickey mismatch\");\n }\n const key = await importJWK(convertBase64StringToJWK(payload.device.jwk));\n const result = await compactVerify(payload.device.jws, key);\n if (\n !equalBytes(\n result.payload,\n getDeviceMessageHash(\n payload.authResponse,\n payload.device.deviceProfile,\n ),\n )\n ) {\n throw new Error(\"Invalid device signature\");\n }\n }\n {\n const { challenge: expectedChallenge } = await createTransactionChallenge(\n payload.startRequest.data.payload,\n payload.startRequest.clientOrigin,\n payload.device.jwk,\n payload.startRequest.rid,\n payload.slotHash,\n payload.slotNumber,\n payload.estimatedSlotHashExpiry,\n );\n const { verified } = await verifyAuthenticationResponse({\n response: payload.authResponse,\n expectedChallenge: bufferToBase64URLString(expectedChallenge),\n expectedRPID: payload.startRequest.rpId,\n expectedOrigin: payload.startRequest.providerOrigin,\n requireUserVerification: false,\n credential: {\n counter: 0,\n id: payload.authResponse.id,\n publicKey: convertPubkeyCompressedToCose(payload.signer),\n },\n });\n\n if (!verified) {\n throw new Error(\"Invalid user siganture\");\n }\n }\n\n const pKey = convertBase64StringToJWK(privateKey);\n if (!pKey.alg) throw new Error(\"Property alg in JWK is missing.\");\n const signature = await new CompactSign(\n createClientAuthorizationCompleteRequestChallenge(request),\n )\n .setProtectedHeader({\n alg: pKey.alg,\n })\n .sign(pKey);\n\n return { ok: true, signature };\n}\n","import {\n initialize,\n type CompleteMessageRequest,\n type CompleteTransactionRequest,\n type StartMessageRequest,\n type StartTransactionRequest,\n} from \"@revibase/core\";\nimport { startRequest } from \"./startRequest\";\nimport { verifyMessage } from \"./verifyMessage\";\nimport { verifyTransaction } from \"./verifyTransaction\";\n\nlet initialized = false;\nfunction ensureInitialize(rpcEndpoint?: string) {\n if (initialized) return;\n if (rpcEndpoint) {\n initialize({ rpcEndpoint });\n initialized = true;\n }\n}\n/** Validates start request, calls Revibase start + getResult, returns user or tx. Pass req.signal for cancel on disconnect. */\nexport async function processClientAuthCallback({\n request,\n publicKey,\n allowedClientOrigins,\n privateKey,\n requireTwoFactorAuthentication,\n}: {\n request:\n | Omit<StartMessageRequest, \"validTill\">\n | Omit<StartTransactionRequest, \"validTill\">\n | CompleteMessageRequest\n | CompleteTransactionRequest;\n allowedClientOrigins: string[];\n publicKey: string;\n privateKey: string;\n requireTwoFactorAuthentication?: {\n rpcEndpoint: string;\n };\n}) {\n ensureInitialize(requireTwoFactorAuthentication?.rpcEndpoint);\n\n if (request.phase === \"start\") {\n if (\n request.data.type === \"message\" &&\n !!requireTwoFactorAuthentication !==\n request.data.requireTwoFactorAuthentication\n ) {\n throw new Error(\"Require 2fa check mismatch\");\n }\n return await startRequest(request, allowedClientOrigins, privateKey);\n } else if (request.phase === \"complete\") {\n if (request.data.type === \"message\") {\n return await verifyMessage(\n request as CompleteMessageRequest,\n publicKey,\n allowedClientOrigins,\n !!requireTwoFactorAuthentication,\n );\n } else if (request.data.type === \"transaction\") {\n return await verifyTransaction(\n request as CompleteTransactionRequest,\n publicKey,\n allowedClientOrigins,\n privateKey,\n );\n } else {\n throw new Error(\"Invalid request type\");\n }\n } else {\n throw new Error(\"Invalid request phase\");\n }\n}\n","import { DEFAULT_JITO_TIPS_URL } from \"../utils/consts\";\n\nexport async function processEstimateJitoTipsCallback(\n priority = \"landed_tips_75th_percentile\",\n url = DEFAULT_JITO_TIPS_URL,\n) {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Jito tips: ${response.status} ${response.statusText}`,\n );\n }\n\n const result = await response.json();\n if (\n !Array.isArray(result) ||\n !result[0] ||\n typeof result[0][priority] !== \"number\"\n ) {\n throw new Error(\"Invalid Jito tips response format\");\n }\n\n const LAMPORTS_PER_SOL = 1_000_000_000;\n return Math.round(result[0][priority] * LAMPORTS_PER_SOL);\n}\n","import { DEFAULT_JITO_BLOCK_ENGINE_SEND_BUNDLE_URL } from \"../utils/consts\";\n\nexport async function processSendJitoBundleCallback(\n serializedTransactions: string[],\n jitoUUID?: string,\n url = DEFAULT_JITO_BLOCK_ENGINE_SEND_BUNDLE_URL,\n): Promise<string> {\n const maxRetries = 5;\n const baseBackoffMs = 250;\n\n const body = JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"sendBundle\",\n params: [\n serializedTransactions,\n {\n encoding: \"base64\",\n },\n ],\n });\n\n let response: Response | null = null;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(jitoUUID ? { \"x-jito-auth\": jitoUUID } : {}),\n },\n body,\n });\n\n if (response.status !== 429) break;\n if (attempt === maxRetries) break;\n\n const backoffMs = Math.min(10_000, baseBackoffMs * 2 ** attempt);\n await sleep(backoffMs);\n }\n\n if (!response) {\n throw new Error(\"Failed to send bundles: no response\");\n }\n\n const data = (await response.json()) as { result?: string; error?: unknown };\n\n if (data.error) {\n throw new Error(\n `Error sending bundles: ${JSON.stringify(data.error, null, 2)}`,\n );\n }\n\n if (!data.result) {\n throw new Error(\"No bundle ID returned from Jito\");\n }\n\n return data.result;\n}\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n"]}
|