import { Address, Commitment, MaybeEncodedAccount, Blockhash, createSolanaRpc, createSolanaRpcSubscriptions, sendAndConfirmTransactionFactory, Transaction, TransactionWithBlockhashLifetime, SignatureBytes } from '@solana/kit';
import { j as U32, e as U256LeBytes, k as U64, U as U128, l as U128LeBytes, h as U512 } from './types-C_V_CaKK.js';
import { A as AesKey, a as AesCiphertextWithMetadata, b as AesPlaintext, X as X25519PublicKey, c as X25519PrivateKey, M as MasterSeed, d as MasterViewingKey, P as PoseidonKey, Y as YearlyViewingKey, e as MonthlyViewingKey, D as DailyViewingKey, f as MintViewingKey, B as Bn254FieldElement, C as Curve25519FieldElement } from './cryptography-BFSJcvi6.js';
import { S as SignedTransaction, T as TransactionSignature, M as MasterSeedLoaderFunction, a as MasterSeedStorerFunction, b as MasterSeedGeneratorFunction, L as LoaderFunction, c as StorerFunction, G as GeneratorFunction, P as ParameterizedLoaderFunction, d as ParameterizedStorerFunction, e as ParameterizedGeneratorFunction } from './types-CxfTIpN9.js';
import { Y as Year, M as Month, D as Day, H as Hour, a as Minute, S as Second } from './types-D1jDUjfN.js';
import { N as Network, f as ProtocolVersionSpecifierFunction, a as AlgorithmVersionSpecifierFunction, g as SchemeVersionSpecifierFunction, e as NetworkSpecifierFunction } from './versions-BRlR36EA.js';
import { N as NetworkConfig } from './networks-RMd3abPE.js';

/**
 * AES Encryption Interfaces
 *
 * This module defines function type interfaces for AES-256-GCM encryption
 * and decryption operations used in UTXO recovery data encryption.
 *
 * ## Overview
 *
 * AES-256-GCM is used in Umbra to encrypt UTXO recovery data, enabling either
 * the sender (ephemeral unlocker) or the receiver (receiver unlocker) to
 * recover the information required to claim a UTXO at a later time. It is
 * distinct from the Rescue cipher used for confidential token account balances.
 *
 * ## Key Derivation
 *
 * - **Ephemeral Unlocker Key**: Derived from `KDF(masterSeed, generationIndex)`.
 *   Allows the sender to recover UTXOs they created, even without knowing the
 *   recipient's key material.
 * - **Receiver Unlocker Key**: Derived from the X25519 Diffie-Hellman shared
 *   secret between the sender's ephemeral private key and the recipient's
 *   X25519 public key. Allows the recipient to independently recover the UTXO.
 *
 * ## Ciphertext Format
 *
 * Both functions operate on the following byte layout:
 * ```
 * [IV (12 bytes) | AuthTag (16 bytes) | Ciphertext (N bytes)]
 * ```
 * This format is self-contained: all information needed for decryption (except
 * the key) is present in the byte array.
 *
 * @packageDocumentation
 * @module interfaces/cryptography/aes
 * @public
 */

/**
 * Function type for AES-256-GCM encryption.
 *
 * Encrypts plaintext data using AES-256-GCM with the provided key.
 * The function generates a random IV internally and returns a combined
 * ciphertext format: `[IV (12) | AuthTag (16) | Ciphertext (N)]`.
 *
 * @param key - The AES-256 encryption key. Must be exactly 32 bytes.
 *   Keys should be derived using a secure KDF (e.g. HKDF, Rescue-Prime).
 * @param plaintext - The data to encrypt. May be any length including zero bytes.
 *   For UTXO recovery the plaintext is 68 bytes: amount (8) + modified
 *   generation index (16) + destination address (32) + domain separator (12).
 * @returns A promise that resolves to the combined ciphertext byte array with
 *   layout `[IV (12) | AuthTag (16) | EncryptedData (N)]`.
 *
 * @remarks
 * ## Implementation Contract
 *
 * Implementations of this type **must** guarantee:
 * 1. A **fresh cryptographically random 12-byte IV** is generated for each call.
 *    Reusing an IV with the same key is catastrophic for GCM security.
 * 2. The authentication tag is **128 bits** (16 bytes) as recommended by NIST SP 800-38D.
 * 3. The output is returned in the canonical format `[IV | AuthTag | Ciphertext]`
 *    (note: NOT the @noble/ciphers internal order of `[Ciphertext | AuthTag]`).
 * 4. The function is **referentially transparent** given the same key and plaintext
 *    except for the random IV (which makes each ciphertext unique).
 *
 * ## Security Considerations
 *
 * - **Never reuse** an IV with the same key. With a 12-byte IV and a CSPRNG, the
 *   probability of accidental collision over 2^32 invocations is approximately 2^-32,
 *   which is acceptable for practical use.
 * - The 128-bit authentication tag provides strong integrity and authenticity.
 * - AES-GCM is an AEAD scheme: an attacker who modifies any byte of the ciphertext
 *   will cause decryption to throw (tag verification failure), protecting against
 *   tampering.
 * - The ciphertext is computationally indistinguishable from random bytes.
 *
 * @public
 *
 * @example
 * ```typescript
 * const encryptor: AesEncryptorFunction = getAesEncryptor();
 *
 * // Derive key from seed + generation index
 * const key = deriveEphemeralUnlockerKey(masterSeed, generationIndex);
 *
 * // Build the UTXO recovery plaintext
 * const plaintext = buildRecoveryPlaintext(amount, genIndex, destination);
 *
 * const ciphertext = await encryptor(key, plaintext);
 * // layout: [IV (12) | AuthTag (16) | EncryptedData (68)] = 96 bytes total
 * ```
 *
 * @see {@link AesDecryptorFunction} — the paired decryption function type
 * @see {@link getAesEncryptor} — factory that returns the default implementation
 * @see {@link defaultAesEncryptor} — pre-instantiated convenience singleton
 */
type AesEncryptorFunction = (key: AesKey, plaintext: AesPlaintext) => Promise<AesCiphertextWithMetadata>;
/**
 * Function type for AES-256-GCM decryption.
 *
 * Decrypts ciphertext data using AES-256-GCM with the provided key.
 * The function expects the combined ciphertext format and extracts the
 * IV and authentication tag from the input before decryption.
 *
 * @param key - The AES-256 decryption key. Must be exactly 32 bytes.
 *   Must be the same key that was used during encryption.
 * @param ciphertext - The combined ciphertext byte array in the format
 *   `[IV (12) | AuthTag (16) | EncryptedData (N)]`. Minimum 28 bytes.
 * @returns A promise that resolves to the decrypted plaintext as an
 *   {@link AesPlaintext} byte array.
 *
 * @throws {Error} If the 128-bit authentication tag fails verification. This
 *   occurs when the wrong key is provided or when any byte of the ciphertext
 *   has been modified. The error message is intentionally generic to avoid
 *   leaking information about which byte caused the failure.
 * @throws {Error} If `key` is not a valid 32-byte {@link AesKey}.
 * @throws {Error} If `ciphertext` is not a valid {@link AesCiphertextWithMetadata}
 *   (less than 28 bytes = IV + AuthTag minimum).
 *
 * @remarks
 * ## Implementation Contract
 *
 * Implementations of this type **must** guarantee:
 * 1. **IV extraction**: bytes 0–11 of `ciphertext` are used as the GCM IV.
 * 2. **AuthTag extraction**: bytes 12–27 are used as the 128-bit authentication tag.
 * 3. **Ciphertext body**: bytes 28+ are the encrypted data.
 * 4. **Authentication before decryption**: The authentication tag is verified in
 *    constant time **before** any plaintext is returned. Partial plaintext
 *    must not be exposed on authentication failure.
 * 5. On success, the returned plaintext is a fresh {@link AesPlaintext} byte array.
 *
 * ## Security Considerations
 *
 * - Authentication failure indicates either the wrong key or tampered bytes.
 *   The caller **must not** use any partially decrypted output on failure.
 * - Catch authentication errors and treat them as hard failures; do not retry
 *   with a modified ciphertext (this would constitute an oracle attack surface).
 * - Clear sensitive decrypted plaintext from memory as soon as it is processed.
 *
 * @public
 *
 * @example
 * ```typescript
 * const decryptor: AesDecryptorFunction = getAesDecryptor();
 *
 * const key = deriveEphemeralUnlockerKey(masterSeed, generationIndex);
 *
 * try {
 *   const plaintext = await decryptor(key, ciphertext);
 *   const { amount, genIndex, destination } = parseRecoveryPlaintext(plaintext);
 * } catch (error) {
 *   // Authentication failed — wrong key or corrupted data.
 *   // Do NOT attempt to parse or use any output from this call.
 *   console.error("Decryption failed:", error);
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Attempting decryption with a different key throws:
 * const wrongKey = deriveEphemeralUnlockerKey(wrongSeed, generationIndex);
 * await decryptor(wrongKey, ciphertext); // throws — authentication tag mismatch
 * ```
 *
 * @see {@link AesEncryptorFunction} — the paired encryption function type
 * @see {@link getAesDecryptor} — factory that returns the default implementation
 * @see {@link defaultAesDecryptor} — pre-instantiated convenience singleton
 */
type AesDecryptorFunction = (key: AesKey, ciphertext: AesCiphertextWithMetadata) => Promise<AesPlaintext>;

/**
 * Solana Provider and Forwarder Interfaces.
 *
 * This module defines the TypeScript contracts for all Solana RPC abstraction
 * layers used by the Umbra SDK. By depending on these interfaces rather than
 * concrete implementations, SDK components remain testable (mock providers can
 * be injected) and portable (different RPC backends can be substituted without
 * changing call sites).
 *
 * @remarks
 * The interfaces are organized into four groups:
 *
 * - **Account Info Provider** — {@link AccountInfoProviderFunction} for
 *   fetching raw encoded account data as a `Map`.
 *
 * - **Blockhash Provider** — {@link LatestBlockhashResult} and
 *   {@link GetLatestBlockhash} for fetching the latest blockhash and its
 *   validity window.
 *
 * - **Epoch Info Provider** — {@link EpochInfoResult} and {@link GetEpochInfo}
 *   for fetching current epoch and slot data (used for Token-2022 fee
 *   calculation).
 *
 * - **Transaction Forwarder** — {@link ForwardSequentially},
 *   {@link ForwardInParallel}, and {@link TransactionForwarder} for submitting
 *   signed transactions to the network.
 *
 * Factory types for `@solana/kit` dependencies are also exported
 * ({@link CreateSolanaRpcFunction}, {@link CreateSolanaRpcSubscriptionsFunction},
 * {@link SendAndConfirmTransactionFactoryFunction}) to allow dependency injection
 * of the underlying `@solana/kit` primitives in tests.
 *
 * @packageDocumentation
 */

/**
 * Object interface for fetching Solana account information from the network.
 *
 * Provides two methods — `fetchAccount` for single-account lookups and
 * `fetchAccounts` for batch lookups — backed by `@solana/kit`'s
 * `fetchEncodedAccount` and `fetchEncodedAccounts` helpers respectively.
 *
 * @remarks
 * Both methods return `MaybeEncodedAccount` values. Callers must check
 * `account.exists` before accessing `account.data` to handle the case where
 * an account has not been initialized on-chain.
 *
 * The returned encoded data is compatible with Codama-generated decoders. Pass
 * the `MaybeEncodedAccount` directly to a decoder such as
 * `decodeEncryptedUserAccount` to obtain a typed program account struct.
 *
 * @example
 * Injecting a mock `AccountInfoProvider` in tests:
 * ```typescript
 * import type { AccountInfoProvider } from "./interfaces";
 * import { address } from "@solana/kit";
 *
 * const mockProvider: AccountInfoProvider = {
 *   fetchAccount: async (addr) => ({
 *     exists: true,
 *     address: addr,
 *     data: new Uint8Array([1, 2, 3, 4]),
 *     executable: false,
 *     lamports: 1_000_000n,
 *     programAddress: address("11111111111111111111111111111111"),
 *   }),
 *   fetchAccounts: async (addrs) =>
 *     addrs.map((addr) => ({
 *       exists: false,
 *       address: addr,
 *     })),
 * };
 * ```
 *
 * @see {@link getRpcAccountInfoProvider} for the default RPC-backed implementation
 * @public
 */
