Skip to content
Smart contracts Audit finding Intermediate

Rounding error in stepDuration calculations.

The vesting contract calculates step duration by integer division, which can round down to zero or cause the schedule to finish early. An attacker could cause a denial of service on the claim function or make vesting complete prematurely.

sl1 Follow with 056Security, 056Security and 21 others

Originally disclosed on Code4rena

Submitted by sl1, also found by 056Security, 056Security, 0xEkko, 0xrex, agadzhalov, codertjay, Drynooo, Fon, gesha17, IzuMan, ka14ar, KiteWeb3, macart224, montecristo, NexusAudits, NexusAudits, oualidpro, pulse, rouhsamad, TheKhans, Viquetour, yuza101, and Z3R0

https://github.com/code-423n4/2024-12-secondswap/blob/214849c3517eb26b31fe194bceae65cb0f52d2c0/contracts/SecondSwap_StepVesting.sol#L133

When deploying a vesting plan, token issuer can specify the end time of the schedule and number of steps over which tokens should be released. StepVesting calculates the duration of each distinctive step by dividing the duration of the schedule by number of steps.

SecondSwap_StepVesting.sol#L131-L133

endTime = _endTime;
numOfSteps = _numOfSteps;
stepDuration = (_endTime - _startTime) / _numOfSteps;

However, currently it’s possible for calculations to round down, which could lead to multiple problems.

First, consider a scenario where calculations of stepDuration round down to 0. This will result in inability to claim funds from the StepVesting contract. In order to claim tokens from the vesting schedule, a user must call claim() function of the contract, which in turn will call claimable() to get the amount of tokens currently available for claim.

SecondSwap_StepVesting.sol#L193-L194

