Skip to content
Business logic Audit finding Intermediate

ERC20TokenEmitter::buyToken function mints more tokens to users than it should do

The buyToken function calculates tokens for creators and buyers separately using the same current token supply, which breaks the VRGDA pricing logic and mints more governance tokens than it should for the same ETH.

osmanozdemir1 Follow with rouhsamad, KupiaSec and 9 others

Originally disclosed on Code4rena

Submitted by osmanozdemir1, also found by rouhsamad, KupiaSec, deepplus, BARW, 0xDING99YA, bart1e, SpicyMeatball, DanielArmstrong, haxatron, Brenzee, and rvierdiiev

https://github.com/code-423n4/2023-12-revolutionprotocol/blob/d42cc62b873a1b2b44f57310f9d4bbfdd875e8d6/packages/revolution/src/ERC20TokenEmitter.sol#L180

https://github.com/code-423n4/2023-12-revolutionprotocol/blob/d42cc62b873a1b2b44f57310f9d4bbfdd875e8d6/packages/revolution/src/ERC20TokenEmitter.sol#L184

https://github.com/code-423n4/2023-12-revolutionprotocol/blob/d42cc62b873a1b2b44f57310f9d4bbfdd875e8d6/packages/revolution/src/ERC20TokenEmitter.sol#L200-L215

Users can buy governance tokens with the ERC20TokenEmitter::buyToken() function. In this protocol, governance token prices are determined by a linear VRGDA calculation. The token price increases if the token supply is ahead of the schedule and decreases if it is behind the schedule.

There are also some other parameters I need to mention, which are creatorRateBps and entropyRateBps.

  • creatorRateBps: The portion that goes to the creator anytime a token is bought.
  • entropyRateBps: The portion of the creator’s cut that is paid directly as ETH. The remaining part of the creator’s cut is used to buy governance tokens for the creator.

For example, if the creator rate is 10%, the entropy rate is 50%, and a user wants to buy 100 ETH worth of tokens:

  • Creator cut is 10 ETH
  • 5 ETH will be sent directly to the creator
  • The other 5 ETH will be used to buy governance tokens for the creator.
  • The user will get 90 ETH worth of governance tokens.

This is the main logic in the ERC20TokenEmitter contract.

Now, let’s examine the buyToken function: https://github.com/code-423n4/2023-12-revolutionprotocol/blob/d42cc62b873a1b2b44f57310f9d4bbfdd875e8d6/packages/revolution/src/ERC20TokenEmitter.sol#L152C3-L230C6

    function buyToken(
        address[] calldata addresses,
        uint[] calldata basisPointSplits,
        ProtocolRewardAddresses calldata protocolRewardsRecipients
    ) public payable nonReentrant whenNotPaused returns (uint256 tokensSoldWad) {
        // ... some code

        // Get value left after protocol rewards
        uint256 msgValueRemaining = _handleRewardsAndGetValueToSend(
            msg.value,
            protocolRewardsRecipients.builder,
            protocolRewardsRecipients.purchaseReferral,
            protocolRewardsRecipients.deployer
        );

        //Share of purchase amount to send to treasury
173.    uint256 toPayTreasury = (msgValueRemaining * (10_000 - creatorRateBps)) / 10_000;

        //Share of purchase amount to reserve for creators
        //Ether directly sent to creators
177.    uint256 creatorDirectPayment = ((msgValueRemaining - toPayTreasury) * entropyRateBps) / 10_000;
        //Tokens to emit to creators
179.      int totalTokensForCreators = ((msgValueRemaining - toPayTreasury) - creatorDirectPayment) > 0
180.-->     ? getTokenQuoteForEther((msgValueRemaining - toPayTreasury) - creatorDirectPayment)
            : int(0);

        // Tokens to emit to buyers
184.--> int totalTokensForBuyers = toPayTreasury > 0 ? getTokenQuoteForEther(toPayTreasury) : int(0); //@audit-issue tokensForCreators and tokensForBuyers are calculated separately based on their proportional ether payments. This breaks VRGDA logic because these separate calculation are both made according to the current token supply. These two calculations should not be independent of each other

        //Transfer ETH to treasury and update emitted
        emittedTokenWad += totalTokensForBuyers;
        if (totalTokensForCreators > 0) emittedTokenWad += totalTokensForCreators;

        //... rest of the code
        // funds are transferred and these amounts are minted.
    }

This function:

  1. Calculates buyers’ ETH share in line 173.
  2. Calculates direct ETH payment to creators in line 177.
  3. Calculates token amount to mint for creators with the remaining ETH after direct payment in lines 179-180 using getTokenQuoteForEther function.
  4. Calculates token amount to mint for buyers in line 184 using getTokenQuoteForEther function
  5. After all of these calculations, it updates emittedTokenWad parameter.

Now let’s check the getTokenQuoteForEther function:

    function getTokenQuoteForEther(uint256 etherAmount) public view returns (int gainedX) {
        //...
        return
            vrgdac.yToX({
                timeSinceStart: toDaysWadUnsafe(block.timestamp - startTime),
-->             sold: emittedTokenWad, //@audit it uses current state variable
                amount: int(etherAmount)
            });
    }

As we can see in this function, how many governance tokens will be minted is calculated according to the current supply, which is emittedTokenWad parameter.

Alright, what is the issue?

The issue is that both of the totalTokensForCreators and totalTokensForBuyers parameters are separately calculated like they are independent of each other, and the emittedTokenWad is updated after that. However, this situation breaks the VRGDA logic and more tokens are minted for the same amount of ETH.