/**
 * Function type for batch-fetching Solana account information as a `Map`.
 *
 * This is the primary account-fetching interface used throughout the Umbra SDK.
 * It accepts a readonly array of addresses and resolves to a `Map` keyed by
 * address. This functional interface supports the SDK's dependency injection
 * pattern and makes mocking trivial.
 *
 * @remarks
 * **Deduplication** — Implementations should deduplicate input addresses before
 * issuing RPC calls to avoid wasting slots in a `getMultipleAccounts` request.
 *
 * **Non-existent accounts** — The `Map` must contain an entry for every input
 * address (after deduplication), even if the account does not exist on-chain.
 * Non-existent accounts are represented by a `MaybeEncodedAccount` with
 * `exists: false`.
 *
 * **Empty input** — Passing an empty array should return an empty `Map`
 * immediately without making an RPC call.
 *
 * **Performance** — For large address arrays, implementations may need to chunk
 * requests because `getMultipleAccounts` has a per-call limit (typically 100
 * accounts on public RPC nodes). Consider rate-limit constraints as well.
 *
 * @param addresses - A `ReadonlyArray` of Solana `Address` values to fetch.
 * @param options - Optional configuration. Pass `{ commitment }` to override the
 *   default `"confirmed"` commitment level for this fetch.
 * @returns A `Promise` resolving to a `Map<Address, MaybeEncodedAccount>` where
 *   each key is an input address and each value is the corresponding account data
 *   (or a `{ exists: false }` sentinel for missing accounts).
 *
 * @example
 * Using the provider to batch-fetch accounts:
 * ```typescript
 * import type { AccountInfoProviderFunction } from "./interfaces";
 * import { address } from "@solana/kit";
 *
 * const fetchAccounts: AccountInfoProviderFunction = getRpcAccountInfoProvider({
 *   rpcUrl: "https://api.mainnet-beta.solana.com",
 * });
 *
 * const addresses = [
 *   address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),
 *   address("11111111111111111111111111111111"),
 * ];
 *
 * const accountMap = await fetchAccounts(addresses);
 *
 * for (const [addr, account] of accountMap) {
 *   if (account.exists) {
 *     console.log(`${addr}: ${account.data.length} bytes`);
 *   } else {
 *     console.log(`${addr}: does not exist`);
 *   }
 * }
 * ```
 *
 * @example
 * Mock implementation for unit testing:
 * ```typescript
 * const mockProvider: AccountInfoProviderFunction = async (addresses) => {
 *   const result = new Map<Address, MaybeEncodedAccount>();
 *   for (const addr of addresses) {
 *     result.set(addr, {
 *       exists: true,
 *       address: addr,
 *       data: new Uint8Array([0, 1, 2, 3]),
 *       executable: false,
 *       lamports: 1_000_000n,
 *       programAddress: address("11111111111111111111111111111111"),
 *     });
 *   }
 *   return result;
 * };
 * ```
 *
 * @see {@link AccountInfoProvider} for the object-oriented alternative
 * @see {@link getRpcAccountInfoProvider} for the default RPC-backed implementation
 * @public
 */
type AccountInfoProviderFunction = (addresses: readonly Address[], options?: {
    readonly commitment?: Commitment;
}) => Promise<Map<Address, MaybeEncodedAccount>>;
/**
 * The result of fetching the latest blockhash from the Solana network.
 *
 * Contains both the blockhash value and the `lastValidBlockHeight`, which
 * together define the lifetime window for a transaction. The two fields must
 * be passed together to `setTransactionMessageLifetimeUsingBlockhash` from
 * `@solana/kit`.
 *
 * @remarks
 * Transactions using this blockhash must be confirmed before the network
 * reaches `lastValidBlockHeight`, otherwise they will be rejected as expired.
 * On mainnet, the validity window is typically around 150 blocks (~60–90
 * seconds), but this can shrink during periods of high slot skip rates.
 *
 * @see {@link GetLatestBlockhash} for the function that returns this type
 * @public
 */
interface LatestBlockhashResult {
    /**
     * A recent blockhash observed from the cluster at the `"confirmed"`
     * commitment level.
     *
     * @remarks
     * This hash serves three purposes:
     * - It sets the transaction's lifetime constraint (expires at `lastValidBlockHeight`).
     * - It prevents replay attacks — once expired, the same blockhash cannot be
     *   reused to submit a duplicate.
     * - It anchors the transaction to a specific fork of the chain.
     */
    readonly blockhash: Blockhash;
    /**
     * The last block height at which this blockhash is considered valid.
     *
     * @remarks
     * After the network surpasses this block height, any transaction referencing
     * `blockhash` will be rejected with `BlockhashNotFound`. Callers must ensure
     * they submit and confirm the transaction before this height is reached.
     *
     * Typical validity window: ~150 blocks (~60–90 seconds on mainnet).
     */
    readonly lastValidBlockHeight: bigint;
}
/**
 * Function type that fetches the latest blockhash and validity window from
 * the Solana network.
 *
 * Every invocation of this function should return a fresh blockhash. Caching
 * is the caller's responsibility; the lifetime window should be factored into
 * any caching strategy.
 *
 * @remarks
 * **Underlying RPC call** — Implementations typically call `getLatestBlockhash`
 * (commitment: `"confirmed"`) on the Solana JSON-RPC API.
 *
 * **Blockhash validity** — Blockhashes are valid for approximately 150 blocks
 * (~1–2 minutes). A transaction must be confirmed before `lastValidBlockHeight`
 * is surpassed; otherwise it will be rejected with `BlockhashNotFound`.
 *
 * **Caching considerations** — Blockhashes can be safely cached for a few
 * seconds to reduce RPC load in high-throughput scenarios, but the cache TTL
 * must be short enough relative to the validity window to avoid expiry.
 *
 * **Integration with `@solana/kit`** — The returned `LatestBlockhashResult` is
 * designed to be passed directly to `setTransactionMessageLifetimeUsingBlockhash`
 * without any transformation:
 *
 * @param options - Optional configuration. Pass `{ commitment }` to override the
 *   default `"confirmed"` commitment level for this RPC call.
 * @returns A `Promise` resolving to a {@link LatestBlockhashResult} containing
 *   the current blockhash and its last valid block height.
 *
 * @throws May reject if the RPC endpoint is unreachable or returns a malformed
 *   response.
 *
 * @example
 * Using in a transaction-building pipeline with `pipe`:
 * ```typescript
 * import type { GetLatestBlockhash } from "./interfaces";
 * import {
 *   createTransactionMessage,
 *   setTransactionMessageLifetimeUsingBlockhash,
 *   pipe,
 * } from "@solana/kit";
 *
 * async function buildTx(getLatestBlockhash: GetLatestBlockhash) {
 *   const blockhashResult = await getLatestBlockhash();
 *   return pipe(
 *     createTransactionMessage({ version: 0 }),
 *     (m) => setTransactionMessageLifetimeUsingBlockhash(blockhashResult, m),
 *   );
 * }
 * ```
 *
 * @example
 * Simple RPC-backed implementation:
 * ```typescript
 * const getLatestBlockhash: GetLatestBlockhash = async () => {
 *   const { value } = await rpc.getLatestBlockhash().send();
 *   return value;
 * };
 * ```
 *
 * @example
 * Implementation with short-lived caching:
 * ```typescript
 * const createCachedBlockhashProvider = (rpc: Rpc): GetLatestBlockhash => {
 *   let cached: { result: LatestBlockhashResult; fetchedAt: number } | null = null;
 *   const CACHE_TTL_MS = 10_000; // 10 seconds
 *
 *   return async () => {
 *     const now = Date.now();
 *     if (cached && now - cached.fetchedAt < CACHE_TTL_MS) {
 *       return cached.result;
 *     }
 *     const { value } = await rpc.getLatestBlockhash().send();
 *     cached = { result: value, fetchedAt: now };
 *     return value;
 *   };
 * };
 * ```
 *
 * @see {@link LatestBlockhashResult} for the returned data shape
 * @see {@link getRpcBlockhashProvider} for the default RPC-backed factory
 * @public
 */
type GetLatestBlockhash = (options?: {
    readonly commitment?: Commitment;
}) => Promise<LatestBlockhashResult>;
/**
 * The result of fetching epoch information from the Solana network.
 *
 * Contains the current epoch number, slot progress within the epoch, absolute
 * slot and block height, and optionally the transaction count for the epoch.
 * The epoch number is particularly important for Token-2022 transfer fee
 * schedule resolution.
 *
 * @remarks
 * Solana mainnet epochs span approximately 432,000 slots (~2–3 days). Epoch
 * boundaries trigger several protocol events: stake reward distribution, leader
 * schedule rotation, and Token-2022 fee schedule transitions.
 *
 * @see {@link GetEpochInfo} for the function that returns this type
 * @public
 */
interface EpochInfoResult {
    /**
     * The current epoch number.
     *
     * @remarks
     * Epochs are sequential, starting from 0 at genesis. Used by Token-2022
     * transfer fee logic to determine which fee schedule (older or newer) is
     * active for a given mint. If `currentEpoch >= newerTransferFee.epoch`,
     * the newer schedule is in effect.
     */
    readonly epoch: bigint;
    /**
     * The current slot index within the epoch (0-based).
     *
     * @remarks
     * Progress through the current epoch: `slotIndex / slotsInEpoch` gives a
     * value in [0, 1). Each slot is approximately 400ms on mainnet.
     */
    readonly slotIndex: bigint;
    /**
     * Total number of slots in the current epoch.
     *
     * @remarks
     * On mainnet, this is typically 432,000. Divide `slotIndex` by this value
     * to get epoch completion percentage.
     */
    readonly slotsInEpoch: bigint;
    /**
     * The absolute slot number since genesis.
     *
     * @remarks
     * Unlike `slotIndex`, this counter never resets. It represents the total
     * number of slots that have elapsed since the cluster's genesis block.
     */
    readonly absoluteSlot: bigint;
    /**
     * The current confirmed block height.
     *
     * @remarks
     * Block height may differ from slot number because some slots are skipped
     * (no block is produced). Block height strictly increases but may have gaps.
     */
    readonly blockHeight: bigint;
    /**
     * The total number of transactions processed in the current epoch, if reported.
     *
     * @remarks
     * Not all RPC nodes expose this field. When the node returns `null` for
     * `transactionCount`, this field is omitted (set to `undefined`) in the
     * result rather than being present with a null value.
     */
    readonly transactionCount?: bigint;
}
/**
 * Function type that fetches current epoch information from the Solana network.
 *
 * The primary use case for this function in the Umbra SDK is determining which
 * Token-2022 transfer fee schedule is active before computing deposit or
 * transfer amounts.
 *
 * @remarks
 * **Underlying RPC call** — Implementations call `getEpochInfo` (commitment:
 * `"confirmed"`) on the Solana JSON-RPC API.
 *
 * **Token-2022 fee schedule selection** — Token-2022 mints with the Transfer
 * Fee extension may define two consecutive schedules: an "older" schedule and a
 * "newer" schedule that takes effect at a future epoch. The active schedule is:
 * - `newerTransferFee` if `currentEpoch >= newerTransferFee.epoch`
 * - `olderTransferFee` otherwise
 *
 * **Caching** — Epochs on mainnet are ~2–3 days long, so caching the result for
 * minutes is safe in most scenarios. Near an epoch boundary, a stale cache could
 * cause the SDK to use the wrong fee schedule; use a conservative TTL (e.g.,
 * 60 seconds) if precision near boundaries matters.
 *
 * @param options - Optional configuration. Pass `{ commitment }` to override the
 *   default `"confirmed"` commitment level for this RPC call.
 * @returns A `Promise` resolving to an {@link EpochInfoResult}.
 *
 * @throws May reject if the RPC endpoint is unreachable or returns a malformed
 *   response.
 *
 * @example
 * Simple RPC-backed implementation:
 * ```typescript
 * const getEpochInfo: GetEpochInfo = async () => {
 *   const result = await rpc.getEpochInfo().send();
 *   return {
 *     epoch: result.epoch,
 *     slotIndex: result.slotIndex,
 *     slotsInEpoch: result.slotsInEpoch,
 *     absoluteSlot: result.absoluteSlot,
 *     blockHeight: result.blockHeight,
 *     ...(result.transactionCount !== null && {
 *       transactionCount: result.transactionCount,
 *     }),
 *   };
 * };
 * ```
 *
 * @example
 * Using epoch info for Token-2022 fee calculation:
 * ```typescript
 * const epochInfo = await getEpochInfo();
 * const feeConfig = extractTransferFeeConfig(mintAccountData);
 * if (feeConfig) {
 *   const fee = calculateTransferFee(feeConfig, epochInfo.epoch, depositAmount);
 *   const grossAmount = depositAmount + fee;
 * }
 * ```
 *
 * @see {@link EpochInfoResult} for the returned data shape
 * @see {@link getRpcEpochInfoProvider} for the default RPC-backed factory
 * @public
 */
