[web3] Belt Finance Logic Error Bug Fix Postmortem. This is a postmortem of a vulnerability… | by Immunefi | Sep, 2021 | Medium
A logic error in Belt Finance's strategy contract caused it to undercount its assets when tokens were sent directly to it, leading to excess shares being minted on deposit. An attacker could exploit this to withdraw more funds than deposited, potentially draining about $60 million.
medium.com
Published on medium.com
Belt Finance
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Belt Finance is a yield farming protocol on Binance Smart Chain. The bug described here sits in the strategy layer of the protocol, which is built from two components:
- a strategy token, which represents shares in the strategy (an interest bearing asset);
- a strategy contract, which manages withdrawals and deposits in the protocol.
Each strategy token represents a pro rata share of the assets deposited to the strategy contract. The strategy contract keeps two notions of value: wantLockedInHere, the balance of the contract that is not put to work generating yield, and balanceSnapshot, which represents the strategy's stake in the yield-generating asset. The total locked funds are the sum of the two. The withdraw path is supposed to send funds to the withdrawing user directly when wantLockedInHere is enough to satisfy the request, and only liquidate the yield-generating asset (updating balanceSnapshot accordingly) when it is not.
Setup
The report does not describe any accounts, roles, tooling or versions used by the researcher. The relevant code is the strategy implementation contract, StrategyAlpacaImpl.sol, at commit [redacted] in the BeltFi/belt-contract repository, line 166. The asset involved is BNB, and the token sent directly to the contract in the attack is wBNB. The attack involves calls to deposit, withdraw and earn and a direct transfer of wBNB to the strategy contract.
Finding it
The core of the vulnerability is in this excerpt of the strategy implementation contract:
if(_wantAmt > wantLockedInHere()) { _withdraw(_wantAmt.sub( wantLockedInHere() ));}balanceSnapshot = balanceSnapshot.sub(_wantAmt);
The withdraw function is supposed to send funds to the withdrawing user directly if the contract has enough wantLockedInHere to satisfy the request. Only if the request cannot be satisfied from wantLockedInHere are funds liquidated from the yield-generating asset and sent to the user. When funds are liquidated, balanceSnapshot needs to be updated to keep track of that liquidation. The bug is that balanceSnapshot is updated even when the contract had enough wantLockedInHere to satisfy the withdrawal without liquidating the yield-generating asset. This double counts the withdrawal: wantLockedInHere is decreased and balanceSnapshot (the yield-generating asset value) is decreased.
The purpose of _withdraw is to reduce the stake in the yield-generating asset, represented by balanceSnapshot. But if tokens are sent directly to the strategy contract, the if statement fails and _withdraw does not get called. The check on wantLockedTotal then returns a value that is too low, which is what the hacker wants. If a call to _withdraw does not happen, the strategy's stake in the yield-generating asset is not appropriately reduced and the attacker receives too many shares.
Exploitation
The attack is repeatable. The step by step guide is as follows.
Step 1: deposit
A malicious hacker calls deposit, sending BNB into the strategy token, which sends into the strategy contract, which then sends into the bank, and then the strategy token mints the hacker a pro rata share of the strategy. This is normal staking into the yield farm.
Step 2: send wBNB directly to the strategy contract
The hacker sends wBNB directly into the strategy contract, so as to cause the if(_wantAmt > wantLockedInHere()) check to fail. This step temporarily causes the hacker to lose money. No deposits are occurring; the hacker is simply sending tokens directly to the strategy contract. Sending wrapped BNB to the strategy contract is an unusual move and is not something that should happen under normal circumstances; it is done only to cause the check to fail.
Step 3: withdraw shares
The hacker withdraws shares. This step triggers the bug. As a result, the strategy does a double count of the withdrawal, and the strategy contract does not think it has as much BNB as it actually does.
Step 4: deposit again
When the hacker goes to deposit again, the strategy token performs an incorrect calculation based on that too-low balance and mints the hacker too many shares.
Step 5: call earn
When the hacker calls earn, the strategy contract overwrites its existing balanceSnapshot by asking the bank directly how much money the strategy contract has. This fixes the too-low balance calculation and makes future calculations return the correct result.
Step 6: withdraw everything
The hacker makes another call to withdraw, claiming the BNB represented by all the shares received in steps 1 and 4. The result is that the hacker has more money than they started with, because they were minted too many shares in step 4.
Root cause
The mistake is the unconditional update of balanceSnapshot after the conditional _withdraw call. The snapshot should only be updated when funds are liquidated from the yield-generating asset, but here it is updated even when wantLockedInHere alone covers the request. Because the snapshot is decremented anyway, the contract's apparent holdings fall below its actual holdings. The deposit calculation then mints shares against the understated total, and the attacker can gain a majority share of the yield farm without depositing a majority of the principal. Resetting balanceSnapshot to the correct value through earn restores accurate accounting, after which the inflated shares can be redeemed for a majority of the funds in the yield farm contract.
Impact
Approximately $60m in BNB was at risk, but the bug was never exploited. A single iteration of the attack could take approximately $10M, and the attack could be repeated until the entire contract was drained. The bug has since been patched.
Belt Finance paid out a bounty of $1,000,000 USDT. Binance Smart Chain's Priority One bounty matching program added $50,000 to the payout, making the total $1,050,000. This represents the largest single bounty Immunefi has ever paid out.
Fix
A patch was applied to Belt's contracts. In addition to fixing the bug described in this report, it makes several improvements to Belt's yield farms. The fixed version of the code is:
if(_wantAmt > wantLockedInHere()) { balanceSnapshot = balanceSnapshot.sub(_wantAmt.sub( wantLockedInHere() )); _withdraw(_wantAmt.sub( wantLockedInHere() ));}
The patch is in commit [redacted] of the BeltFi/belt-contract repository. Credits go to Alexander Schlindwein for finding the bug and Duncan Townsend, CTO of Immunefi, for developing a fix that the Belt team has used in production.
Variants to test
- Direct token transfers to a strategy or vault contract. Send the underlying token straight to the contract and observe whether any accounting variable (a snapshot, a cached balance, a total-assets figure) diverges from the real balance. A positive result is a share price or share mint calculation that no longer matches the contract's actual holdings.
- Withdraw paths with a conditional liquidation branch. Look for code where a cached balance is updated outside the branch that performs the liquidation. A positive result is a withdrawal that reduces the cached balance even though no liquidation occurred, which can be confirmed by comparing the cached value with a fresh on-chain balance query.
- Deposit after an accounting drift. After causing any understatement of total assets, deposit a small amount and check the number of shares minted. A positive result is more shares than the deposit's pro rata value warrants.
- Refresh functions such as
earn. Check whether a function that re-reads the true balance from the underlying source can be used to reset a manipulated cached value, which is what makes the inflated shares redeemable at full value. - Repeatability. Run the sequence more than once and check whether each iteration extracts value, which would allow draining the contract rather than a single capped loss.
What happened, in plain words
Belt Finance is a service that runs on a blockchain called Binance Smart Chain. People put cryptocurrency into it, and the service tries to earn them a little extra over time, a bit like putting money in a savings account that pays interest. On 10 August 2021, a security researcher named Alexander Schlindwein reported a serious mistake in the code that runs one part of Belt Finance. The mistake made one of Belt's contracts believe it held less money than it really did. Because of that wrong belief, the contract handed out too many "shares" to anyone who made a new deposit at the right moment. Those extra shares could then be cashed in for a much larger slice of the money in the contract than the person had actually put in. The trick could be repeated. About $60 million in BNB (a cryptocurrency) was exposed to this, but nobody used the flaw to steal anything before it was fixed.
Belt Finance paid the researcher a reward, called a bug bounty, of $1,000,000 USDT (another cryptocurrency). A programme run by Binance Smart Chain, called Priority One, added $50,000, bringing the total to $1,050,000. At the time this was the largest single bounty Immunefi had ever paid out.

