- Home
- Guides & Education
- Advanced Smart Contract Auditing Techniques: How to Detect Stale Balance Vulnerabilities Like the UniLend Exploit
Advanced Smart Contract Auditing Techniques: How to Detect Stale Balance Vulnerabilities Like the UniLend Exploit

The January 13, 2025 UniLend Finance exploit — a $197,000 flash loan attack caused by a stale balance vulnerability — provides an excellent case study for advanced smart contract auditing. While beginner-level auditing focuses on common patterns like reentrancy and integer overflow, the UniLend exploit demonstrates a subtler class of vulnerability: temporal state inconsistency. This tutorial walks through how to detect, analyze, and prevent these vulnerabilities using professional auditing techniques.
Table of Contents
The Objective
This guide aims to equip experienced smart contract developers and security researchers with a systematic methodology for identifying stale balance and stale state vulnerabilities in DeFi protocols. By the end, you will understand how to recognize the specific code patterns that enabled the UniLend exploit and how to apply formal verification techniques to prove their absence in your own contracts.
Prerequisites
This tutorial assumes familiarity with Solidity, DeFi lending protocol architecture, and basic security auditing concepts. You should understand how health factors work in lending protocols, how flash loans enable atomic transaction exploitation, and how ERC-20 token approvals function. Tools you will need include Foundry (for local testing), Slither (for static analysis), and access to Etherscan for transaction analysis. Understanding of the EVM execution model — particularly how storage slots are read and written within a single transaction — is essential.
Step-by-Step Walkthrough
Step 1: Understand the vulnerability pattern. The UniLend exploit centered on the checkHealthFactorLtv1 function, which called userBalanceOftoken0 to retrieve the pool's USDC balance for health factor calculation. The critical flaw: this function returned a cached or stale balance rather than querying the actual current state. When the attacker deposited 60 million USDC via flash loan, the health factor calculation used the pre-deposit balance, making the attacker's position appear healthier than it actually was.
To detect this pattern, examine every function in a lending protocol that makes financial decisions — liquidations, borrowings, redemptions — and trace the data flow for every variable used in the decision logic. If a balance is fetched from a variable that might not reflect the current state of the contract, you have found a potential stale balance vulnerability.
Step 2: Static analysis with Slither. Configure Slither to detect state variable reads that occur after external calls without re-reading. The pattern looks like this:
uint balance = pool.balanceOf(token); // first read
token.transferFrom(msg.sender, address(pool), amount); // state change
// pool.balanceOf(token) has now changed, but 'balance' still holds old value
require(collateral >= borrowAmount * ratio); // uses stale 'balance'
Run Slither with the --detect stale-storage flag and review any flagged instances. Note that Slelter may produce false positives — each flagged instance requires manual verification.
Step 3: Dynamic testing with Foundry. Create a Foundry test that replicates the UniLend attack pattern. Your test should: (1) deploy the protocol contracts, (2) fund a liquidity pool with initial assets, (3) execute a flash loan to deposit a large amount, (4) immediately attempt a redemption that should fail the health factor check, and (5) assert whether the redemption was correctly rejected. If the redemption succeeds, you have confirmed the stale balance vulnerability.
The key assertion: after the flash loan deposit, the health factor calculation must use the updated pool balance. If your Foundry test shows the redemption succeeding with stale balances, the vulnerability is confirmed.
Step 4: Formal verification with Halmos or Certora. For production protocols, formal verification provides mathematical proof that certain properties hold under all possible execution paths. Define an invariant: "For any redemption, the health factor must be calculated using the current pool balances after all preceding state changes in the same transaction." Use Halmos to symbolically execute the contract and verify this invariant holds for all possible transaction orderings.
The UniLend vulnerability would fail this invariant because the symbolic execution would find a path where the balance variable is read before the flash loan deposit is reflected, allowing a redemption that should have been rejected.
Step 5: Cross-reference with known attack patterns. The stale balance vulnerability is not unique to UniLend. Similar patterns have been exploited in bZx (2020), Cream Finance (2021), and several smaller protocols. Maintain a database of known exploit patterns and systematically check each new protocol against this database. The attack transaction hash for UniLend (0x44037ffc0993327176975e08789b71c1058318f48ddeff25890a577d6555b6ba) provides a concrete example to study.
Troubleshooting
False positives in Slither: Slither may flag legitimate caching patterns that are correctly invalidated. To distinguish real vulnerabilities from false positives, trace whether the cached value is invalidated after every state-changing external call. If invalidation is guaranteed, the flag is a false positive.
Foundry test gas optimization: Reproducing flash loan attacks in Foundry can consume significant gas. Use vm.prank and deal to set up balances directly rather than routing through actual flash loan providers. This simplifies the test without affecting the vulnerability detection logic.
Formal verification complexity: For complex DeFi protocols, formal verification may be intractable due to the number of possible execution paths. In these cases, focus verification efforts on the specific functions that make financial decisions — liquidation checks, health factor calculations, and withdrawal validations.
Mastering the Skill
Detecting stale balance vulnerabilities requires moving beyond pattern matching to developing a deep understanding of state transitions within smart contracts. Practice by auditing open-source DeFi protocols on GitHub — many have known vulnerabilities documented in their issue trackers that you can use as training data. Participate in Code4rena and Sherlock audit competitions to test your skills against real protocols with real bounties. The UniLend exploit, while relatively small at $197,000, demonstrates that this class of vulnerability can persist even in audited, live protocols — making it an essential skill for any serious smart contract auditor.
This article is for educational purposes only. Smart contract auditing is a complex discipline that requires extensive training and experience. Always engage professional auditors before deploying contracts that handle real funds.
25 Comments