type GetEpochInfo = (options?: {
    readonly commitment?: Commitment;
}) => Promise<EpochInfoResult>;
/**
 * Factory function type for creating a Solana JSON-RPC client.
 *
 * Mirrors the signature of `createSolanaRpc` from `@solana/kit`. Expressed as
 * a type alias so that factory functions in the SDK can accept either the real
 * `createSolanaRpc` or a test double without importing the concrete function.
 *
 * @typeParam TUrl - The literal string type of the RPC URL, preserved through
 *   the return type for nominal URL typing in `@solana/kit`.
 *
 * @param rpcUrl - The HTTP or HTTPS URL of the Solana JSON-RPC endpoint.
 * @returns A Solana RPC client instance with typed method wrappers.
 *
 * @remarks
 * The default implementation is `createSolanaRpc` from `@solana/kit`. Override
 * this in tests to inject a mock client that returns controlled responses.
 *
 * @example
 * ```typescript
 * import { createSolanaRpc } from "@solana/kit";
 * import type { CreateSolanaRpcFunction } from "./interfaces";
 *
 * const myFactory: CreateSolanaRpcFunction = (url) => createSolanaRpc(url);
 * ```
 *
 * @public
 */
type CreateSolanaRpcFunction = <TUrl extends string>(rpcUrl: TUrl) => ReturnType<typeof createSolanaRpc<TUrl>>;
/**
 * Factory function type for creating a Solana RPC subscriptions client.
 *
 * Mirrors the signature of `createSolanaRpcSubscriptions` from `@solana/kit`.
 * Used by the websocket-based transaction forwarder to establish a WebSocket
 * connection for real-time transaction confirmation notifications.
 *
 * @typeParam TUrl - The literal string type of the WebSocket URL.
 *
 * @param rpcSubscriptionsUrl - The WebSocket URL of the Solana RPC endpoint
 *   (typically starts with `wss://`).
 * @returns A Solana RPC subscriptions client instance.
 *
 * @remarks
 * The default implementation is `createSolanaRpcSubscriptions` from
 * `@solana/kit`. Override in tests to inject a mock subscriptions client.
 *
 * @example
 * ```typescript
 * import { createSolanaRpcSubscriptions } from "@solana/kit";
 * import type { CreateSolanaRpcSubscriptionsFunction } from "./interfaces";
 *
 * const myFactory: CreateSolanaRpcSubscriptionsFunction = (url) =>
 *   createSolanaRpcSubscriptions(url);
 * ```
 *
 * @see {@link getWebsocketTransactionForwarder} for the factory that uses this
 * @public
 */
type CreateSolanaRpcSubscriptionsFunction = <TUrl extends string>(rpcSubscriptionsUrl: TUrl) => ReturnType<typeof createSolanaRpcSubscriptions<TUrl>>;
/**
 * Factory function type for `sendAndConfirmTransactionFactory` from `@solana/kit`.
 *
 * Expressed as a type alias to enable dependency injection in the websocket-based
 * transaction forwarder. The factory takes an `{ rpc, rpcSubscriptions }` options
 * object and returns a `sendAndConfirmTransaction` function that submits a signed
 * transaction and waits for confirmation via a WebSocket subscription.
 *
 * @remarks
 * The default implementation is `sendAndConfirmTransactionFactory` from
 * `@solana/kit`. Override in tests to inject a mock that avoids real network
 * I/O.
 *
 * @example
 * ```typescript
 * import { sendAndConfirmTransactionFactory } from "@solana/kit";
 * import type { SendAndConfirmTransactionFactoryFunction } from "./interfaces";
 *
 * const myFactory: SendAndConfirmTransactionFactoryFunction = (opts) =>
 *   sendAndConfirmTransactionFactory(opts);
 * ```
 *
 * @see {@link getWebsocketTransactionForwarder} for the factory that uses this
 * @public
 */
type SendAndConfirmTransactionFactoryFunction = typeof sendAndConfirmTransactionFactory;
/**
 * Function type that forwards signed transactions to the Solana network
 * sequentially, waiting for each to be confirmed before sending the next.
 *
 * Use sequential forwarding when transactions have dependencies — for example,
 * when transaction N creates an account that transaction N+1 writes to. If any
 * transaction fails, subsequent transactions are not attempted.
 *
 * @param transactions - An ordered, readonly array of fully signed transactions.
 *   Index 0 is submitted first.
 * @returns A `Promise` resolving to an array of {@link TransactionSignature}
 *   values in the same order as the input transactions.
 *
 * @throws Rejects if any transaction in the sequence fails to confirm. The error
 *   should identify which transaction failed and may carry the signatures of any
 *   previously confirmed transactions in its context.
 *
 * @remarks
 * **Execution semantics:**
 * - Transactions are submitted in array order (index 0 first).
 * - Each transaction is awaited before the next is submitted.
 * - A failure aborts the remaining transactions — they are not retried.
 *
 * **Use cases:**
 * - Creating an account then performing operations on it.
 * - Initializing a program then calling its instructions.
 * - Any scenario where the correctness of transaction N depends on N-1 landing.
 *
 * @example
 * ```typescript
 * const signatures = await forwarder.forwardSequentially([
 *   createAccountTx,
 *   depositTx,
 * ]);
 * console.log(`Account created: ${signatures[0]}`);
 * console.log(`Deposit landed: ${signatures[1]}`);
 * ```
 *
 * @see {@link ForwardInParallel} for the parallel alternative
 * @see {@link TransactionForwarder} for the interface that contains both methods
 * @public
 */
type ForwardSequentially = (transactions: readonly SignedTransaction[]) => Promise<readonly TransactionSignature[]>;
/**
 * Function type that forwards signed transactions to the Solana network in
 * parallel, submitting all without waiting for individual confirmations.
 *
 * Use parallel forwarding when transactions are fully independent — they do not
 * share writable accounts and their outcomes do not affect each other. Parallel
 * forwarding is significantly faster than sequential forwarding for large batches.
 *
 * @param transactions - A readonly array of fully signed transactions to submit
 *   simultaneously.
 * @returns A `Promise` resolving to an array of {@link TransactionSignature}
 *   values in the same order as the input transactions (not confirmation order).
 *
 * @throws Rejects if any transaction fails. Because all transactions are
 *   submitted simultaneously, some may succeed while others fail. The error
 *   should indicate which transactions failed.
 *
 * @remarks
 * **Execution semantics:**
 * - All transactions are submitted at approximately the same time.
 * - Confirmations may arrive in any order; results are always returned in input order.
 * - Partial failure is possible: some transactions may confirm while others fail.
 *
 * **Performance considerations:**
 * - Ideal for batch transfers to independent recipients.
 * - May hit per-second rate limits on public RPC nodes with large batches.
 * - The `onTransactionConfirmed` callback is not invoked during parallel forwarding.
 *
 * @example
 * ```typescript
 * const transferTxs = recipients.map((r) => buildTransfer(sender, r, amount));
 * const signatures = await forwarder.forwardInParallel(transferTxs);
 * signatures.forEach((sig, i) => {
 *   console.log(`Transfer to ${recipients[i]}: ${sig}`);
 * });
 * ```
 *
 * @see {@link ForwardSequentially} for the sequential alternative
 * @see {@link TransactionForwarder} for the interface that contains both methods
 * @public
 */
type ForwardInParallel = (transactions: readonly SignedTransaction[]) => Promise<readonly TransactionSignature[]>;
/**
 * Interface for forwarding fully signed transactions to the Solana network.
 *
 * This interface provides two complementary strategies for transaction
 * submission. Choosing the right strategy affects both correctness and
 * performance:
 *
 * - Use `forwardSequentially` when transactions have dependencies (state
 *   produced by one transaction is consumed by the next).
 * - Use `forwardInParallel` when transactions are independent (no shared
 *   writable accounts, no ordering requirement).
 *
 * @remarks
 * **Compile-time safety** — Both methods accept only `SignedTransaction`, a
 * branded type that indicates the transaction has at least one signature and
 * carries a blockhash lifetime constraint. Unsigned or partially unsigned
 * transactions produce a compile-time error, preventing accidental submission
 * of incomplete transactions.
 *
 * **Implementation requirements** — Concrete implementations should handle:
 * - RPC endpoint selection, failover, and connection management.
 * - Retry logic for transient send failures.
 * - Blockhash expiry detection (the transaction window closes at
 *   `lastValidBlockHeight`).
 * - Structured error propagation with diagnostic context.
 *
 * **Available implementations:**
 * - {@link getWebsocketTransactionForwarder} — uses WebSocket subscriptions
 *   for efficient confirmation (lower latency, requires WebSocket access).
 * - {@link getPollingTransactionForwarder} — polls `getSignatureStatuses`
 *   (works in environments that block WebSocket; configurable timeouts and
 *   per-transaction callbacks).
 *
 * @example
 * Using the interface polymorphically:
 * ```typescript
 * import type { TransactionForwarder } from "./interfaces";
 *
 * async function submitOperations(
 *   forwarder: TransactionForwarder,
 *   initTx: SignedTransaction,
 *   operationTxs: readonly SignedTransaction[],
 * ) {
 *   // Init must land before operations can reference the new account
 *   await forwarder.forwardSequentially([initTx]);
 *
 *   // Operations are independent of each other
 *   const sigs = await forwarder.forwardInParallel(operationTxs);
 *   return sigs;
 * }
 * ```
 *
 * @see {@link ForwardSequentially} for the sequential method type
 * @see {@link ForwardInParallel} for the parallel method type
 * @see {@link getWebsocketTransactionForwarder} for the WebSocket implementation
 * @see {@link getPollingTransactionForwarder} for the polling implementation
 * @public
 */
interface TransactionForwarder {
    /**
     * Forwards transactions sequentially.
     *
     * Each transaction is submitted and confirmed before the next transaction
     * is sent. Aborts on the first failure.
     *
     * @see {@link ForwardSequentially}
     */
    forwardSequentially: ForwardSequentially;
    /**
     * Forwards transactions in parallel.
     *
     * All transactions are submitted simultaneously. Confirmations are awaited
     * concurrently. Results are returned in input order regardless of confirmation
     * order.
     *
     * @see {@link ForwardInParallel}
     */
    forwardInParallel: ForwardInParallel;
    /**
     * Sends a transaction without waiting for confirmation.
     *
     * Use for best-effort operations like rent reclamation where blocking
     * on confirmation is unnecessary.
     */
    fireAndForget: FireAndForget;
}
/**
 * Sends a single signed transaction to the network without awaiting confirmation.
 * Returns the signature immediately after submission.
 */
type FireAndForget = (transaction: SignedTransaction) => Promise<TransactionSignature>;

/**
 * Arcium Computation Monitor Implementations.
 *
 * Monitors an Arcium `ComputationAccount` for finalization or pruning after
 * a `queue_computation` transaction has been sent. The monitor uses **slot-based
 * timeout**: it reads the `slot` field from the on-chain `ComputationAccount`
 * (the slot when the computation was queued) and compares against the current
 * slot to determine if the computation has been pruned.
 *
 * Two factory functions produce {@link ComputationMonitor} implementations:
 *
 * - **{@link getWebsocketComputationMonitor}** — Subscribes to account change
 *   notifications via WebSocket for low-latency finalization detection.
 *
 * - **{@link getPollingComputationMonitor}** — Periodically fetches the
 *   ComputationAccount via HTTP. Suitable for environments without WebSocket.
 *
 * ## Outcomes
 *
 * - **Finalized** — The MPC callback landed successfully. The `ComputationAccount.status`
 *   transitioned to `Finalized` within the slot window.
 * - **Pruned** — The slot window elapsed without finalization. The MPC nodes either
 *   failed to complete or all callback attempts failed. The computation will not
 *   finalize and should be considered abandoned.
 *
 * ## Slot-Based Timeout
 *
 * Arcium MPC callbacks typically arrive within ~180 slots (~72 seconds) of queueing.
 * The monitor uses a configurable slot window ({@link DEFAULT_MAX_SLOT_WINDOW} = 200)
 * measured from the `ComputationAccount.slot` field. A wall-clock safety timeout
 * ({@link DEFAULT_SAFETY_TIMEOUT_MS} = 300s) provides a fallback if RPC is unresponsive.
 *
 * @packageDocumentation
 * @module arcium/computation-monitor
 * @since 2.0.0
 */

