/**
 * Diamond Hands SDK - Main Entry Point
 *
 * This is the primary SDK class that orchestrates all modules.
 * It provides a clean, high-level API for interacting with the Diamond Hands protocol.
 *
 * Architecture:
 * - Thin orchestrator (< 500 lines)
 * - Delegates to specialized modules
 * - No business logic (all in modules)
 * - Dependency injection pattern
 * - Result-based error handling
 */
import { Result } from "../types/result";
import { Satoshis } from "../types/branded/domain-values";
import { SDKError } from "../utils/error-handler";
import type { CreateLoanRequest, CreateLoanResult, LoanDataDetail, UCDMintRequest, UCDMintResult, PartialPaymentRequest, PartialPaymentResult, BTCWithdrawalResult, RenewPositionRequest, RenewPositionResult, LiquidationRequest, LiquidationResult, ConfirmBalanceRequest, ConfirmBalanceResult, TermsWithFeesResult } from "../interfaces/chunks/loan-operations.i";
import type { DiamondHandsSDKConfig } from "../interfaces/chunks/config.i";
import type { PKPData } from "../interfaces/chunks/pkp-integration.i";
import { ContractManager } from "./contract/contract-manager.module";
import { BitcoinOperations } from "./bitcoin/bitcoin-operations.module";
import type { SupportedStablecoinData } from "../graphs/diamond-hands";
type PositionDetailsView = {
    positionId: string;
    pkpId: string;
    ucdDebt: any;
    debt?: any;
    btcVault?: any;
    btcVaultBalance?: any;
    btcPrice?: any;
    [key: string]: any;
};
/**
 * Diamond Hands SDK
 *
 * Main SDK class providing high-level API for the Diamond Hands lending protocol.
 *
 * @example
 * ```typescript
 * const sdkResult = await DiamondHandsSDK.create({
 *   mode: 'service',
 *   serviceEndpoint: 'https://lit-ops.example.com',
 *   contractSigner: wallet,
 * });
 *
 * if (!sdkResult.success) {
 *   console.error('Failed to initialize SDK:', sdkResult.error);
 *   return;
 * }
 *
 * const sdk = sdkResult.value;
 *
 * // Create a loan
 * const result = await sdk.createLoan({ selectedTerm: 12 });
 * if (result.success) {
 *   console.log('Position created:', result.value.positionId);
 * }
 *
 * // Clean up when done
 * sdk.dispose();
 * ```
 */
