Skip to content
Business logic Audit finding Intermediate

Incorrect voting power calculation when create_lock and increase_amount are called in the same transaction

When create_lock and increase_amount are called in the same transaction, the checkpoint function creates a new epoch with the same timestamp, causing the second lock to be ignored in balanceOfNFT. As a result, voting power is calculated using only the old lock amount, so users receive fewer rewards than they should.

dreamcoder Follow with fullstop

Originally disclosed on Code4rena

Submitted by dreamcoder, also found by fullstop

VotingEscrow.sol #L760

Summary

In VotingEscrow.sol:

function _checkpoint(
        uint _tokenId,
        IVotingEscrow.LockedBalance memory old_locked,
        IVotingEscrow.LockedBalance memory new_locked
    ) internal {

    // ...

    if (_tokenId != 0) {

        // ...
        uint user_epoch = votingBalanceLogicData.user_point_epoch[_tokenId] + 1;

        votingBalanceLogicData.user_point_epoch[_tokenId] = user_epoch;
        u_new.ts = block.timestamp;
        u_new.blk = block.number;
        votingBalanceLogicData.user_point_history[_tokenId][user_epoch] = u_new;

    }

}

If the second _checkpoint runs in the same transaction as the first _checkpoint, the function creates a new epoch even though both locks has the same timestamp. As a result, when calculating balanceOfNFT, the second lock is ignored. This means the voting power is computed using the old lock amount, and the newly added amount is not included.

Therefore, voting power is calculated incorrectly and users will lose rewards when the functions that call checkpoint (increaseamount, depositfor, createlock, merge, split etc) are executed within the same transaction.

Recommended mitigation steps

function _checkpoint(
        uint _tokenId,
        IVotingEscrow.LockedBalance memory old_locked,
        IVotingEscrow.LockedBalance memory new_locked
    ) internal {

    // ...

    if (_tokenId != 0) {

        // ...
-        uint user_epoch = votingBalanceLogicData.user_point_epoch[_tokenId] + 1;
-        votingBalanceLogicData.user_point_epoch[_tokenId] = user_epoch;
-        u_new.ts = block.timestamp;
-        u_new.blk = block.number;
-        votingBalanceLogicData.user_point_history[_tokenId][user_epoch] = u_new;

+        uint user_epoch = votingBalanceLogicData.user_point_epoch[_tokenId];
+        if (user_epoch > 0 && votingBalanceLogicData.user_point_history[_tokenId][user_epoch].ts == block.timestamp) {
      // overwrite the latest point (same timestamp)
+            u_new.ts = block.timestamp;
+            u_new.blk = block.number;
+            votingBalanceLogicData.user_point_history[_tokenId][user_epoch] = u_new;
+         } else {
      // append new point
+            user_epoch = user_epoch + 1;
+            votingBalanceLogicData.user_point_epoch[_tokenId] = user_epoch;
+            u_new.ts = block.timestamp;
+            u_new.blk = block.number;
+            votingBalanceLogicData.user_point_history[_tokenId][user_epoch] = u_new;
         }
    }

}

Proof of concept

In /ve33/test/C4PoC.t.sol:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

import "forge-std/Test.sol";

import {C4PoCTestbed} from "./C4PoCTestbed.t.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Bribe} from "../contracts/Bribes.sol";