/**
 * Default maximum slot window. If `currentSlot - queuedSlot` exceeds this
 * value, the computation is considered pruned.
 *
 * @remarks
 * Arcium callbacks typically arrive within ~180 slots (~72 seconds).
 * The default of 200 provides a ~20-slot buffer.
 *
 * @since 2.0.0
 * @public
 */
declare const DEFAULT_MAX_SLOT_WINDOW = 200;
/**
 * Default wall-clock safety timeout in milliseconds. This is a fallback
 * for cases where the RPC is unresponsive and slot progression cannot be
 * tracked. Under normal conditions, the slot-based window resolves first.
 *
 * @since 2.0.0
 * @public
 */
declare const DEFAULT_SAFETY_TIMEOUT_MS = 300000;
/**
 * Default interval in milliseconds between successive poll attempts.
 *
 * @since 2.0.0
 * @public
 */
declare const DEFAULT_POLLING_INTERVAL_MS = 2000;
/**
 * Default limit for the `getSignaturesForAddress` RPC call when retrieving
 * the callback transaction signature after finalization.
 *
 * @since 2.0.0
 * @public
 */
declare const DEFAULT_SIGNATURE_RETRIEVAL_LIMIT = 20;
/**
 * Result when the MPC computation finalizes successfully.
 *
 * @since 2.0.0
 * @public
 */
interface ComputationFinalizedResult {
    /** The computation completed and the callback landed on-chain. */
    readonly status: "finalized";
    /** Wall-clock milliseconds from monitor start to finalization detection. */
    readonly elapsedMs: number;
    /** The slot at which the computation was originally queued. */
    readonly queuedSlot: bigint;
    /**
     * The callback transaction signature, if `retrieveCallbackSignature` was `true`.
     * `undefined` otherwise.
     */
    readonly callbackSignature?: TransactionSignature;
}
/**
 * Result when the computation is pruned (no successful callback within the slot window).
 *
 * @since 2.0.0
 * @public
 */
interface ComputationPrunedResult {
    /** The slot window elapsed without a successful callback. */
    readonly status: "pruned";
    /** Wall-clock milliseconds from monitor start to pruning detection. */
    readonly elapsedMs: number;
    /** The slot at which the computation was originally queued. */
    readonly queuedSlot: bigint;
    /** The current slot at the time pruning was detected. */
    readonly currentSlot: bigint;
}
/**
 * Discriminated union of all computation monitoring outcomes.
 *
 * @remarks
 * Callers must check `result.status` to determine the outcome:
 *
 * ```typescript
 * const result = await monitor.awaitComputation(address);
 * if (result.status === "finalized") {
 *   // MPC succeeded — continue with the encrypted result
 * } else {
 *   // Pruned — the computation will never finalize
 *   console.log(`Pruned: ${result.currentSlot - result.queuedSlot} slots elapsed`);
 * }
 * ```
 *
 * @since 2.0.0
 * @public
 */
type ComputationMonitorResult = ComputationFinalizedResult | ComputationPrunedResult;
/**
 * Extended finalized result with a guaranteed callback signature.
 * Returned when `retrieveCallbackSignature` is `true` and the computation finalized.
 *
 * @since 2.0.0
 * @public
 */
interface ComputationFinalizedResultWithSignature extends Omit<ComputationFinalizedResult, "callbackSignature"> {
    /** The base58-encoded transaction signature of the successful Arcium callback. */
    readonly callbackSignature: TransactionSignature;
}
/**
 * Result type when `retrieveCallbackSignature` is `true`.
 * If finalized, the callback signature is guaranteed present.
 * If pruned, no signature is available.
 *
 * @since 2.0.0
 * @public
 */
type ComputationMonitorResultWithSignature = ComputationFinalizedResultWithSignature | ComputationPrunedResult;
/**
 * Progress event types fired via the `onProgress` callback.
 *
 * @remarks
 * - `queued` — the ComputationAccount was found with status `Queued`
 * - `finalized` — the computation status transitioned to `Finalized`
 * - `pruned` — the slot window elapsed without finalization
 *
 * @since 2.0.0
 * @public
 */
type ComputationMonitorProgressEvent = {
    readonly type: "queued";
    readonly queuedSlot: bigint;
} | {
    readonly type: "finalized";
    readonly callbackSignature?: TransactionSignature;
} | {
    readonly type: "pruned";
    readonly queuedSlot: bigint;
    readonly currentSlot: bigint;
};
/**
 * Options for a computation monitoring invocation.
 *
 * @since 2.0.0
 * @public
 */
interface ComputationMonitorOptions {
    /**
     * Maximum number of slots after the queued slot before the computation
     * is considered pruned. The monitor reads the `slot` field from the
     * `ComputationAccount` and compares against the current on-chain slot.
     *
     * @defaultValue {@link DEFAULT_MAX_SLOT_WINDOW} (200 slots ≈ 80 seconds)
     */
    readonly maxSlotWindow?: number;
    /**
     * Wall-clock safety timeout in milliseconds. This is a fallback that fires
     * only if slot progression cannot be tracked (e.g. RPC is unresponsive).
     * Under normal conditions, the slot-based window resolves first.
     *
     * @remarks
     * When this fires, a {@link ComputationMonitorError} with stage `"timeout"`
     * is thrown. This indicates an infrastructure problem, not a pruned computation.
     *
     * @defaultValue {@link DEFAULT_SAFETY_TIMEOUT_MS} (300,000 ms / 5 minutes)
     */
    readonly safetyTimeoutMs?: number;
    /**
     * If `true`, perform a `getSignaturesForAddress` call after finalization
     * to retrieve the successful callback transaction signature.
     * Has no effect if the computation is pruned.
     *
     * @defaultValue `false`
     */
    readonly retrieveCallbackSignature?: boolean;
    /**
     * Progress callback fired as status changes occur.
     *
     * @remarks
     * This callback is synchronous and should not perform blocking operations.
     * It is informational and does not affect the monitoring loop.
     */
    readonly onProgress?: (event: ComputationMonitorProgressEvent) => void;
    /**
     * Commitment level for account fetches and subscriptions.
     *
     * @defaultValue `"confirmed"`
     */
    readonly commitment?: Commitment;
    /**
     * An `AbortSignal` for external cancellation of the monitoring operation.
     *
     * @remarks
     * When aborted, the monitor throws a {@link ComputationMonitorError} with
     * stage `"timeout"`. This enables callers to cancel from external code
     * (user navigation, component unmount).
     */
    readonly signal?: AbortSignal;
}
/**
 * Polling-specific options extending the base monitor options.
 *
 * @since 2.0.0
 * @public
 */
interface PollingComputationMonitorOptions extends ComputationMonitorOptions {
    /**
     * Time in milliseconds between successive account fetch attempts.
     *
     * @defaultValue {@link DEFAULT_POLLING_INTERVAL_MS} (2,000 ms)
     */
    readonly pollingIntervalMs?: number;
}
/**
 * Monitors an Arcium `ComputationAccount` for finalization or pruning.
 *
 * @since 2.0.0
 * @public
 */
interface ComputationMonitor {
    /**
     * Monitors a ComputationAccount until it finalizes or is pruned.
     *
     * @param computationAddress - The on-chain address of the ComputationAccount PDA.
     * @param options - Monitor options.
     * @returns A promise resolving to a finalized or pruned result.
     *
     * @throws {ComputationMonitorError} With stage `"timeout"` if the safety wall-clock
     *   timeout fires (indicates RPC issues, not normal pruning).
     * @throws {ComputationMonitorError} With stage `"subscription"` if WebSocket fails.
     * @throws {ComputationMonitorError} With stage `"signature-retrieval"` if callback
     *   signature lookup fails after finalization.
     */
    awaitComputation: {
        (computationAddress: Address, options?: ComputationMonitorOptions & {
            retrieveCallbackSignature?: false;
        }): Promise<ComputationMonitorResult>;
        (computationAddress: Address, options: ComputationMonitorOptions & {
            retrieveCallbackSignature: true;
        }): Promise<ComputationMonitorResultWithSignature>;
    };
}
/**
 * Configuration for the WebSocket-based computation monitor.
 *
 * @since 2.0.0
 * @public
 */
interface WebsocketBasedComputationMonitorConfig {
    /** HTTP/HTTPS URL of the Solana JSON-RPC endpoint. */
    readonly rpcUrl: string;
    /** WebSocket URL of the Solana RPC subscriptions endpoint. */
    readonly rpcSubscriptionsUrl: string;
}
/**
 * Optional dependencies for the WebSocket-based computation monitor.
 *
 * @since 2.0.0
 * @public
 */
interface WebsocketBasedComputationMonitorDeps {
    /** Override `createSolanaRpc` from `@solana/kit`. */
    readonly createRpc?: CreateSolanaRpcFunction;
    /** Override `createSolanaRpcSubscriptions` from `@solana/kit`. */
    readonly createRpcSubscriptions?: CreateSolanaRpcSubscriptionsFunction;
}
/**
 * Configuration for the polling-based computation monitor.
 *
 * @since 2.0.0
 * @public
 */
interface PollingBasedComputationMonitorConfig {
    /** HTTP/HTTPS URL of the Solana JSON-RPC endpoint. */
    readonly rpcUrl: string;
}
/**
 * Optional dependencies for the polling-based computation monitor.
 *
 * @since 2.0.0
 * @public
 */
interface PollingBasedComputationMonitorDeps {
    /** Override `createSolanaRpc` from `@solana/kit`. */
    readonly createRpc?: CreateSolanaRpcFunction;
}
/**
 * Creates a {@link ComputationMonitor} that uses WebSocket account change
 * subscriptions for real-time detection of computation finalization or pruning.
 *
 * @remarks
 * **Detection strategy:** Subscribes to `accountNotifications` for the
 * computation account. On each notification, decodes the account and checks
 * the `status` field. Periodically fetches the current slot to detect pruning
 * when the slot window is exceeded.
 *
 * **Initial state check:** Before subscribing, performs an HTTP fetch to handle
 * the case where the computation already finalized before the monitor started.
 *
 * @param config - HTTP RPC URL and WebSocket URL.
 * @param deps - Optional dependency overrides for testing.
 * @returns A {@link ComputationMonitor} instance.
 *
 * @throws {ComputationMonitorError} Stage `"timeout"` if safety timeout fires.
 * @throws {ComputationMonitorError} Stage `"subscription"` if WebSocket fails.
 * @throws {ComputationMonitorError} Stage `"signature-retrieval"` if lookup fails.
 *
 * @example
 * ```typescript
 * const monitor = getWebsocketComputationMonitor({
 *   rpcUrl: "https://api.mainnet-beta.solana.com",
 *   rpcSubscriptionsUrl: "wss://api.mainnet-beta.solana.com",
 * });
 *
 * const result = await monitor.awaitComputation(computationAddress);
 * if (result.status === "finalized") {
 *   console.log(`Done in ${result.elapsedMs}ms`);
 * } else {
 *   console.log(`Pruned after ${result.currentSlot - result.queuedSlot} slots`);
 * }
 * ```
 *
 * @see {@link getPollingComputationMonitor} for the polling alternative
 * @since 2.0.0
 * @public
 */
