Skip to content
Business logic Audit finding Beginner

ArcTokenPurchase::withdrawUnsoldArcTokens() Fails to Reduce totalAmountForSale, Leaving Availability Counters Wrong

The withdrawUnsoldArcTokens function transfers unsold tokens out of the contract without reducing totalAmountForSale, so the getMaxNumberOfTokens helper reports more tokens as available than actually remain. Honest buyers may then submit buy transactions that revert with ContractBalanceInsufficient, wasting gas.

Plume Network

Originally disclosed on Immunefi

50889 sc low arctokenpurchase withdrawunsoldarctokens fails to reduce totalamountforsale leaving availability counters wrong

Submitted on Jul 29th 2025 at 11:56:37 UTC by @Paludo0x for Attackathon | Plume Network

Description

Vulnerability Details

ArcTokenPurchase::withdrawUnsoldArcTokens() allows the token admin to pull unsold ArcTokens out of the contract without decreasing totalAmountForSale.

The helper getMaxNumberOfTokens() is intended to report how many ArcToken base-units are still available in an ongoing sale:

{% code title="getMaxNumberOfTokens" %}

Solidity
function getMaxNumberOfTokens(
    address _tokenContract
) external view returns (uint256) {
    TokenInfo storage info = _getPurchaseStorage().tokenInfo[_tokenContract];
    return info.totalAmountForSale - info.amountSold;
}

{% endcode %}

Because withdrawUnsoldArcTokens() does not decrement totalAmountForSale when transferring tokens out, front-ends that call getMaxNumberOfTokens() will display inflated availability. Honest buyers may then submit buy() transactions which revert with ContractBalanceInsufficient, wasting gas.

Impact Details

{% hint style="warning" %} No funds are lost, but front-ends display inflated availability; honest buyers can waste gas on failing transactions. {% endhint %}

Recommended Fix

Adjust accounting whenever unsold tokens are withdrawn. Example patch:

{% code title="Suggested fix" %}

Solidity
function withdrawUnsoldArcTokens(...)
    external onlyTokenAdmin(_tokenContract)
{
    TokenInfo storage info = ps.tokenInfo[_tokenContract];

    if (amount > (info.totalAmountForSale - info.amountSold)) {
        revert InsufficientUnsoldTokens();
    }

    info.totalAmountForSale -= amount;      // ← keep quota consistent
    token.safeTransfer(to, amount);
}

{% endcode %}

Proof of Concept

Relevant snippet from the contract showing current behavior:

{% code title="withdrawUnsoldArcTokens (current)" %}

{% endcode %}

