calculate

fun calculate(events: List<LedgerEvent>, walletAddress: String): Balance

Calculate balance for a specific address from ledger events.

CRITICAL: This method validates event ordering and detects balance underflow. Negative balance indicates double-spend or corrupted event stream.

Event Ordering:

  • Events MUST be processed in ascending ID order (chronological)

  • Out-of-order events can cause incorrect balance calculation

  • Method sorts by ID to ensure correctness

Balance Underflow Detection:

  • If balance goes negative, throws BalanceUnderflowException

  • Indicates double-spend attack or corrupted blockchain state

  • Wallet MUST stop processing and alert user

Future: UTXO Tracking

  • Currently assumes account model (balance-based)

  • Midnight uses UTXO model (output-based)

  • Need to track spent/unspent outputs for proper validation

Return

Balance for this address

Parameters

events

List of deserialized ledger events (will be sorted by ID)

walletAddress

Wallet address to calculate balance for

Throws

if balance would go negative