declare function getWebsocketComputationMonitor(config: WebsocketBasedComputationMonitorConfig, deps?: WebsocketBasedComputationMonitorDeps): ComputationMonitor;
/**
 * Creates a {@link ComputationMonitor} that uses periodic HTTP account fetching
 * for detection of computation finalization or pruning.
 *
 * @remarks
 * Each poll iteration fetches the `ComputationAccount` and the current slot
 * in parallel. If the account is finalized, the monitor resolves. If the slot
 * window is exceeded, the monitor resolves with a pruned result.
 *
 * **Transient error handling** — RPC fetch errors during polling are silently
 * swallowed and the poll loop continues.
 *
 * @param config - HTTP RPC endpoint URL.
 * @param deps - Optional dependency overrides for testing.
 * @returns A {@link ComputationMonitor} instance.
 *
 * @throws {ComputationMonitorError} Stage `"timeout"` if safety timeout fires.
 * @throws {ComputationMonitorError} Stage `"signature-retrieval"` if lookup fails.
 *
 * @example
 * ```typescript
 * const monitor = getPollingComputationMonitor({
 *   rpcUrl: "https://api.mainnet-beta.solana.com",
 * });
 *
 * const result = await monitor.awaitComputation(computationAddress, {
 *   maxSlotWindow: 250,
 *   pollingIntervalMs: 3_000,
 *   retrieveCallbackSignature: true,
 * });
 *
 * if (result.status === "finalized") {
 *   console.log(`Callback: ${result.callbackSignature}`);
 * }
 * ```
 *
 * @see {@link getWebsocketComputationMonitor} for the WebSocket alternative
 * @since 2.0.0
 * @public
 */
declare function getPollingComputationMonitor(config: PollingBasedComputationMonitorConfig, deps?: PollingBasedComputationMonitorDeps): ComputationMonitor;

/**
 * Umbra Interfaces — UTXO indexer interfaces for Merkle proofs and UTXO scanning.
 *
 * @module umbra/interfaces/indexer
 * @since 2.0.0
 */

/**
 * Base interface for Umbra Indexer configuration.
 *
 * @remarks
 * Contains the essential configuration needed to connect to an Umbra indexer service.
 * The indexer maintains an off-chain database of protocol state for efficient querying.
 *
 * **Indexer Selection:**
 * Multiple indexer providers may exist. Choose one based on:
 * - Geographic proximity (lower latency)
 * - Uptime and reliability
 * - Query performance
 *
 * @example
 * ```typescript
 * const indexer: IUmbraIndexer = {
 *     apiEndpoint: 'https://indexer.umbra.finance'
 * };
 * ```
 *
 * @public
 */
interface IUmbraIndexer {
    /**
     * The HTTP endpoint of the indexer service.
     *
     * @remarks
     * This should be a fully qualified URL including the protocol.
     * The endpoint must support CORS for browser-based clients.
     *
     * @example "https://indexer.umbra.finance"
     */
    apiEndpoint: string;
}
/**
 * Timestamp components returned by the indexer.
 *
 * @remarks
 * Represents the decomposed timestamp of when the UTXO was created.
 * Used for transaction viewing key derivation.
 *
 * @see {@link H1Components}
 * @public
 */
interface TimestampComponents {
    /** Year (e.g., 2024) */
    year: Year;
    /** Month (1-12) */
    month: Month;
    /** Day (1-31) */
    day: Day;
    /** Hour (0-23) */
    hour: Hour;
    /** Minute (0-59) */
    minute: Minute;
    /** Second (0-59) */
    second: Second;
}
/**
 * H1 components returned by the indexer for UTXO data reconstruction.
 *
 * @remarks
 * These are the public components needed to reconstruct the H1 hash
 * during claim operations. H1 contains metadata about the deposit
 * that is public knowledge.
 *
 * @see {@link UtxoDataItem}
 * @public
 */
interface H1Components {
    /** Protocol version identifier */
    version: U64;
    /** Index of the commitment in the Merkle tree */
    commitmentIndex: U128;
    /** Lower 128 bits of the sender's address */
    senderAddressLow: U128;
    /** Upper 128 bits of the sender's address */
    senderAddressHigh: U128;
    /** Fixed SOL fees paid to relayer (in lamports) */
    relayerFixedSolFees: U64;
    /** Lower 128 bits of the mint address */
    mintAddressLow: U128;
    /** Upper 128 bits of the mint address */
    mintAddressHigh: U128;
    /** Timestamp components for TVK derivation */
    timestamp: TimestampComponents;
    /** Cumulative SPL token volume in the pool at insertion time (base units) */
    poolVolumeSpl: U64;
    /** Cumulative SOL volume in the pool at insertion time (lamports) */
    poolVolumeSol: U64;
}
/**
 * Data returned from the Merkle proof endpoint.
 *
 * @remarks
 * Contains the Merkle root, proof path (sibling hashes), and the leaf value
 * for a specific insertion in the Merkle tree.
 *
 * **Hash Encoding:**
 * All hashes are little-endian byte arrays (U256LeBytes).
 * The API returns hex strings with `0x` prefix which are converted.
 *
 * @see {@link MerkleProofFetcherFunction}
 * @public
 */
interface MerkleProofData {
    /** The Merkle root at the time of the query */
    merkleRoot: U256LeBytes;
    /** The tree index containing this leaf */
    treeIndex: U32;
    /** The insertion index within the tree */
    insertionIndex: U32;
    /** Array of sibling hashes from leaf to root */
    merklePath: U256LeBytes[];
    /** The leaf node value (commitment) */
    leaf: U256LeBytes;
}
/**
 * Function type for fetching Merkle proofs from the indexer.
 *
 * @remarks
 * Fetches Merkle proofs for one or more leaves in a specific tree.
 * The returned Map is keyed by insertion index for easy lookup.
 *
 * @param treeIndex - The Merkle tree index to query
 * @param insertionIndices - Array of insertion indices to fetch proofs for
 * @returns A Map from insertion index to its Merkle proof data
 *
 * @example
 * ```typescript
 * const proofs = await fetchMerkleProof(0, [42, 43, 44]);
 * const proof = proofs.get(42);
 * if (proof) {
 *     console.log('Root:', proof.merkleRoot);
 *     console.log('Path length:', proof.merklePath.length);
 * }
 * ```
 *
 * @see {@link MerkleProofData}
 * @public
 */
type MerkleProofFetcherFunction = (treeIndex: U32, insertionIndices: readonly U32[]) => Promise<Map<U32, MerkleProofData>>;
/**
 * Arguments for creating a Merkle proof fetcher function.
 *
 * @example
 * ```typescript
 * const args: GetMerkleProofFetcherArgs = {
 *     apiEndpoint: 'https://indexer.umbra.finance'
 * };
 * ```
 *
 * @see {@link MerkleProofFetcherFunction}
 * @public
 */
interface GetMerkleProofFetcherArgs {
    /** The HTTP endpoint of the indexer service */
    apiEndpoint: string;
}
/**
 * Optional dependencies for the Merkle proof fetcher factory.
 *
 * @remarks
 * Allows injection of a custom fetch implementation for testing
 * or environments without global fetch.
 *
 * @see {@link MerkleProofFetcherFunction}
 * @public
 */
interface GetMerkleProofFetcherDeps {
    /**
     * Custom fetch implementation.
     * @default globalThis.fetch
     */
    fetch?: typeof globalThis.fetch;
}
/**
 * Individual UTXO data item from the indexer API.
 *
 * @remarks
 * Contains all the data needed to reconstruct and claim a UTXO,
 * including H1/H2 hashes, encrypted data, and metadata.
 *
 * **Absolute Index Calculation:**
 * ```
 * absoluteIndex = treeIndex * 1,048,576 + insertionIndex
 * ```
 *
 * @see {@link UtxoDataFetcherFunction}
 * @see {@link H1Components}
 * @public
 */
interface UtxoDataItem {
    /** Absolute index in the global UTXO sequence */
    absoluteIndex: bigint;
    /** Tree index containing this UTXO */
    treeIndex: U32;
    /** Insertion index within the tree */
    insertionIndex: U32;
    /** Final commitment h(h1_hash, h2_hash) */
    finalCommitment: U256LeBytes;
    /** H1 components for claim proof generation */
    h1Components: H1Components;
    /** H1 hash value */
    h1Hash: U256LeBytes;
    /** H2 hash value */
    h2Hash: U256LeBytes;
    /** AES encrypted UTXO data (amount, destination, gen index, domain separator) */
    aesEncryptedData: AesCiphertextWithMetadata;
    /** Depositor's X25519 public key for decryption */
    depositorX25519PublicKey: X25519PublicKey;
    /** Block timestamp (Unix epoch seconds) */
    timestamp: U64;
    /** Solana slot number */
    slot: U64;
    /** Event type: 'deposit' or 'callback' */
    eventType: "deposit" | "callback";
}
/**
 * Paginated result from the UTXO data endpoint.
 *
 * @remarks
 * Contains the fetched UTXO items along with pagination metadata
 * for iterating through large result sets.
 *
 * @see {@link UtxoDataFetcherFunction}
 * @see {@link UtxoDataItem}
 * @public
 */
interface UtxoFetchResult {
    /** Map of insertion index to UTXO data */
    items: Map<U32, UtxoDataItem>;
    /** Whether there are more results available */
    hasMore: boolean;
    /** Next cursor to continue pagination (use as startIndex for next request) */
    nextCursor: bigint | undefined;
    /** Total count of records in the requested range */
    totalCount: U64;
}
/**
 * Function type for fetching UTXO data from the indexer.
 *
 * @remarks
 * Fetches UTXO data by absolute index range with pagination support.
 *
 * **Pagination:**
 * - Use `startIndex` and optional `endIndex` to define the range
 * - Use `limit` to control page size (default: 1000, max: 5000)
 * - Use `nextCursor` from result as `startIndex` for next page
 *
 * @param startIndex - Starting absolute index (inclusive)
 * @param endIndex - Optional ending absolute index (inclusive)
 * @param limit - Maximum number of records to return (default: 1000, max: 5000)
 * @returns Paginated result with UTXO items and metadata
 *
 * @example
 * ```typescript
 * // Fetch first page
 * let result = await fetchUtxoData(0n, undefined, 1000);
 * console.log(`Fetched ${result.items.size} UTXOs`);
 *
 * // Continue pagination
 * while (result.hasMore && result.nextCursor !== undefined) {
 *     result = await fetchUtxoData(result.nextCursor, undefined, 1000);
 *     console.log(`Fetched ${result.items.size} more UTXOs`);
 * }
 * ```
 *
 * @see {@link UtxoFetchResult}
 * @public
 */
type UtxoDataFetcherFunction = (startIndex: bigint, endIndex?: bigint, limit?: U32) => Promise<UtxoFetchResult>;
/**
 * Arguments for creating a UTXO data fetcher function.
 *
 * @example
 * ```typescript
 * const args: GetUtxoDataFetcherArgs = {
 *     apiEndpoint: 'https://indexer.umbra.finance'
 * };
 * ```
 *
 * @see {@link UtxoDataFetcherFunction}
 * @public
 */
interface GetUtxoDataFetcherArgs {
    /** The HTTP endpoint of the indexer service */
    apiEndpoint: string;
}
/**
 * Optional dependencies for the UTXO data fetcher factory.
 *
 * @remarks
 * Allows injection of a custom fetch implementation for testing
 * or environments without global fetch.
 *
 * @see {@link UtxoDataFetcherFunction}
 * @public
 */
interface GetUtxoDataFetcherDeps {
    /**
     * Custom fetch implementation.
     * @default globalThis.fetch
     */
    fetch?: typeof globalThis.fetch;
}
/**
 * Decrypted UTXO data from successful AES decryption.
 *
 * @remarks
 * Contains the plaintext values extracted from the AES-encrypted UTXO data,
 * along with the original UTXO metadata and the determined unlocker type.
 *
 * **AES Plaintext Structure (68 bytes):**
 * | Offset | Size | Field |
 * |--------|------|-------|
 * | 0 | 8 | Amount (LE) |
 * | 8 | 32 | Destination address |
 * | 40 | 16 | Modified generation index (LE) |
 * | 56 | 12 | Domain separator |
 *
 * @see {@link ClaimableUtxoData}
 * @public
 */
interface DecryptedUtxoData {
    /** Decrypted UTXO amount */
    amount: U64;
    /** Decrypted destination address */
    destinationAddress: Address;
    /** Modified generation index from decrypted AES data */
    modifiedGenerationIndex: U128LeBytes;
    /** Tree index containing this UTXO */
    treeIndex: U32;
    /** Insertion index within the tree */
    insertionIndex: U32;
    /** H1 components for claim proof generation */
    h1Components: H1Components;
    /** H1 hash value */
    h1Hash: U256LeBytes;
    /** H2 hash value */
    h2Hash: U256LeBytes;
    /**
     * The type of unlocker determined by the domain separator.
     * - 'self-burnable': Encrypted-balance deposit, self-claimable (you deposited it, you can burn it)
     * - 'received': Encrypted-balance deposit, receiver-claimable (someone sent it to you)
     * - 'public-self-burnable': Public-balance deposit, self-claimable (you deposited it via public ATA)
     * - 'public-received': Public-balance deposit, receiver-claimable (someone sent it to you via public ATA)
     */
    unlockerType: "self-burnable" | "received" | "public-self-burnable" | "public-received";
}
/**
 * Full claim-ready UTXO data with Merkle proof.
 *
 * @remarks
 * Contains all the data needed to submit a claim transaction,
 * including the Merkle proof and decrypted values.
 * This structure is designed to be passed directly to claim functions.
 *
 * @see {@link ClaimableUtxoResult}
 * @see {@link ClaimableUtxoScannerFunction}
 * @public
 */