export declare class DiamondHandsSDK {
    private readonly config;
    private readonly contractManager;
    private readonly cacheManager;
    private readonly litOps;
    private readonly pkpManager;
    private readonly loanCreator;
    private readonly loanQuery;
    private readonly bitcoinOperations;
    private readonly mockTokenManager?;
    private readonly graphClient;
    /**
     * Session helper for the lit-ops-server. Set in service mode; undefined
     * in standalone mode (no server to authenticate against). Use
     * `this.getAuthHeader()` which centralizes the undefined check.
     */
    private readonly serverSession?;
    private isInitialized;
    private isDisposed;
    /**
     * Audit H-13: per-position write serialization. Tracks positions with an
     * in-flight state-mutating call so a concurrent mint / payment / extend /
     * withdraw / liquidation for the same position fast-fails locally instead
     * of paying a full Lit-Action round-trip + gas only to revert on-chain
     * via the M-4 flash-loan protection's `lastInteractionBlockByPosition`
     * guard. Stored as a Set — no Promise needed since callers don't await
     * on each other; they get an immediate refusal and can retry once their
     * sibling call has completed.
     */
    private readonly inFlightWrites;
    /**
     * Acquire the per-position write lock. Returns `null` on success, or a
     * structured failure when another write is already in flight. The caller
     * must `cast` the failure to the method's specific result type — every
     * write-method result includes a `{ success: false; error: string }`
     * branch so the cast is safe.
     */
    private tryAcquireWriteLock;
    /** Release the per-position write lock. Safe to call when not held. */
    private releaseWriteLock;
    /**
     * Build the `Authorization: Bearer <jwt>` header for a request to
     * lit-ops-server. Returns an empty object in standalone mode (no server
     * to authenticate to) or when the session helper has not been wired —
     * in which case the server's `requireSessionToken` middleware will
     * reject the call with 401, which is the correct outcome.
     */
    private getAuthHeader;
    /**
     * Audit H-9: invalidate the LoanQuery cache so subsequent reads return
     * the post-write state. We clear the entire loan-query cache (not just
     * the entry for this position) because the cache keys by `pkpId` and we
     * don't always have it in scope at the release site — a position-keyed
     * helper would require a pre-write lookup that defeats the cache. The
     * blast radius is bounded: the cache is per-process and a fresh fetch
     * is cheap relative to a Lit Action call.
     *
     * `includePkpCache: true` is passed by liquidation to also drop the
     * 24-hour PKP-data cache entry — the Lit auth-context attached to a
     * PKP changes when ownership transfers, so the cached `ethAddress`
     * (used for capacity-credit delegation) must be re-derived.
     */
    private invalidateCachesForPosition;
    /**
     * Audit H-11: pre-flight check for `PositionManager.getProtocolPauseStatus()`.
     *
     * Returns `{ ok: true }` if none of the supplied pause keys are set, or
     * `{ ok: false, error }` if the protocol is paused for this operation
     * type. Caller returns the structured failure to the user before paying
     * for a LIT Action round-trip + gas that the on-chain function would
     * later revert.
     *
     * Best-effort: if no EVM provider is available (e.g., service-mode setup
     * without `ethRpcUrl`) or the read itself fails, we return `{ ok: true }`
     * with a debug log — the on-chain call remains the final authority.
     */
    private preflightProtocolPause;
    /**
     * Private constructor - use DiamondHandsSDK.create() instead
     *
     * @param config - SDK configuration
     */
    private constructor();
    /**
     * Create and initialize a new Diamond Hands SDK instance
     *
     * This is the recommended way to create an SDK instance. It validates the
     * configuration, initializes all modules, and verifies connectivity before
     * returning the SDK instance.
     *
     * @param config - SDK configuration (discriminated union based on mode)
     * @returns Result containing initialized SDK or error
     *
     * @example Service Mode
     * ```typescript
     * const result = await DiamondHandsSDK.create({
     *   mode: 'service',
     *   serviceEndpoint: 'https://lit-ops.example.com',
     *   contractSigner: wallet,
     * });
     * ```
     *
     * @example Standalone Mode
     * ```typescript
     * const result = await DiamondHandsSDK.create({
     *   mode: 'standalone',
     *   litOpsSigner: wallet,
     *   contractSigner: wallet,
     * });
     * ```
     */
    static create(config: DiamondHandsSDKConfig): Promise<Result<DiamondHandsSDK, SDKError>>;
    /**
     * Enrich configuration with network defaults from network-configs.ts
     *
     * If contractAddresses or subgraphs are not provided, attempt to load them
     * from the network configuration based on the detected chainId.
     */
    private static enrichConfigWithNetworkDefaults;
    /**
     * Initialize the SDK and verify it's ready for use
     *
     * This method:
     * 1. Marks the SDK as initialized
     * 2. Verifies network connectivity
     * 3. Validates contract addresses
     *
     * @returns Result indicating success or failure
     */
    private initialize;
    /**
     * Verify network connectivity and contract availability
     */
    private verifyConnection;
    /**
     * Dispose of the SDK and clean up resources
     *
     * This method:
     * - Clears all caches
     * - Removes event listeners
     * - Marks the SDK as disposed
     *
     * After calling dispose(), the SDK instance cannot be reused.
     */
    dispose(): void;
    /**
     * Check if SDK is ready for operations
     */
    private _relayNotification;
    private checkInitialized;
    private toSDKError;
    /**
     * Get SDK initialization state
     */
    get initialized(): boolean;
    /**
     * Get SDK disposal state
     */
    get disposed(): boolean;
    /**
     * Create a new loan
     *
     * Complete flow: PKP creation → address derivation → authorization → contract call
     *
     * @param request - Loan creation request
     * @returns Loan creation result with position ID and audit trail
     * @example
     * ```typescript
     * const result = await sdk.createLoan({
     *   collateralAmount: 25_000,
     *   collateralRatio: 150,
     *   selectedTerm: 3,
     * });
     * if (result.success) {
     *   console.log(result.value.positionId);
     * }
     * ```
     */
    createLoan(request: CreateLoanRequest): Promise<Result<CreateLoanResult, SDKError>>;
    /**
     * Request UCD minting against existing collateral
     * Performs LIT Action validation and calls contract
     *
     * @param request - Mint request with position ID and amount
     * @returns Mint result with transaction details
     * @example
     * ```typescript
     * const mint = await sdk.requestMintUCD({ positionId, amount: 100 });
     * if (!mint.success) {
     *   console.error(mint.error);
     * }
     * ```
     */
    requestMintUCD(request: UCDMintRequest): Promise<UCDMintResult>;
    /**
     * Request UCD minting using the SDK-wide `Result` contract.
     *
     * Use this in new integrations when you want a consistent error model that
     * avoids thrown exceptions for routine operation failures.
     *
     * @param request - Mint request with position ID and amount.
     * @returns `Result` containing mint transaction data or an `SDKError`.
     * @example
     * ```typescript
     * const result = await sdk.requestMintUCDResult({ positionId, amount: 100 });
     * if (!result.success) {
     *   console.error(result.error.code, result.error.message);
     *   return;
     * }
     * console.log(result.value.transactionHash);
     * ```
     */
    requestMintUCDResult(request: UCDMintRequest): Promise<Result<UCDMintResult, SDKError>>;
    private _requestMintUCDAttempt;
    /**
     * @notice Liquidate position using commit-reveal system with MEV protection
     * @dev Executes liquidation with randomized delay to prevent MEV attacks using LIQUIDATOR_ROLE.
     * On-chain liquidation burns the position debt in UCD from the liquidator via `UCDController`;
     * `UCDToken` (M-4) requires an allowance from the liquidator to UCDController. Before
     * `commitLiquidation`, the SDK checks UCD balance and allowance; if allowance is below debt
     * it submits `approve(ucdController, debt)` unless `request.skipUcdApproval` is true.
     * @param request - Liquidation request with position ID and options
     * @returns Liquidation result with transaction details
     * @example
     * ```typescript
     * const liq = await sdk.liquidatePosition({ positionId });
     * if (!liq.success) {
     *   console.error(liq.error);
     * }
     * ```
     */
    liquidatePosition(request: LiquidationRequest): Promise<LiquidationResult>;
    /**
     * Liquidate a position using the SDK-wide `Result` contract.
     *
     * @param request - Liquidation request payload.
     * @returns `Result` containing liquidation details or an `SDKError`.
     * @example
     * ```typescript
     * const result = await sdk.liquidatePositionResult({ positionId });
     * if (result.success) {
     *   console.log(result.value.transactionHash);
     * }
     * ```
     */
    liquidatePositionResult(request: LiquidationRequest): Promise<Result<LiquidationResult, SDKError>>;
    /**
     * Extend position term
     *
     * Follows main's security pattern: authorization → LIT validation → contract execution
     * Same pattern as makePayment: generate user auth, call lit-ops for LIT Action, then call contract.
     *
     * @param _positionId - Position identifier
     * @param _selectedTerm - Extension term in months
     * @returns Transaction receipt
     */
    private extendPosition;
    /**
     * Renew (extend) position with consistent response structure
     *
     * This method provides a consistent API for position renewal that returns
     * structured transaction details instead of raw TransactionReceipt.
     *
     * @param request - Renew position request with position ID and selected term
     * @returns Structured renewal result with transaction details
     * @example
     * ```typescript
     * const renewal = await sdk.renewPosition({ positionId, selectedTerm: 6 });
     * if (renewal.success) {
     *   console.log(renewal.transactionHash);
     * }
     * ```
     */
    renewPosition(request: RenewPositionRequest): Promise<RenewPositionResult>;
    /**
     * Renew a position using the SDK-wide `Result` contract.
     *
     * @param request - Renewal request with position and term.
     * @returns `Result` containing renewal details or an `SDKError`.
     * @example
     * ```typescript
     * const result = await sdk.renewPositionResult({ positionId, selectedTerm: 3 });
     * if (!result.success) {
     *   throw result.error;
     * }
     * ```
     */
    renewPositionResult(request: RenewPositionRequest): Promise<Result<RenewPositionResult, SDKError>>;
    /**
     * Confirm Bitcoin balance for a position
     *
     * This method:
     * 1. Queries BTC balance via LIT Action
     * 2. Gets PKP signature for the balance
     * 3. Calls PositionManager.updateBalance() on-chain
     * 4. Transitions position status to PENDING_MINT
     *
     * @param request - Confirm balance request with position ID
     * @returns Confirmation result with transaction details
     */
    confirmBalance(request: ConfirmBalanceRequest): Promise<ConfirmBalanceResult>;
    /**
     * Make a payment on a loan position
     *
     * Follows main's security pattern: authorization → LIT validation → contract execution
     *
     * @param request - Payment request with position ID and amount
     * @returns Payment result with transaction details
     */
    makePayment(request: PartialPaymentRequest): Promise<PartialPaymentResult>;
    /**
     * Withdraw Bitcoin from a position
     *
     * @param positionId - Position identifier
     * @param withdrawalAddress - Bitcoin address to send BTC to
     * @param withdrawalAmount - Amount to withdraw in satoshis (REQUIRED)
     * @param networkFee - Network fee for Bitcoin transaction in satoshis (REQUIRED)
     * @returns Withdrawal result with transaction details
     */
    /**
     * Withdraw BTC from position vault
     *
     * IMPORTANT: withdrawalAmount is the TOTAL DEDUCTION from vault.
     * The operator will deduct the actual network fee at execution time.
     * User receives: withdrawalAmount - actualNetworkFee
     *
     * @param positionId - Position identifier
     * @param withdrawalAddress - Bitcoin address to receive withdrawn funds
     * @param withdrawalAmount - Total amount to deduct from vault in satoshis (includes fee)
     * @param rpcUrl - Optional RPC URL override for LIT Action (for local testing)
     * @param customBitcoinRpcUrl - Optional custom Bitcoin RPC URL (for local testing)
     * @returns Withdrawal result with transaction details
     */
    withdrawBTC(positionId: string, withdrawalAddress: string, withdrawalAmount: number): Promise<BTCWithdrawalResult>;
    /**
     * Execute Bitcoin withdrawal (Phase 2)
     *
     * Signs and broadcasts the Bitcoin transaction for an authorized withdrawal.
     * User must have previously authorized the withdrawal via withdrawBTC().
     *
     * @param request - Execution request with positionId, utxoIdentifier, and networkFee
     * @returns Execution result with Bitcoin txid
     */
    executeBTCWithdrawal(request: {
        positionId: string;
        utxoIdentifier: string;
        utxoSatoshis: number;
        networkFee: number;
        destination: string;
        /**
         * User-authorized withdrawal amount in satoshis (Phase 1 `withdrawalAmount`).
         * Bound into the Phase-2 signature alongside `destination` so the Lit
         * Action can cross-check against the on-chain authorizer record.
         */
        targetAmount: number;
    }): Promise<{
        success: boolean;
        txid?: string;
        amountSent?: number;
        networkFee?: number;
        destination?: string;
        error?: string;
    }>;
    /**
     * Execute pending Bitcoin transfers
     *
     * Queries authorized spends that haven't been broadcast to Bitcoin network yet
     * and executes them by signing and broadcasting the transactions.
     *
     * @param positionId - Position identifier
     * @param networkFee - Network fee for Bitcoin transaction in satoshis
     * @param rpcUrl - Optional RPC URL override for LIT Action (for local testing)
     * @returns Array of execution results for each pending transfer
     */
    executePendingBtcTransfers(positionId: string, networkFee: number): Promise<Array<{
        success: boolean;
        utxoIdentifier?: string;
        txid?: string;
        amountSent?: number;
        networkFee?: number;
        destination?: string;
        error?: string;
    }>>;
    /**
     * Get pending BTC withdrawals for a position
     *
     * Returns all authorized spends recorded in BTCSpendAuthorizer that have not yet
     * been broadcast to the Bitcoin network. An empty array means no pending withdrawals.
     *
     * @param positionId - Position identifier
     * @returns Array of pending withdrawals, each including a pre-computed utxoKey for use with cancelPendingWithdrawal
     */
    getPendingWithdrawals(positionId: string): Promise<Array<{
        txid: string;
        vout: number;
        satoshis: number;
        targetAddress: string;
        targetAmount: number;
        authorizedAt: number;
        utxoKey: string;
    }>>;
    /**
     * Cancel a pending BTC withdrawal
     *
     * Removes a stale authorized spend from BTCSpendAuthorizer, unlocking the UTXO
     * and allowing the borrower to retry the withdrawal from scratch.
     * Only the position's borrower may call this — requires a connected signer.
     *
     * @param positionId - Position identifier
     * @param txid - Bitcoin UTXO transaction ID (from getPendingWithdrawals)
     * @param vout - Output index (from getPendingWithdrawals)
     * @returns Transaction hash of the cancellation EVM transaction
     */
    /**
     * Recover (clear) a stale BTC reservation via LIT-attested proof.
     *
     * Replaces the disabled borrower-callable cleanup path (`markSpentByOwner` /
     * `cancelStaleSpendByOwner`, both permanently revert with
     * `BorrowerBTCSpendMutationDisabled` as of audit #62210). The recovery is
     * permissionless on-chain — any caller with a valid LIT attestation can
     * invoke `BTCSpendAuthorizer.cancelStaleSpendWithProof`.
     *
     * Two-step flow:
     *   1. Call `staleSpendRecoveryValidator` LIT Action with `invalidatorTxid`.
     *      The action verifies on Bitcoin that the original authorized UTXO is
     *      provably consumed at depth ≥ 6 confirmations, and signs an
     *      EIP-712 `StaleSpendRecovery` attestation.
     *   2. Submit the attestation to `BTCSpendAuthorizer.cancelStaleSpendWithProof`
     *      on-chain. The contract enforces freshness
     *      (`MAX_ATTESTATION_AGE = 1 hour`) and replay-protects via
     *      `authorizedAt` binding.
     *
     * `invalidatorTxid` is either:
     *   - the borrower's own authorized broadcast (classified "consumed-as-authorized"
     *     by the LIT validator), once it has ≥6 confirmations on the BTC
     *     network — the natural post-withdrawal cleanup case; OR
     *   - a vault-to-vault self-spend (PKP-signed) that consumed the original
     *     UTXO before the authorized broadcast landed, classified "invalidated".
     *
     * @returns Transaction hash + classification on success, or error on failure.
     */
    recoverStaleSpend(params: {
        positionId: string;
        utxoTxid: string;
        utxoVout: number;
        invalidatorTxid: string;
        minConfirmations?: number;
        rpcUrl?: string;
    }): Promise<{
        success: boolean;
        transactionHash?: string;
        classification?: "invalidated" | "consumed-as-authorized";
        attestation?: {
            positionId: string;
            utxoKey: string;
            authorizedAt: string;
            invalidatorTxid: string;
            attestationTimestamp: number;
        };
        error?: string;
        failedStep?: "attestation" | "submit" | "config";
    }>;
    /**
     * Withdraw BTC and execute transfer (Complete Flow)
     *
     * Performs both Phase 1 (authorization) and Phase 2 (execution) in sequence:
     * 1. Authorizes withdrawal on contract (withdrawBTC)
     * 2. Executes pending Bitcoin transfers (signs and broadcasts)
     *
     * @param positionId - Position identifier
     * @param withdrawalAddress - Bitcoin address to receive withdrawn funds
     * @param withdrawalAmount - Total amount to deduct from vault in satoshis
     * @param networkFee - Network fee for Bitcoin transaction in satoshis
     * @param rpcUrl - Optional RPC URL override for LIT Action (for local testing)
     * @param customBitcoinRpcUrl - Optional custom Bitcoin RPC URL (for local testing)
     * @returns Complete withdrawal result with both authorization and execution details
     */
    withdrawBTCAndExecute(positionId: string, withdrawalAddress: string, withdrawalAmount: number, networkFee: number): Promise<{
        success: boolean;
        authorization?: BTCWithdrawalResult;
        transfers?: Array<{
            success: boolean;
            utxoIdentifier?: string;
            txid?: string;
            amountSent?: number;
            networkFee?: number;
            destination?: string;
            error?: string;
        }>;
        error?: string;
    }>;
    /**
     * Get loan data by position ID
     *
     * @param positionId - Position ID
     * @param enrichBalance - Whether to enrich with current Bitcoin balance
     * @returns Detailed loan data
     */
    getLoanById(positionId: string, enrichBalance?: boolean): Promise<Result<LoanDataDetail | null, SDKError>>;
    /**
     * Get loan data by PKP ID
     *
     * @param pkpId - PKP token ID
     * @param enrichBalance - Whether to enrich with current Bitcoin balance
     * @returns Loan data
     */
    getLoanByPkpId(pkpId: string, enrichBalance?: boolean): Promise<Result<LoanDataDetail | null, SDKError>>;
    /**
     * Get loans for a borrower
     *
     * @param borrower - Borrower address
     * @param pagination - Optional pagination parameters (page, pageSize)
     * @returns Paginated loans response with loans array, page info, and total count
     */
    getLoansByBorrower(borrower: string, pagination?: {
        page: number;
        pageSize: number;
    }, orderBy?: "createdAt" | "lastUpdatedAt" | "ucdDebt", orderDirection?: "asc" | "desc"): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
    /**
     * Get all active loans
     *
     * @param pagination - Optional pagination parameters (page, pageSize)
     * @returns Paginated loans response with loans array, page info, and total count
     */
    getActiveLoans(pagination?: {
        page: number;
        pageSize: number;
    }): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
    /**
     * Get loans by state/status
     *
     * @param state - Loan state (PENDING_DEPOSIT, ACTIVE, EXPIRED, REPAID, LIQUIDATED, EXTENDED, CLOSED)
     * @param pagination - Optional pagination parameters (page, pageSize)
     * @returns Paginated loans response with loans array, page info, and total count
     */
    getLoansByState(state: string, pagination?: {
        page: number;
        pageSize: number;
    }): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
    /**
     * Get all loans with pagination
     *
     * @param pagination - Pagination parameters (page, maxRows, orderBy, orderDirection)
     * @param enrichBalance - Whether to enrich loans with Bitcoin balance (not used currently)
     * @param source - Data source: "subgraph" (default) or "contract"
     * @returns Paginated loans response with loans array, page info, and total count
     */
    getLoansAll(pagination?: {
        page?: number;
        maxRows?: number;
        orderBy?: "createdAt" | "lastUpdatedAt" | "ucdDebt";
        orderDirection?: "asc" | "desc";
    }, source?: "subgraph" | "contract"): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
    /**
     * Get all events for a loan position from the subgraph
     */
    getLoanEvents(positionId: string, filter?: import("../types/event-types").LoanEventsFilter): Promise<Result<import("../types/event-types").LoanEvents, SDKError>>;
    /**
     * Get protocol-wide events across all indexed entity types.
     * Returns a merged, sorted discriminated-union timeline.
     * Narrow to a position with filter.positionId, or restrict event kinds with filter.kinds.
     */
    getAllEvents(filter?: import("../types/protocol-event-types").ProtocolEventsFilter): Promise<import("../types/protocol-event-types").ProtocolEventsResult>;
    /**
     * Return PSM-supported stablecoins from the subgraph, including indexed reserves,
     * fees, exchange rate, and volume stats.
     *
     * @param onlySupported - When true (default) filters to currently-supported coins only.
     */
    getPSMStablecoins(onlySupported?: boolean): Promise<SupportedStablecoinData[]>;
    /**
     * Return the live on-chain swap and redeem limits for a single stablecoin in the PSM.
     * All amounts are returned as bigint in the token's native decimals (stablecoin decimals
     * for swap limits, 18 decimals for redeem limits which are denominated in UCD).
     *
     * @param stablecoinAddress - EVM address of the stablecoin to query.
     */
    getPSMLimits(stablecoinAddress: string): Promise<{
        minSwapAmount: bigint;
        maxSwapAmount: bigint;
        minRedeemAmount: bigint;
        maxRedeemAmount: bigint;
    }>;
    /**
     * Return the live on-chain available reserve balance for a single stablecoin in the PSM.
     * Prefer this over the subgraph `reserves` field when freshness matters (e.g. pre-swap validation).
     *
     * @param stablecoinAddress - EVM address of the stablecoin to query.
     */
    getPSMAvailableReserves(stablecoinAddress: string): Promise<bigint>;
    /**
     * Wait for the subgraph to index up to (and including) the given block number.
     * Call after on-chain actions (createLoan, mintUCD, etc.) before querying the subgraph.
     *
     * @param targetBlock - Block number the subgraph must have indexed
     * @param options - Override timeout/interval for this call
     * @throws if timeout is reached before subgraph catches up
     */
    /**
     * Get Bitcoin balance for an address
     *
     * @param address - Bitcoin address
     * @returns Balance in satoshis
     */
    getBitcoinBalance(address: string): Promise<Result<import("./bitcoin/bitcoin-operations.module").EnrichedBitcoinBalance, SDKError>>;
    /**
     * Get the current Bitcoin price
     *
     * @returns the current Bitcoin price in USD
     */
    getBitcoinPrice(): Promise<{
        price: number;
        priceE8: string;
        timestamp: number;
        source: string;
        signature?: undefined;
        signer?: undefined;
    } | {
        price: number;
        priceE8: string;
        timestamp: number;
        source: string;
        signature: string | undefined;
        signer: string | undefined;
    }>;
    /**
     * Derive Bitcoin addresses from PKP public key
     *
     * @param publicKey - PKP public key
     * @returns Bitcoin addresses for all networks
     */
    deriveBitcoinAddresses(publicKey: string): Promise<Result<import("../interfaces/chunks/loan-operations.i").BitcoinAddresses, SDKError>>;
    /**
     * Get PKP data by token ID
     *
     * @param tokenId - PKP token ID
     * @returns PKP data
     */
    getPKPData(tokenId: string): Promise<Result<PKPData | null, SDKError>>;
    /**
     * Get PKP public key by token ID
     *
     * @param tokenId - PKP token ID
     * @returns PKP public key
     */
    getPKPPublicKey(tokenId: string): Promise<Result<string, SDKError>>;
    /**
     * Get all available loan terms with their fees
     *
     * Retrieves all valid loan terms from the TermManager contract along with
     * their origination fees and extension/renewal fees.
     *
     * @returns Result containing array of terms with fees
     *
     * @example
     * ```typescript
     * const result = await sdk.getTermsWithFees();
     * if (result.success) {
     *   result.value.terms.forEach(term => {
     *     console.log(`${term.termMonths} months: ${term.originationFeeBps}bps origination, ${term.extensionFeeBps}bps renewal`);
     *   });
     * }
     * ```
     */
    getTermsWithFees(): Promise<Result<TermsWithFeesResult, SDKError>>;
    getProtocolConfig(): Promise<Result<{
        liquidationThreshold: string;
        minimumLoanValueUcd: string;
        minimumLoanValueWei: string;
        maxSingleLoanValueUcd: string;
        maxSingleLoanValueWei: string;
    }, SDKError>>;
    getGasBalance(address: string): Promise<Result<{
        balanceWei: string;
        balanceEth: string;
    }, SDKError>>;
    getVaultBalance(positionId: string): Promise<Result<{
        vaultAddress: string;
        balanceSats: string;
        balanceBtc: string;
        btcPrice: string;
    }, SDKError>>;
    /**
     * Get a PKP-signed TOTAL confirmed Bitcoin balance for a raw vault ADDRESS
     * (no positionId) via the `btc-address-balance` LIT Action.
     *
     * Exercises the balance-query path (BitcoinProviderRegistry decrypt →
     * cross-provider consensus → PKP signature) using only an address. This is
     * NOT a protocol trusted/available balance: authorized spends are not
     * subtracted, and the returned signature is an `AddressBalanceAttestation`
     * (NOT a `BalanceConfirmation` — it is not consumable by
     * `PositionManager.updateBalance`).
     */
    getAddressBalance(vaultAddress: string): Promise<Result<{
        vaultAddress: string;
        totalBalanceSats: string;
        totalBalanceBtc: string;
        providerCount: number;
        signature: string;
        validatorPkp: string;
    }, SDKError>>;
    /**
     * Mint mock BTC tokens (test networks only)
     *
     * @param amount - Amount in satoshis
     * @param recipient - Recipient address
     * @returns Transaction result
     */
    mintMockBTC(amount: Satoshis, recipient: string): Promise<Result<import("./mock/mock-token-manager.module").MockTokenTransactionResult, SDKError>>;
    /**
     * Approve mock BTC spending (test networks only)
     *
     * @param spender - Spender address
     * @param amount - Amount in satoshis
     * @returns Transaction result
     */
    approveMockBTC(spender: string, amount: Satoshis): Promise<Result<import("./mock/mock-token-manager.module").MockTokenTransactionResult, SDKError>>;
    /**
     * Get SDK configuration
     */
    getConfig(): DiamondHandsSDKConfig;
    /**
     * Clear all caches
     */
    clearAllCaches(): void;
    /**
     * Get cache statistics
     */
    getCacheStats(): Record<string, import("./cache/cache-manager.module").CacheStats>;
    /**
     * Get contract manager (for advanced usage)
     */
    getContractManager(): ContractManager;
    /**
     * Get Bitcoin operations module (for advanced usage)
     */
    getBitcoinOperations(): BitcoinOperations;
    /**
     * Check if running on production network
     */
    private isProductionNetwork;
    /**
     * Get Bitcoin network based on chain.
     *
     * Priority order:
     *  1. explicit `bitcoinNetwork` config override
     *  2. first configured bitcoinProvider's `network` field — keeps provider
     *     config as the single source of truth (e.g. Sepolia EVM + regtest faucet)
     *  3. chain-name inference (mainnet/sepolia/other)
     */
    private getBitcoinNetwork;
    /**
     * Extract error message from LIT Action response
     * Checks both `error` and `reason` fields and parses nested error structures
     *
     * @private
     * @remarks Production-ready error parser for LIT Protocol responses
     *          Will be integrated into core methods in Round 2
     */
    private extractLitActionError;
    /**
     * Build the Chipotle service-mode fallback config for getPKPPublicKeyFromTokenId.
     * Returns undefined in standalone mode so the helper falls back to throwing.
     */
    private getChipotlePublicKeyFallback;
    /**
     * Get provider or throw error
     */
    private getProviderOrThrow;
    /**
     * Get signer or throw error
     */
    private getSignerOrThrow;
    /**
     * Get contract addresses or throw error
     */
    private getContractAddressesOrThrow;
    /**
     * Ensure SDK is initialized
     */
    private ensureInitialized;
    /**
     * Convert decimal position ID to bytes32 format
     */
    private toBytes32;
    /**
     * Check if an error indicates a technical failure vs business logic rejection
     */
    /**
     * Get position details view from contract
     * Queries PositionManagerCoreModule directly for reliability (subgraph listens to core module)
     */
    getPositionDetailsView(positionId: string): Promise<PositionDetailsView>;
    /**
     * Get position by ID (internal helper)
     * Uses getPositionDetailsView which queries core module directly
     */
    private getPosition;
    /**
     * Verify position exists in core contract (PositionManagerCoreModule)
     * This is critical because mint operations check the core contract, not PositionManager
     *
     * @param positionId - Position ID to verify
     * @param retries - Number of retries with exponential backoff (default: 3)
     * @param retryDelayMs - Initial retry delay in milliseconds (default: 1000)
     * @returns Promise<boolean> - true if position exists, false otherwise
     */
    verifyPositionExistsInCore(positionId: string, retries?: number, retryDelayMs?: number): Promise<boolean>;
    /**
     * Get loan operations accessor
     * Returns a helper object for interacting with loan operations contract
     */
    loanOps(): {
        getProtocolConfig(): Promise<{
            liquidationThreshold: any;
            minimumLoanValueUcd: string;
            minimumLoanValueWei: any;
            maxSingleLoanValueUcd: string;
            maxSingleLoanValueWei: string;
        }>;
    };
    /**
     * Calculate reveal delay for MEV protection in commit-reveal liquidation
     * @param positionId Position identifier (for entropy)
     * @param quantumTimestamp LIT quantum timestamp (for additional entropy)
     * @returns Delay in seconds before reveal phase can execute
     */
    private calculateRevealDelay;
    /**
     * Call the liquidation validator server endpoint to obtain a signed authorization
     * (signature + quantumTimestamp + btcPrice + btcAmountSats) for the current market state.
     * Invoked once at commit time and again at reveal time (H-7: reveal requires a fresh
     * signature so it cannot execute against a stale commit-time BTC vault snapshot).
     */
    private requestLiquidationAuthorization;
    /**
     * Calculate the exact reveal delay by replicating LiquidationManager._calculateRandomizedDelay.
     * Reads vrfSeeds[positionId] from the contract and applies the same two-step keccak256 formula.
     * Falls back to the local estimate if the contract read fails.
     */
    private calculateRevealDelayFromContract;
    /**
     * Wait for the specified delay period (MEV protection)
     * @param delaySeconds Number of seconds to wait
     */
    private waitForRevealDelay;
}
export {};