function claim() external {
    (uint256 claimableAmount, uint256 claimableSteps) = claimable(
        msg.sender
    );

When claimable() is invoked, it will try to calculate current step by dividing elapsed time by duration of the step, which will revert as solidity does not support division by 0.

SecondSwap_StepVesting.sol#L173

uint256 currentStep = elapsedTime / stepDuration;

Secondly, because of the rounding, it’s possible that vesting will be completed earlier than the schedule. Consider a 3 month vesting plan which equals 7884000 seconds and the number of steps is 1000000. The step duration will be calculated as 7884000 / 1000000 = 7.884, which will round down to 7. Now the actual time it will take to complete the schedule is 7 * 1000000 = 7000000 seconds, which is 81 days, meaning that vesting is completed roughly 10 days earlier than the schedule.

Impact

DoS of the claim() function of the StepVesting contract and premature ending of the vesting schedule.

Proof of Concept

To set up the following PoC in foundry please follow the steps.

Inside the hardhat project directory:

  • npm install --save-dev @nomicfoundation/hardhat-foundry
  • Add import "@nomicfoundation/hardhat-foundry"; to the top of your hardhat.config.js file.
  • Run npx hardhat init-foundry in your terminal. This will generate a foundry.toml file based on your Hardhat project’s existing configuration, and will install the forge-std library.

Run it with forge test --match-test 'test_sl1VestingCompletedEarlier' -vv.

import "lib/forge-std/src/Test.sol";
import "lib/forge-std/src/console2.sol";
import {SecondSwap_Marketplace} from "../contracts/SecondSwap_Marketplace.sol";
import {SecondSwap_MarketplaceSetting} from "../contracts/SecondSwap_MarketplaceSetting.sol";
import {SecondSwap_StepVesting} from "../contracts/SecondSwap_StepVesting.sol";
import {SecondSwap_VestingDeployer} from "../contracts/SecondSwap_VestingDeployer.sol";
import {SecondSwap_VestingManager} from "../contracts/SecondSwap_VestingManager.sol";
import {TestToken1} from "../contracts/USDT.sol";

contract sl1Test is Test {
    SecondSwap_Marketplace public marketplace;
    SecondSwap_MarketplaceSetting public marketplaceSettings;
    SecondSwap_VestingDeployer public vestingDeployer;
    SecondSwap_VestingManager public vestingManager;
    TestToken1 public USDT;

    address admin = makeAddr("admin");
    address whitelist;

    function setUp() public {
        vm.startPrank(admin);
        USDT = new TestToken1();
        vestingManager = new SecondSwap_VestingManager();
        vestingManager.initialize(admin);
        marketplaceSettings = new SecondSwap_MarketplaceSetting(
            admin,
            admin,
            whitelist,
            address(vestingManager),
            address(USDT)
        );
        marketplace = new SecondSwap_Marketplace();
        marketplace.initialize(address(USDT), address(marketplaceSettings));
        vestingDeployer = new SecondSwap_VestingDeployer();
        vestingDeployer.initialize(admin, address(vestingManager));

        vestingManager.setVestingDeployer(address(vestingDeployer));
        vestingManager.setMarketplace(address(marketplace));
        vm.stopPrank();
    }

    function test_sl1VestingCompletedEarlier() public {
        address alice = makeAddr("alice");

        vm.startPrank(admin);

        vestingDeployer.setTokenOwner(address(USDT), admin);
        // step duration is 7.884, but it rounds down to 7
        vestingDeployer.deployVesting(
            address(USDT),
            block.timestamp,
            // 3 month vesting
            block.timestamp + 7884000,
            // num of steps
            1000000,
            "1"
        );
        // Got the address by console logging it in deployVesting func
        address stepVesting = 0xD478411c1478E645A6bb53209E689080aE5101A1;

        USDT.approve(stepVesting, 10000e18);
        vestingDeployer.createVesting(alice, 10000e18, stepVesting);

        vm.stopPrank();

        // vesting completed 884000 earlier, which is 10 days earlier than the schedule
        vm.warp(block.timestamp + 1000000 * 7);
        vm.prank(alice);
        SecondSwap_StepVesting(stepVesting).claim();
        assertEq(USDT.balanceOf(alice), 10000e18);
    }

Recommended Mitigation

When calculating stepDuration revert when _endTime - _startTime is not perfectly divisible by _numOfSteps.

sl1 (warden) commented:

Hey Koolex, thank you for judging!

The only reason why I submitted this finding is because contest page mentioned that sponsor’s concerns were: “What would happen if the amount of locked tokens, duration or number of cycles are on the reaches extremes?“.

And even though I don’t necessarily think that 1000000 steps is a super extreme value, but even if we consider it as such, given the attack ideas section of the contest page, I believe this issue should be valid.

Koolex (judge) commented:

@sl1

First, consider a scenario where calculations of stepDuration round down to 0.

Can you explain the possibility of such scenario? what would be the setting by token issuer?

Also, can you give other possibilities with less steps and less vesting plan?

At this moment, it’s duped to F-121. Although, this might be selected as main.

Note: F-121 is S-867 at this moment.

sl1 (warden) commented:

For stepDuration to round down to 0, the result of a calculation should be a 0.999 value or anything less. For example, if the duration of the vesting schedule is 86400 and number of steps is 86401, the calculations will round down to 0. Personally, I think this is less likely than the second scenario provided, so I want to focus on that more.

When calculating stepDuration we use this formula: (_endTime - _startTime) / _numOfSteps;. Here, the maximum “loss” in seconds can be at most 1 second per step (since at most we can round down from 0.99). If the duration is 190000 and num of steps is 100000, the result value will be 1 second per steps (instead of 1.9 seconds per step), which means that a vesting will be completed 0.9 * 100000 seconds earlier, which in this case is roughly 1 day. The same is true for any other scenario where calculations round down, the only difference would be the magnitude of the issue as there could be a rounding from a lower value, such as 1.4 rounding down to 1, the vesting in this case would be completed 0.4 * 100000 seconds earlier.

I think I don’t have much to add further to the discussion and will leave the decision up to you, thank you!

0xrex (warden) commented:

Hi @Koolex, I would like to stress that both scenarios 1 & 2, pointed out by @sl1 are both very likely to occur in the same weight. I have already left a simple explainer for scenario 1 where the stepDuration does round to 0, but I’ll just grab it from the original report and chunk it here to follow up:

  1. jvotoken protocol owner gets whitelisted by the SecondSwap team to deploy a vesting contract for the jvo token
  2. jvotoken protocol owner calls deployVesting with the following startTime & endTime: startTime = 1733902691, endTime = 1733902692.
  3. jvotoken protocol then proceeds to vest 100e18 of jvo tokens to user A. user A’s releaseRate will be 100e18 / 24 = 4,166,666,666,666,666,666
  4. The entire duration of the vesting elapses. User calls claim. currentTime returned would be the endTime 1733902692. elapsedTime would be 1 because (1733902692 - 1733902691). and in the next line, the function would revert because of a division by 0.
function deployVesting(
        address tokenAddress,
        uint256 startTime,
        uint256 endTime,
        uint256 steps,
        string memory vestingId
    ) external {
        ...
          // @audit not enough validation
@>        require(startTime < endTime, "SS_VestingDeployer: start time must be before end time");
        require(steps > 0, "SS_VestingDeployer: steps must be greater than 0");
        require(manager != address(0), "SS_VestingDeployer: manager not set");

        address newVesting = address(
            new SecondSwap_StepVesting(
                msg.sender, // jvo token protocol
                manager,
                IERC20(tokenAddress), // jvo token
                startTime, // 1733902691
                endTime, // 1733902692
                steps, // 24
                address(this)
            )
        );
        IVestingManager(manager).setSellable(newVesting, true);
        emit VestingDeployed(tokenAddress, newVesting, vestingId);
    }
function claimable(address _beneficiary) public view returns (uint256, uint256) {
        Vesting memory vesting = _vestings[_beneficiary];
        if (vesting.totalAmount == 0) {
            return (0, 0);
        }

 @>       uint256 currentTime = Math.min(block.timestamp, endTime);
        if (currentTime < startTime) {
            return (0, 0);
        }

        uint256 elapsedTime = currentTime - startTime; // 1
@>      uint256 currentStep = elapsedTime / stepDuration; // 1 / 0
        uint256 claimableSteps = currentStep - vesting.stepsClaimed;

        uint256 claimableAmount;

        if (vesting.stepsClaimed + claimableSteps >= numOfSteps) {
            //[BUG FIX] user can buy more than they are allocated
            claimableAmount = vesting.totalAmount - vesting.amountClaimed;
            return (claimableAmount, claimableSteps);
        }

        claimableAmount = vesting.releaseRate * claimableSteps;
        return (claimableAmount, claimableSteps);
    }

Thus, I believe @sl1 is right and these issue sets should be a higher severity than LOW.

Koolex (judge) commented:

Based on the input above, this is a valid Med. This also will be the main submission.


The original report as published on Code4rena, by sl1. 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 integer division truncation when calculating stepDuration, without checking for divisibility or a minimum value.

Impact

The claim function can become unusable (denial of service) if stepDuration rounds to zero, and the vesting schedule may end earlier than intended, releasing tokens prematurely.

What the attacker needed

Token issuer deploys vesting with specific parameters

The fix

The calculation should revert if the duration is not perfectly divisible by the number of steps.

How it was found

  1. Deploy a vesting plan with a duration and number of steps such that the division rounds down (e.g., duration 7884000 seconds, 1000000 steps).
  2. Create a vesting schedule for a beneficiary.
  3. Advance time to when the rounded-down schedule would complete.
  4. Call claim() and observe that the full amount is claimable earlier than the intended end time.

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.

When a vesting schedule is set up, the time between steps is calculated by dividing the total duration by the number of steps. If the division doesn't produce a whole number, the result is rounded down, which can make the step duration zero or make the whole schedule end sooner than intended. This can break the claim function or release tokens too early.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by sl1

View all

4 more disclosed reports, best first.

More from SecondSwap

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.