contract MockBribeToken is ERC20 {
    constructor(string memory name, string memory symbol) ERC20(name, symbol) {
        _mint(msg.sender, 1_000_000e18);
    }
    function mint(address to, uint256 amount) external {
        _mint(to, amount);
    }
}
contract C4PoC is C4PoCTestbed {
    function setUp() public override {
        super.setUp();
    }

function test_incorrect_voting_power_increase_amount_in_same_transaction() public {
        uint256 WEEK = 1800 + 301;
        vm.warp(3 * WEEK);
        // Actors
        address alice = vm.addr(100);
        address bob = vm.addr(200);
        uint256 lockAmount = 1_000e18;
        uint256 bribeReward = 500e18;

        // Bribe Setup
        MockBribeToken bribeToken = new MockBribeToken("Bribe Coin", "BC");
        address bribeTokenAddress = address(bribeToken);
        bribeFactoryV3.initialize(address(voter), address(gaugeManager), address(permissionsRegistry), address(tokenHandler));
        permissionsRegistry.setRoleFor(deployer, "GOVERNANCE");
        vm.startPrank(deployer);
        tokenHandler.whitelistToken(address(bribeToken));
        tokenHandler.whitelistToken(address(hybr));
        tokenHandler.whitelistConnector(address(hybr));
        tokenHandler.whitelistConnector(address(bribeToken));
        vm.stopPrank();
        address pool = thenaFiFactory.createPair(address(hybr), address(bribeToken), false);
        (address _gauge, address _internal_bribe, address _external_bribe) = gaugeManager.createGauge(address(pool), 0);

Bribe bribeContract = Bribe(_internal_bribe);
        address bribeAddress = _internal_bribe;

        // Fund Alice and bob
        vm.startPrank(deployer);
        hybr.transfer(alice, lockAmount * 2);
        hybr.transfer(bob, lockAmount);
        vm.stopPrank();

        uint256 lockDuration = 365 * 86400; // 1 years in seconds
        uint256 lockEnd = block.timestamp + lockDuration;

//create lock
        //Alice locks lockAmount /2 and increase lockAmount / 2, so total =  lockAmount

        vm.startPrank(alice);
        hybr.approve(address(votingEscrow), lockAmount);
        uint256 aliceTokenId = votingEscrow.create_lock(lockAmount / 2, lockEnd);
        votingEscrow.increase_amount(aliceTokenId, lockAmount / 2);

        //Bob locks lockAmount lockAmount, so total = lockAmount
        vm.stopPrank();
        vm.startPrank(bob);
        hybr.approve(address(votingEscrow), lockAmount);
        uint256 bobTokenId = votingEscrow.create_lock(lockAmount, lockEnd);
        vm.stopPrank();

        uint256 finalAliceBalance = bribeToken.balanceOf(alice);
        uint256 finalBobBalance = bribeToken.balanceOf(bob);

// voting
        address[] memory pools = new address[](1);
        pools[0] = address(pool);
        uint256[] memory weights = new uint256[](1);
        weights[0] = 10000;
        vm.prank(alice);
        voter.vote(aliceTokenId, pools, weights);

        vm.prank(bob);
        voter.vote(bobTokenId, pools, weights);

// bribe reward
        vm.prank(deployer);
        bribeToken.mint(deployer, bribeReward);
        bribeToken.approve(bribeAddress, bribeReward);
        vm.prank(deployer);
        bribeContract.notifyRewardAmount(bribeTokenAddress, bribeReward);

vm.warp(block.timestamp + lockDuration + 10200);

        address[][] memory tokens = new address[][](1);
        tokens[0] = new address[](1);
        tokens[0][0] = bribeTokenAddress;

        address[] memory bribes = new address[](1);
        bribes[0] = address(bribeContract);

        vm.prank(alice);
        gaugeManager.claimBribes(bribes, tokens, aliceTokenId);

vm.prank(bob);
        gaugeManager.claimBribes(bribes, tokens, bobTokenId);

finalAliceBalance = bribeToken.balanceOf(alice);
        finalBobBalance = bribeToken.balanceOf(bob);
        (int128 amount1, ,) = votingEscrow.locked(aliceTokenId);
        (int128 amount2, ,) = votingEscrow.locked(bobTokenId);
        console.log("Alice's lock balance = ", amount1);
        console.log("Bob's lock balance = ", amount2);
        console.log("Alice's Final Bribe Balance = ", finalAliceBalance);
        console.log("Bob's Final Bribe Balance = ", finalBobBalance);

    }
}

Run command

forge test --mt test_incorrect_voting_power_increase_amount_in_same_transaction -vv

Output:

  Alice's lock balance =  1000000000000000000000
  Bob's lock balance =  1000000000000000000000
  Alice's Final Bribe Balance =  166666666666666666666
  Bob's Final Bribe Balance =  333333333333333333333

As result shows, both users have the same lock balance, but Alice received less reward by incorrect power voting calculation.

Hybra Finance mitigated:

S-635 Fix voting power when createlock + increaseamount in same tx Ensure correct voting power calculation when createlock and increaseamount are called in the same transaction. S-470 Penalty Mechanism for PartnerNFT

Status: Mitigation confirmed. Full details in the mitigation review reports from niffylord, rayss, and ZanyBonzy.


The original report as published on Code4rena, by dreamcoder. 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

The _checkpoint function always appends a new epoch without checking if an epoch with the same timestamp already exists, so a second checkpoint in the same transaction overwrites the first but balanceOfNFT only reads the first.

Impact

Users who call create_lock and increase_amount in the same transaction receive less voting power and therefore fewer rewards than they should, as demonstrated by Alice receiving half the reward of Bob despite equal lock balances.

What the attacker needed

Ability to call create_lock and increase_amount in one…; A voting escrow system with checkpoint logic

The fix

The _checkpoint function should check if the latest epoch has the same timestamp and overwrite it instead of appending a new one; the project mitigated this and the mitigation was confirmed.

How it was found

  1. Alice calls create_lock with half the amount and then increase_amount with the other half in the same transaction.
  2. Bob calls create_lock with the full amount in a separate transaction.
  3. Both users vote with their token IDs.
  4. Bribe rewards are distributed and both users claim.
  5. Alice receives less reward than Bob despite having the same final lock balance.

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 bug in a voting escrow system. When a user creates a lock and then increases the amount in the same transaction, the contract records two separate checkpoints with the same timestamp. The balance calculation only looks at the first checkpoint, so the extra amount is ignored and the user gets less voting power and fewer rewards.

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 from Hybra Finance

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.