These two calculations should not be independent. Total governance tokens to mint for the total ETH payment should be calculated first, and then the governance token amounts should be proportionally distributed.

Calculating proportional ETH amounts for the buyer and the creator first, and then determining the corresponding governance tokens to mint separately, leads to a higher total number of governance tokens to be minted compared to calculating the total governance tokens required based on the overall ETH amounts to be paid.

Impact

  • Protocol mints more governance tokens are minted than it should be.

Proof of Concept

Coded PoC

Down below you can find a basic PoC that proves calculating tokens to mint separately results in many more tokens than calculating it only once with total payment.

You can use the protocol’s own setup to run this PoC -Copy and paste the snippet into the ERC20TokenEmitter.t.sol test file -Run it with forge test --match-test testTokenQuoteForEther_is1plus1equal2 -vvv

    function testTokenQuoteForEther_is1plus1equal2() public {
        int256 tokenToGetFor100ether = erc20TokenEmitter.getTokenQuoteForEther(100e18);
        int256 tokenToGetFor500ether = erc20TokenEmitter.getTokenQuoteForEther(500e18);
        int256 tokenToGetFor600ether = erc20TokenEmitter.getTokenQuoteForEther(600e18);

        // Calculating mint amounts separately will result in minting much more tokens.
        assertGt(tokenToGetFor100ether + tokenToGetFor500ether, tokenToGetFor600ether);
        console2.log("current total: ", tokenToGetFor100ether + tokenToGetFor500ether);
        console2.log("supposed total: ", tokenToGetFor600ether);
    }

Results after running:

Running 1 test for test/token-emitter/ERC20TokenEmitter.t.sol:ERC20TokenEmitterTest
[PASS] testTokenQuoteForEther_is1plus1equal2() (gas: 41635)
Logs:
  current total:  586751802158813828000
  supposed total:  581798293495083372000

Test result: ok. 1 passed; 0 failed; 0 skipped; finished in 41.60ms.

Ran 1 test suites: 1 tests passed, 0 failed, 0 skipped (1 total tests).

Tools Used

Foundry

Recommended Mitigation Steps

There are two ways to resolve this issue. An unfair but much easier one, and the fair but not that easy one

Unfair One: The protocol team should decide which side (creators or buyers) will suffer from the unfairness, and update the emittedTokenWad in the middle of two calculations. The latter calculation will buy tokens at a higher price.

In the example below, the change is in favour of the creators. Buyers get tokens with updated prices to keep the VRGDA logic intact.

        //Tokens to emit to creators
        int totalTokensForCreators = ((msgValueRemaining - toPayTreasury) - creatorDirectPayment) > 0
            ? getTokenQuoteForEther((msgValueRemaining - toPayTreasury) - creatorDirectPayment)
            : int(0);

+       // Moving this here will keep the VRGDA logic intact, and the calculation for buyers will be made with updated token supply.
+       if (totalTokensForCreators > 0) emittedTokenWad += totalTokensForCreators;

        // Tokens to emit to buyers
        int totalTokensForBuyers = toPayTreasury > 0 ? getTokenQuoteForEther(toPayTreasury) : int(0);

        //Transfer ETH to treasury and update emitted
        emittedTokenWad += totalTokensForBuyers;
-       if (totalTokensForCreators > 0) emittedTokenWad += totalTokensForCreators;

Fair One: This one requires a little more work but it is more fair. The function should:

  1. Calculate the total ETH payment (creators + buyers) for the governance token purchase.
  2. Calculate how many total governance tokens will be minted with this total ETH payment
  3. Then mint proportional amounts to buyers and creators.

Example:

// Note: This is not diff. It is just an example

// Creators ETH payment for purchase
uint256 creatorsPayment = (msgValueRemaining - toPayTreasury) - creatorDirectPayment)

// Total ETH payment for purchase (toPayTreasury is already buyers payment)
uint256 totalPayment = toPayTreasury + creatorsPayment;

// Get total governance tokens to mint
int totalGovernanceTokenAmount = getTokenQuoteForEther(totalPayment);

// Calculate proportional governance token amounts.
// Note: I didn't check this for rounding. Care should be taken if this method will be implemented
int totalTokensForCreators = (totalGovernanceTokenAmount * creatorsPayment) / totalPayment;
int totalTokensForBuyers = (totalGovernanceTokenAmount * toPayTreasury) / totalPayment;

rocketman-21 (Revolution) confirmed


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

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the token amounts for the buyer and creator portions are computed independently from the same pre-update supply instead of first computing the total tokens for the combined ETH and then splitting proportionally.

Impact

The protocol mints more governance tokens than it should for the same ETH, diluting the token supply.

What the attacker needed

None

The fix

The function should calculate the total ETH payment for both creators and buyers, get the total governance tokens for that amount, and then distribute proportionally; alternatively, update emittedTokenWad between the two calculations.

How it was found

  1. Call getTokenQuoteForEther with 100 ether and with 500 ether.
  2. Call getTokenQuoteForEther with 600 ether.
  3. Compare the sum of the first two results with the third result.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

This is a smart contract that sells governance tokens at a price that rises as more tokens are sold. The bug is that when a purchase is split between the buyer and the creator, the contract works out each share's token amount as if the other share did not exist, so it hands out too many tokens overall.

What is Business logic?

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

More by osmanozdemir1

View all

5 more disclosed reports, best first.

More from Revolution Protocol

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.