interface ClaimableUtxoData {
    /** Current Merkle root of the mixer tree */
    merkleRoot: U256LeBytes;
    /** Array of sibling hashes from leaf to root */
    merklePath: U256LeBytes[];
    /** Leaf index in the Merkle tree */
    leafIndex: U128;
    /** Decrypted UTXO amount */
    amount: U64;
    /** Decrypted destination address */
    destinationAddress: Address;
    /** Modified generation index from decrypted AES data */
    depositModifiedGenerationIndex: U128;
    /** Protocol version identifier */
    version: U64;
    /** Index of the commitment in the Merkle tree */
    commitmentIndex: U128;
    /** Lower 128 bits of the sender's address */
    senderAddressLow: U128;
    /** Upper 128 bits of the sender's address */
    senderAddressHigh: U128;
    /** Fixed SOL fees paid to relayer (in lamports) */
    relayerFixedSolFees: U64;
    /** Lower 128 bits of the mint address */
    mintAddressLow: U128;
    /** Upper 128 bits of the mint address */
    mintAddressHigh: U128;
    /** Timestamp components for TVK derivation */
    timestamp: TimestampComponents;
    /** Cumulative SPL token volume in the pool at insertion time (base units) */
    poolVolumeSpl: U64;
    /** Cumulative SOL volume in the pool at insertion time (lamports) */
    poolVolumeSol: U64;
}
/**
 * Result from fetching claimable UTXOs.
 *
 * @remarks
 * Groups claimable UTXOs by unlocker type for easy processing.
 * Each array contains claim-ready data that can be passed directly
 * to the appropriate claim function.
 *
 * @example
 * ```typescript
 * const result: ClaimableUtxoResult = await fetchClaimableUtxos({...});
 * console.log(`Self-burnable: ${result.selfBurnable.length}`);
 * console.log(`Received: ${result.received.length}`);
 * ```
 *
 * @see {@link ClaimableUtxoScannerFunction}
 * @see {@link ClaimableUtxoData}
 * @public
 */
interface ClaimableUtxoResult {
    /**
     * Encrypted-balance deposit UTXOs you can burn yourself (you created them).
     * Pass to `SelfClaimableUtxoToEncryptedBalanceClaimerFunction` or
     * `SelfClaimableUtxoToPublicBalanceClaimerFunction`.
     */
    selfBurnable: ClaimableUtxoData[];
    /**
     * Encrypted-balance deposit UTXOs sent to you by others.
     * Pass to `ReceiverClaimableUtxoToEncryptedBalanceClaimerFunction`.
     */
    received: ClaimableUtxoData[];
    /**
     * Public-balance deposit UTXOs you can burn yourself (you created them via public ATA).
     * Pass to `SelfClaimableUtxoToEncryptedBalanceClaimerFunction` or
     * `SelfClaimableUtxoToPublicBalanceClaimerFunction`.
     */
    publicSelfBurnable: ClaimableUtxoData[];
    /**
     * Public-balance deposit UTXOs sent to you by others via public ATA.
     * Pass to `ReceiverClaimableUtxoToEncryptedBalanceClaimerFunction`.
     */
    publicReceived: ClaimableUtxoData[];
}
/**
 * A decrypted UTXO as returned by the scanner, before merkle proofs are attached.
 *
 * @remarks
 * This is the output of the scan phase. Merkle proofs are fetched later at
 * claim time, per-batch, via the batch proof endpoint to guarantee a consistent
 * root across all UTXOs in a ZK proof batch.
 *
 * @see {@link ScannedUtxoResult}
 * @see {@link ClaimableUtxoData} — the enriched type after proofs are attached
 * @public
 */
type ScannedUtxoData = DecryptedUtxoData;
/**
 * Result from scanning UTXOs (no merkle proofs attached).
 *
 * @remarks
 * Groups scanned UTXOs by unlocker type. Merkle proofs are fetched at claim
 * time, not scan time, so these entries do not yet contain proof data.
 *
 * @see {@link ScannedUtxoData}
 * @public
 */
interface ScannedUtxoResult {
    /** Encrypted-balance deposit UTXOs you can burn yourself. */
    selfBurnable: ScannedUtxoData[];
    /** Encrypted-balance deposit UTXOs sent to you by others. */
    received: ScannedUtxoData[];
    /** Public-balance deposit UTXOs you can burn yourself. */
    publicSelfBurnable: ScannedUtxoData[];
    /** Public-balance deposit UTXOs sent to you by others via public ATA. */
    publicReceived: ScannedUtxoData[];
}
/**
 * Result of a batch merkle proof fetch from the indexer.
 *
 * @remarks
 * All proofs share a single `root` because they were generated under a single
 * tree read lock. This guarantees consistency for ZK batch claims.
 *
 * @public
 */
interface BatchMerkleProofResult {
    /** The shared merkle root for all proofs in this batch. */
    root: U256LeBytes;
    /** Per-leaf proof data, keyed by insertion index. */
    proofs: Map<U32, {
        merklePath: U256LeBytes[];
        leaf: U256LeBytes;
    }>;
}
/**
 * Function type for fetching batch merkle proofs with a consistent root.
 *
 * @remarks
 * Used at claim time (not scan time) to fetch proofs for all UTXOs in a
 * single ZK proof batch. The indexer guarantees all returned proofs share
 * the same merkle root by holding a single read lock.
 *
 * @see {@link BatchMerkleProofResult}
 * @public
 */
type BatchMerkleProofFetcherFunction = (treeIndex: U32, insertionIndices: readonly U32[]) => Promise<BatchMerkleProofResult>;
/**
 * Function type for fetching claimable UTXOs.
 *
 * @remarks
 * Fetches, decrypts, and categorizes all UTXOs that belong to the client
 * within the specified tree and index range.
 *
 * **Workflow:**
 * 1. Fetch UTXO data from indexer (paginated)
 * 2. For each UTXO, try to decrypt using client's X25519 key
 * 3. Check domain separator to determine unlocker type
 * 4. Fetch Merkle proofs for successfully decrypted UTXOs
 * 5. Return grouped results
 *
 * @param treeIndex - The Merkle tree index to scan
 * @param startInsertionIndex - Starting insertion index (inclusive)
 * @param endInsertionIndex - Optional ending insertion index (inclusive)
 * @returns Promise resolving to grouped claimable UTXOs
 *
 * @example
 * ```typescript
 * const fetchClaimable = getClaimableUtxoScannerFunction({ client });
 *
 * // Scan tree 0 for claimable UTXOs
 * const result = await fetchClaimable(0, 0, 10000);
 *
 * console.log(`Found ${result.ephemeral.length} self-deposited UTXOs`);
 * console.log(`Found ${result.receiver.length} UTXOs from others`);
 * ```
 *
 * @see {@link ClaimableUtxoResult}
 * @public
 */
type ClaimableUtxoScannerFunction = (treeIndex: U32, startInsertionIndex: U32, endInsertionIndex?: U32) => Promise<ScannedUtxoResult>;
/**
 * Arguments for creating a claimable UTXO fetcher function.
 *
 * @example
 * ```typescript
 * const args: GetClaimableUtxoScannerFunctionArgs = {
 *     client: myUmbraClient
 * };
 * ```
 *
 * @see {@link ClaimableUtxoScannerFunction}
 * @public
 */
interface GetClaimableUtxoScannerFunctionArgs {
    /** The Umbra client providing cryptographic keys for decryption */
    client: IUmbraClient;
}
/**
 * Optional dependencies for the claimable UTXO fetcher factory.
 *
 * @remarks
 * Allows injection of custom implementations for testing
 * or alternative implementations.
 *
 * @see {@link ClaimableUtxoScannerFunction}
 * @public
 */
interface GetClaimableUtxoScannerFunctionDeps {
    /**
     * Custom UTXO data fetcher.
     * @default Created from client's indexerApiEndpoint
     */
    fetchUtxoData?: UtxoDataFetcherFunction;
    /**
     * Custom Merkle proof fetcher.
     * @default Created from client's indexerApiEndpoint
     */
    fetchMerkleProof?: MerkleProofFetcherFunction;
    /**
     * Custom AES decryptor function.
     * @default getAesDecryptor()
     */
    aesDecryptor?: AesDecryptorFunction;
    /**
     * Custom X25519 public key derivation function.
     * @default x25519.getPublicKey
     */
    x25519GetPublicKey?: (privateKey: X25519PrivateKey) => X25519PublicKey;
    /**
     * Custom X25519 shared secret computation function.
     * @default x25519.getSharedSecret
     */
    x25519GetSharedSecret?: (privateKey: X25519PrivateKey, publicKey: X25519PublicKey) => Uint8Array;
    /**
     * Custom fetch implementation for indexer API calls.
     * @default globalThis.fetch
     */
    fetch?: typeof globalThis.fetch;
}

/**
 * Umbra Interfaces — Client and signer interfaces — the core SDK configuration object.
 *
 * @module umbra/interfaces/client
 * @since 2.0.0
 */

/**
 * A transaction with blockhash lifetime constraint, ready for signing.
 *
 * This is the intersection of a base `Transaction` (containing `messageBytes`
 * and `signatures`) with `TransactionWithBlockhashLifetime` (containing the
 * `lifetimeConstraint` with blockhash and lastValidBlockHeight).
 *
 * @remarks
 * All Umbra transaction signing flows expect this type. Construct it by
 * fetching a recent blockhash and attaching it to a compiled transaction
 * via the `@solana/kit` utilities before passing to `IUmbraSigner.signTransaction`.
 *
 * @example
 * ```typescript
 * import { pipe } from "@solana/functional";
 * import { setTransactionMessageLifetimeUsingBlockhash } from "@solana/kit";
 *
 * const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
 * const signable: SignableTransaction = pipe(
 *   txMessage,
 *   (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
 *   (tx) => compileTransaction(tx),
 * );
 * ```
 *
 * @see {@link IUmbraSigner}
 * @public
 */
type SignableTransaction = Transaction & TransactionWithBlockhashLifetime;
/**
 * Result of signing an arbitrary message.
 *
 * Contains both the original message and its cryptographic signature,
 * allowing verification without needing to reconstruct the message.
 *
 * @remarks
 * Returned by {@link IUmbraSigner.signMessage}. All three fields are required
 * for off-chain signature verification.
 *
 * @example
 * ```typescript
 * const signed: SignedMessage = await signer.signMessage(
 *     new TextEncoder().encode("Hello, Umbra!")
 * );
 * console.log(signed.signer);    // base58 address
 * console.log(signed.signature); // 64-byte Ed25519 signature
 * ```
 *
 * @sealed
 * @see {@link IUmbraSigner}
 * @public
 */
