[web3] Unprotected Swap Function: A ERC777 Reentrancy Vulnerability. Introduction | by Heuss | Jun, 2023 | Medium
The swap function in a bridge/DEX updated internal balances only after calling safeTransferFrom on the input token, so an ERC777 token's transfer hook let an attacker re-enter swap before the first call finished. The attacker could then swap a larger amount than they actually paid, inflating their balance at the protocol's expense.
medium.com
Published on medium.com
Smart Contract Security
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
The target is a bridge/DEX pool contract that exposes a swap() function. The function takes a token pair, an input amount dx, a minimum output minDy and a deadline, and swaps one coin for another. The pool keeps its own accounting in a balances mapping, separate from the actual token balances held by the contract, and it measures how much was really received by comparing the contract's token balance before and after the transfer.
The article describes a reentrancy vulnerability in that function that can lead to unauthorised balance inflation. The author notes that this was their very first finding when starting bug hunting, a year before writing.
Setup
The only precondition the article states is the token type: the bug is only true for ERC777 tokens. ERC777 tokens call a hook on the sender (and recipient) during a transfer, and that callback is what makes reentrancy possible. No specific deployment, chain, tooling or account setup is described.
Finding it
The swap() implementation shows the order of operations: the contract calls safeTransferFrom() on the input token before it updates its internal balances mapping. With an ERC777 token, that transfer invokes the _callTokensToSend() hook on the sender, which means attacker-controlled code runs while the pool's accounting still reflects the pre-swap state. That gap is what allows the function to be re-entered.
Exploitation
The vulnerable function, as shown in the article:
function swap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline) external ensure(deadline) returns (uint256) { require(dx <= coins[tokenIndexFrom].balanceOf(msg.sender), "O3SwapPool: INSUFFICIENT_BALANCE"); uint256 balanceBefore = coins[tokenIndexFrom].balanceOf(address(this)); coins[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 transferredDx = coins[tokenIndexFrom].balanceOf(address(this)) - balanceBefore; (uint256 dy, uint256 dyFee) = _calculateSwap(tokenIndexFrom, tokenIndexTo, transferredDx); require(dy >= minDy, "O3SwapPool: INSUFFICIENT_OUTPUT_AMOUNT"); uint256 dyAdminFee = dyFee * adminFee / FEE_DENOMINATOR / tokenPrecisionMultipliers[tokenIndexTo]; balances[tokenIndexFrom] += transferredDx; balances[tokenIndexTo] -= dy + dyAdminFee; coins[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo); return dy; }
The important parts of this code, in order:
require(dx <= coins[tokenIndexFrom].balanceOf(msg.sender), ...)checks the caller holds at leastdxof the input token.balanceBeforerecords the pool's balance of the input token.safeTransferFrom(msg.sender, address(this), dx)pulls the tokens in. For an ERC777 token this is where the sender hook fires.transferredDxis computed as the difference between the pool's balance after the transfer andbalanceBefore._calculateSwapderives the outputdyand feedyFeefromtransferredDx, anddy >= minDyis enforced.- Only then are
balances[tokenIndexFrom]andbalances[tokenIndexTo]updated, and the output token sent to the caller.
The risk breakdown given in the article:
- The attacker initiates a swap with the minimum amount (
dx). - Before the
safetransferfrom()function is executed, the attacker's code exploits the_callTokensToSend()hook in the ERC777 token. - This re-entrancy allows the attacker to re-enter the
swap()function, this time with a largerdxvalue. - The transaction concludes the second swap, inflating the ending balance.
- The attacker successfully swaps a larger amount of tokens while only using the minimal amount authorised in the first transaction.
Step by step scenario
The article gives a quick conceptual scenario:
- Initiate swap with
dx = 1. - Re-enter swap with
dx = 1000using tokensToSend (an ERC777) hook. - Complete second swap, inflating the ending balance.
- Successfully swap a larger amount of tokens in the first swap, while using minimal amount authorised initially.
The mechanism is that the hook runs inside safeTransferFrom(), before the pool has updated balances. The re-entrant call therefore executes against accounting that has not yet been changed by the outer swap, and the attacker uses the callback to drive a second swap with a much larger dx than the amount they actually committed to in the first call.
Root cause
The mistake is the ordering of state updates relative to the external call. The pool performs an external token transfer (safeTransferFrom) before it writes the new values into balances, so control passes to attacker code while the contract's accounting is still stale. ERC777 makes this reachable because the token itself invokes a sender hook during the transfer. The ensure(deadline) modifier and the dx <= balanceOf(msg.sender) check do not prevent re-entry, and the article does not describe any reentrancy guard on the function.
Impact
By exploiting the callback, an attacker could artificially inflate their balance and manipulate the outcome of the swap. Consequently, the attacker could swap tokens for a larger amount than they initially provided, leading to financial gains at the expense of the protocol and other users. The article stresses that this bug is only true for ERC777 tokens.
Fix
To mitigate the vulnerability, the article says it is essential to add a reentrancy guard to the swap() function. It also advises following good practice by including proper checks and locks to prevent multiple re-entrances within a single transaction, and by checking that the final balance corresponds to the expected balance. The article does not say whether any of this was applied to the target.
Variants to test
The author notes that this class of bug is classic and that the chances of finding one in a project listed on Immunefi are now rather low, but it is still worth keeping in mind while auditing contracts. The concrete advice: if the project accepts all tokens, check how the functions react to the different types of existing tokens. The article links a short list of tokens with "weird" behaviour:
https://github.com/d-xo/weird-erc20#revert-on-zero-value-transfers
The article advises checking how functions react to the different types of existing tokens if the project accepts all tokens.
What happened, in plain words
A security researcher found a bug in a smart contract that lets people swap one cryptocurrency token for another. The bug meant that someone could trick the contract into giving them more tokens than they actually paid in. The researcher describes it as their very first finding when they started looking for bugs, about a year before writing the article.
To follow the rest of this article you only need to understand a few ideas. A smart contract is a small program that lives on a blockchain (a shared, public record of transactions). Once deployed, it runs exactly as written, and anyone can send it instructions. A token is a digital asset managed by such a contract. A DEX (decentralised exchange) is a service that lets people trade one token for another without a middleman. A bridge moves tokens between different blockchains. The contract in this article is a pool used by a bridge/DEX: people put tokens in, and the pool swaps them.
The bug is a reentrancy vulnerability. The everyday comparison: imagine you are at a till paying for something, and while the cashier is still counting your money, you jump back into the queue and start a second, much bigger purchase before the first one has been recorded. Because the till has not yet written down your first payment, it gets confused about what you have actually paid. In a smart contract, the same thing happens when the contract calls out to another contract (the token) and that call lets the attacker run their own code before the contract has updated its records.
The article stresses one condition: this bug is only true for ERC777 tokens. ERC777 is a token standard (a set of rules a token contract follows) that includes a callback: during a transfer, the token contract calls a function on the sender. That callback is the doorway the attacker uses.
The vulnerable function
The article shows the swap() function of the pool contract. A function is a named block of code that someone can call. Here is the code exactly as published:
function swap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline) external ensure(deadline) returns (uint256) { require(dx <= coins[tokenIndexFrom].balanceOf(msg.sender), "O3SwapPool: INSUFFICIENT_BALANCE"); uint256 balanceBefore = coins[tokenIndexFrom].balanceOf(address(this)); coins[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 transferredDx = coins[tokenIndexFrom].balanceOf(address(this)) - balanceBefore; (uint256 dy, uint256 dyFee) = _calculateSwap(tokenIndexFrom, tokenIndexTo, transferredDx); require(dy >= minDy, "O3SwapPool: INSUFFICIENT_OUTPUT_AMOUNT"); uint256 dyAdminFee = dyFee * adminFee / FEE_DENOMINATOR / tokenPrecisionMultipliers[tokenIndexTo]; balances[tokenIndexFrom] += transferredDx; balances[tokenIndexTo] -= dy + dyAdminFee; coins[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo); return dy; }
Line by line, in plain words:
function swap(...)declares a public function (externalmeans anyone outside the contract can call it). It takes five inputs: which token you pay with (tokenIndexFrom), which token you want (tokenIndexTo), how much you pay in (dx), the smallest amount of output you will accept (minDy), and a time limit (deadline). Theensure(deadline)part rejects the call if the deadline has passed.require(dx <= coins[tokenIndexFrom].balanceOf(msg.sender), ...)checks that the person calling (msg.sender) actually holds at leastdxof the input token. If not, the call stops with the error message shown.uint256 balanceBefore = coins[tokenIndexFrom].balanceOf(address(this));writes down how many input tokens the pool itself holds right now.address(this)means the pool contract's own address.coins[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx);movesdxtokens from the caller to the pool. This is the external call, and for an ERC777 token this is where the sender callback fires.uint256 transferredDx = coins[tokenIndexFrom].balanceOf(address(this)) - balanceBefore;works out how many tokens actually arrived, by subtracting the earlier recorded balance from the current one.(uint256 dy, uint256 dyFee) = _calculateSwap(...)asks an internal helper how much output (dy) the pool will give fortransferredDx, and what fee (dyFee) applies.require(dy >= minDy, ...)checks the output is at least the minimum the caller asked for.uint256 dyAdminFee = ...computes the share of the fee that goes to the protocol's admin.balances[tokenIndexFrom] += transferredDx;andbalances[tokenIndexTo] -= dy + dyAdminFee;update the pool's own internal record of how much of each token it holds. This is the bookkeeping step, and it happens only now.coins[tokenIndexTo].safeTransfer(msg.sender, dy);sends the output tokens to the caller.emit TokenSwap(...)writes a log entry (an event) so the swap can be seen on the blockchain, andreturn dy;hands the output amount back to the caller.
The key detail is the order: the pool calls out to the token (step 4) before it updates its own records (step 9). While that external call is running, the pool's records still show the old state.
How the attack works
The article gives a risk breakdown as a numbered list:
- The attacker initiates a swap with the minimum amount (
dx). - Before the
safetransferfrom()function is executed, the attacker's code exploits the_callTokensToSend()hook in the ERC777 token. - This re-entrancy allows the attacker to re-enter the
swap()function, this time with a largerdxvalue. - The transaction concludes the second swap, inflating the ending balance.
- The attacker successfully swaps a larger amount of tokens while only using the minimal amount authorised in the first transaction.
A hook here is simply a function that the token contract calls on the sender during a transfer. Because the sender can be a contract written by the attacker, that hook runs the attacker's own code. Re-entering means calling swap() again from inside that hook, before the first call has finished.
The article then gives a quick conceptual scenario:
- Initiate swap with
dx = 1. - Re-enter swap with
dx = 1000using tokensToSend (an ERC777) hook. - Complete second swap, inflating the ending balance.
- Successfully swap a larger amount of tokens in the first swap, while using minimal amount authorised initially.
In plain words: the attacker starts a tiny swap (paying in 1 unit). The pool begins moving that 1 unit and, because the token is ERC777, calls the attacker's hook. Inside the hook the attacker calls swap() again, this time claiming to pay in 1000 units. In the article's conceptual scenario, the second call runs before the first swap's bookkeeping is updated, and the attacker swaps a larger amount than the minimal amount authorised initially.
Why it works
The root cause is the ordering of the steps. The pool makes an external call (the token transfer) before it writes the new values into its balances record. That means control passes to attacker code while the contract's accounting is out of date. ERC777 makes this reachable because the token itself calls the sender's hook during the transfer. The deadline check and the balance check do not stop re-entry, and the article does not describe any reentrancy guard on the function. A reentrancy guard is a simple lock: a flag that says "this function is already running, refuse a second entry until it finishes".
Impact
By exploiting the callback, an attacker could artificially inflate their balance and manipulate the outcome of the swap. As a result, the attacker could swap tokens for a larger amount than they initially provided, leading to financial gains at the expense of the protocol and other users. The article repeats that this bug is only true for ERC777 tokens.
The fix
To mitigate the vulnerability, the article says it is essential to add a reentrancy guard to the swap() function. It also advises following good practice: include proper checks and locks to prevent multiple re-entrances within a single transaction, and check that the final balance corresponds to the expected balance. The article does not say whether any of this was applied to the target.
What to look for elsewhere
The author notes that this class of bug is classic, and that the chances of finding one in a project listed on Immunefi (a platform where projects publish bug bounty programmes) are now rather low. It is still worth keeping in mind while auditing contracts. The concrete advice: if the project accepts all tokens, check how the functions react to the different types of existing tokens. The article links a short list of tokens with "weird" behaviour:
https://github.com/d-xo/weird-erc20#revert-on-zero-value-transfers
The article advises checking how functions react to the different types of existing tokens if the project accepts all tokens.
Glossary
- Smart contract: a program stored on a blockchain that runs exactly as written and can be called by anyone.
- Blockchain: a shared, public record of transactions maintained by many computers.
- Token: a digital asset managed by a smart contract.
- DEX (decentralised exchange): a service that lets people trade one token for another without a central operator.
- Bridge: a service that moves tokens between different blockchains.
- Pool: a contract that holds tokens and lets users swap them against that stock.
- Function: a named block of code in a contract that can be called with inputs and may return a value.
external: a visibility keyword meaning the function can be called from outside the contract.require: a check that stops the call with an error if its condition is false.msg.sender: the address of whoever called the function.address(this): the contract's own address.balanceOf: a function that reports how many tokens an address holds.safeTransferFrom: a token function that moves tokens from one address to another and checks the result.safeTransfer: a token function that sends tokens to an address and checks the result.balancesmapping: the pool's internal record of how much of each token it believes it holds.dx: the amount of input token the caller pays in.dy: the amount of output token the pool pays out.minDy: the smallest output the caller will accept.deadline: a time limit after which the call is rejected.ensure(deadline): the modifier that enforces that time limit.- Modifier: a reusable check attached to a function that runs before or after it.
- Fee (
dyFee,dyAdminFee): a cut of the swap taken by the pool and by the protocol's admin. - Event (
emit TokenSwap): a log entry written to the blockchain so the action can be observed. - ERC777: a token standard that calls a hook on the sender (and recipient) during a transfer.
- Hook (
_callTokensToSend): a function the token contract calls on the sender during a transfer, which can run attacker code. - Reentrancy: calling a function again from inside an external call it made, before the first call has finished.
- Reentrancy guard: a lock that prevents a function from being entered a second time while it is still running.
- Stale accounting: internal records that have not yet been updated and so no longer match reality.
- Immunefi: a platform where projects publish bug bounty programmes.
- Bug bounty: a programme that pays people for reporting security bugs.
- Auditing: reviewing a contract's code for security mistakes.