How do you handle overdrafts if everything is an unsigned integer?
Last updated: May 7, 2025
Handling Overdrafts with Unsigned Integers in a Ledger System
When designing a financial ledger or transaction system, especially one that handles accounts and monetary values, a common question arises: How are overdrafts handled if everything is stored as an unsigned integer?
To address this question effectively, let's explore how the concept of unsigned integers interacts with account balances and transactions in the context of a system such as Formance's ledger. A key insight into this design is that although balances are often treated as unsigned integers, the system cleverly manages overdrafts by storing volumes, not balances, and applying specific rules when processing transactions.
Understanding the Basics: Volumes and Balances
📄 What's the difference between Volumes & Balances?
How Does This Solve the Overdraft Problem?
Overdrafts typically occur when an account tries to process a withdrawal that exceeds its available balance, leading to a negative balance. In traditional systems, an account balance might be allowed to go negative, resulting in an overdraft. In the Ledger, however, negative values cannot be directly represented. So, how do we handle such situations?
Monetaries in NumScript: In the context of Formance’s ledger, the system supports the concept of monetaries or numbers in its scripting language, NumScript. Technically, these monetaries can represent negative values, but using them in such a way will result in runtime errors. This prevents the system from directly handling negative amounts in transactions.
Transaction Inputs and Outputs: The core design is to manage overdrafts through the transaction system itself. Inputs and outputs are stored as unsigned integers, meaning the ledger internally ensures that any transaction represents positive amounts (or zero). If a transaction attempts to process more output than available input, the system will reject or fail the transaction, preventing overdrafts from occurring.
Practical Example: Preventing Overdrafts
Consider the following simplified example:
Account A has an input volume of 100 USD and output volume of 20 USD;
As a result, balance = input - output = 80 USDAccount A tries to send 150 units.
The ledger checks the input and output volumes. Since the input volume is 100, which is less than the output of 150, the system detects this as an overdraft attempt. Then the transaction fails, and the overdraft is prevented. Unless you force it to do so.