```solidity /** * @dev Allows the token admin to withdraw unsold ArcTokens after a sale (or if disabled). * @param _tokenContract The ArcToken contract address. * @param to The address to send the tokens to. * @param amount The amount of ArcTokens to withdraw. */ function withdrawUnsoldArcTokens( address _tokenContract, address to, uint256 amount ) external onlyTokenAdmin(_tokenContract) { if (to == address(0)) { revert CannotWithdrawToZeroAddress(); } if (amount == 0) { revert AmountMustBePositive(); }

ArcToken token = ArcToken(_tokenContract);
uint256 contractBalance = token.balanceOf(address(this));
if (contractBalance < amount) {
    revert InsufficientUnsoldTokens();
}

bool success = token.transfer(to, amount);
if (!success) {
    revert ArcTokenWithdrawalFailed();
}

}

The original report as published on Immunefi. Images and videos are our own copies; raw HTML is shown as text. View it on Immunefi.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

ArcTokenPurchase is a smart contract in the Plume Network codebase that manages the sale of ArcTokens. It tracks, per token contract, how many tokens are on offer and how many have been sold, and exposes a view helper so that front-ends can show buyers how much is still available. The contract also gives a token admin the ability to pull unsold tokens back out once a sale has ended or has been disabled.

The report targets the following file:

Text
https://github.com/immunefi-team/attackathon-plume-network/blob/main/arc/src/ArcTokenPurchase.sol

The relevant feature is the pair of functions getMaxNumberOfTokens() (a read-only helper) and withdrawUnsoldArcTokens() (an admin-only withdrawal). The first is meant to report the remaining quota of a sale; the second is meant to remove tokens that were not sold.

Setup

This is a smart contract review, so there are no accounts, sessions or tools to configure beyond reading the source. The actors involved are:

  • The token admin, the only caller authorised to invoke withdrawUnsoldArcTokens() (enforced by the onlyTokenAdmin(_tokenContract) modifier).
  • Honest buyers, who call buy() based on the availability figure shown by a front-end.
  • The front-end, which reads availability through getMaxNumberOfTokens().

The precondition for the bug is simply that a sale exists and that the admin withdraws unsold tokens at some point. No special state, timing or privilege beyond the admin role is needed.

Finding it

The researcher compared the two functions that are supposed to agree on the sale quota. getMaxNumberOfTokens() computes availability as the difference between the total on sale and the amount already sold:

Solidity
function getMaxNumberOfTokens(
    address _tokenContract
) external view returns (uint256) {
    TokenInfo storage info = _getPurchaseStorage().tokenInfo[_tokenContract];
    return info.totalAmountForSale - info.amountSold;
}

That figure is only correct if totalAmountForSale is reduced whenever tokens leave the contract outside of a sale. The withdrawal function, however, transfers tokens out without touching totalAmountForSale, so the two values drift apart. The helper keeps reporting the original quota even though part of the backing tokens are no longer in the contract.

Exploitation

Step 1: the admin withdraws unsold tokens

The current implementation of the withdrawal function, as quoted in the report, is:

Solidity
/**
 * @dev Allows the token admin to withdraw unsold ArcTokens after a sale (or if disabled).
 * @param _tokenContract The ArcToken contract address.
 * @param to The address to send the tokens to.
 * @param amount The amount of ArcTokens to withdraw.
 */
function withdrawUnsoldArcTokens(
    address _tokenContract,
    address to,
    uint256 amount
) external onlyTokenAdmin(_tokenContract) {
    if (to == address(0)) {
        revert CannotWithdrawToZeroAddress();
    }
    if (amount == 0) {
        revert AmountMustBePositive();
    }

    ArcToken token = ArcToken(_tokenContract);
    uint256 contractBalance = token.balanceOf(address(this));
    if (contractBalance < amount) {
        revert InsufficientUnsoldTokens();
    }

    bool success = token.transfer(to, amount);
    if (!success) {
        revert ArcTokenWithdrawalFailed();
    }
}

The function validates the destination, rejects a zero amount, checks that the contract actually holds at least amount tokens, and then transfers them. What it never does is decrement info.totalAmountForSale. The only balance check is against the live token balance, not against the recorded sale quota.

Step 2: the availability figure stays inflated

After the withdrawal, getMaxNumberOfTokens() still returns info.totalAmountForSale - info.amountSold, which now exceeds the number of tokens the contract can actually deliver. Any front-end that relies on this helper shows buyers more availability than exists.

Step 3: buyers waste gas on reverting purchases

A buyer who trusts the displayed figure submits a buy() transaction. Because the contract no longer holds enough tokens to cover the reported quota, the purchase reverts with ContractBalanceInsufficient. The buyer pays gas for a transaction that cannot succeed.

Root cause

The accounting for the sale quota is split across two places that are not kept in sync. totalAmountForSale is the authoritative figure used by getMaxNumberOfTokens(), but the withdrawal path only checks the contract's token balance and never adjusts the quota. The balance check in withdrawUnsoldArcTokens() guards against over-withdrawing relative to the tokens actually held, so it does not catch the inconsistency between the recorded quota and the remaining balance. The result is a stale counter that overstates availability.

Impact

No funds are lost. The effect is that front-ends display inflated availability, and honest buyers can waste gas on buy() transactions that revert with ContractBalanceInsufficient. The report classifies this under theft of gas and rates it low severity. The condition for the impact is that the admin has withdrawn unsold tokens.

Fix

The report recommends adjusting the accounting whenever unsold tokens are withdrawn, and supplies an example patch:

Solidity
function withdrawUnsoldArcTokens(...)
    external onlyTokenAdmin(_tokenContract)
{
    TokenInfo storage info = ps.tokenInfo[_tokenContract];

    if (amount > (info.totalAmountForSale - info.amountSold)) {
        revert InsufficientUnsoldTokens();
    }

    info.totalAmountForSale -= amount;      // ← keep quota consistent
    token.safeTransfer(to, amount);
}

The patch does two things: it bounds the withdrawal by the unsold quota (totalAmountForSale - amountSold) rather than only by the contract balance, and it decrements totalAmountForSale by the withdrawn amount so that getMaxNumberOfTokens() stays accurate.

Variants to test

  • Look for other view helpers that derive availability from a stored total minus a stored sold counter, and check every code path that moves tokens out of the contract (admin withdrawals, refunds, migrations). A positive result is a helper whose output exceeds the contract's actual token balance after such a path runs.
  • Check withdrawal and rescue functions that validate only against balanceOf(address(this)). A positive result is a function that can move tokens without updating the counters the rest of the contract reads.
  • Compare every state-changing function against the fields it is expected to maintain. A positive result is a field that is written on purchase but never on removal, leaving derived views stale.
  • Exercise the boundary in the suggested fix: withdrawing exactly totalAmountForSale - amountSold. A positive result is a path where the quota can still be exceeded or where the subtraction underflows.

Hunting notes

This class of bug hides in the gap between a contract's bookkeeping and its actual token balance. During review, list every stored counter that feeds a public view, then trace every function that transfers tokens in or out and confirm the counter is updated on each path.

The impact here is indirect, which is why it lands as low severity: the researcher showed a concrete consequence, buyers submitting buy() transactions that revert with ContractBalanceInsufficient and paying gas for nothing, and tied it to a specific helper that front-ends call.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

What happened, in plain words

A smart contract called ArcTokenPurchase is in charge of selling a digital token called ArcToken. Think of it as a shop till and a stock ledger combined: it keeps a record of how many tokens are on offer and how many have already been sold, and it lets a website show buyers how many are still up for grabs.

The shop also has a manager, called the token admin, who is allowed to take back any tokens that did not sell. The problem is that when the manager takes tokens back, the contract moves the tokens out but forgets to update the record of how many were on offer. The website keeps showing the old, larger number, so buyers think there is more stock than there really is. A buyer then tries to buy, the purchase fails because the tokens are no longer there, and the buyer still pays the small fee (called gas) for the failed attempt.

No tokens or money are stolen. The loss is the wasted gas, and the report rates this as a low severity issue.

Background you need first

A few ideas come up again and again, so here they are from scratch.

  • Blockchain and smart contract: a blockchain is a shared record book that many computers keep copies of. A smart contract is a small program that lives on that record book and runs automatically when someone calls it. Nobody can quietly edit its records afterwards.
  • Token: a digital item tracked by a smart contract. Here, ArcToken is the item being sold. Each token is divisible into tiny base units, the way a pound divides into pence, and the contract counts in those base units.
  • Gas: the fee paid to the network for running a transaction. You pay it whether the transaction succeeds or fails, because the computers still did the work of checking it.
  • Front-end: the website or app a person uses. It does not hold the tokens itself; it asks the smart contract questions and shows the answers on screen.
  • View function: a question you can ask a smart contract that only reads information and changes nothing. It costs no gas to ask.
  • Revert: when a smart contract refuses to finish a transaction because a rule was broken. The transaction is undone, but the gas already spent is not refunded.
  • Modifier: a small guard attached to a function that checks a condition before the function body runs. onlyTokenAdmin(_tokenContract) is one: it makes sure the caller is the token admin for that token.
  • address: the identifier of an account or contract on the blockchain, similar to an account number.
  • uint256: a whole number that cannot be negative, used for amounts and counters.

The file under review

The report looks at one file in the Plume Network codebase:

Text
https://github.com/immunefi-team/attackathon-plume-network/blob/main/arc/src/ArcTokenPurchase.sol

Two functions in that file matter. getMaxNumberOfTokens() is the read-only helper the website calls to learn how many tokens are still available. withdrawUnsoldArcTokens() is the admin-only function that takes unsold tokens back out of the contract. The bug lives in the gap between them.

Who is involved

There are no accounts, logins or tools to set up. This is a reading exercise on source code. The people and parts involved are:

  1. The token admin: the only account allowed to call withdrawUnsoldArcTokens(), enforced by the onlyTokenAdmin(_tokenContract) modifier.
  2. Honest buyers: ordinary users who call buy() after seeing the availability number on the website.
  3. The front-end: the website that reads availability through getMaxNumberOfTokens() and displays it.

The only precondition is that a sale exists and that the admin withdraws unsold tokens at some point. No special timing or extra permission is needed beyond the admin role itself.

Finding it

The researcher compared the two functions that are supposed to agree about how much is left for sale. The read-only helper works out availability as the total put on sale minus the amount already sold:

Solidity
function getMaxNumberOfTokens(
    address _tokenContract
) external view returns (uint256) {
    TokenInfo storage info = _getPurchaseStorage().tokenInfo[_tokenContract];
    return info.totalAmountForSale - info.amountSold;
}

Line by line:

  • function getMaxNumberOfTokens( starts the definition of a function named getMaxNumberOfTokens.
  • address _tokenContract is the input: the address of the token contract being asked about.
  • external view returns (uint256) means anyone outside the contract can call it, it only reads (view), and it gives back a non-negative whole number.
  • TokenInfo storage info = _getPurchaseStorage().tokenInfo[_tokenContract]; fetches the stored record for that token. storage means it points at the contract's permanent records rather than a temporary copy.
  • return info.totalAmountForSale - info.amountSold; subtracts the number already sold from the number put on sale and returns the result.

That subtraction is only correct if totalAmountForSale is lowered every time tokens leave the contract outside a normal sale. The withdrawal function, however, sends tokens out without touching totalAmountForSale. The two numbers drift apart, and the helper keeps reporting the original amount even though some of the tokens backing it are no longer in the contract.

Exploitation

Step 1: the admin withdraws unsold tokens

This is the withdrawal function as quoted in the report:

Solidity
/**
 * @dev Allows the token admin to withdraw unsold ArcTokens after a sale (or if disabled).
 * @param _tokenContract The ArcToken contract address.
 * @param to The address to send the tokens to.
 * @param amount The amount of ArcTokens to withdraw.
 */
function withdrawUnsoldArcTokens(
    address _tokenContract,
    address to,
    uint256 amount
) external onlyTokenAdmin(_tokenContract) {
    if (to == address(0)) {
        revert CannotWithdrawToZeroAddress();
    }
    if (amount == 0) {
        revert AmountMustBePositive();
    }

    ArcToken token = ArcToken(_tokenContract);
    uint256 contractBalance = token.balanceOf(address(this));
    if (contractBalance < amount) {
        revert InsufficientUnsoldTokens();
    }

    bool success = token.transfer(to, amount);
    if (!success) {
        revert ArcTokenWithdrawalFailed();
    }
}

Line by line:

  • The comment block above the function explains its purpose: let the token admin take back unsold ArcTokens after a sale, or when the sale has been disabled. It also documents the three inputs.
  • function withdrawUnsoldArcTokens( begins the function, which takes _tokenContract (which token), to (where the tokens go) and amount (how many).
  • external onlyTokenAdmin(_tokenContract) means it can be called from outside, but the modifier first checks that the caller is the admin for that token.
  • if (to == address(0)) checks whether the destination is the special zero address, which is a common way of saying "nowhere". If so, revert CannotWithdrawToZeroAddress(); stops the transaction with that error.
  • if (amount == 0) rejects a withdrawal of nothing, reverting with AmountMustBePositive();.
  • ArcToken token = ArcToken(_tokenContract); treats the supplied address as an ArcToken contract so its functions can be called.
  • uint256 contractBalance = token.balanceOf(address(this)); asks the token contract how many tokens this contract currently holds. address(this) means "this contract's own address".
  • if (contractBalance < amount) checks that the contract actually holds at least the requested amount. If not, it reverts with InsufficientUnsoldTokens();.
  • bool success = token.transfer(to, amount); sends the tokens and records whether the transfer reported success.
  • if (!success) reverts with ArcTokenWithdrawalFailed(); if the transfer did not succeed.

What the function never does is lower info.totalAmountForSale. Its only check is against the live token balance, not against the recorded sale amount. So the tokens leave, but the ledger entry for how much was on sale stays where it was.

Step 2: the availability figure stays inflated

After the withdrawal, getMaxNumberOfTokens() still returns info.totalAmountForSale - info.amountSold. That number is now larger than the number of tokens the contract can actually hand over. Any website that relies on this helper shows buyers more availability than really exists.

A simple comparison: a ticket office prints 100 tickets, sells 40, and the manager takes the remaining 60 back to head office. The board outside still says 60 seats available, but the box office has none left to give.

Step 3: buyers waste gas on reverting purchases

A buyer who trusts the displayed number submits a buy() transaction. Because the contract no longer holds enough tokens to cover the reported amount, the purchase reverts with ContractBalanceInsufficient. The buyer pays gas for a transaction that could never succeed.

Root cause

The record of how much is for sale is kept in two places that are not kept in step. totalAmountForSale is the figure getMaxNumberOfTokens() relies on, but the withdrawal path only checks the contract's token balance and never adjusts that figure. The balance check in withdrawUnsoldArcTokens() does stop the admin taking more than the contract holds, so it does not catch the mismatch between the recorded sale amount and the remaining balance. The result is a stale counter that overstates availability.

Impact

No funds are lost. The effect is that websites show inflated availability, and honest buyers can waste gas on buy() transactions that revert with ContractBalanceInsufficient. The report files this under theft of gas and rates it low severity. The impact only appears once the admin has withdrawn unsold tokens.

Fix

The report recommends adjusting the accounting whenever unsold tokens are withdrawn, and gives an example patch:

Solidity
function withdrawUnsoldArcTokens(...)
    external onlyTokenAdmin(_tokenContract)
{
    TokenInfo storage info = ps.tokenInfo[_tokenContract];

    if (amount > (info.totalAmountForSale - info.amountSold)) {
        revert InsufficientUnsoldTokens();
    }

    info.totalAmountForSale -= amount;      // ← keep quota consistent
    token.safeTransfer(to, amount);
}

Line by line:

  • function withdrawUnsoldArcTokens(...) is the same function, with the argument list shortened here for brevity.
  • external onlyTokenAdmin(_tokenContract) keeps the same admin-only guard.
  • TokenInfo storage info = ps.tokenInfo[_tokenContract]; loads the stored record for this token so its fields can be changed.
  • if (amount > (info.totalAmountForSale - info.amountSold)) checks the request against the unsold amount (total on sale minus sold) rather than only against the contract balance. If the request is larger, it reverts with InsufficientUnsoldTokens();.
  • info.totalAmountForSale -= amount; lowers the recorded total by the amount withdrawn, with a comment noting that this keeps the sale amount consistent.
  • token.safeTransfer(to, amount); sends the tokens out.

The patch does two things: it limits the withdrawal to the unsold amount rather than just the contract balance, and it lowers totalAmountForSale by the withdrawn amount so getMaxNumberOfTokens() stays accurate.

Variants to test

These are wider checks useful when reviewing similar code:

  1. Look for other read-only helpers that work out availability from a stored total minus a stored sold counter, and check every path that moves tokens out of the contract (admin withdrawals, refunds, migrations). A positive result is a helper whose answer is larger than the contract's real token balance after such a path runs.
  2. Check withdrawal and rescue functions that validate only against balanceOf(address(this)). A positive result is a function that can move tokens without updating the counters the rest of the contract reads.
  3. Compare every function that changes state against the fields it is expected to maintain. A positive result is a field that is written on purchase but never on removal, leaving derived views stale.
  4. Test the boundary in the suggested fix: withdrawing exactly totalAmountForSale - amountSold. A positive result is a path where the amount can still be exceeded or where the subtraction underflows (goes below zero, which an unsigned number cannot do).

Hunting notes

This kind of bug hides in the gap between a contract's bookkeeping and its actual token balance. During a review, list every stored counter that feeds a public view, then trace every function that moves tokens in or out and confirm the counter is updated on each path.

The impact here is indirect, which is why it lands as low severity. The researcher showed a concrete consequence, buyers submitting buy() transactions that revert with ContractBalanceInsufficient and paying gas for nothing, and tied it to a specific helper that websites call.

Glossary

  • Admin: the account with special permission to run certain functions, here the token admin.
  • Blockchain: a shared record book kept by many computers, which smart contracts run on.
  • buy(): the function a buyer calls to purchase tokens.
  • ContractBalanceInsufficient: the error the purchase reverts with when the contract does not hold enough tokens to fulfil it.
  • Counter: a stored number that the contract keeps and updates, such as how many tokens were sold.
  • Front-end: the website or app a person uses, which reads data from the smart contract and displays it.
  • Gas: the fee paid to the network for running a transaction, charged even when the transaction fails.
  • Modifier: a guard attached to a function that checks a condition before the function body runs, such as onlyTokenAdmin.
  • Revert: when a smart contract refuses to finish a transaction because a rule was broken; the transaction is undone but the gas is not refunded.
  • Smart contract: a small program that lives on a blockchain and runs automatically when called.
  • Stale counter: a stored number that was not updated after something changed, so it no longer matches reality.
  • Token: a digital item tracked by a smart contract; here, ArcToken.
  • totalAmountForSale: the stored figure for how many tokens were put on sale.
  • amountSold: the stored figure for how many tokens have been sold.
  • Underflow: when a subtraction on an unsigned number would go below zero, which is not allowed.
  • View function: a function that only reads information from a contract and changes nothing; it costs no gas to call.

More from Plume Network

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.