The image above is the header of the published review, titled "Belt Finance Logic Error Bugfix Review, Largest Ever Bounty Payout".
Before going further, a few words need explaining, because the rest of this article depends on them.
- A blockchain is a shared record book that many computers keep copies of. Once something is written into it, changing it is very hard. Binance Smart Chain is one such blockchain.
- A smart contract is a small program that lives on the blockchain. It runs automatically when someone sends it a request, and nobody can switch it off or edit it after it is deployed. Think of it as a vending machine: you put something in, it follows its built-in rules, and it gives something back.
- A token is a digital unit of value recorded on the blockchain. BNB is the main token of Binance Smart Chain. wBNB ("wrapped BNB") is a version of BNB that behaves like a standard token so that contracts can handle it more easily. USDT is a token designed to be worth about one US dollar.
- A function is a named action a smart contract offers, such as
deposit(put money in),withdraw(take money out) orearn(go and collect the interest). Anyone can call these functions by sending a transaction to the contract. - A bug bounty is a reward a company offers to anyone who finds a security problem and reports it privately instead of abusing it.
The two pieces of Belt Finance involved
Belt Finance has a part called a strategy. You can picture it as a small fund inside the larger service. The strategy is built from two pieces:
- A strategy token. This is like a receipt, or a share certificate. If you deposit into the strategy, you receive strategy tokens. Each one represents a pro rata share of everything deposited in the strategy contract. "Pro rata" means "in proportion": if you own 10% of all the shares, you are entitled to 10% of the money in the pot.
- A strategy contract. This is the program that actually holds the money and handles deposits and withdrawals.
The strategy contract keeps track of value in two separate ways:
wantLockedInHere: the amount of the token sitting idle in the contract, not currently lent out to earn interest. "Want" is just the name Belt gives to the token it works with.balanceSnapshot: a saved number representing how much the strategy has lent out to the interest-earning side (called the "yield-generating asset").
The total locked funds are simply the sum of those two numbers: the idle money plus the lent-out money.
When someone withdraws, the contract is supposed to behave like this: if there is enough idle money (wantLockedInHere) to pay the person straight away, just pay them from that. Only if the idle money is not enough should the contract go and pull money back from the interest-earning side, and when it does that, it must lower balanceSnapshot to record that less money is now lent out.
Finding the mistake
The heart of the problem is in a short piece of the strategy contract's code. Here it is exactly as it appears in the report:
if(_wantAmt > wantLockedInHere()) { _withdraw(_wantAmt.sub( wantLockedInHere() ));}balanceSnapshot = balanceSnapshot.sub(_wantAmt);
Line by line, in plain words:
if(_wantAmt > wantLockedInHere())asks a question: is the amount being withdrawn (_wantAmt) larger than the idle money available (wantLockedInHere())?- If the answer is yes, the contract runs
_withdraw(_wantAmt.sub(wantLockedInHere())).submeans subtract, so this pulls back from the interest-earning side only the shortfall, the part the idle money could not cover. - Then, outside the
ifblock, the last line runs every time, whether or not theifwas true:balanceSnapshot = balanceSnapshot.sub(_wantAmt);. This lowers the saved record of lent-out money by the full withdrawal amount.
That last line is the bug. The saved record of lent-out money should only go down when money is actually pulled back from the interest-earning side. But here it goes down on every withdrawal, even when the idle money alone was enough and nothing was pulled back. The report calls this a double count: the idle money goes down and the lent-out record goes down, so the contract subtracts the same withdrawal twice from its sense of its own wealth.
To see why that matters, imagine a wallet that holds £100 in cash and has £900 in a savings account, so it believes it has £1,000. You take out £100 from the cash. Correctly, the wallet now has £0 cash and £900 saved, still £1,000 in total. The buggy version would also write down the savings by £100, so the wallet now believes it has £0 cash and £800 saved, only £800 in total, even though the real money is still £900 in savings. The wallet has undercounted itself.
There is a second ingredient. The if check depends on wantLockedInHere(), the idle balance. If someone sends tokens directly to the contract, bypassing the normal deposit function, that idle balance goes up in a way the contract's own bookkeeping does not expect. The if check then fails, _withdraw is never called, and yet the last line still lowers balanceSnapshot. The strategy's recorded stake in the interest-earning side is reduced without anything actually being pulled back. The contract's apparent total falls below its real total.
Why would an attacker want the contract to think it is poorer than it is? Because of how shares are priced. When you deposit, the contract works out how many shares to give you based on the total it believes it holds. If that total is artificially low, each deposit buys more shares than it should. A lower apparent total means more shares minted for the same money, which is exactly what an attacker wants.
How the attack would work, step by step
The attack is repeatable, meaning it can be run again and again. Here is the sequence from the report.
Step 1: deposit
The attacker calls deposit, sending BNB into the strategy token. The strategy token passes it to the strategy contract, which passes it on to the bank (the place that pays interest), and the strategy token mints the attacker a pro rata share of the strategy. This is completely normal: it is just ordinary staking into the yield farm.
Step 2: send wBNB directly to the strategy contract
The attacker sends wBNB directly to the strategy contract, not through deposit. The purpose is to make the if(_wantAmt > wantLockedInHere()) check fail during the next withdrawal. This step temporarily costs the attacker money, because the tokens are simply handed over and no shares are minted in return. The report stresses that this is unusual behaviour: sending wrapped BNB straight to the strategy contract is not something that should happen in normal use, and it is done only to make that check fail.
Step 3: withdraw shares
The attacker calls withdraw. This is the step that triggers the bug. Because of the direct transfer in step 2, the if check fails, _withdraw is not called, but balanceSnapshot is still reduced. The strategy double counts the withdrawal, and the contract now believes it holds less BNB than it really does.
Step 4: deposit again
With the contract believing it is poorer than it is, the attacker calls deposit again. The strategy token calculates shares from that too-low total and mints the attacker too many shares for the money deposited.
Step 5: call earn
The attacker calls earn. This function makes the strategy contract overwrite its saved balanceSnapshot by asking the bank directly how much money the strategy contract actually has. That resets the figure to the truth and makes future calculations correct again.
Step 6: withdraw everything
The attacker calls withdraw once more, this time claiming the BNB represented by all the shares received in steps 1 and 4. Because step 4 handed out too many shares, the attacker ends up with more money than they started with.
The root cause, restated
The mistake is that balanceSnapshot is updated unconditionally, outside the if block, after the conditional _withdraw call. The withdraw logic assumes every withdrawal reduces the strategy's stake in the interest-earning side, but when the idle money alone covers the request, nothing is pulled back and the snapshot should not move. Because it is lowered anyway, the contract's apparent holdings drop below its real holdings. The deposit calculation then mints shares against that understated total, letting an attacker gain a majority share of the yield farm without depositing a majority of the principal. Calling earn resets the snapshot to the correct value, after which the inflated shares can be redeemed for a majority of the funds.
Impact
About $60 million in BNB was at risk, but the flaw was never exploited. A single run of the attack could take roughly $10 million, and it could be repeated until the whole contract was drained. The bug has since been patched.
Belt Finance paid a bounty of $1,000,000 USDT. Binance Smart Chain's Priority One bounty matching programme added $50,000, making the total $1,050,000, the largest single bounty Immunefi had paid out at that point.
The fix
A patch was applied to Belt's contracts. Besides fixing this bug, it makes several improvements to Belt's yield farms. Here is the fixed code, exactly as given in the report:
if(_wantAmt > wantLockedInHere()) { balanceSnapshot = balanceSnapshot.sub(_wantAmt.sub( wantLockedInHere() )); _withdraw(_wantAmt.sub( wantLockedInHere() ));}
Line by line:
if(_wantAmt > wantLockedInHere())still asks whether the withdrawal is larger than the idle money.- Inside the block,
balanceSnapshot = balanceSnapshot.sub(_wantAmt.sub(wantLockedInHere()));now lowers the saved record only by the shortfall, the amount that actually has to be pulled back from the interest-earning side. If the idle money covers everything, the shortfall is zero and the snapshot does not move. _withdraw(_wantAmt.sub(wantLockedInHere()));then pulls back exactly that shortfall.
The key change is that the snapshot update now sits inside the branch where money is really liquidated, and it is reduced only by the amount liquidated. The patch is in commit [redacted] of the BeltFi/belt-contract repository. Credit goes to Alexander Schlindwein for finding the bug and to Duncan Townsend, CTO of Immunefi, for developing the fix that the Belt team put into production.
Similar things to look for
These are patterns a security researcher can check for in other projects:
- Direct token transfers to a strategy or vault contract. Send the underlying token straight to the contract and watch whether any saved accounting number (a snapshot, a cached balance, a total-assets figure) drifts away from the real balance. A positive sign is a share price or share-mint calculation that no longer matches what the contract actually holds.
- Withdraw paths with a conditional liquidation branch. Look for code where a cached balance is updated outside the branch that does the liquidation. A positive sign is a withdrawal that lowers the cached balance even though nothing was liquidated, which you can confirm by comparing the cached value with a fresh on-chain balance query.
- Deposit after an accounting drift. After causing any understatement of total assets, deposit a small amount and check how many shares are minted. A positive sign is more shares than the deposit's pro rata value deserves.
- Refresh functions such as
earn. Check whether a function that re-reads the true balance from the underlying source can be used to reset a manipulated cached value, which is what makes inflated shares redeemable at full value. - Repeatability. Run the sequence more than once and check whether each run extracts value, which would allow draining the contract rather than a single capped loss.
Glossary
- Blockchain: a shared, tamper-resistant record book kept by many computers at once.
- Smart contract: a program stored on a blockchain that runs automatically when called and cannot be edited after deployment.
- Token: a digital unit of value recorded on a blockchain.
- BNB: the main cryptocurrency token of Binance Smart Chain.
- wBNB (wrapped BNB): a version of BNB that behaves like a standard token so contracts can handle it easily.
- USDT: a cryptocurrency token designed to be worth about one US dollar.
- Binance Smart Chain: the blockchain on which Belt Finance runs.
- Belt Finance: a yield farming service on Binance Smart Chain.
- Yield farming: putting cryptocurrency into a service so it can be lent out or invested to earn interest.
- Strategy: a part of Belt Finance that manages deposits and withdrawals and earns interest on them.
- Strategy token: a token representing a share of the money in the strategy contract.
- Strategy contract: the smart contract that holds the strategy's money and handles deposits and withdrawals.
- Pro rata: in proportion, so that owning a given percentage of shares entitles you to the same percentage of the pot.
- Function: a named action a smart contract offers, such as
deposit,withdraworearn. deposit: the function that puts money in and mints shares.withdraw: the function that takes money out.earn: the function that re-reads the true balance from the bank and resets the saved snapshot.wantLockedInHere: the amount of the token sitting idle in the contract, not lent out.balanceSnapshot: a saved number representing how much the strategy has lent out to the interest-earning side.- Total locked funds: the sum of
wantLockedInHereandbalanceSnapshot. - Yield-generating asset: the place the strategy lends money to in order to earn interest, referred to as the bank in the report.
- Liquidate (in this context): pull money back from the interest-earning side so it can be paid out.
- Double count: subtracting the same withdrawal twice from the contract's sense of its own wealth.
- Logic error: a bug where the code does what it was written to do, but the written logic is wrong.
- Bug bounty: a reward a company offers to anyone who finds and privately reports a security problem.
- Immunefi: the bug bounty platform that published this review and handled the report.
- Priority One: Binance Smart Chain's bounty matching programme, which added $50,000 to the payout.
- Commit: a saved snapshot of a code repository at a particular point in its history, identified by a long code.
- Patch: a change to code that fixes a bug.