/** * Vault Balance Module - Super Module for Trusted Balance Calculation * * Combines Bitcoin network data with smart contract state to calculate * the "trusted balance" - the amount available for new authorizations. * * Formula: Available Balance = Total UTXOs - Authorized Spends * * This is the primary source of truth for determining if a new spending * authorization can be created for a given position. */ import { AuthorizedSpend, UTXO, VaultBalanceConfig, VaultBalanceResult } from "../interfaces/chunks/vault-balance.i"; import { IVaultBalance } from "../interfaces/chunks/vault-balance-module.i"; /** * Vault Balance Module * * This module is the "super module" that combines: * 1. Bitcoin network data (UTXOs from bitcoin-data-provider) * 2. Smart contract state (authorized spends from contract) * * To produce: Trusted Balance = Total - Authorized * * DESIGN NOTES: * * 1. Change Output Handling: * When a UTXO is spent, the change output will have a DIFFERENT txid. * This means we don't need special logic for change - it appears as a new UTXO. * The old UTXO (original deposit) will be gone from Bitcoin queries. * * 2. Authorization is Commitment: * Any UTXO in the AuthorizedSpend array is considered committed/consumed. * Once authorized, it's the user's responsibility to sign and broadcast. * If they don't, that's their problem - not the ecosystem's concern. * * 3. Security Model - Dual Source of Truth: * - Bitcoin Network: What UTXOs actually exist * - Smart Contract: What UTXOs are authorized to be spent * - Available Balance = Total UTXOs - Authorized UTXOs * * This prevents double-spending by ensuring the same UTXO cannot be * authorized twice. The contract's isAuthorizedSpend mapping enforces this. * * 4. Race Condition Protection: * The FAFO (First Actor Fails Others) model protects against concurrent * authorization attempts via state hash commitment in quantum time windows. * This module provides the trusted balance INPUT to that authorization process. * * 5. UTXO Matching: * We match authorized spends to UTXOs by (txid, vout) pair. * A UTXO is available if it exists in Bitcoin but NOT in authorized spends. * * 6. Edge Cases: * - UTXO authorized but not yet spent: Appears in Bitcoin, appears in contract * - UTXO spent: Doesn't appear in Bitcoin, may still appear in contract * - New deposit: Appears in Bitcoin, doesn't appear in contract * * 7. Confirmed-Only Gate (+ self-change carve-out): * A UTXO contributes to availableBalance only once it reaches * minConfirmations — a 0-conf third-party deposit is RBF-replaceable / * double-spendable and must never back a signed collateral figure. * EXCEPTION: unconfirmed "self-change" (change returned to the vault by a * transaction whose every input spends a confirmed, vault-owned output) * counts as confirmed-equivalent. Only the vault's PKP can sign such a * transaction, so no third party can replace it; excluding it would zero a * position's visible collateral for ~minConfirmations blocks after every * partial withdrawal and make healthy positions transiently liquidatable. * The self-change proof (parent tx inputs, prevout ownership, funding-tx * depth) is verified independently against EVERY registered provider and * requires unanimity; any disagreement or provider failure aborts the * calculation (fail-closed) so a single compromised provider can neither * inflate the balance (fabricated change) nor deflate it (suppressed * change enabling wrongful liquidation). * See docs/vault-balance-confirmed-gate-plan-2026-07-14.md §3.1. */ export declare class VaultBalanceModule implements IVaultBalance { private config; private bitcoinProvider; constructor(config: VaultBalanceConfig); /** * Calculate balance (arithmetic only - no UTXO validation) * * Balance-only calculation: Total Balance - Authorized Balance = Available. * * ⚠️ SECURITY (remediation P1/#5): this result skips UTXO validation, the * confirmed-consensus gate, and self-change proofing. It must NEVER feed a * signed BalanceConfirmation or any authorization decision. No production * action calls it (the `skipUTXOValidation` fast path that used to route * here was deleted); it exists for read-only diagnostics and tests. Adding * a production caller requires Master sign-off. * * @param positionId - The position ID to check * @param vaultAddress - Bitcoin address of the vault * @returns Complete breakdown of vault balance (with empty UTXO arrays) */ calculateBalance(positionId: string, vaultAddress: string): Promise; /** * Calculate trusted balance for a position (full validation) * * This is the main entry point for determining available balance with full validation. * * CRITICAL: Validates that all authorized spends have been properly broadcasted * to Bitcoin network with sufficient confirmations. Throws errors if: * 1. Authorized transaction not found on network (not broadcasted) * 2. Authorized transaction has insufficient confirmations (network updating) * * NOTE: the `skipUTXOValidation` fast path was removed (remediation P1/#5). * Every trusted-balance read runs full UTXO validation + consensus; a * balance that skipped validation must never feed a signed * BalanceConfirmation. * * @param positionId - The position ID to check * @param vaultAddress - Bitcoin address of the vault * @returns Complete breakdown of vault balance * @throws Error if authorized spends are in invalid state */ calculateTrustedBalance(positionId: string, vaultAddress: string): Promise; /** * Get just the trusted balance amount * * Convenience method when you only need the number. * * @param positionId - The position ID to check * @param vaultAddress - Bitcoin address of the vault * @returns Available balance in satoshis */ getTrustedBalance(positionId: string, vaultAddress: string): Promise; /** * Get available UTXOs that can be used for new authorizations * * This is useful when you need to select specific UTXOs for authorization. * * @param positionId - The position ID to check * @param vaultAddress - Bitcoin address of the vault * @returns Array of available UTXOs */ getAvailableUTXOs(positionId: string, vaultAddress: string): Promise; /** * Check if a specific UTXO is available for authorization * * @param positionId - The position ID to check * @param vaultAddress - Bitcoin address of the vault * @param txid - Transaction ID of the UTXO * @param vout - Output index of the UTXO * @returns True if UTXO is available, false otherwise */ isUTXOAvailable(positionId: string, vaultAddress: string, txid: string, vout: number): Promise; /** * Check if a UTXO is authorized (appears in authorized spends) * * @param utxo - The UTXO to check * @param authorizedSpends - List of authorized spends from contract * @returns True if UTXO is authorized, false otherwise */ private isUTXOAuthorized; /** * Query smart contract for authorized spends * * Calls the contract's getAuthorizedSpends(positionId) view function * to retrieve all authorized Bitcoin spends for this position. * * Contract struct AuthorizedSpend: * - txid: string * - vout: uint32 * - satoshis: uint256 * - authorizedAt: uint256 (timestamp) * * @param positionId - The position ID to query * @returns Array of authorized spends for this position */ protected getAuthorizedSpendsFromContract(positionId: string): Promise; /** * Compute authorized spends hash matching contract implementation * * CRITICAL: Must match LoanOperationsManager.getAuthorizedSpendsHash() * * Algorithm: * 1. For each AuthorizedSpend, hash all 6 fields: * - keccak256(txid string) * - vout (uint32) * - satoshis (uint256) * - keccak256(targetAddress string) * - targetAmount (uint256) * - authorizedAt (uint256 timestamp) * 2. Hash the array: keccak256(abi.encode(positionId, array of hashed spends)) * * @param positionId - Position identifier * @param authorizedSpends - Array of authorized spends * @returns bytes32 hash matching contract */ private computeAuthorizedSpendsHash; } /** * Factory function to create VaultBalanceModule instance * * @param config - Configuration for the module * @returns VaultBalanceModule instance */ export declare function createVaultBalanceModule(config: VaultBalanceConfig): VaultBalanceModule; /** * USAGE EXAMPLE: * * ```typescript * import { createVaultBalanceModule } from './vault-balance.module'; * import { BitcoinDataProvider } from './bitcoin-data-provider.module'; * * const bitcoinProvider = new BitcoinDataProvider({ * providerUrl: 'https://blockstream.info/testnet/api' * }); * * const vaultBalance = createVaultBalanceModule({ * contractAddress: '0x...', * chain: 'sepolia', * bitcoinProvider, * minConfirmations: 6 * }); * * // Get complete balance breakdown * const result = await vaultBalance.calculateTrustedBalance( * 'position123', * 'tb1q...' * ); * * console.log('Total Balance:', result.totalBalance, 'sats'); * console.log('Authorized Balance:', result.authorizedBalance, 'sats'); * console.log('Available Balance:', result.availableBalance, 'sats'); * * // Or just get the available amount * const available = await vaultBalance.getTrustedBalance('position123', 'tb1q...'); * console.log('Can authorize:', available, 'sats'); * ``` */ //# sourceMappingURL=vault-balance.module.d.ts.map