ClaimRewards Fails to Update State for Zero-Value Periods, Causing Permanent Fund Freeze in unstake
The reward-claiming function returns early when a batch of claimable periods is worth zero, so the user's last-claimed checkpoint never advances. A user with more claimable periods than the configured maximum can then never clear the backlog and is permanently blocked from unstaking their principal.
Vechain | Stargate Hayabusa
Originally disclosed on Immunefi
# 59997 sc medium claimrewards fails to update state for zero value periods causing permanent fund freeze in unstake 
* **Submitted on Nov 17th 2025 at 13:07:33 UTC by @hunraj for Audit Comp | Vechain | Stargate Hayabusa**
* **Report ID:** #59997
* **Report Type:** Smart Contract
* **Report severity:** Medium
* **Target:** <https://github.com/immunefi-team/audit-comp-vechain-stargate-hayabusa/tree/main/packages/contracts/contracts/Stargate.sol>
* **Impacts:** Permanent freezing of funds
## Description
### Brief / Intro
A logic flaw exists in the `_claimRewards` function. When a user has a backlog of claimable periods with a total reward value of zero, the function returns early without updating the user's `lastClaimedPeriod` state. This creates a "trap" state: the user cannot call `unstake` because `unstake` checks `_exceedsMaxClaimablePeriods` and relies on `claimRewards` to advance the checkpoint. Since `claimRewards` returns early, the backlog never shrinks and the user's principal becomes permanently frozen in the contract.
### Vulnerability Details
The protocol uses two safety mechanisms that interact incorrectly:
1. `unstake` Gas Safety: `unstake` reverts if the user has more claimable periods than `maxClaimablePeriods` (e.g., 832) to avoid out-of-gas errors during automatic reward claims. This forces manual clearing of the backlog.
2. `claimRewards` Batching: `claimRewards` is intended to clear the backlog in batches, advancing `lastClaimedPeriod` per batch.
Root cause: `_claimRewards` returns early if the batch's `claimableAmount` is zero, and therefore never updates `lastClaimedPeriod`.
Code excerpt showing the root cause:
```solidity
// In Stargate.sol
function _claimRewards(StargateStorage storage $, uint256 _tokenId) private {
// ... (logic to determine the first and last period of the current batch) ...
uint256 claimableAmount = _claimableRewards($, _tokenId, 0);
// [!] VULNERABILITY ROOT CAUSE [!]
if (claimableAmount == 0) {
return; // The function exits prematurely.
}
// This state update is the entire purpose of the function for clearing the backlog.
// It is NEVER REACHED if rewards are zero.
$.lastClaimedPeriod[_tokenId] = lastClaimedPeriod;
// ... (transfer logic) ...
}
```
### The Catch-22 Execution Path
{% stepper %}
{% step %}
### Step: Pre-condition
A user (Alice) has an `EXITED` delegation with > maxClaimablePeriods (e.g., 832) claimable periods, all with value 0 VTHO (e.g., delegating to an offline validator).
{% endstep %}
{% step %}
### Step: Alice calls `unstake()`
`unstake()` reverts with `MaxClaimablePeriodsExceeded`. This is the intended gas safety mechanism.
{% endstep %}
{% step %}
### Step: Alice calls `claimRewards()`
`_claimRewards` computes `claimableAmount` for the first batch (e.g., first 832 periods). Because rewards are zero, `claimableAmount == 0` and the function executes `return`. `lastClaimedPeriod` is not updated; no backlog progress is made.
{% endstep %}
{% step %}
### Step: Alice calls `unstake()` again
`unstake()` reverts with `MaxClaimablePeriodsExceeded` for the same reason. Alice cannot progress and is permanently locked out from withdrawing her principal.
{% endstep %}
{% endstepper %}
### Impact
This is a Critical outcome: permanent freezing of user funds. A user can be permanently blocked from unstaking if they accumulate many zero-value claimable periods.
## Recommended Remediation
Always update `lastClaimedPeriod` when processing a batch, even when the batch's reward is zero. The function's responsibility is both to pay rewards and to advance the checkpoint for processed periods. Move the state update before returning for zero-value batches.
Proposed fix (move the state update before the zero-amount return):
```solidity
function _claimRewards(StargateStorage storage $, uint256 _tokenId) private {
(uint32 firstClaimablePeriod, uint32 lastClaimedPeriod) = _claimableDelegationPeriods($, _tokenId);
// Check if there are any periods to process at all.
if (firstClaimablePeriod > lastClaimedPeriod) {
return;
}
// Determine the end of the current batch.
uint32 batchEndPeriod = firstClaimablePeriod + $.maxClaimablePeriods - 1;
if (batchEndPeriod > lastClaimedPeriod) {
batchEndPeriod = lastClaimedPeriod;
}
uint256 claimableAmount = 0;
// Calculate rewards ONLY if there's a chance to have them.
if (firstClaimablePeriod <= batchEndPeriod) {
// This loop would calculate the rewards for the batch [firstClaimablePeriod...batchEndPeriod]
// For this PoC, we can represent it as the call to _claimableRewards
claimableAmount = _claimableRewards($, _tokenId, 0);
}
// [!] FIX: Always update the state, regardless of the amount.
// The state update now happens BEFORE the early return.
$.lastClaimedPeriod[_tokenId] = batchEndPeriod;
if (claimableAmount == 0) {
// We've updated the period, so we can now safely return.
return;
}
// Proceed with the transfer logic only if there's an amount to send.
address tokenOwner = $.stargateNFTContract.ownerOf(_tokenId);
VTHO_TOKEN.safeTransfer(tokenOwner, claimableAmount);
emit DelegationRewardsClaimed(
tokenOwner,
_tokenId,
$.delegationIdByTokenId[_tokenId],
claimableAmount,
firstClaimablePeriod,
batchEndPeriod
);
}
```
This ensures progress is always made on clearing claimable periods and prevents permanent lockouts.
## Proof of Concept
A runnable PoC test was provided. The ProtocolStakerMock was slightly modified to allow setting delegator rewards to zero via a helper function so the test can simulate the "unlucky delegator" scenario.
Modification to ProtocolStakerMock.sol (added state variable + helper setter):
```solidity
// In ProtocolStakerMock.sol
contract ProtocolStakerMock is IProtocolStaker {
// Added state variable, initialized to the original hardcoded value.
uint256 private mockDelegatorRewards = 0.1 ether;
// Added helper function to allow the test to change the reward value.
function helper__setDelegatorRewards(uint256 _rewards) external {
mockDelegatorRewards = _rewards;
}
function getDelegatorsRewards(
address _validator,
uint32 _stakingPeriod
) external view override returns (uint256 rewards) {
if (_stakingPeriod > validations[_validator].completedPeriods + 1) {
return 0;
}
// Used the state variable instead of the hardcoded value.
return mockDelegatorRewards;
}
// ... rest of the contract is unchanged
}
```
Runnable Hardhat Test (excerpt):
```javascript
import { expect } from "chai";
import { ethers } from "hardhat";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import {
Stargate,
StargateNFTMock,
ProtocolStakerMock,
StargateNFTMock__factory,
ProtocolStakerMock__factory,
MyERC20__factory,
} from "../../typechain-types";
import { createLocalConfig } from "@repo/config/contracts/envs/local";
import { getOrDeployContracts } from "../helpers";
describe("PoC: Permanent Fund Freeze in unstake", () => {
let deployer: HardhatEthersSigner;
let alice: HardhatEthersSigner;
let validatorX: HardhatEthersSigner;
let stargateContract: Stargate;
let stargateNFTMock: StargateNFTMock;
let protocolStakerMock: ProtocolStakerMock;
const LEVEL_ID = 1;
const MAX_CLAIMABLE_PERIODS = 10;
const VET_STAKED = ethers.parseEther("100");
let aliceTokenId: bigint;
beforeEach(async () => {
// --- 1. SETUP THE FULL TEST ENVIRONMENT ---
const config = createLocalConfig();
[deployer, alice, validatorX] = await ethers.getSigners();
const protocolStakerMockFactory = new ProtocolStakerMock__factory(deployer);
protocolStakerMock = await protocolStakerMockFactory.deploy();
await protocolStakerMock.waitForDeployment();
const stargateNFTMockFactory = new StargateNFTMock__factory(deployer);
stargateNFTMock = await stargateNFTMockFactory.deploy();
await stargateNFTMock.waitForDeployment();
const VTHO_TOKEN_ADDRESS = "0x0000000000000000000000000000456E65726779";
const vthoTokenContractFactory = new MyERC20__factory(deployer);
const tokenContract = await vthoTokenContractFactory.deploy(deployer.address, deployer.address);
await tokenContract.waitForDeployment();
const tokenContractBytecode = await ethers.provider.getCode(await tokenContract.getAddress());
await ethers.provider.send("hardhat_setCode", [VTHO_TOKEN_ADDRESS, tokenContractBytecode]);
config.PROTOCOL_STAKER_CONTRACT_ADDRESS = await protocolStakerMock.getAddress();
config.STARGATE_NFT_CONTRACT_ADDRESS = await stargateNFTMock.getAddress();
config.MAX_CLAIMABLE_PERIODS = MAX_CLAIMABLE_PERIODS;
const contracts = await getOrDeployContracts({ forceDeploy: true, config });
stargateContract = contracts.stargateContract;
await protocolStakerMock.helper__setStargate(await stargateContract.getAddress());
// --- 2. SIMULATE ALICE'S JOURNEY ---
await stargateNFTMock.helper__setLevel({ id: LEVEL_ID, name: "Test Level", isX: false, maturityBlocks: 0, scaledRewardFactor: 100, vetAmountRequiredToStake: VET_STAKED });
await protocolStakerMock.addValidation(validatorX.address, 120);
await protocolStakerMock.helper__setValidatorStatus(validatorX.address, 2);
await stargateContract.connect(alice).stake(LEVEL_ID, { value: VET_STAKED });
aliceTokenId = await stargateNFTMock.getCurrentTokenId();
await stargateNFTMock.helper__setToken({ tokenId: aliceTokenId, levelId: LEVEL_ID, mintedAtBlock: 1, vetAmountStaked: VET_STAKED, lastVetGeneratedVthoClaimTimestamp_deprecated: 0 });
await stargateContract.connect(alice).delegate(aliceTokenId, validatorX.address);
// --- 3. CREATE THE "UNLUCKY DELEGATOR" SCENARIO ---
const INACTIVE_PERIODS = 25;
const lastCompletedPeriod = INACTIVE_PERIODS + 1;
await protocolStakerMock.helper__setValidationCompletedPeriods(validatorX.address, lastCompletedPeriod);
await protocolStakerMock.helper__setDelegatorRewards(0); // CRITICAL STEP: SIMULATE ZERO REWARDS
await stargateContract.connect(alice).requestDelegationExit(aliceTokenId);
await protocolStakerMock.helper__setValidationCompletedPeriods(validatorX.address, lastCompletedPeriod + 1);
const status = await stargateContract.getDelegationStatus(aliceTokenId);
expect(status).to.equal(3); // 3 = EXITED
});
it("should TRAP Alice, preventing her from unstaking her funds", async () => {
// --- VERIFY THE TRAP CONDITIONS ---
const [first, last] = await stargateContract.claimableDelegationPeriods(aliceTokenId);
const numPeriods = last - first + BigInt(1);
console.log(` - Alice has ${numPeriods} claimable periods.`);
console.log(` - Max claimable periods is ${MAX_CLAIMABLE_PERIODS}.`);
expect(numPeriods).to.be.greaterThan(MAX_CLAIMABLE_PERIODS);
const batchRewards = await stargateContract["claimableRewards(uint256,uint32)"](aliceTokenId, 0);
expect(batchRewards).to.equal(0);
console.log(` - Alice's rewards for the first batch: ${batchRewards} VTHO.`);
// --- SPRING THE TRAP ---
console.log("\n ATTEMPT 1: Alice tries to unstake...");
await expect(stargateContract.connect(alice).unstake(aliceTokenId)).to.be.revertedWithCustomError(stargateContract, "MaxClaimablePeriodsExceeded");
console.log(" �
Unstake correctly reverted with MaxClaimablePeriodsExceeded.");
// --- PROVE THE FREEZE IS PERMANENT ---
console.log("\n ATTEMPT 2: Alice tries to claim rewards to clear the periods...");
const claimTx = await stargateContract.connect(alice).claimRewards(aliceTokenId);
await claimTx.wait();
console.log(" �
claimRewards() executed, but the underlying state did not change.");
const [firstAfterClaim, lastAfterClaim] = await stargateContract.claimableDelegationPeriods(aliceTokenId);
const numPeriodsAfterClaim = lastAfterClaim - firstAfterClaim + BigInt(1);
expect(numPeriodsAfterClaim).to.equal(numPeriods);
console.log(` - Alice STILL has ${numPeriodsAfterClaim} claimable periods.`);
console.log("\n ATTEMPT 3: Alice tries to unstake one last time...");
await expect(stargateContract.connect(alice).unstake(aliceTokenId)).to.be.revertedWithCustomError(stargateContract, "MaxClaimablePeriodsExceeded");
console.log(" �
Unstake reverted AGAIN. Alice's funds are permanently frozen.");
console.log("\n --- VULNERABILITY CONFIRMED ---");
});
});
```
Test output from the PoC run:
```
PoC: Permanent Fund Freeze in unstake
- Alice has 26 claimable periods.
- Max claimable periods is 10.
- Alice's rewards for the first batch: 0 VTHO.
ATTEMPT 1: Alice tries to unstake...
�
Unstake correctly reverted with MaxClaimablePeriodsExceeded.
ATTEMPT 2: Alice tries to claim rewards to clear the periods...
�
claimRewards() executed, but the underlying state did not change.
- Alice STILL has 26 claimable periods.
ATTEMPT 3: Alice tries to unstake one last time...
�
Unstake reverted AGAIN. Alice's funds are permanently frozen.
--- VULNERABILITY CONFIRMED ---
✔ should TRAP Alice, preventing her from unstaking her funds
```
***
If you want, I can:
* Produce a patch/PR diff applying the proposed fix in the repository structure referenced.
* Run through alternative mitigations (e.g., special-case `unstake` to allow manual exception flows).## Context
Stargate is the staking contract in the Vechain Stargate Hayabusa codebase, at `packages/contracts/contracts/Stargate.sol`. Users stake VET, receive a Stargate NFT that represents the position, and can delegate that position to a validator. While delegated, the position accrues VTHO rewards per staking period. When the delegation ends, the position enters an `EXITED` state and the accrued rewards become claimable across a range of periods.
Two functions matter here. `claimRewards` pays out the rewards for a batch of periods and is supposed to advance a per-token checkpoint, `lastClaimedPeriod`, so that repeated calls work through a long backlog. `unstake` returns the principal, but only after checking that the number of outstanding claimable periods does not exceed `maxClaimablePeriods`. That check exists to avoid running out of gas while automatically claiming rewards during the unstake. The report shows that these two mechanisms interact badly when the rewards in a batch are worth zero.
## Setup
The proof of concept is a Hardhat test against the project's local configuration, using the project's own mocks and helpers:
- `Stargate`, the contract under test.
- `StargateNFTMock`, the NFT mock.
- `ProtocolStakerMock`, the protocol staker mock, slightly modified for the test.
- `MyERC20`, deployed and then placed at the VTHO token address with `hardhat_setCode`.
- `createLocalConfig` from `@repo/config/contracts/envs/local` and `getOrDeployContracts` from the test helpers.
The test uses three signers: `deployer`, `alice` (the victim) and `validatorX`. The relevant constants are `LEVEL_ID = 1`, `MAX_CLAIMABLE_PERIODS = 10` and `VET_STAKED = 100 VET`. The VTHO token address used in the test is:
```text
[redacted]
```
The precondition for the bug is a user whose delegation has exited while the number of claimable periods is above `maxClaimablePeriods`, and where the rewards for those periods are zero. The report describes this as delegating to an offline validator, an "unlucky delegator" scenario.
## Finding it
The researcher read `_claimRewards` and noticed that it computes the claimable amount for the current batch and then returns early when that amount is zero:
```solidity
// In Stargate.sol
function _claimRewards(StargateStorage storage $, uint256 _tokenId) private {
// ... (logic to determine the first and last period of the current batch) ...
uint256 claimableAmount = _claimableRewards($, _tokenId, 0);
// [!] VULNERABILITY ROOT CAUSE [!]
if (claimableAmount == 0) {
return; // The function exits prematurely.
}
// This state update is the entire purpose of the function for clearing the backlog.
// It is NEVER REACHED if rewards are zero.
$.lastClaimedPeriod[_tokenId] = lastClaimedPeriod;
// ... (transfer logic) ...
}
```
The state update that advances `lastClaimedPeriod` sits after the zero-amount return, so a batch worth nothing is never marked as processed. Since `unstake` relies on `claimRewards` to shrink the backlog, a user whose backlog is entirely zero-value has no way to get below the threshold. The report calls this a trap state and a Catch-22.
## Exploitation
### Step 1: Pre-condition
Alice has an `EXITED` delegation with more than `maxClaimablePeriods` claimable periods, all worth 0 VTHO. In the test this is created by setting the validator's completed periods, setting the delegator rewards to zero, requesting the delegation exit and then advancing the validator's completed periods by one so the delegation status becomes `EXITED` (status value 3).
### Step 2: Alice calls `unstake()`
`unstake()` reverts with `MaxClaimablePeriodsExceeded`. This is the intended gas safety mechanism firing.
### Step 3: Alice calls `claimRewards()`
`_claimRewards` computes `claimableAmount` for the first batch. Because the rewards are zero, `claimableAmount == 0`, the function executes `return`, and `lastClaimedPeriod` is not updated. No backlog progress is made.
### Step 4: Alice calls `unstake()` again
`unstake()` reverts with `MaxClaimablePeriodsExceeded` for the same reason. Alice cannot progress and cannot withdraw her principal.
The runnable test reproduces this. The mock is first modified to allow the delegator rewards to be set to zero:
```solidity
// In ProtocolStakerMock.sol
contract ProtocolStakerMock is IProtocolStaker {
// Added state variable, initialized to the original hardcoded value.
uint256 private mockDelegatorRewards = 0.1 ether;
// Added helper function to allow the test to change the reward value.
function helper__setDelegatorRewards(uint256 _rewards) external {
mockDelegatorRewards = _rewards;
}
function getDelegatorsRewards(
address _validator,
uint32 _stakingPeriod
) external view override returns (uint256 rewards) {
if (_stakingPeriod > validations[_validator].completedPeriods + 1) {
return 0;
}
// Used the state variable instead of the hardcoded value.
return mockDelegatorRewards;
}
// ... rest of the contract is unchanged
}
```
The test itself sets up the environment, stakes, delegates, creates the zero-reward exited delegation and then runs the three attempts:
```javascript
import { expect } from "chai";
import { ethers } from "hardhat";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import {
Stargate,
StargateNFTMock,
ProtocolStakerMock,
StargateNFTMock__factory,
ProtocolStakerMock__factory,
MyERC20__factory,
} from "../../typechain-types";
import { createLocalConfig } from "@repo/config/contracts/envs/local";
import { getOrDeployContracts } from "../helpers";
describe("PoC: Permanent Fund Freeze in unstake", () => {
let deployer: HardhatEthersSigner;
let alice: HardhatEthersSigner;
let validatorX: HardhatEthersSigner;
let stargateContract: Stargate;
let stargateNFTMock: StargateNFTMock;
let protocolStakerMock: ProtocolStakerMock;
const LEVEL_ID = 1;
const MAX_CLAIMABLE_PERIODS = 10;
const VET_STAKED = ethers.parseEther("100");
let aliceTokenId: bigint;
beforeEach(async () => {
// --- 1. SETUP THE FULL TEST ENVIRONMENT ---
const config = createLocalConfig();
[deployer, alice, validatorX] = await ethers.getSigners();
const protocolStakerMockFactory = new ProtocolStakerMock__factory(deployer);
protocolStakerMock = await protocolStakerMockFactory.deploy();
await protocolStakerMock.waitForDeployment();
const stargateNFTMockFactory = new StargateNFTMock__factory(deployer);
stargateNFTMock = await stargateNFTMockFactory.deploy();
await stargateNFTMock.waitForDeployment();
const VTHO_TOKEN_ADDRESS = "[redacted]";
const vthoTokenContractFactory = new MyERC20__factory(deployer);
const tokenContract = await vthoTokenContractFactory.deploy(deployer.address, deployer.address);
await tokenContract.waitForDeployment();
const tokenContractBytecode = await ethers.provider.getCode(await tokenContract.getAddress());
await ethers.provider.send("hardhat_setCode", [VTHO_TOKEN_ADDRESS, tokenContractBytecode]);
config.PROTOCOL_STAKER_CONTRACT_ADDRESS = await protocolStakerMock.getAddress();
config.STARGATE_NFT_CONTRACT_ADDRESS = await stargateNFTMock.getAddress();
config.MAX_CLAIMABLE_PERIODS = MAX_CLAIMABLE_PERIODS;
const contracts = await getOrDeployContracts({ forceDeploy: true, config });
stargateContract = contracts.stargateContract;
await protocolStakerMock.helper__setStargate(await stargateContract.getAddress());
// --- 2. SIMULATE ALICE'S JOURNEY ---
await stargateNFTMock.helper__setLevel({ id: LEVEL_ID, name: "Test Level", isX: false, maturityBlocks: 0, scaledRewardFactor: 100, vetAmountRequiredToStake: VET_STAKED });
await protocolStakerMock.addValidation(validatorX.address, 120);
await protocolStakerMock.helper__setValidatorStatus(validatorX.address, 2);
await stargateContract.connect(alice).stake(LEVEL_ID, { value: VET_STAKED });
aliceTokenId = await stargateNFTMock.getCurrentTokenId();
await stargateNFTMock.helper__setToken({ tokenId: aliceTokenId, levelId: LEVEL_ID, mintedAtBlock: 1, vetAmountStaked: VET_STAKED, lastVetGeneratedVthoClaimTimestamp_deprecated: 0 });
await stargateContract.connect(alice).delegate(aliceTokenId, validatorX.address);
// --- 3. CREATE THE "UNLUCKY DELEGATOR" SCENARIO ---
const INACTIVE_PERIODS = 25;
const lastCompletedPeriod = INACTIVE_PERIODS + 1;
await protocolStakerMock.helper__setValidationCompletedPeriods(validatorX.address, lastCompletedPeriod);
await protocolStakerMock.helper__setDelegatorRewards(0); // CRITICAL STEP: SIMULATE ZERO REWARDS
await stargateContract.connect(alice).requestDelegationExit(aliceTokenId);
await protocolStakerMock.helper__setValidationCompletedPeriods(validatorX.address, lastCompletedPeriod + 1);
const status = await stargateContract.getDelegationStatus(aliceTokenId);
expect(status).to.equal(3); // 3 = EXITED
});
it("should TRAP Alice, preventing her from unstaking her funds", async () => {
// --- VERIFY THE TRAP CONDITIONS ---
const [first, last] = await stargateContract.claimableDelegationPeriods(aliceTokenId);
const numPeriods = last - first + BigInt(1);
console.log(` - Alice has ${numPeriods} claimable periods.`);
console.log(` - Max claimable periods is ${MAX_CLAIMABLE_PERIODS}.`);
expect(numPeriods).to.be.greaterThan(MAX_CLAIMABLE_PERIODS);
const batchRewards = await stargateContract["claimableRewards(uint256,uint32)"](aliceTokenId, 0);
expect(batchRewards).to.equal(0);
console.log(` - Alice's rewards for the first batch: ${batchRewards} VTHO.`);
// --- SPRING THE TRAP ---
console.log("\n ATTEMPT 1: Alice tries to unstake...");
await expect(stargateContract.connect(alice).unstake(aliceTokenId)).to.be.revertedWithCustomError(stargateContract, "MaxClaimablePeriodsExceeded");
console.log(" �
Unstake correctly reverted with MaxClaimablePeriodsExceeded.");
// --- PROVE THE FREEZE IS PERMANENT ---
console.log("\n ATTEMPT 2: Alice tries to claim rewards to clear the periods...");
const claimTx = await stargateContract.connect(alice).claimRewards(aliceTokenId);
await claimTx.wait();
console.log(" �
claimRewards() executed, but the underlying state did not change.");
const [firstAfterClaim, lastAfterClaim] = await stargateContract.claimableDelegationPeriods(aliceTokenId);
const numPeriodsAfterClaim = lastAfterClaim - firstAfterClaim + BigInt(1);
expect(numPeriodsAfterClaim).to.equal(numPeriods);
console.log(` - Alice STILL has ${numPeriodsAfterClaim} claimable periods.`);
console.log("\n ATTEMPT 3: Alice tries to unstake one last time...");
await expect(stargateContract.connect(alice).unstake(aliceTokenId)).to.be.revertedWithC
```
The test first asserts the trap conditions: the number of claimable periods is greater than `MAX_CLAIMABLE_PERIODS`, and `claimableRewards(uint256,uint32)` for the first batch returns zero. It then attempts `unstake`, expects the `MaxClaimablePeriodsExceeded` custom error, calls `claimRewards`, and checks that the number of claimable periods is unchanged. The final `unstake` reverts again.
The recorded output of the run:
```text
PoC: Permanent Fund Freeze in unstake
- Alice has 26 claimable periods.
- Max claimable periods is 10.
- Alice's rewards for the first batch: 0 VTHO.
ATTEMPT 1: Alice tries to unstake...
�
Unstake correctly reverted with MaxClaimablePeriodsExceeded.
ATTEMPT 2: Alice tries to claim rewards to clear the periods...
�
claimRewards() executed, but the underlying state did not change.
- Alice STILL has 26 claimable periods.
ATTEMPT 3: Alice tries to unstake one last time...
�
Unstake reverted AGAIN. Alice's funds are permanently frozen.
--- VULNERABILITY CONFIRMED ---
✔ should TRAP Alice, preventing her from unstaking her funds
```
Alice has 26 claimable periods against a limit of 10, the first batch pays 0 VTHO, `claimRewards` succeeds but leaves the count at 26, and `unstake` keeps reverting.
## Root cause
The bug is an ordering mistake in `_claimRewards`. The function has two responsibilities: pay the rewards for a batch and advance `lastClaimedPeriod` so the batch is not processed again. The early return on `claimableAmount == 0` skips the second responsibility entirely. Because `unstake` uses `_exceedsMaxClaimablePeriods` as a gas guard and depends on `claimRewards` to move the checkpoint, the guard can never be satisfied for a backlog made only of zero-value periods. The existing defence, the `maxClaimablePeriods` check, is what turns the missing state update into a permanent lockout rather than a temporary inconvenience.
## Impact
A user can be permanently blocked from unstaking if they accumulate many zero-value claimable periods, for example by delegating to an offline validator. The principal stays frozen in the contract. The report describes this as a Critical outcome, permanent freezing of user funds, while the report itself is filed as Medium severity.
## Fix
The recommendation is to always update `lastClaimedPeriod` when a batch is processed, even when the batch reward is zero, by moving the state update before the zero-amount return. The proposed patch:
```solidity
function _claimRewards(StargateStorage storage $, uint256 _tokenId) private {
(uint32 firstClaimablePeriod, uint32 lastClaimedPeriod) = _claimableDelegationPeriods($, _tokenId);
// Check if there are any periods to process at all.
if (firstClaimablePeriod > lastClaimedPeriod) {
return;
}
// Determine the end of the current batch.
uint32 batchEndPeriod = firstClaimablePeriod + $.maxClaimablePeriods - 1;
if (batchEndPeriod > lastClaimedPeriod) {
batchEndPeriod = lastClaimedPeriod;
}
uint256 claimableAmount = 0;
// Calculate rewards ONLY if there's a chance to have them.
if (firstClaimablePeriod <= batchEndPeriod) {
// This loop would calculate the rewards for the batch [firstClaimablePeriod...batchEndPeriod]
// For this PoC, we can represent it as the call to _claimableRewards
claimableAmount = _claimableRewards($, _tokenId, 0);
}
// [!] FIX: Always update the state, regardless of the amount.
// The state update now happens BEFORE the early return.
$.lastClaimedPeriod[_tokenId] = batchEndPeriod;
if (claimableAmount == 0) {
// We've updated the period, so we can now safely return.
return;
}
// Proceed with the transfer logic only if there's an amount to send.
address tokenOwner = $.stargateNFTContract.ownerOf(_tokenId);
VTHO_TOKEN.safeTransfer(tokenOwner, claimableAmount);
emit DelegationRewardsClaimed(
tokenOwner,
_tokenId,
$.delegationIdByTokenId[_tokenId],
claimableAmount,
firstClaimablePeriod,
batchEndPeriod
);
}
```
With this ordering, every processed batch advances the checkpoint, so repeated `claimRewards` calls eventually bring the backlog under the limit and `unstake` succeeds.
- Look for other functions that return early on a zero amount before writing a checkpoint or cursor. A positive result is a state variable that stays unchanged after a successful call that should have advanced it.
- Check any gas guard that counts outstanding items (periods, epochs, rounds) and depends on a separate claim or settle function to reduce the count. A positive result is a guard that cannot be satisfied when the items are worth nothing.
- Test reward or accrual paths where the reward rate can legitimately be zero, for example an inactive or offline validator. A positive result is a batch that pays zero and leaves the backlog untouched.
- Compare the batch size used by the claim function with the threshold used by the guard. A positive result is a backlog larger than the threshold that the claim function cannot reduce in one call.
This kind of bug hides in the interaction between a safety limit and a state-advancing function. During review, look for early returns that sit before checkpoint updates, and for guards that assume another function will make progress. The signal is a limit expressed in countable items plus a claim or settle function that can no-op. To show impact, reproduce the full sequence: hit the guard, call the claim function, show the state is unchanged, and hit the guard again. A runnable test with a clear before-and-after count, as in this report, makes the freeze concrete without needing a live deployment.## What happened, in plain words
Imagine a car park with a barrier. To leave, you must first pay for your parking at a machine. The machine is supposed to stamp your ticket each time you pay a batch of hours. But if the amount owed for a batch happens to be zero, the machine prints nothing and does not stamp the ticket. The barrier still sees an unpaid ticket, so it will not let you out. You try paying again, the amount is still zero, the machine still does not stamp, and the barrier still refuses. You are stuck in the car park even though you owe nothing.
That is essentially the bug described here, but with money locked inside a smart contract instead of a car. A user staked cryptocurrency (VET) through a contract called Stargate, earned rewards over many time periods, and then wanted to take the stake back. Because the rewards for those periods were worth zero, the function that is supposed to mark periods as "handled" quietly did nothing. A safety check then kept refusing the withdrawal, and there was no way out.
This write-up explains the whole thing from scratch: what the product does, what a smart contract is, what the two functions involved do, how the researcher proved the problem with a test, and how it could be fixed. No prior security knowledge is needed.
## Background concepts, from zero
Before the details, a few ideas that come up constantly.
- **Blockchain and smart contracts.** A blockchain is a shared ledger that many computers keep copies of. A smart contract is a small program that lives on that ledger. Once deployed, its code runs exactly as written, and anyone can call its functions. Nobody can quietly edit it afterwards, which is why a mistake in the code can lock funds permanently.
- **Staking.** You lock up some cryptocurrency for a while, usually to help secure a network, and in return you may earn rewards. Here the locked currency is VET, and the reward currency is VTHO.
- **Validator.** A participant that processes the network's work. Users can "delegate" their staked position to a validator, and the rewards depend on how well that validator performs. An offline or inactive validator can produce zero rewards.
- **NFT as a receipt.** When you stake, Stargate gives you a non-fungible token (NFT). Think of it as a numbered receipt that proves the position is yours. The contract tracks everything about your stake against that token's ID number.
- **Period.** The protocol measures time in chunks called staking periods. Rewards accrue period by period, so a long delegation produces a long list of periods, each with its own reward amount.
- **State and state variables.** A contract remembers things in variables stored on the blockchain. Changing one of those variables is called a state update. If a function returns early without writing to a variable, the blockchain's memory of that variable stays exactly as it was.
- **Gas.** Every operation on a blockchain costs a small fee, measured in units called gas. Loops that run many times cost more gas. If a transaction needs more gas than the network allows, it fails. This is why contracts often cap how much work they do in one call.
- **Revert.** When a contract refuses to continue, it "reverts": the transaction is cancelled and any changes it made are undone. A revert is the blockchain equivalent of an error message plus a full rollback.
- **Custom error.** A named error defined by the contract, such as `MaxClaimablePeriodsExceeded`, so that callers can tell exactly why a transaction was rejected.
- **Mock.** A simplified stand-in version of a contract, used in tests so you can control its behaviour. Here the test uses mocks for the NFT and for the staker, so the researcher can force rewards to be zero on demand.
- **Hardhat.** A development tool for writing and running tests against smart contracts on a simulated local blockchain, without spending real money.
- **Proof of concept (PoC).** A small, runnable demonstration that proves a bug is real. It is the difference between saying "this might break" and showing it break.
## Context: what Stargate does
Stargate is the staking contract in the Vechain Stargate Hayabusa codebase, located at `packages/contracts/contracts/Stargate.sol`. A user stakes VET, receives a Stargate NFT representing the position, and can delegate that position to a validator. While delegated, the position earns VTHO rewards for each staking period. When the delegation ends, the position enters a state called `EXITED`, and the accumulated rewards become claimable across a range of periods.
Two functions matter for this bug.
1. `claimRewards` pays out the rewards for a batch of periods. It is also supposed to move a per-token bookmark called `lastClaimedPeriod` forward, so that calling it repeatedly works through a long backlog, batch by batch. Think of the bookmark as the page number in a book: each call should turn some pages.
2. `unstake` gives the principal back, but only after checking that the number of outstanding claimable periods does not exceed a limit called `maxClaimablePeriods`. That check exists to avoid running out of gas while automatically claiming rewards during the unstake.
The report shows that these two mechanisms interact badly when the rewards in a batch are worth zero.
## Setup: how the test environment was built
The proof of concept is a Hardhat test that runs against the project's local configuration, using the project's own mocks and helpers:
- `Stargate`, the contract under test.
- `StargateNFTMock`, the NFT mock.
- `ProtocolStakerMock`, the protocol staker mock, slightly modified for the test.
- `MyERC20`, a simple token contract deployed and then placed at the VTHO token address using `hardhat_setCode`.
- `createLocalConfig` from `@repo/config/contracts/envs/local` and `getOrDeployContracts` from the test helpers.
The test uses three signers, which are simulated accounts: `deployer`, `alice` (the victim in the story) and `validatorX`. The relevant constants are `LEVEL_ID = 1`, `MAX_CLAIMABLE_PERIODS = 10` and `VET_STAKED = 100 VET`. The VTHO token address used in the test is:
```text
[redacted]
```
This is the address the contract expects the VTHO token to live at. Because the test runs on a simulated chain, the researcher deploys a simple token and copies its code to that address, so the contract under test finds a working token where it expects one.
The precondition for the bug is a user whose delegation has exited while the number of claimable periods is above `maxClaimablePeriods`, and where the rewards for those periods are zero. The report describes this as delegating to an offline validator, an "unlucky delegator" scenario.
## Finding it: the early return
The researcher read `_claimRewards` and noticed that it calculates the claimable amount for the current batch and then returns early when that amount is zero:
```solidity
// In Stargate.sol
function _claimRewards(StargateStorage storage $, uint256 _tokenId) private {
// ... (logic to determine the first and last period of the current batch) ...
uint256 claimableAmount = _claimableRewards($, _tokenId, 0);
// [!] VULNERABILITY ROOT CAUSE [!]
if (claimableAmount == 0) {
return; // The function exits prematurely.
}
// This state update is the entire purpose of the function for clearing the backlog.
// It is NEVER REACHED if rewards are zero.
$.lastClaimedPeriod[_tokenId] = lastClaimedPeriod;
// ... (transfer logic) ...
}
```
Line by line:
- `function _claimRewards(StargateStorage storage $, uint256 _tokenId) private {` declares an internal helper that takes the contract's storage and a token ID. The underscore prefix is a naming convention meaning "internal helper".
- The comment marks where the code works out which periods belong to the current batch.
- `uint256 claimableAmount = _claimableRewards($, _tokenId, 0);` asks a helper how much reward this batch is worth and stores the answer in a variable.
- `if (claimableAmount == 0) { return; }` is the early exit: if the batch is worth nothing, stop here and do nothing else.
- `$.lastClaimedPeriod[_tokenId] = lastClaimedPeriod;` is the bookmark update. It records that the batch has been processed.
- The final comment notes that the transfer of tokens follows.
The problem is ordering. The bookmark update sits after the zero-amount return, so a batch worth nothing is never marked as processed. Since `unstake` relies on `claimRewards` to shrink the backlog, a user whose backlog is entirely zero-value has no way to get below the threshold. The report calls this a trap state and a Catch-22, after the novel where the only way out requires something you cannot get until you are out.
## Exploitation: the four steps
### Step 1: Pre-condition
Alice has an `EXITED` delegation with more than `maxClaimablePeriods` claimable periods, all worth 0 VTHO. In the test this is created by setting the validator's completed periods, setting the delegator rewards to zero, requesting the delegation exit, and then advancing the validator's completed periods by one so the delegation status becomes `EXITED` (status value 3).
Why each action: the completed-periods setting simulates time passing on the validator. Setting rewards to zero simulates the unlucky case. Requesting the exit starts the wind-down. Advancing one more period pushes the status over the line into `EXITED`, which is the state in which rewards become claimable.
### Step 2: Alice calls `unstake()`
`unstake()` reverts with `MaxClaimablePeriodsExceeded`. This is the intended gas safety mechanism firing. The contract is saying: there are too many periods left to process in one go, so I will not attempt the withdrawal.
### Step 3: Alice calls `claimRewards()`
`_claimRewards` computes `claimableAmount` for the first batch. Because the rewards are zero, `claimableAmount == 0`, the function executes `return`, and `lastClaimedPeriod` is not updated. No backlog progress is made. The call succeeds, which is what makes this confusing: nothing looks broken from the outside, but nothing changed either.
### Step 4: Alice calls `unstake()` again
`unstake()` reverts with `MaxClaimablePeriodsExceeded` for the same reason. Alice cannot progress and cannot withdraw her principal.
The runnable test reproduces this. The mock is first modified to allow the delegator rewards to be set to zero:
```solidity
// In ProtocolStakerMock.sol
contract ProtocolStakerMock is IProtocolStaker {
// Added state variable, initialized to the original hardcoded value.
uint256 private mockDelegatorRewards = 0.1 ether;
// Added helper function to allow the test to change the reward value.
function helper__setDelegatorRewards(uint256 _rewards) external {
mockDelegatorRewards = _rewards;
}
function getDelegatorsRewards(
address _validator,
uint32 _stakingPeriod
) external view override returns (uint256 rewards) {
if (_stakingPeriod > validations[_validator].completedPeriods + 1) {
return 0;
}
// Used the state variable instead of the hardcoded value.
return mockDelegatorRewards;
}
// ... rest of the contract is unchanged
}
```
Line by line:
- `contract ProtocolStakerMock is IProtocolStaker {` declares the mock contract, which promises to behave like the real staker interface.
- `uint256 private mockDelegatorRewards = 0.1 ether;` adds a variable holding the reward amount, starting at the value the original code had hardcoded.
- `function helper__setDelegatorRewards(uint256 _rewards) external {` adds a helper that anyone can call in the test to change that value. The `helper__` prefix marks it as test-only scaffolding.
- `mockDelegatorRewards = _rewards;` stores the new value.
- `function getDelegatorsRewards(...)` is the function the real contract uses to report rewards for a validator and period.
- `if (_stakingPeriod > validations[_validator].completedPeriods + 1) { return 0; }` keeps the original rule: periods in the future pay nothing.
- `return mockDelegatorRewards;` now returns the adjustable value instead of a fixed one.
The test itself sets up the environment, stakes, delegates, creates the zero-reward exited delegation, and then runs the three attempts:
```javascript
import { expect } from "chai";
import { ethers } from "hardhat";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import {
Stargate,
StargateNFTMock,
ProtocolStakerMock,
StargateNFTMock__factory,
ProtocolStakerMock__factory,
MyERC20__factory,
} from "../../typechain-types";
import { createLocalConfig } from "@repo/config/contracts/envs/local";
import { getOrDeployContracts } from "../helpers";
describe("PoC: Permanent Fund Freeze in unstake", () => {
let deployer: HardhatEthersSigner;
let alice: HardhatEthersSigner;
let validatorX: HardhatEthersSigner;
let stargateContract: Stargate;
let stargateNFTMock: StargateNFTMock;
let protocolStakerMock: ProtocolStakerMock;
const LEVEL_ID = 1;
const MAX_CLAIMABLE_PERIODS = 10;
const VET_STAKED = ethers.parseEther("100");
let aliceTokenId: bigint;
beforeEach(async () => {
// --- 1. SETUP THE FULL TEST ENVIRONMENT ---
const config = createLocalConfig();
[deployer, alice, validatorX] = await ethers.getSigners();
const protocolStakerMockFactory = new ProtocolStakerMock__factory(deployer);
protocolStakerMock = await protocolStakerMockFactory.deploy();
await protocolStakerMock.waitForDeployment();
const stargateNFTMockFactory = new StargateNFTMock__factory(deployer);
stargateNFTMock = await stargateNFTMockFactory.deploy();
await stargateNFTMock.waitForDeployment();
const VTHO_TOKEN_ADDRESS = "[redacted]";
const vthoTokenContractFactory = new MyERC20__factory(deployer);
const tokenContract = await vthoTokenContractFactory.deploy(deployer.address, deployer.address);
await tokenContract.waitForDeployment();
const tokenContractBytecode = await ethers.provider.getCode(await tokenContract.getAddress());
await ethers.provider.send("hardhat_setCode", [VTHO_TOKEN_ADDRESS, tokenContractBytecode]);
config.PROTOCOL_STAKER_CONTRACT_ADDRESS = await protocolStakerMock.getAddress();
config.STARGATE_NFT_CONTRACT_ADDRESS = await stargateNFTMock.getAddress();
config.MAX_CLAIMABLE_PERIODS = MAX_CLAIMABLE_PERIODS;
const contracts = await getOrDeployContracts({ forceDeploy: true, config });
stargateContract = contracts.stargateContract;
await protocolStakerMock.helper__setStargate(await stargateContract.getAddress());
// --- 2. SIMULATE ALICE'S JOURNEY ---
await stargateNFTMock.helper__setLevel({ id: LEVEL_ID, name: "Test Level", isX: false, maturityBlocks: 0, scaledRewardFactor: 100, vetAmountRequiredToStake: VET_STAKED });
await protocolStakerMock.addValidation(validatorX.address, 120);
await protocolStakerMock.helper__setValidatorStatus(validatorX.address, 2);
await stargateContract.connect(alice).stake(LEVEL_ID, { value: VET_STAKED });
aliceTokenId = await stargateNFTMock.getCurrentTokenId();
await stargateNFTMock.helper__setToken({ tokenId: aliceTokenId, levelId: LEVEL_ID, mintedAtBlock: 1, vetAmountStaked: VET_STAKED, lastVetGeneratedVthoClaimTimestamp_deprecated: 0 });
await stargateContract.connect(alice).delegate(aliceTokenId, validatorX.address);
// --- 3. CREATE THE "UNLUCKY DELEGATOR" SCENARIO ---
const INACTIVE_PERIODS = 25;
const lastCompletedPeriod = INACTIVE_PERIODS + 1;
await protocolStakerMock.helper__setValidationCompletedPeriods(validatorX.address, lastCompletedPeriod);
await protocolStakerMock.helper__setDelegatorRewards(0); // CRITICAL STEP: SIMULATE ZERO REWARDS
await stargateContract.connect(alice).requestDelegationExit(aliceTokenId);
await protocolStakerMock.helper__setValidationCompletedPeriods(validatorX.address, lastCompletedPeriod + 1);
const status = await stargateContract.getDelegationStatus(aliceTokenId);
expect(status).to.equal(3); // 3 = EXITED
});
it("should TRAP Alice, preventing her from unstaking her funds", async () => {
// --- VERIFY THE TRAP CONDITIONS ---
const [first, last] = await stargateContract.claimableDelegationPeriods(aliceTokenId);
const numPeriods = last - first + BigInt(1);
console.log(` - Alice has ${numPeriods} claimable periods.`);
console.log(` - Max claimable periods is ${MAX_CLAIMABLE_PERIODS}.`);
expect(numPeriods).to.be.greaterThan(MAX_CLAIMABLE_PERIODS);
const batchRewards = await stargateContract["claimableRewards(uint256,uint32)"](aliceTokenId, 0);
expect(batchRewards).to.equal(0);
console.log(` - Alice's rewards for the first batch: ${batchRewards} VTHO.`);
// --- SPRING THE TRAP ---
console.log("\n ATTEMPT 1: Alice tries to unstake...");
await expect(stargateContract.connect(alice).unstake(aliceTokenId)).to.be.revertedWithCustomError(stargateContract, "MaxClaimablePeriodsExceeded");
console.log(" �
Unstake correctly reverted with MaxClaimablePeriodsExceeded.");
// --- PROVE THE FREEZE IS PERMANENT ---
console.log("\n ATTEMPT 2: Alice tries to claim rewards to clear the periods...");
const claimTx = await stargateContract.connect(alice).claimRewards(aliceTokenId);
await claimTx.wait();
console.log(" �
claimRewards() executed, but the underlying state did not change.");
const [firstAfterClaim, lastAfterClaim] = await stargateContract.claimableDelegationPeriods(aliceTokenId);
const numPeriodsAfterClaim = lastAfterClaim - firstAfterClaim + BigInt(1);
expect(numPeriodsAfterClaim).to.equal(numPeriods);
console.log(` - Alice STILL has ${numPeriodsAfterClaim} claimable periods.`);
console.log("\n ATTEMPT 3: Alice tries to unstake one last time...");
await expect(stargateContract.connect(alice).unstake(aliceTokenId)).to.be.revertedWithC
```
What the test does, section by section:
- The imports bring in the assertion library, the Hardhat runtime, type definitions for the contracts, the local configuration and a helper that deploys the whole set of contracts.
- The `describe` block names the test suite. The `let` lines declare variables for the three accounts, the three contracts, the constants and Alice's token ID.
- `beforeEach` runs before the test itself, so every run starts from a clean, fully set-up world.
- In section 1, the three accounts are created, the two mocks are deployed, a simple token is deployed and its code is copied to the VTHO address, the configuration is pointed at the mocks, and the full contract set is deployed. The staker mock is told where Stargate lives.
- In section 2, a staking level is defined, a validator is registered and marked active, Alice stakes 100 VET, her token ID is read, the token's details are set, and she delegates to the validator. This is the normal happy path a real user would follow.
- In section 3, the validator is given 26 completed periods, rewards are set to zero, Alice requests the exit, one more period is completed, and the test asserts the delegation status is 3, meaning `EXITED`. This is the unlucky delegator scenario.
- The test body first reads the range of claimable periods, computes how many there are, prints them, and asserts the count is above the limit. It then asks for the first batch's reward and asserts it is zero. These assertions confirm the trap conditions exist before trying anything.
- Attempt 1 calls `unstake` and expects the custom error `MaxClaimablePeriodsExceeded`.
- Attempt 2 calls `claimRewards`, waits for it to be mined, then reads the claimable periods again and asserts the count is unchanged. This is the heart of the proof: a successful call that changed nothing.
- Attempt 3 calls `unstake` again and expects the same error, showing the situation is permanent.
The recorded output of the run:
```text
PoC: Permanent Fund Freeze in unstake
- Alice has 26 claimable periods.
- Max claimable periods is 10.
- Alice's rewards for the first batch: 0 VTHO.
ATTEMPT 1: Alice tries to unstake...
�
Unstake correctly reverted with MaxClaimablePeriodsExceeded.
ATTEMPT 2: Alice tries to claim rewards to clear the periods...
�
claimRewards() executed, but the underlying state did not change.
- Alice STILL has 26 claimable periods.
ATTEMPT 3: Alice tries to unstake one last time...
�
Unstake reverted AGAIN. Alice's funds are permanently frozen.
--- VULNERABILITY CONFIRMED ---
✔ should TRAP Alice, preventing her from unstaking her funds
```
Alice has 26 claimable periods against a limit of 10, the first batch pays 0 VTHO, `claimRewards` succeeds but leaves the count at 26, and `unstake` keeps reverting. The check marks are just the test runner reporting that each expected outcome happened.
## Root cause
The bug is an ordering mistake in `_claimRewards`. The function has two responsibilities: pay the rewards for a batch, and advance `lastClaimedPeriod` so the batch is not processed again. The early return on `claimableAmount == 0` skips the second responsibility entirely. Because `unstake` uses `_exceedsMaxClaimablePeriods` as a gas guard and depends on `claimRewards` to move the bookmark, the guard can never be satisfied for a backlog made only of zero-value periods. The existing defence, the `maxClaimablePeriods` check, is what turns the missing state update into a permanent lockout rather than a temporary inconvenience.
In everyday terms: the safety limit assumes another function will make progress. When that function can silently do nothing, the limit becomes a wall with no door.
## Impact
A user can be permanently blocked from unstaking if they accumulate many zero-value claimable periods, for example by delegating to an offline validator. The principal stays frozen in the contract. The report describes this as a Critical outcome, permanent freezing of user funds, while the report itself is filed as Medium severity.
## Fix
The recommendation is to always update `lastClaimedPeriod` when a batch is processed, even when the batch reward is zero, by moving the state update before the zero-amount return. The proposed patch:
```solidity
function _claimRewards(StargateStorage storage $, uint256 _tokenId) private {
(uint32 firstClaimablePeriod, uint32 lastClaimedPeriod) = _claimableDelegationPeriods($, _tokenId);
// Check if there are any periods to process at all.
if (firstClaimablePeriod > lastClaimedPeriod) {
return;
}
// Determine the end of the current batch.
uint32 batchEndPeriod = firstClaimablePeriod + $.maxClaimablePeriods - 1;
if (batchEndPeriod > lastClaimedPeriod) {
batchEndPeriod = lastClaimedPeriod;
}
uint256 claimableAmount = 0;
// Calculate rewards ONLY if there's a chance to have them.
if (firstClaimablePeriod <= batchEndPeriod) {
// This loop would calculate the rewards for the batch [firstClaimablePeriod...batchEndPeriod]
// For this PoC, we can represent it as the call to _claimableRewards
claimableAmount = _claimableRewards($, _tokenId, 0);
}
// [!] FIX: Always update the state, regardless of the amount.
// The state update now happens BEFORE the early return.
$.lastClaimedPeriod[_tokenId] = batchEndPeriod;
if (claimableAmount == 0) {
// We've updated the period, so we can now safely return.
return;
}
// Proceed with the transfer logic only if there's an amount to send.
address tokenOwner = $.stargateNFTContract.ownerOf(_tokenId);
VTHO_TOKEN.safeTransfer(tokenOwner, claimableAmount);
emit DelegationRewardsClaimed(
tokenOwner,
_tokenId,
$.delegationIdByTokenId[_tokenId],
claimableAmount,
firstClaimablePeriod,
batchEndPeriod
);
}
```
Line by line:
- The function signature is unchanged.
- `(uint32 firstClaimablePeriod, uint32 lastClaimedPeriod) = _claimableDelegationPeriods($, _tokenId);` fetches the range of periods that still need handling.
- `if (firstClaimablePeriod > lastClaimedPeriod) { return; }` is the only early exit left: if there is genuinely nothing to process, stop. This is a legitimate no-op.
- `uint32 batchEndPeriod = firstClaimablePeriod + $.maxClaimablePeriods - 1;` works out where this batch would end if it used the full allowed size.
- `if (batchEndPeriod > lastClaimedPeriod) { batchEndPeriod = lastClaimedPeriod; }` clamps that end point so it never goes past the last period that exists.
- `uint256 claimableAmount = 0;` starts the reward total at zero.
- The `if (firstClaimablePeriod <= batchEndPeriod)` block calculates the reward for the batch, with a comment noting that the real loop is represented by the call to `_claimableRewards`.
- `$.lastClaimedPeriod[_tokenId] = batchEndPeriod;` is the fix: the bookmark is written before any early return, so every processed batch counts as progress.
- `if (claimableAmount == 0) { return; }` now exits only after the bookmark has moved, which is safe.
- The remaining lines look up the token owner, transfer the reward, and emit an event recording what was claimed and for which period range.
With this ordering, every processed batch advances the bookmark, so repeated `claimRewards` calls eventually bring the backlog under the limit and `unstake` succeeds.
- Look for other functions that return early on a zero amount before writing a bookmark or cursor. A positive result is a state variable that stays unchanged after a successful call that should have advanced it.
- Check any gas guard that counts outstanding items (periods, epochs, rounds) and depends on a separate claim or settle function to reduce the count. A positive result is a guard that cannot be satisfied when the items are worth nothing.
- Test reward or accrual paths where the reward rate can legitimately be zero, for example an inactive or offline validator. A positive result is a batch that pays zero and leaves the backlog untouched.
- Compare the batch size used by the claim function with the threshold used by the guard. A positive result is a backlog larger than the threshold that the claim function cannot reduce in one call.
This kind of bug hides in the interaction between a safety limit and a state-advancing function. During review, look for early returns that sit before bookmark updates, and for guards that assume another function will make progress. The signal is a limit expressed in countable items plus a claim or settle function that can do nothing. To show impact, reproduce the full sequence: hit the guard, call the claim function, show the state is unchanged, and hit the guard again. A runnable test with a clear before-and-after count, as in this report, makes the freeze concrete without needing a live deployment.
## Glossary
- **Blockchain**: a shared ledger kept by many computers, where records cannot be quietly changed after the fact.
- **Smart contract**: a program stored on a blockchain that runs exactly as written when called.
- **Staking**: locking up cryptocurrency for a period, often to help secure a network, in exchange for possible rewards.
- **VET**: the cryptocurrency staked in this protocol.
- **VTHO**: the reward currency earned by staking and delegating in this protocol.
- **Validator**: a network participant that does the processing work; delegating to one affects the rewards earned.
- **Delegation**: assigning your staked position to a validator so it can earn rewards.
- **NFT (non-fungible token)**: a unique digital token; here it acts as a numbered receipt for a staking position.
- **Token ID**: the number identifying a specific NFT.
- **Period (staking period)**: a chunk of time used to measure reward accrual.
- **State**: the stored memory of a contract on the blockchain.
- **State variable**: a named slot in that memory.
- **State update**: writing a new value into a state variable.
- **Checkpoint / bookmark**: a stored marker recording how far processing has got, here `lastClaimedPeriod`.
- **Gas**: the fee unit for computation on a blockchain; running out of it makes a transaction fail.
- **Revert**: cancelling a transaction and undoing its changes, usually with an error.
- **Custom error**: a named error defined by a contract, such as `MaxClaimablePeriodsExceeded`.
- **`EXITED`**: the delegation status meaning the delegation has ended and rewards are claimable.
- **`claimRewards`**: the function that pays rewards for a batch of periods and should advance the bookmark.
- **`unstake`**: the function that returns the staked principal, subject to a limit on outstanding periods.
- **`maxClaimablePeriods`**: the cap on how many claimable periods may remain before `unstake` refuses, to avoid running out of gas.
- **`lastClaimedPeriod`**: the stored marker of the last period already processed for a token.
- **Batch**: a group of periods handled in one function call.
- **Mock**: a simplified stand-in contract used in tests to control behaviour.
- **Hardhat**: a development environment for building and testing smart contracts on a simulated local blockchain.
- **`hardhat_setCode`**: a Hardhat command that places given bytecode at a chosen address on the simulated chain.
- **Bytecode**: the compiled machine-level form of a contract that actually runs on the chain.
- **Signer**: a simulated account in a test that can send transactions.
- **Proof of concept (PoC)**: a runnable demonstration that proves a bug is real.
- **Assertion**: a test statement that checks a condition and fails the test if it is not met.
- **Early return**: leaving a function before its later lines run.
- **Catch-22**: a situation where the only way out requires something you cannot obtain until you are already out.
- **Severity**: the rating of how serious a bug is, here filed as Medium while the described outcome is called Critical.