interface SignedMessage {
    /**
     * The original message bytes that were signed.
     */
    readonly message: Uint8Array;
    /**
     * The Ed25519 signature over the message.
     *
     * This is a 64-byte signature that can be verified using the
     * signer's public key (address).
     */
    readonly signature: SignatureBytes;
    /**
     * The address of the signer who produced this signature.
     *
     * This can be used to verify the signature against the expected
     * signer's public key.
     */
    readonly signer: Address;
}
/**
 * Interface for signing Solana transactions and messages in the Umbra protocol.
 *
 * This interface abstracts the signing implementation, allowing different
 * backends such as:
 * - In-memory key pairs (for testing or non-sensitive operations)
 * - Hardware wallets (Ledger, Trezor)
 * - Mobile secure enclaves
 * - Browser wallet extensions
 * - Multi-party computation (MPC) signers
 *
 * ## Design Principles
 *
 * 1. **Partial Signing**: Methods return partially signed transactions,
 *    allowing for multi-signature workflows where multiple parties must sign.
 *
 * 2. **Signature Only**: The signer only signs transactions; it does not
 *    submit them to the network. This separation allows for:
 *    - Transaction inspection before submission
 *    - Batching multiple transactions
 *    - Custom submission strategies (retry logic, priority fees, etc.)
 *
 * 3. **Lifetime Preservation**: Transactions already contain their blockhash
 *    and lifetime constraints. The signer preserves this information.
 *
 * @example
 * ```typescript
 * import { IUmbraSigner, SignableTransaction } from '@umbra-privacy/sdk';
 *
 * // Example: Using a signer to sign a transaction
 * async function signAndInspect(
 *   signer: IUmbraSigner,
 *   transaction: SignableTransaction
 * ) {
 *   // Get the signer's address
 *   console.log(`Signing with: ${signer.address}`);
 *
 *   // Sign the transaction
 *   const signedTx = await signer.signTransaction(transaction);
 *
 *   // Transaction still has its lifetime info
 *   console.log(`Valid until block: ${signedTx.lifetimeConstraint.lastValidBlockHeight}`);
 *
 *   return signedTx;
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Example: Batch signing multiple transactions
 * async function batchSign(
 *   signer: IUmbraSigner,
 *   transactions: SignableTransaction[]
 * ) {
 *   // Sign all transactions in one call
 *   const signedTransactions = await signer.signTransactions(transactions);
 *
 *   // Each transaction is signed independently
 *   for (const tx of signedTransactions) {
 *     console.log(`Blockhash: ${tx.lifetimeConstraint.blockhash}`);
 *   }
 *
 *   return signedTransactions;
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Example: Signing an arbitrary message for off-chain verification
 * async function createSignedAttestation(
 *   signer: IUmbraSigner,
 *   data: string
 * ) {
 *   const message = new TextEncoder().encode(data);
 *   const signedMessage = await signer.signMessage(message);
 *
 *   return {
 *     data,
 *     signature: signedMessage.signature,
 *     signer: signedMessage.signer,
 *   };
 * }
 * ```
 *
 * @public
 */
interface IUmbraSigner {
    /**
     * The public address of this signer.
     *
     * This is the base58-encoded Ed25519 public key that corresponds to
     * the private key used for signing. It uniquely identifies this signer
     * on the Solana network.
     *
     * @remarks
     * The address is derived from the public key and serves as:
     * - The account owner for token accounts
     * - The fee payer identifier in transactions
     * - The key to look up signatures in signed transactions
     *
     * @example
     * ```typescript
     * const signer: IUmbraSigner = getUmbraSigner(config);
     * console.log(`Signer address: ${signer.address}`);
     * // Output: "8xH3kJLmV9..."
     * ```
     */
    readonly address: Address;
    /**
     * Signs a single transaction.
     *
     * Takes a compiled transaction with its blockhash lifetime already set
     * and returns the same transaction with the signer's signature added.
     *
     * @param transaction - The transaction to sign. Must include:
     *   - `messageBytes`: The serialized transaction message
     *   - `signatures`: Existing signatures map (may be empty)
     *   - `lifetimeConstraint`: Blockhash and last valid block height
     *
     * @returns A promise that resolves to the signed transaction with:
     *   - The signer's signature added to the `signatures` map
     *   - All other fields preserved unchanged
     *
     * @remarks
     * ## Partial Signing
     *
     * This method performs partial signing, meaning:
     * - Only adds a signature for this signer's address
     * - Does not validate that all required signatures are present
     * - The returned transaction may need additional signatures
     *
     * ## Error Conditions
     *
     * The method may throw if:
     * - The signer's address is not in the transaction's account list
     * - The underlying signing operation fails (hardware wallet disconnected, etc.)
     * - The user rejects the signing request (for interactive signers)
     *
     * @example
     * ```typescript
     * const transaction: SignableTransaction = buildShieldTransaction(...);
     *
     * // Sign the transaction
     * const signedTx = await signer.signTransaction(transaction);
     *
     * console.log('Transaction signed successfully');
     * ```
     */
    signTransaction: (transaction: SignableTransaction) => Promise<SignedTransaction>;
    /**
     * Signs multiple transactions in a batch.
     *
     * This method signs an array of transactions, returning them in the
     * same order with signatures added. Each transaction is signed
     * independently with its own blockhash lifetime preserved.
     *
     * @param transactions - Array of transactions to sign. Each must include
     *   the same fields as required by `signTransaction`.
     *
     * @returns A promise that resolves to an array of signed transactions,
     *   in the same order as the input array.
     *
     * @remarks
     * ## Batch Efficiency
     *
     * Implementations may optimize batch signing by:
     * - Reducing round-trips to hardware wallets
     * - Batching user approval prompts
     * - Parallelizing cryptographic operations
     *
     * ## Atomicity
     *
     * Batch signing is **not atomic**. If signing fails partway through:
     * - Some transactions may be signed, others not
     * - The method will throw, but partial results may not be recoverable
     * - Callers should handle failures by re-signing the entire batch
     *
     * ## Order Preservation
     *
     * The returned array maintains the same order as the input:
     * - `result[i]` is the signed version of `transactions[i]`
     * - Each transaction retains its original blockhash lifetime
     *
     * @example
     * ```typescript
     * const transactions: SignableTransaction[] = [
     *   buildShieldTransaction(mint1, amount1),
     *   buildShieldTransaction(mint2, amount2),
     *   buildShieldTransaction(mint3, amount3),
     * ];
     *
     * // Sign all transactions at once
     * const signedTransactions = await signer.signTransactions(transactions);
     *
     * // Submit each signed transaction
     * for (const tx of signedTransactions) {
     *   await submitTransaction(tx);
     * }
     * ```
     */
    signTransactions: (transactions: readonly SignableTransaction[]) => Promise<SignedTransaction[]>;
    /**
     * Signs an arbitrary message.
     *
     * This method signs a raw byte array using the signer's private key,
     * producing an Ed25519 signature. This is useful for:
     * - Off-chain message authentication
     * - Proving ownership of an address
     * - Creating verifiable attestations
     *
     * @param message - The raw bytes to sign. Can be any data, but common
     *   patterns include:
     *   - UTF-8 encoded strings
     *   - Structured data (JSON, protobuf, etc.)
     *   - Hash digests
     *
     * @returns A promise that resolves to a signed message containing:
     *   - The original message bytes
     *   - The 64-byte Ed25519 signature
     *   - The signer's address for verification
     *
     * @remarks
     * ## Message Prefixing
     *
     * Some signer implementations may prefix the message with a domain
     * separator (e.g., "\x19Solana Signed Message:\n") to prevent
     * signature reuse attacks. Verifiers must use the same prefix.
     *
     * ## Security Considerations
     *
     * - Never sign messages you don't understand
     * - Be cautious of messages that look like transaction data
     * - Consider using structured message formats with clear semantics
     *
     * @example
     * ```typescript
     * // Sign a simple text message
     * const message = new TextEncoder().encode('Hello, Umbra!');
     * const signedMessage = await signer.signMessage(message);
     *
     * // The signature can be verified off-chain
     * const isValid = await verifySignature(
     *   signedMessage.message,
     *   signedMessage.signature,
     *   signedMessage.signer
     * );
     * ```
     *
     * @example
     * ```typescript
     * // Sign structured data
     * const attestation = {
     *   action: 'verify_ownership',
     *   address: signer.address,
     *   timestamp: Date.now(),
     * };
     *
     * const message = new TextEncoder().encode(JSON.stringify(attestation));
     * const signedAttestation = await signer.signMessage(message);
     * ```
     */
    signMessage: (message: Uint8Array) => Promise<SignedMessage>;
}
/**
 * Function type for retrieving the master seed from secure storage.
 *
 * This function type is used to abstract the retrieval of the master seed,
 * which is the root cryptographic secret used to derive all keys in the
 * Umbra protocol (viewing keys, spending keys, encryption keys, etc.).
 *
 * @returns A `Promise` that resolves to the `MasterSeed` - a 64-byte
 *          Keccak-512 hash that serves as the root of the key hierarchy.
 *
 * @remarks
 * ## Why Use a Function?
 *
 * The master seed is stored in the device's secure storage (e.g., iOS Keychain,
 * Android Keystore, or platform-specific secure enclaves) rather than being
 * held in memory. Using a function to retrieve it provides several benefits:
 *
 * - **Lazy Loading**: The seed is only loaded into memory when needed
 * - **Security**: Minimizes the time sensitive data spends in application memory
 * - **Abstraction**: Allows different implementations for different platforms
 *   (mobile secure storage, hardware wallets, browser extensions, etc.)
 * - **Async Support**: Secure storage APIs are typically asynchronous
 *
 * ## Security Considerations
 *
 * - The master seed should NEVER be logged, transmitted, or stored in plain text
 * - Implementations should clear the seed from memory after use when possible
 * - Consider using secure memory handling techniques on supported platforms
 * - The seed should only be accessed when cryptographic operations are required
 *
 * @example
 * ```typescript
 * import { GetMasterSeedFunction } from '@umbra-privacy/sdk';
 * import * as SecureStore from 'expo-secure-store';
 *
 * // Example implementation using Expo SecureStore
 * const getMasterSeed: GetMasterSeedFunction = async () => {
 *   const seedHex = await SecureStore.getItemAsync('umbra_master_seed');
 *   if (!seedHex) {
 *     throw new Error('Master seed not found in secure storage');
 *   }
 *   return hexToBytes(seedHex) as MasterSeed;
 * };
 * ```
 *
 * @see {@link IUmbraClient}
 * @public
 */
type GetMasterSeedFunction = () => Promise<MasterSeed>;
/**
 * Configuration interface for the Umbra client.
 *
 * This interface defines the required configuration for initializing an Umbra
 * client instance. It includes network endpoints, the master seed retrieval
 * function, and other essential settings for interacting with the Umbra
 * privacy protocol on Solana.
 *
 * @remarks
 * ## Master Seed Function
 *
 * The `getMasterSeed` property is a function rather than a direct value because
 * the master seed is typically stored in the device's secure storage system:
 *
 * - **iOS**: Keychain Services
 * - **Android**: Android Keystore
 * - **Desktop**: OS-specific credential managers
 * - **Browser**: Web Crypto API or extension-based secure storage
 *
 * By using a function, we ensure:
 * 1. The seed is retrieved on-demand, not held in memory unnecessarily
 * 2. Each retrieval can include biometric/PIN verification if configured
 * 3. The implementation can vary across platforms without changing the interface
 *
 * ## Network Configuration
 *
 * The client requires both HTTP and WebSocket endpoints:
 * - `rpcUrl`: Used for sending transactions and querying account state
 * - `rpcSubscriptionsUrl`: Used for real-time account change notifications
 *
 * @example
 * ```typescript
 * import { IUmbraClient } from '@umbra-privacy/sdk';
 * import * as SecureStore from 'expo-secure-store';
 *
 * const config: IUmbraClient = {
 *   // Solana RPC endpoint for transactions and queries
 *   rpcUrl: 'https://api.mainnet-beta.solana.com',
 *
 *   // WebSocket endpoint for real-time subscriptions
 *   rpcSubscriptionsUrl: 'wss://api.mainnet-beta.solana.com',
 *
 *   // Function to retrieve master seed from secure storage
 *   // This is called on-demand when cryptographic operations are needed
 *   getMasterSeed: async () => {
 *     const seedHex = await SecureStore.getItemAsync('umbra_master_seed');
 *     if (!seedHex) {
 *       throw new Error('Master seed not found');
 *     }
 *     return hexToBytes(seedHex) as MasterSeed;
 *   },
 *
 *   // Optional: Commitment level for transactions
 *   commitment: 'confirmed',
 * };
 *
 * const client = createUmbraClient(config);
 * ```
 *
 * @example
 * ```typescript
 * // React Native with biometric protection
 * import * as LocalAuthentication from 'expo-local-authentication';
 *
 * const secureConfig: IUmbraClient = {
 *   rpcUrl: process.env.SOLANA_RPC_URL,
 *   rpcSubscriptionsUrl: process.env.SOLANA_WS_URL,
 *   getMasterSeed: async () => {
 *     // Require biometric authentication before accessing seed
 *     const authResult = await LocalAuthentication.authenticateAsync({
 *       promptMessage: 'Authenticate to access your private keys',
 *     });
 *
 *     if (!authResult.success) {
 *       throw new Error('Biometric authentication failed');
 *     }
 *
 *     const seedHex = await SecureStore.getItemAsync('umbra_master_seed');
 *     return hexToBytes(seedHex) as MasterSeed;
 *   },
 * };
 * ```
 *
 * @public
 */
