Unbounded loops may cause exercise() s and withdraw() s to fail
The smart contract functions that transfer assets out during exercise or withdrawal loop over an unbounded number of assets, so if gas costs rise or assets are gas-heavy, the transaction can fail due to block gas limit. An attacker could create an order with many assets, causing the buyer to pay the premium but be unable to receive the assets.
Submitted by IllIllI, also found by 0xNineDec, sashiketh, shung, and xiaoming90_
Impact
There are no bounds on the number of tokens transferred in an order, and gas requirements can change (especially since orders can have a duration of 27 years), so orders filled at time T1 may not be exercisable/withdrawable at time T2, or with the provided assets if the assets use a lot of gas during their transfers (e.g. aTokens and cTokens). The buyer of the option will have paid the premium, and will be unable to get the assets they are owed.
Proof of Concept
There are no upper bounds on the number of assets being transferred in these loops:
File: contracts/src/PuttyV2.sol #1
636 function _transferERC20sOut(ERC20Asset[] memory assets) internal {
637 for (uint256 i = 0; i < assets.length; i++) {
638 ERC20(assets[i].token).safeTransfer(msg.sender, assets[i].tokenAmount);
639 }
640 }
File: contracts/src/PuttyV2.sol #2
646 function _transferERC721sOut(ERC721Asset[] memory assets) internal {
647 for (uint256 i = 0; i < assets.length; i++) {
648 ERC721(assets[i].token).safeTransferFrom(address(this), msg.sender, assets[i].tokenId);
649 }
650 }
File: contracts/src/PuttyV2.sol #3
657 function _transferFloorsOut(address[] memory floorTokens, uint256[] memory floorTokenIds) internal {
658 for (uint256 i = 0; i < floorTokens.length; i++) {
659 ERC721(floorTokens[i]).safeTransferFrom(address(this), msg.sender, floorTokenIds[i]);
660 }
661 }
Recommended Mitigation Steps
Have an upper bound on the number of assets, or allow them to be transferred out one at a time, if necessary
outdoteth (Putty Finance) acknowledged, but disagreed with severity and commented:
Adding a hardcoded check at the contract level is not a viable fix given that gas costs and limits are subject change over time. Instead, there already exists a limit of 30 assets on the frontend/db level.
outdoteth (Putty Finance) commented:
Report: Unbounded loop can prevent put option from being exercised.
Medium severity is justified because, while very unlikely to happen, there could be a loss of assets.
hyh (warden) reviewed mitigation:
Now addressed on UI/DB level.
Context
Putty is an on-chain options protocol. PuttyV2 is the contract that holds the logic for creating, filling, exercising and withdrawing orders. When an option is exercised or withdrawn, the contract has to hand assets back to the caller: ERC20 tokens, ERC721 tokens, or a set of "floor" ERC721 tokens. Three internal helper functions do that work, and each of them walks an array of assets with a for loop.
The report is a Code4rena finding against the 2022-06 Putty audit. It was submitted by IllIllI and also found by 0xNineDec, sashik*eth, shung and xiaoming90. The issue is that nothing in the contract caps how many assets an order may contain, so the loops can grow without limit.
Setup
The finding is a code review of the public repository, at commit [redacted], file contracts/src/PuttyV2.sol. No deployment, account or tooling is described. The relevant preconditions are properties of the protocol itself:
- An order can carry an arbitrary number of ERC20, ERC721 and floor assets, because the contract imposes no upper bound.
- An order can have a very long duration. The report points at line 287 of the same file as the place where a duration of 27 years is possible.
- Assets are transferred with
safeTransferandsafeTransferFrom, so the gas cost of each transfer depends on the token contract. Some token types, such as aTokens and cTokens, use a lot of gas during transfers.
Finding it
The researcher looked at the three functions that send assets out of the contract during exercise and withdrawal and noticed that each one iterates over a caller-supplied array with no length check. Combined with the long order duration and the variable gas cost of token transfers, an order that is fillable and exercisable at one point in time may become impossible to exercise or withdraw later, or may only work with assets that are cheap to transfer. The buyer has already paid the premium by then.
Exploitation
The report does not give a transaction sequence. It shows the three loops and reasons about the conditions under which they fail.
Step 1: ERC20 assets are sent out in an unbounded loop
File: contracts/src/PuttyV2.sol #1
636 function _transferERC20sOut(ERC20Asset[] memory assets) internal {
637 for (uint256 i = 0; i < assets.length; i++) {
638 ERC20(assets[i].token).safeTransfer(msg.sender, assets[i].tokenAmount);
639 }
640 }
The loop bound is assets.length, which comes from the order. Every iteration performs a safeTransfer to msg.sender, so the total gas is the sum of the cost of each token transfer. Nothing rejects a long array.
Step 2: ERC721 assets are sent out in an unbounded loop
File: contracts/src/PuttyV2.sol #2
646 function _transferERC721sOut(ERC721Asset[] memory assets) internal {
647 for (uint256 i = 0; i < assets.length; i++) {
648 ERC721(assets[i].token).safeTransferFrom(address(this), msg.sender, assets[i].tokenId);
649 }
650 }
Same pattern for NFTs: one safeTransferFrom per element, with the array length taken from the order.
Step 3: floor tokens are sent out in an unbounded loop
File: contracts/src/PuttyV2.sol #3
657 function _transferFloorsOut(address[] memory floorTokens, uint256[] memory floorTokenIds) internal {
658 for (uint256 i = 0; i < floorTokens.length; i++) {
659 ERC721(floorTokens[i]).safeTransferFrom(address(this), msg.sender, floorTokenIds[i]);
660 }
661 }
662 }
The floor-token loop is bounded by floorTokens.length, again supplied by the order.
Step 4: the failure condition
Because the loops have no cap, the gas needed to complete an exercise or withdrawal is a function of the order contents and of the token contracts involved. If the block gas limit, or the gas the caller is willing to pay, is lower than that total, the call reverts. The report notes two ways this arises: the same order may be fine at time T1 and not at time T2, and an order may be fine with cheap tokens but not with assets that consume a lot of gas during transfer, such as aTokens and cTokens. The buyer has paid the premium and cannot obtain the assets they are owed.
Root cause
The contract trusts the length of the asset arrays in an order and performs one external transfer per element, with no upper bound on the count. Gas costs and limits can change over a long order duration, so an order executable at one time may not be later. The report does not discuss any other defence in the contract.
Impact
A buyer who has paid the premium can end up holding an option that cannot be exercised or withdrawn, either because the order has too many assets for the available gas or because the assets are expensive to transfer. The judge justified medium severity on the basis that, while very unlikely to happen, there could be a loss of assets.
Fix
The report recommends an upper bound on the number of assets, or allowing assets to be transferred out one at a time if necessary.
The Putty team (outdoteth) acknowledged the issue but disagreed with the severity, arguing that a hardcoded check at the contract level is not a viable fix because gas costs and limits change over time. They stated that a limit of 30 assets already exists at the frontend and database level. The judge kept medium severity.
Variants to test
- Look for other loops over user-supplied arrays in exercise, withdraw, cancel and fill paths. A positive result is a loop whose bound comes from calldata or storage written by the user, with an external call inside.
- Check whether array lengths are validated when an order is created or filled. A positive result is a create or fill path that accepts an array of any length while the payout path loops over it.
- Check order durations against the gas assumptions of the payout path. A positive result is a long-lived order whose payout cost can grow or whose token set can include expensive-to-transfer tokens.
- Check whether assets can be claimed individually. A positive result is a payout function that only offers an all-or-nothing transfer of the full asset list.
Hunting notes
This kind of bug hides in payout and settlement code: functions that iterate over lists of tokens, recipients or ids taken from user input, especially where the same list was accepted earlier without a cap. During review, look for for loops whose bound is a parameter or a stored array length, and for safeTransfer or safeTransferFrom inside them. Long-duration instruments, such as options and vesting contracts, are good places to look, because the gas environment at payout time is not the one at creation time. The report shows no exploit transaction; the argument rests on the code and the protocol's parameters. The judge justified medium severity because, while very unlikely, there could be a loss of assets.
What happened, in plain words
Putty is a service that runs on a blockchain (a shared, public computer that many people use at once). It lets people create and trade options. An option is a deal where one person pays a small amount up front (the premium) for the right to receive certain assets later, under agreed conditions. The person who pays is the buyer; the assets they are owed are held by the Putty smart contract (a program that lives on the blockchain and holds money and tokens) until the buyer claims them.
Claiming happens in two ways: exercising the option, or withdrawing from it. In both cases the contract has to send assets back to the person calling it. Those assets can be ERC20 tokens (ordinary fungible tokens, like a digital currency), ERC721 tokens (unique tokens, commonly called NFTs), or a set of "floor" ERC721 tokens (a group of NFTs used as a price floor reference).
The contract sends these assets out with three small helper functions, and each one uses a for loop. A for loop is a way of telling a program to repeat the same action over and over, once for each item in a list. The problem this report describes is that nothing in the contract limits how long that list can be. If an order contains a very large number of assets, the loop has to run a very large number of times, and each repetition costs gas.
Gas is the unit that measures how much computational work a blockchain transaction does, and the person sending the transaction pays for it. Every block (the batch of transactions added to the chain at one time) has a maximum amount of gas it can hold. If a transaction needs more gas than that limit, or more than the sender is willing to pay, it fails and is cancelled: the blockchain undoes it. So an order that worked when it was created may become impossible to exercise or withdraw later, and the buyer, who has already paid the premium, cannot get the assets they are owed.
The finding was submitted by IllIllI and also found by 0xNineDec, sashik*eth, shung and xiaoming90. It was rated medium severity.
The setup: what the researcher looked at
This is a code review, not a live attack. The researcher read the public source code of the Putty project at a specific saved version (commit) [redacted], in the file contracts/src/PuttyV2.sol. No deployment, test account or tooling is described.
The report lists three conditions that together make the bug possible:
- An order can carry any number of ERC20, ERC721 and floor assets, because the contract sets no upper limit.
- An order can last a very long time. The report points to line 287 of the same file as the place where a duration of 27 years is possible.
- Assets are moved with
safeTransferandsafeTransferFrom. These are standard functions for sending tokens, and their gas cost depends on the token's own contract. Some kinds of token, such as aTokens and cTokens (tokens that represent a deposit in a lending protocol), use a lot of gas when transferred.
Finding it
The researcher looked at the three functions that send assets out of the contract during exercise and withdrawal. Each one walks through a list of assets supplied by the order, with no check on how long the list is. Combined with the long order duration and the variable gas cost of token transfers, an order that can be filled and exercised at one moment may become impossible to exercise or withdraw later, or may only work if the assets happen to be cheap to transfer. By then the buyer has already paid the premium.
How the problem plays out
The report does not give a step-by-step attack transaction. It shows the three loops and explains the conditions under which they fail.
Step 1: ERC20 assets are sent out in an unbounded loop
File: contracts/src/PuttyV2.sol #1
636 function _transferERC20sOut(ERC20Asset[] memory assets) internal {
637 for (uint256 i = 0; i < assets.length; i++) {
638 ERC20(assets[i].token).safeTransfer(msg.sender, assets[i].tokenAmount);
639 }
640 }
Line by line:
- Line 636 declares a function called
_transferERC20sOut. It takes one input,assets, which is a list (an array) of ERC20 assets.internalmeans the function can only be called from inside the contract, not directly by an outside user. - Line 637 starts the loop.
uint256 i = 0creates a counter starting at zero.i < assets.lengthmeans "keep going while the counter is smaller than the number of items in the list".i++adds one to the counter after each pass. - Line 638 is the action repeated on every pass. It takes the token at position
iin the list and callssafeTransferto sendtokenAmountof it tomsg.sender, the person who called the contract. - Line 640 closes the function.
The important detail is that the loop's stopping point is assets.length, which comes from the order itself. Every pass performs a real transfer, so the total gas is the sum of the cost of every transfer. Nothing rejects a long list.
Step 2: ERC721 assets are sent out in an unbounded loop
File: contracts/src/PuttyV2.sol #2
646 function _transferERC721sOut(ERC721Asset[] memory assets) internal {
647 for (uint256 i = 0; i < assets.length; i++) {
648 ERC721(assets[i].token).safeTransferFrom(address(this), msg.sender, assets[i].tokenId);
649 }
650 }
Line by line:
- Line 646 declares
_transferERC721sOut, which takes a list of ERC721 assets. ERC721 tokens are unique, so each one is identified by atokenId(a number that distinguishes it from every other token of the same contract). - Line 647 is the same counting loop as before, again bounded by the length of the list.
- Line 648 sends one NFT per pass.
safeTransferFrommoves the token fromaddress(this)(the contract itself, which is holding the asset) tomsg.sender(the caller), using the token'stokenId. - Line 650 closes the function.
It is the same pattern as step 1: one transfer per item, with the number of items taken from the order.
Step 3: floor tokens are sent out in an unbounded loop
File: contracts/src/PuttyV2.sol #3
657 function _transferFloorsOut(address[] memory floorTokens, uint256[] memory floorTokenIds) internal {
658 for (uint256 i = 0; i < floorTokens.length; i++) {
659 ERC721(floorTokens[i]).safeTransferFrom(address(this), msg.sender, floorTokenIds[i]);
660 }
661 }
662 }
Line by line:
- Line 657 declares
_transferFloorsOut. It takes two lists that run in parallel:floorTokens, the addresses of the NFT contracts, andfloorTokenIds, the specific token numbers inside those contracts. - Line 658 loops while the counter is smaller than the number of entries in
floorTokens. - Line 659 sends the NFT at position
ifrom the contract to the caller, pairingfloorTokens[i]withfloorTokenIds[i]. - Line 661 closes the function, and line 662 closes the surrounding block of code.
The floor-token loop is bounded by floorTokens.length, which again comes from the order.
Step 4: when it breaks
Because none of the loops has a cap, the gas needed to finish an exercise or withdrawal depends on what the order contains and on the token contracts involved. If the block gas limit, or the gas the caller is willing to pay, is lower than that total, the call fails and is undone. The report names two ways this happens:
- The same order may be fine at time T1 and not at time T2, because gas costs and limits change over time.
- An order may be fine with cheap tokens but not with assets that consume a lot of gas during transfer, such as aTokens and cTokens.
Either way, the buyer has paid the premium and cannot obtain the assets they are owed.
Root cause
The contract trusts the length of the asset lists in an order and performs one external transfer per item, with no upper limit on the count. Gas costs and limits can change over a long order duration, so an order executable at one time may not be later. The report does not discuss any other safeguard in the contract.
Impact
A buyer who has paid the premium can end up holding an option that cannot be exercised or withdrawn, either because the order has too many assets for the available gas or because the assets are expensive to transfer. The buyer has paid the premium and cannot obtain the assets they are owed. The judge justified medium severity on the basis that, while very unlikely to happen, there could be a loss of assets.
The fix and the discussion
The report recommends putting an upper limit on the number of assets, or allowing assets to be transferred out one at a time if necessary.
The Putty team (outdoteth) acknowledged the issue but disagreed with the severity. They argued that a hardcoded check at the contract level is not a viable fix because gas costs and limits change over time. They stated that a limit of 30 assets already exists at the frontend and database level. The frontend is the website people use to interact with the contract, and the database is the storage behind that website; a limit there is not enforced by the contract itself.
The judge kept medium severity.
Variants to test
If you want to look for similar problems elsewhere, these angles follow from the finding:
- Look for other loops over user-supplied lists in the exercise, withdraw, cancel and fill paths. A positive result is a loop whose stopping point comes from data the user supplies, with an external call inside it.
- Check whether list lengths are validated when an order is created or filled. A positive result is a create or fill path that accepts a list of any length while the payout path loops over it.
- Check order durations against the gas assumptions of the payout path. A positive result is a long-lived order whose payout cost can grow, or whose token set can include tokens that are expensive to transfer.
- Check whether assets can be claimed individually. A positive result is a payout function that only offers an all-or-nothing transfer of the full asset list.
Hunting notes
This kind of bug hides in payout and settlement code: functions that loop over lists of tokens, recipients or ids taken from user input, especially where the same list was accepted earlier without a cap. During review, look for for loops whose stopping point is a parameter or a stored list length, and for safeTransfer or safeTransferFrom inside them. Long-duration instruments, such as options and vesting contracts (contracts that release tokens gradually over time), are good places to look, because the gas environment at payout time is not the one at creation time. The report shows no exploit transaction; the argument rests on the code and the protocol's parameters. The judge justified medium severity because, while very unlikely, there could be a loss of assets.
Glossary
- Blockchain: a shared, public record of transactions maintained by many computers, where programs can run and hold assets.
- Smart contract: a program that lives on a blockchain and can hold and move tokens according to its code.
- Putty: an on-chain options protocol; PuttyV2 is the contract holding the logic for creating, filling, exercising and withdrawing orders.
- Option: a deal where a buyer pays a premium up front for the right to receive certain assets later under agreed conditions.
- Premium: the amount a buyer pays up front for an option.
- Exercise: the act of claiming the assets an option entitles the buyer to.
- Withdraw: the act of taking assets out of an order through the contract.
- Order: the record of an option deal, including which assets it involves and how long it lasts.
- ERC20: the standard for fungible tokens, where every unit is interchangeable with every other.
- ERC721: the standard for unique tokens, commonly called NFTs, each identified by a
tokenId. - Floor tokens: a set of ERC721 tokens used as a price floor reference, sent out together by the contract.
forloop: a programming construct that repeats the same action once for each item in a list.- Array: an ordered list of items in a program.
assets.length/floorTokens.length: the number of items in a list, used as the loop's stopping point.- Gas: the unit measuring how much computational work a transaction does, paid for by the sender.
- Block gas limit: the maximum amount of gas all transactions in one block can use together.
- Revert: when a transaction fails and the blockchain undoes it, as if it never happened.
safeTransfer/safeTransferFrom: standard functions for sending ERC20 and ERC721 tokens, whose gas cost depends on the token's own contract.- aTokens / cTokens: tokens that represent a deposit in a lending protocol and use a lot of gas when transferred.
msg.sender: the address of the person or contract that called the function.address(this): the address of the contract itself, which is holding the assets.tokenId: the number that identifies one specific ERC721 token.- Frontend: the website people use to interact with the contract.
- Database: the storage behind the website, separate from the contract.
- Commit: a saved version of a code repository, identified by a long code such as
[redacted]. - Code4rena: the platform that ran the audit and published the finding.
- Warden: a security researcher taking part in a Code4rena audit.
- Judge: the person who decides the severity of findings in a Code4rena audit.
- Medium severity: the rating given to this finding, justified by the judge because, while very unlikely, there could be a loss of assets.