interface IUmbraClient {
    /**
     * The signer used for signing transactions and messages.
     *
     * This signer is used for:
     * - Signing transactions during registration, shielding, unshielding
     * - Paying transaction fees (as the fee payer)
     * - Identifying the user's address for PDA derivation
     * - Generating the master seed (via signature-based derivation)
     *
     * The signer is stored when the client is created via `getUmbraClient`
     * and reused for all subsequent operations.
     */
    readonly signer: IUmbraSigner;
    /**
     * Network environment for the client.
     *
     * @remarks
     * - `'mainnet'`: Production network
     * - `'devnet'`: Development/testing network
     * - `'localnet'`: Local validator for development
     */
    readonly network: Network;
    /**
     * Network-specific configuration for the protocol deployment.
     *
     * Contains the program ID, MXE account address, MXE X25519 public key,
     * Arcium program address, and cluster offset for the current network.
     *
     * @remarks
     * Populated at client construction time from the SDK's per-network
     * config (see `packages/sdk/src/constants/networks.ts`). If the
     * network has not been configured, client construction will throw.
     */
    readonly networkConfig: NetworkConfig;
    /**
     * Version specifications for protocol, algorithm, and scheme.
     *
     * These version specifiers are used during key derivation to ensure
     * keys are derived with the correct versioning context.
     *
     * @remarks
     * Each specifier is a function that returns a version object with:
     * - `name`: The version identifier (e.g., "umbra", "kmac", "default")
     * - `version`: Semver string (e.g., "1.0.0")
     */
    readonly versions: {
        readonly protocol: ProtocolVersionSpecifierFunction;
        readonly algorithm: AlgorithmVersionSpecifierFunction;
        readonly scheme: SchemeVersionSpecifierFunction;
        readonly network: NetworkSpecifierFunction;
    };
    /**
     * U512 offsets for key derivation.
     *
     * Each offset is used in the domain separator during key derivation
     * to create distinct keys for different purposes.
     *
     * @remarks
     * - masterViewingKey: Offset for master viewing key derivation
     * - poseidonPrivateKey: Offset for Poseidon private key derivation
     * - x25519UserAccountPrivateKey: Offset for user account X25519 keypair (token registration)
     * - x25519MasterViewingKeyEncryptingPrivateKey: Offset for MVK-encrypting X25519 keypair (anonymous registration)
     * - mintX25519PrivateKey: Offset for per-mint X25519 keypair (reencrypt_shared operations)
     * - rescueCommitmentBlindingFactor: Offset for Rescue commitment blinding
     * - randomCommitmentFactor: Offset for random commitment factor
     *
     * Time-based keys (yearly/monthly/daily) and mint viewing keys do not
     * use offsets as they have parameters that provide sufficient separation.
     */
    readonly offsets: {
        readonly masterViewingKey: U512;
        readonly poseidonPrivateKey: U512;
        readonly x25519UserAccountPrivateKey: U512;
        readonly x25519MasterViewingKeyEncryptingPrivateKey: U512;
        readonly mintX25519PrivateKey: U512;
        readonly rescueCommitmentBlindingFactor: U512;
        readonly randomCommitmentFactor: U512;
    };
    /**
     * Pre-constructed Solana infrastructure dependencies.
     *
     * These dependencies are constructed by the client factory from URLs
     * or custom implementations provided in the factory options.
     */
    readonly accountInfoProvider: AccountInfoProviderFunction;
    readonly blockhashProvider: GetLatestBlockhash;
    readonly transactionForwarder: TransactionForwarder;
    readonly epochInfoProvider: GetEpochInfo;
    /**
     * Optional computation monitor for tracking Arcium MPC computation status.
     *
     * @remarks
     * When provided, enables monitoring of ComputationAccount status changes
     * (Queued → Finalized) after queue_computation transactions. Callers invoke
     * `computationMonitor.awaitComputation(address)` to wait for finalization.
     *
     * If not provided, callers must implement their own monitoring logic or
     * use fire-and-forget behavior (send the queue transaction and don't wait
     * for the callback).
     *
     * Constructed by the client factory from `rpcUrl` and `rpcSubscriptionsUrl`
     * using the WebSocket-based strategy by default. Can be overridden in
     * `GetUmbraClientDeps`.
     */
    readonly computationMonitor?: ComputationMonitor;
    /**
     * Optional indexer functions for UTXO discovery.
     *
     * Constructed by the client factory from indexerApiEndpoint URL
     * or custom implementations provided in the factory options.
     *
     * Required for fetching claimable UTXOs. The indexer maintains an off-chain
     * database of protocol state for efficient querying of UTXOs, Merkle proofs,
     * and nullifier status.
     *
     * @remarks
     * If not provided, UTXO discovery operations will not be available.
     */
    readonly fetchMerkleProof?: MerkleProofFetcherFunction;
    readonly fetchBatchMerkleProof?: BatchMerkleProofFetcherFunction;
    readonly fetchUtxoData?: UtxoDataFetcherFunction;
    /**
     * Master seed storage operations.
     *
     * The master seed is the root of all key derivation. These functions
     * control how the seed is loaded, stored, and generated.
     *
     * @remarks
     * - `load`: Attempts to load existing seed from storage
     * - `store`: Persists the seed to storage
     * - `generate`: Generates a new seed via signature-based derivation
     * - `getMasterSeed`: Convenience method combining load and generate
     */
    readonly masterSeed: {
        readonly load: MasterSeedLoaderFunction;
        readonly store: MasterSeedStorerFunction;
        readonly generate: MasterSeedGeneratorFunction;
        readonly getMasterSeed: () => Promise<MasterSeed>;
    };
    /**
     * Master viewing key storage operations.
     *
     * @remarks
     * The master viewing key is derived from the master seed and is used
     * to derive all other viewing keys in the hierarchy.
     */
    readonly masterViewingKey: {
        readonly load: LoaderFunction<MasterViewingKey>;
        readonly store: StorerFunction<MasterViewingKey>;
        readonly generate: GeneratorFunction<MasterViewingKey>;
    };
    /**
     * Poseidon private key storage operations.
     *
     * @remarks
     * Used for Poseidon hash-based cryptographic operations.
     */
    readonly poseidonPrivateKey: {
        readonly load: LoaderFunction<PoseidonKey>;
        readonly store: StorerFunction<PoseidonKey>;
        readonly generate: GeneratorFunction<PoseidonKey>;
    };
    /**
     * X25519 private key storage operations.
     *
     * @remarks
     * Used for elliptic curve Diffie-Hellman key exchange.
     */
    readonly x25519PrivateKey: {
        readonly load: LoaderFunction<X25519PrivateKey>;
        readonly store: StorerFunction<X25519PrivateKey>;
        readonly generate: GeneratorFunction<X25519PrivateKey>;
    };
    /**
     * Yearly viewing key storage operations.
     *
     * @remarks
     * Time-based viewing keys are parameterized by year.
     */
    readonly yearlyViewingKey: {
        readonly load: ParameterizedLoaderFunction<YearlyViewingKey, {
            year: Year;
        }>;
        readonly store: ParameterizedStorerFunction<YearlyViewingKey, {
            year: Year;
        }>;
        readonly generate: ParameterizedGeneratorFunction<YearlyViewingKey, {
            year: Year;
        }>;
    };
    /**
     * Monthly viewing key storage operations.
     *
     * @remarks
     * Time-based viewing keys are parameterized by year and month.
     */
    readonly monthlyViewingKey: {
        readonly load: ParameterizedLoaderFunction<MonthlyViewingKey, {
            year: Year;
            month: Month;
        }>;
        readonly store: ParameterizedStorerFunction<MonthlyViewingKey, {
            year: Year;
            month: Month;
        }>;
        readonly generate: ParameterizedGeneratorFunction<MonthlyViewingKey, {
            year: Year;
            month: Month;
        }>;
    };
    /**
     * Daily viewing key storage operations.
     *
     * @remarks
     * Time-based viewing keys are parameterized by year, month, and day.
     */
    readonly dailyViewingKey: {
        readonly load: ParameterizedLoaderFunction<DailyViewingKey, {
            year: Year;
            month: Month;
            day: Day;
        }>;
        readonly store: ParameterizedStorerFunction<DailyViewingKey, {
            year: Year;
            month: Month;
            day: Day;
        }>;
        readonly generate: ParameterizedGeneratorFunction<DailyViewingKey, {
            year: Year;
            month: Month;
            day: Day;
        }>;
    };
    /**
     * Mint viewing key storage operations.
     *
     * @remarks
     * Mint-specific viewing keys are parameterized by mint address.
     */
    readonly mintViewingKey: {
        readonly load: ParameterizedLoaderFunction<MintViewingKey, {
            mint: Address;
        }>;
        readonly store: ParameterizedStorerFunction<MintViewingKey, {
            mint: Address;
        }>;
        readonly generate: ParameterizedGeneratorFunction<MintViewingKey, {
            mint: Address;
        }>;
    };
    /**
     * Rescue commitment blinding factor storage operations.
     *
     * @remarks
     * Used for blinding Rescue-based commitments.
     */
    readonly rescueCommitmentBlindingFactor: {
        readonly load: LoaderFunction<Bn254FieldElement>;
        readonly store: StorerFunction<Bn254FieldElement>;
        readonly generate: GeneratorFunction<Bn254FieldElement>;
    };
    /**
     * Random commitment factor storage operations.
     *
     * @remarks
     * Used for randomness in commitment schemes.
     */
    readonly randomCommitmentFactor: {
        readonly load: LoaderFunction<Curve25519FieldElement>;
        readonly store: StorerFunction<Curve25519FieldElement>;
        readonly generate: GeneratorFunction<Curve25519FieldElement>;
    };
}

export { type MerkleProofData as $, type AccountInfoProviderFunction as A, type BatchMerkleProofFetcherFunction as B, type CreateSolanaRpcFunction as C, DEFAULT_MAX_SLOT_WINDOW as D, type PollingBasedComputationMonitorDeps as E, type PollingComputationMonitorOptions as F, type GetLatestBlockhash as G, type WebsocketBasedComputationMonitorDeps as H, type IUmbraSigner as I, getPollingComputationMonitor as J, getWebsocketComputationMonitor as K, type GetMasterSeedFunction as L, type MerkleProofFetcherFunction as M, type ClaimableUtxoResult as N, type DecryptedUtxoData as O, type PollingBasedComputationMonitorConfig as P, type EpochInfoResult as Q, type FireAndForget as R, type SendAndConfirmTransactionFactoryFunction as S, type TransactionForwarder as T, type UtxoDataFetcherFunction as U, type ForwardInParallel as V, type WebsocketBasedComputationMonitorConfig as W, type ForwardSequentially as X, type H1Components as Y, type IUmbraIndexer as Z, type LatestBlockhashResult as _, type GetEpochInfo as a, type ScannedUtxoResult as a0, type SignableTransaction as a1, type SignedMessage as a2, type TimestampComponents as a3, type UtxoDataItem as a4, type UtxoFetchResult as a5, type CreateSolanaRpcSubscriptionsFunction as b, type ComputationMonitor as c, type IUmbraClient as d, type GetMerkleProofFetcherArgs as e, type GetMerkleProofFetcherDeps as f, type GetUtxoDataFetcherArgs as g, type GetUtxoDataFetcherDeps as h, type ScannedUtxoData as i, type BatchMerkleProofResult as j, type ClaimableUtxoData as k, type GetClaimableUtxoScannerFunctionArgs as l, type GetClaimableUtxoScannerFunctionDeps as m, type ClaimableUtxoScannerFunction as n, type AesDecryptorFunction as o, type AesEncryptorFunction as p, type ComputationFinalizedResult as q, type ComputationFinalizedResultWithSignature as r, type ComputationMonitorOptions as s, type ComputationMonitorProgressEvent as t, type ComputationMonitorResult as u, type ComputationMonitorResultWithSignature as v, type ComputationPrunedResult as w, DEFAULT_POLLING_INTERVAL_MS as x, DEFAULT_SAFETY_TIMEOUT_MS as y, DEFAULT_SIGNATURE_RETRIEVAL_LIMIT as z };
