Skip to content
Business logic Audit finding Intermediate

State sync omission in staking transfers forces transferred slong holders into penalized emergency exits

The staking vault records per-account stake entries only on deposit and never updates them when sLONG shares are transferred, so a recipient holds shares but no stake entries. Such a recipient cannot pass the normal withdrawal check and is forced into the emergency withdrawal path, which burns shares and sends a penalty to the treasury.

Belong

Originally disclosed on Immunefi

Critical View original

57298 sc critical state sync omission in staking transfers forces transferred slong holders into penalized emergency exits

Description

Brief / Intro

The staking vault mints and allows free transfer of sLONG (ERC4626-style shares), but it does not synchronize the per-account stake ledger on transfers. A recipient who obtains sLONG via ERC20 transfer receives shares (ERC20 balance) but has no corresponding unlocked stake entries in the contract's per-account ledger. Such recipients cannot pass the normal withdrawal checks and are forced to use the emergency withdrawal path, which burns shares and applies a permanent penalty routed to the treasury.

Root cause

The per-account stake ledger:

  • Is declared as mapping(address staker => Stake[] times) public stakes;
  • Is appended to only on deposits (via _deposit)
  • Is never reconciled or updated on ERC20 transfers (no transfer hooks or overrides)

Thus, transferred-in sLONG holders have token balances but zero stake entries, so they cannot consume "unlocked" stakes via the normal withdrawal flow and are blocked into emergency withdrawals with penalties.

Vulnerability Details (selected snippets)

  • File: contracts/v2/periphery/Staking.sol
  • stakes declaration:
Solidity
	/// @notice User stake entries stored as arrays per staker.
	/// @dev Public getter: `stakes(user, i)` → `(shares, timestamp)`.
	mapping(address staker => Stake[] times) public stakes;
  • _deposit — locks freshly minted shares on deposit:
Solidity
	function _deposit(address by, address to, uint256 assets, uint256 shares) internal override {
		super._deposit(by, to, assets, shares);
		// lock freshly minted shares
		stakes[to].push(Stake({shares: shares, timestamp: block.timestamp}));
	}
  • _withdraw — requires consumption of unlocked stake entries:
Solidity
	function _withdraw(address by, address to, address _owner, uint256 assets, uint256 shares) internal override {
		_consumeUnlockedSharesOrRevert(_owner, shares);
		super._withdraw(by, to, _owner, assets, shares);
	}
  • _consumeUnlockedSharesOrRevert — iterates per-account stake entries and reverts if not enough unlocked shares:
Solidity
	function _consumeUnlockedSharesOrRevert(address staker, uint256 need) internal {
		Stake[] storage userStakes = stakes[staker];
		uint256 _min = minStakePeriod;
		uint256 nowTs = block.timestamp;
		uint256 remaining = need;

		for (uint256 i; i < userStakes.length && remaining > 0;) {
			Stake memory s = userStakes[i];
			if (nowTs >= s.timestamp + _min) {
				uint256 take = s.shares <= remaining ? s.shares : remaining;
				if (take == s.shares) {
					// full consume → swap and pop
					remaining -= take;
					userStakes[i] = userStakes[userStakes.length - 1];
					userStakes.pop();
					// don't ++i: a new element is now at index i
				} else {
					// partial consume
					userStakes[i].shares = s.shares - take;
					remaining = 0;
					unchecked {
						++i;
					}
				}
			} else {
				unchecked {
					++i;
				}
			}
		}

		if (remaining != 0) revert MinStakePeriodNotMet();
	}
  • _emergencyWithdraw — burns shares regardless of lock status and applies penalty:
Solidity
	function _emergencyWithdraw(address by, address to, address _owner, uint256 assets, uint256 shares) internal {
		require(shares > 0, SharesEqZero());

		uint256 penalty = FixedPointMathLib.fullMulDiv(assets, penaltyPercentage, SCALING_FACTOR);
		uint256 payout;
		unchecked {
			payout = assets - penalty;
		}

		if (by != _owner) _spendAllowance(_owner, by, shares);

		_removeAnySharesFor(_owner, shares);
		_burn(_owner, shares);

		LONG.safeTransfer(to, payout);
		LONG.safeTransfer(treasury, penalty);

		emit EmergencyWithdraw(by, to, _owner, assets, shares);
		// also emit standard ERC4626 Withdraw for indexers/analytics
		emit Withdraw(by, to, _owner, assets, shares);
	}

Note: line ranges cited in the report correspond to the repository's current main branch at the time of reporting.

Impact (concise)

  • Transfers only move ERC20 balances and do not update stakes[...]. Recipients have shares but no stake entries.
  • Attempting a standard withdraw/redeem calls _consumeUnlockedSharesOrRevert and reverts with MinStakePeriodNotMet because the recipient has no unlocked stake entries.
  • Recipients are forced to use emergencyWithdraw/emergencyRedeem, which burns shares, applies the configured penalty (default 10%), and sends the penalty to treasury.
  • Monetary impact: transferred-in holders permanently lose a fraction of their assets proportional to penaltyPercentage. This can be arbitrarily large depending on transferred amount.
  • Attack surface: any integration or flow that transfers sLONG balances (e.g., auto-stake, rewards routing, third-party transfers) can inadvertently subject recipients to penalized exits.

References

Proof of Concept

Below is the Hardhat test PoC used to reproduce the issue: depositor stakes LONG, transfers the minted sLONG to a recipient, and the recipient cannot perform normal redeem — only emergency redeem succeeds (with penalty).

File: test/v2/platform/staking-transfer-poc.test.ts

TypeScript
import { ethers } from 'hardhat';
import { expect } from 'chai';
import { loadFixture, time } from '@nomicfoundation/hardhat-network-helpers';
import { deployLONG, deployStaking } from '../../../helpers/deployFixtures';
import { LONG, Staking } from '../../../typechain-types';

/**
 * ============================================================================
 * POC: Transferred sLONG Holders Are Locked Out Of Standard Withdrawals
 * ============================================================================
 *
 * This Hardhat test recreates the scenario where a depositor stakes LONG,
 * transfers the resulting sLONG shares to a recipient, and that recipient can
 * no longer perform a normal (non-emergency) withdrawal. Even after the lock
 * period elapses, `_consumeUnlockedSharesOrRevert` finds no stake entries for
 * the recipient and reverts with `MinStakePeriodNotMet`, forcing the user into
 * the emergency withdrawal path which burns shares and charges the penalty.
 */
describe('Staking - Transferred Holder Forced Emergency PoC', function () {
  async function fixture() {
    const [owner, treasury, depositor, recipient] = await ethers.getSigners();

    // Deploy proxy LONG token and staking vault.
    const long: LONG = await deployLONG(depositor.address, owner.address, owner.address);
    const staking: Staking = await deployStaking(owner.address, treasury.address, long.address);

    // Shorten the lock period to simplify the reproduction.
    await staking.connect(owner).setMinStakePeriod(1);

    const depositAmount = ethers.utils.parseEther('100');

    // Depositor stakes LONG and receives sLONG along with a stake entry.
    await long.connect(depositor).approve(staking.address, depositAmount);
    await staking.connect(depositor).deposit(depositAmount, depositor.address);
    const mintedShares = await staking.balanceOf(depositor.address);
    const recordedStake = await staking.stakes(depositor.address, 0);

    console.log(`\n[Setup] Depositor minted ${ethers.utils.formatEther(mintedShares)} sLONG shares`);
    console.log(`[Setup] Stake entry recorded with timestamp ${recordedStake.timestamp.toString()}`);

    return {
      owner,
      treasury,
      depositor,
      recipient,
      long,
      staking,
      depositAmount,
      mintedShares,
    };
  }

  it('proves transferred holders must use penalized emergency exits', async () => {
    const { treasury, depositor, recipient, long, staking, depositAmount, mintedShares } = await loadFixture(fixture);

    // Depositor transfers the entire sLONG balance to the recipient.
    await staking.connect(depositor).transfer(recipient.address, mintedShares);

    await expect(staking.callStatic.stakes(recipient.address, 0)).to.be.reverted;
    console.log('[Transfer] Recipient received shares but has zero stake entries');

    // Advance time beyond the (shortened) minimum stake period.
    await time.increase(2);
    await time.advanceBlock();

    // Recipient attempts a standard redeem and gets blocked by MinStakePeriodNotMet.
    await expect(
      staking.connect(recipient).redeem(mintedShares, recipient.address, recipient.address),
    ).to.be.revertedWithCustomError(staking, 'MinStakePeriodNotMet');
    console.log('[Redeem Attempt] Normal redeem reverts with MinStakePeriodNotMet');

    // Emergency redeem succeeds but pays penalty to treasury.
    const scalingFactor = await staking.SCALING_FACTOR();
    const penaltyPercentage = await staking.penaltyPercentage();
    const expectedAssets = await staking.convertToAssets(mintedShares);
    const expectedPenalty = expectedAssets.mul(penaltyPercentage).div(scalingFactor);

    const recipientBefore = await long.balanceOf(recipient.address);
    const treasuryBefore = await long.balanceOf(treasury.address);

    const emergencyTx = await staking
      .connect(recipient)
      .emergencyRedeem(mintedShares, recipient.address, recipient.address);
    await emergencyTx.wait();

    const recipientAfter = await long.balanceOf(recipient.address);
    const treasuryAfter = await long.balanceOf(treasury.address);

    const recipientGain = recipientAfter.sub(recipientBefore);
    const treasuryGain = treasuryAfter.sub(treasuryBefore);

    console.log(
      `[Emergency] Recipient forced to emergencyRedeem, receiving ${ethers.utils.formatEther(recipientGain)} LONG`,
    );
    console.log(`[Emergency] Treasury collects penalty of ${ethers.utils.formatEther(treasuryGain)} LONG`);

    expect(recipientGain).to.eq(expectedAssets.sub(expectedPenalty));
    expect(treasuryGain).to.eq(expectedPenalty);
    expect(await staking.balanceOf(recipient.address)).to.eq(0);
  });
});

Example run:

yarn hardhat test test/v2/platform/staking-transfer-poc.test.ts
...
[Setup] Depositor minted 100.0 sLONG shares
[Setup] Stake entry recorded with timestamp 1761366088
[Transfer] Recipient received shares but has zero stake entries
[Redeem Attempt] Normal redeem reverts with MinStakePeriodNotMet
[Emergency] Recipient forced to emergencyRedeem, receiving 90.0 LONG
[Emergency] Treasury collects penalty of 10.0 LONG
✔ proves transferred holders must use penalized emergency exits

(Full console output and test artifacts omitted for brevity.)


If you want, I can:

  • Suggest minimal code fixes or design approaches to keep per-account stake consistency on transfers (e.g., hooks updating stakes on transfer, or migrating stakes on transfer/delegation).
  • Draft a patch/PR against the referenced repository demonstrating a fix.

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.

Context

The target is Staking.sol in the Belong audit competition repository, a staking vault built around an ERC4626-style share token called sLONG. Users deposit the LONG token and receive sLONG shares. The vault tracks, per account, when each batch of shares was created, so that a minimum stake period can be enforced before those shares may be withdrawn normally. Shares that have not yet passed the minimum period are locked; shares that have are unlocked and can be consumed by a standard withdrawal.

The contract keeps this per-account history in a public mapping of stake entries, and it also exposes the shares as a freely transferable ERC20 balance. The report's central claim is that these two views of ownership, the ERC20 balance and the stake ledger, are never synchronised when shares move between accounts.

Setup

The proof of concept is a Hardhat test written in TypeScript, placed at test/v2/platform/staking-transfer-poc.test.ts. It uses the project's own deployment helpers, deployLONG and deployStaking, and the Hardhat network helpers loadFixture and time.

The fixture creates four signers: owner, treasury, depositor and recipient. It deploys the LONG token as a proxy with deployLONG(depositor.address, owner.address, owner.address) and the staking vault with deployStaking(owner.address, treasury.address, long.address). The owner then shortens the lock period with setMinStakePeriod(1) so the reproduction does not have to wait out the real minimum stake period. The deposit amount is 100 LONG, expressed with ethers.utils.parseEther('100').

No special tooling beyond Hardhat, Chai and the Hardhat network helpers is involved, and the report gives no version numbers.

Finding it

The researcher compared two pieces of the contract. The first is the stake ledger declaration:

Solidity
	/// @notice User stake entries stored as arrays per staker.
	/// @dev Public getter: `stakes(user, i)` → `(shares, timestamp)`.
	mapping(address staker => Stake[] times) public stakes;

The second is the deposit hook, which is the only place the ledger is appended to:

Solidity
	function _deposit(address by, address to, uint256 assets, uint256 shares) internal override {
		super._deposit(by, to, assets, shares);
		// lock freshly minted shares
		stakes[to].push(Stake({shares: shares, timestamp: block.timestamp}));
	}

Because sLONG is an ERC20, a holder can transfer the balance to anyone. Nothing in the contract overrides transfer or transferFrom, and there are no transfer hooks, so the recipient's stakes array stays empty while their token balance grows. The withdrawal path, however, checks the ledger rather than the balance:

Solidity
	function _withdraw(address by, address to, address _owner, uint256 assets, uint256 shares) internal override {
		_consumeUnlockedSharesOrRevert(_owner, shares);
		super._withdraw(by, to, _owner, assets, shares);
	}

_consumeUnlockedSharesOrRevert walks the caller's stake entries, takes shares from entries whose timestamp plus the minimum period has passed, and reverts with MinStakePeriodNotMet if it could not satisfy the full amount:

Solidity
	function _consumeUnlockedSharesOrRevert(address staker, uint256 need) internal {
		Stake[] storage userStakes = stakes[staker];
		uint256 _min = minStakePeriod;
		uint256 nowTs = block.timestamp;
		uint256 remaining = need;

		for (uint256 i; i < userStakes.length && remaining > 0;) {
			Stake memory s = userStakes[i];
			if (nowTs >= s.timestamp + _min) {
				uint256 take = s.shares <= remaining ? s.shares : remaining;
				if (take == s.shares) {
					// full consume → swap and pop
					remaining -= take;
					userStakes[i] = userStakes[userStakes.length - 1];
					userStakes.pop();
					// don't ++i: a new element is now at index i
				} else {
					// partial consume
					userStakes[i].shares = s.shares - take;
					remaining = 0;
					unchecked {
						++i;
					}
				}
			} else {
				unchecked {
					++i;
				}
			}
		}

		if (remaining != 0) revert MinStakePeriodNotMet();
	}

For a recipient with an empty array the loop body never runs, remaining stays equal to the requested amount, and the function reverts. The only remaining exit is the emergency path:

Solidity
	function _emergencyWithdraw(address by, address to, address _owner, uint256 assets, uint256 shares) internal {
		require(shares > 0, SharesEqZero());

		uint256 penalty = FixedPointMathLib.fullMulDiv(assets, penaltyPercentage, SCALING_FACTOR);
		uint256 payout;
		unchecked {
			payout = assets - penalty;
		}

		if (by != _owner) _spendAllowance(_owner, by, shares);

		_removeAnySharesFor(_owner, shares);
		_burn(_owner, shares);

		LONG.safeTransfer(to, payout);
		LONG.safeTransfer(treasury, penalty);

		emit EmergencyWithdraw(by, to, _owner, assets, shares);
		// also emit standard ERC4626 Withdraw for indexers/analytics
		emit Withdraw(by, to, _owner, assets, shares);
	}

This path ignores lock status entirely, burns the shares, and splits the underlying assets between the recipient and the treasury according to penaltyPercentage. The report notes that the default penalty is 10%.

Exploitation

Step 1: deploy and shorten the lock period

The fixture deploys the LONG token and the staking vault, then calls setMinStakePeriod(1) as the owner. This is only to make the test fast; the bug does not depend on the length of the period.

Step 2: deposit and observe the stake entry

The depositor approves the vault for 100 LONG and calls deposit(depositAmount, depositor.address). The test then reads balanceOf and stakes(depositor.address, 0) and logs the minted share amount and the recorded timestamp. At this point the depositor has both shares and a matching ledger entry, which is the normal, working case.

Step 3: transfer the shares

The depositor transfers the entire sLONG balance to the recipient:

TypeScript
    await staking.connect(depositor).transfer(recipient.address, mintedShares);

    await expect(staking.callStatic.stakes(recipient.address, 0)).to.be.reverted;

The second line asserts that reading the recipient's first stake entry reverts, which is how a Solidity array getter behaves when the index is out of bounds. The recipient now holds the shares but has zero stake entries.

Step 4: wait past the lock period and attempt a normal redeem

The test advances time by two seconds and mines a block, so the minimum period of one second is comfortably passed. It then calls a standard redeem:

TypeScript
    await expect(
      staking.connect(recipient).redeem(mintedShares, recipient.address, recipient.address),
    ).to.be.revertedWithCustomError(staking, 'MinStakePeriodNotMet');

The call reverts with MinStakePeriodNotMet, even though the shares were minted long enough ago to be unlocked. The lock is not the problem; the missing ledger entry is.

Step 5: emergency redeem and measure the loss

The test reads SCALING_FACTOR, penaltyPercentage and convertToAssets(mintedShares), computes the expected penalty, and records the recipient's and treasury's LONG balances before and after calling emergencyRedeem(mintedShares, recipient.address, recipient.address). It then asserts that the recipient gained exactly the assets minus the penalty, that the treasury gained exactly the penalty, and that the recipient's share balance is now zero.

The example run in the report shows the outcome:

Text
yarn hardhat test test/v2/platform/staking-transfer-poc.test.ts
...
[Setup] Depositor minted 100.0 sLONG shares
[Setup] Stake entry recorded with timestamp 1761366088
[Transfer] Recipient received shares but has zero stake entries
[Redeem Attempt] Normal redeem reverts with MinStakePeriodNotMet
[Emergency] Recipient forced to emergencyRedeem, receiving 90.0 LONG
[Emergency] Treasury collects penalty of 10.0 LONG
✔ proves transferred holders must use penalized emergency exits

A 100 sLONG position exits as 90 LONG to the holder and 10 LONG to the treasury, matching the 10% default penalty.

Root cause

The stake ledger is written only in _deposit and is never reconciled on ERC20 transfers. There is no transfer hook and no override of transfer or transferFrom, so the invariant that a holder's share balance is backed by stake entries of the same total does not survive a transfer. The withdrawal guard trusts the ledger, so a recipient whose balance arrived by transfer has nothing the guard will accept. The emergency path, which exists to let people out regardless of lock status, then becomes the only exit and applies its penalty unconditionally.

Impact

Any account that receives sLONG by transfer rather than by depositing is pushed into the emergency exit and permanently loses a fraction of the position equal to penaltyPercentage, with the penalty routed to the treasury. The loss scales with the transferred amount, so it can be arbitrarily large. The report lists auto-stake, rewards routing and third-party transfers as examples of flows that could subject recipients to this. The impact category is griefing: no profit motive is required, and the harm falls on users and the protocol.

Fix

It suggests, as design approaches, keeping per-account stake consistency on transfers, for example with hooks that update stakes on transfer, or by migrating stakes on transfer or delegation.

  1. Partial transfers. Transfer only part of a balance and check whether the sender's ledger and the recipient's balance diverge in a way that lets either side withdraw more than their entitlement. A positive result is a successful normal withdrawal that consumes stake entries the account no longer economically owns.
  2. Transfer back to the original depositor. Send shares to a fresh account and back, then attempt a normal redeem. If the original entries were consumed or duplicated, the redeem either reverts unexpectedly or succeeds for more shares than held.
  3. Other ERC4626 vaults with per-account lock ledgers. Look for the same pattern: a Stake[]-style array appended on deposit and read on withdraw, with no transfer override. A positive result is a transferred-in holder reverting with the lock error after the lock period has passed.
  4. Penalty parameter changes. Check whether an owner can raise penaltyPercentage after shares have been transferred, which would increase the loss for already-trapped recipients. A positive result is a successful parameter change that increases the penalty applied to an existing transferred position.
  5. Allowance-based emergency exits. Since _emergencyWithdraw spends allowance when the caller is not the owner, test whether a third party with an allowance can force a penalised exit on a transferred holder. A positive result is a successful emergencyWithdraw initiated by another account that burns the holder's shares and sends the penalty to the treasury.

This class of bug hides wherever a token balance and a separate accounting structure are both treated as authoritative. During review, look for mappings or arrays written in deposit or mint hooks and read in withdraw or burn hooks, then check whether the token's transfer functions are overridden or hooked. If they are not, transfers create accounts whose balance and ledger disagree.

The signal is a public getter over a per-user array combined with a custom lock error such as MinStakePeriodNotMet. If the error can be triggered for an account that never deposited, the ledger is not being maintained on transfer.

To show impact, the researcher built a minimal end-to-end test: deposit, transfer, wait past the lock, show the normal redeem reverting, then show the emergency redeem succeeding with a measurable penalty paid to the treasury. The test asserts exact amounts on both sides, which turns a design observation into a concrete, reproducible loss.

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

What happened, in plain words

Belong runs a staking product. You hand over a token called LONG, and the system gives you a different token called sLONG in return. That sLONG token is a receipt: it says "I put in this much, and I can take it back out later". The system also keeps a separate notebook, one page per person, recording when each batch of sLONG was created. That notebook exists so the product can enforce a rule: your sLONG has to sit still for a minimum period before you can take the LONG back out normally.

The problem is that sLONG can be sent to another person like any ordinary token, but the notebook is never updated when that happens. The sender's page still shows the old entries, and the receiver's page stays empty. When the receiver later tries to take the LONG out the normal way, the system checks the notebook, finds nothing on the receiver's page, and refuses. The only door left open is the "emergency" exit, and that door charges a fee, which goes to the project's treasury. So anyone who receives sLONG by transfer loses a slice of their money through no fault of their own.

The report rates this Critical and files it under griefing: nobody has to make a profit for the harm to happen, and the harm lands on ordinary users and on the protocol.

The pieces involved

Before the details, here is what each part is, in everyday terms.

  • A smart contract is a small program that lives on a blockchain. Once deployed it runs the same way for everyone, and nobody can quietly change its behaviour. Think of it as a vending machine that anyone can walk up to and use, with the rules written into the machine.
  • A token is a smart contract that keeps a list of who owns how much of something. LONG is one such token, and sLONG is another.
  • ERC20 is the common standard for tokens on Ethereum-style chains. It defines a fixed set of actions, including transfer (send tokens to someone) and balanceOf (ask how many tokens an address holds). Because every ERC20 token has the same actions, wallets and websites can handle them all the same way.
  • ERC4626 is a standard for a particular kind of token called a vault share. You put an asset in, and you get shares back that represent your slice of the pool. Later you hand the shares back and get your asset out, plus or minus whatever the pool earned or lost. It is like a coat-check ticket: the ticket is not the coat, but it entitles you to the coat.
  • A staking vault is the product here. You deposit LONG, you get sLONG shares, and the vault holds the LONG.
  • A mapping is a lookup table inside a smart contract. You give it a key (here, a person's address) and it gives you back a value (here, a list of stake entries).
  • An address is a user's account identifier on the blockchain, a long string of characters. It works like an account number.
  • A signer is a test account with a private key, used in automated tests to act as a particular user.
  • A hook is a piece of code that the contract runs automatically at a certain moment, for example whenever a deposit happens. If no hook exists for transfers, nothing runs on transfers.
  • A revert is how a smart contract refuses an action. It undoes everything and returns an error. It is the blockchain version of a shop assistant saying "sorry, I can't do that" and handing your item back.
  • A penalty here is a percentage of your assets that the contract keeps when you use the emergency exit, sending it to the treasury.
  • The treasury is the project's own account, where fees are collected.
  • Hardhat is a tool for developers that runs a pretend blockchain on your own computer, so tests can be run quickly without spending real money.
  • A proof of concept (PoC) is a small, self-contained demonstration that a bug is real. It is the difference between saying "this looks wrong" and showing it happening.

Context: what the product does

The target is a file called Staking.sol in the Belong audit competition repository. It is the staking vault described above, built around an ERC4626-style share token called sLONG. Users deposit LONG and receive sLONG shares.

The vault keeps, for each account, a record of when each batch of shares was created. That record is what allows a minimum stake period to be enforced before those shares can be withdrawn normally. Shares that have not yet passed the minimum period are locked. Shares that have passed it are unlocked and can be used in a standard withdrawal.

The contract stores this per-account history in a public mapping of stake entries. At the same time, it exposes the shares as a freely transferable ERC20 balance. The report's central claim is that these two views of ownership, the ERC20 balance and the stake ledger, are never kept in step when shares move between accounts.

Setup: how the demonstration was built

The proof of concept is a Hardhat test written in TypeScript, placed at test/v2/platform/staking-transfer-poc.test.ts. It uses the project's own deployment helpers, deployLONG and deployStaking, and the Hardhat network helpers loadFixture and time.

The fixture creates four signers: owner, treasury, depositor and recipient. It deploys the LONG token as a proxy with deployLONG(depositor.address, owner.address, owner.address) and the staking vault with deployStaking(owner.address, treasury.address, long.address). The owner then shortens the lock period with setMinStakePeriod(1) so the reproduction does not have to wait out the real minimum stake period. The deposit amount is 100 LONG, expressed with ethers.utils.parseEther('100').

No special tooling beyond Hardhat, Chai and the Hardhat network helpers is involved, and the report gives no version numbers.

The deployment helpers reuse the project's real setup code, so the test runs against the same contracts the product uses rather than a simplified copy. Shortening the lock period is purely for speed; the bug does not depend on how long the period is.

Finding it: reading the contract

The researcher compared two pieces of the contract. The first is the stake ledger declaration:

Solidity
	/// @notice User stake entries stored as arrays per staker.
	/// @dev Public getter: `stakes(user, i)` → `(shares, timestamp)`.
	mapping(address staker => Stake[] times) public stakes;

Line by line:

  • The two lines starting with /// are comments. They are notes for humans and do nothing when the contract runs. The first says the mapping holds each user's stake entries as arrays. The second explains that anyone can read an entry by calling stakes(user, i), which returns the number of shares and the timestamp.
  • mapping(address staker => Stake[] times) declares the lookup table. The key is an address (a person's account), and the value is a list (Stake[]) of stake records. Each record holds a number of shares and a timestamp.
  • public means the table can be read from outside the contract. stakes is the name of the table.

In plain words: for every account, the contract keeps a list of "this many shares were created at this moment".

The second piece is the deposit hook, which is the only place the ledger is appended to:

Solidity
	function _deposit(address by, address to, uint256 assets, uint256 shares) internal override {
		super._deposit(by, to, assets, shares);
		// lock freshly minted shares
		stakes[to].push(Stake({shares: shares, timestamp: block.timestamp}));
	}

Line by line:

  • function _deposit(...) defines an internal function that runs whenever someone deposits. internal means it can only be called from inside the contract or contracts built on top of it, not directly by a user.
  • The parameters are by (who is paying), to (who receives the shares), assets (how much LONG went in) and shares (how much sLONG came out).
  • super._deposit(by, to, assets, shares); runs the standard deposit logic from the parent contract first, so the normal ERC4626 bookkeeping happens.
  • stakes[to].push(...) then adds a new entry to the recipient's list. push means "append to the end of the list".
  • Stake({shares: shares, timestamp: block.timestamp}) builds the record: the number of shares just created, and the current block's timestamp, which is the blockchain's clock.

In plain words: every deposit writes a new line in the depositor's notebook page, saying how many shares and when.

Because sLONG is an ERC20, a holder can transfer the balance to anyone. Nothing in the contract overrides transfer or transferFrom, and there are no transfer hooks, so the recipient's stakes array stays empty while their token balance grows. The withdrawal path, however, checks the ledger rather than the balance:

Solidity
	function _withdraw(address by, address to, address _owner, uint256 assets, uint256 shares) internal override {
		_consumeUnlockedSharesOrRevert(_owner, shares);
		super._withdraw(by, to, _owner, assets, shares);
	}

Line by line:

  • function _withdraw(...) is the internal function that runs on a normal withdrawal. The parameters are who is asking (by), who receives the LONG (to), whose shares are being used (_owner), how much LONG to release (assets) and how many shares to burn (shares).
  • _consumeUnlockedSharesOrRevert(_owner, shares); is the guard. It checks the owner's notebook page and removes unlocked entries to cover the requested shares. If it cannot, it stops the whole withdrawal.
  • super._withdraw(...) then performs the standard ERC4626 withdrawal, releasing the LONG and burning the shares.

In plain words: before any normal withdrawal, the contract insists that the notebook page contains enough unlocked entries. The token balance alone is not enough.

_consumeUnlockedSharesOrRevert walks the caller's stake entries, takes shares from entries whose timestamp plus the minimum period has passed, and reverts with MinStakePeriodNotMet if it could not satisfy the full amount:

Solidity
	function _consumeUnlockedSharesOrRevert(address staker, uint256 need) internal {
		Stake[] storage userStakes = stakes[staker];
		uint256 _min = minStakePeriod;
		uint256 nowTs = block.timestamp;
		uint256 remaining = need;

		for (uint256 i; i < userStakes.length && remaining > 0;) {
			Stake memory s = userStakes[i];
			if (nowTs >= s.timestamp + _min) {
				uint256 take = s.shares <= remaining ? s.shares : remaining;
				if (take == s.shares) {
					// full consume → swap and pop
					remaining -= take;
					userStakes[i] = userStakes[userStakes.length - 1];
					userStakes.pop();
					// don't ++i: a new element is now at index i
				} else {
					// partial consume
					userStakes[i].shares = s.shares - take;
					remaining = 0;
					unchecked {
						++i;
					}
				}
			} else {
				unchecked {
					++i;
				}
			}
		}

		if (remaining != 0) revert MinStakePeriodNotMet();
	}

Line by line:

  • function _consumeUnlockedSharesOrRevert(address staker, uint256 need) defines the guard. It takes the account to check (staker) and how many shares must be covered (need).
  • Stake[] storage userStakes = stakes[staker]; grabs a reference to that account's list. storage means it points at the real stored data, so changes to it are permanent.
  • uint256 _min = minStakePeriod; copies the minimum lock period into a local variable.
  • uint256 nowTs = block.timestamp; reads the current time from the blockchain.
  • uint256 remaining = need; starts a counter at the full amount still to be covered.
  • for (uint256 i; i < userStakes.length && remaining > 0;) walks the list from the start, stopping when the list ends or when nothing is left to cover. The counter is advanced by hand inside the loop, which is why there is no i++ in the loop header.
  • Stake memory s = userStakes[i]; copies the current entry into memory for inspection.
  • if (nowTs >= s.timestamp + _min) asks: has this entry's timestamp plus the lock period already passed? If yes, the entry is unlocked.
  • uint256 take = s.shares <= remaining ? s.shares : remaining; decides how many shares to take from this entry: all of them if the entry is smaller than what is still needed, otherwise just what is needed.
  • If the whole entry is taken (take == s.shares), the code subtracts it from remaining, moves the last entry of the list into this slot, and removes the last slot with pop. This is a common trick to delete an item from a list cheaply. The comment notes that the index is not advanced, because a different entry has just landed in the current slot.
  • Otherwise, only part of the entry is taken: the entry's share count is reduced, remaining is set to zero, and the index moves on.
  • If the entry is still locked, the index simply moves on.
  • if (remaining != 0) revert MinStakePeriodNotMet(); is the final check. If anything is still uncovered, the whole call is refused with the error MinStakePeriodNotMet.

In plain words: the guard looks through the notebook page for entries old enough to use, takes what it needs, and refuses the withdrawal if the page cannot cover the request.

For a recipient with an empty array the loop body never runs, remaining stays equal to the requested amount, and the function reverts. The only remaining exit is the emergency path:

Solidity
	function _emergencyWithdraw(address by, address to, address _owner, uint256 assets, uint256 shares) internal {
		require(shares > 0, SharesEqZero());

		uint256 penalty = FixedPointMathLib.fullMulDiv(assets, penaltyPercentage, SCALING_FACTOR);
		uint256 payout;
		unchecked {
			payout = assets - penalty;
		}

		if (by != _owner) _spendAllowance(_owner, by, shares);

		_removeAnySharesFor(_owner, shares);
		_burn(_owner, shares);

		LONG.safeTransfer(to, payout);
		LONG.safeTransfer(treasury, penalty);

		emit EmergencyWithdraw(by, to, _owner, assets, shares);
		// also emit standard ERC4626 Withdraw for indexers/analytics
		emit Withdraw(by, to, _owner, assets, shares);
	}

Line by line:

  • function _emergencyWithdraw(...) is the emergency exit. It takes the same kinds of parameters as a normal withdrawal.
  • require(shares > 0, SharesEqZero()); refuses a request for zero shares, with the error SharesEqZero.
  • uint256 penalty = FixedPointMathLib.fullMulDiv(assets, penaltyPercentage, SCALING_FACTOR); calculates the fee: the assets multiplied by the penalty percentage, divided by a scaling factor. The scaling factor exists because percentages are stored as whole numbers rather than decimals.
  • payout = assets - penalty; works out what the user will actually receive. It sits inside unchecked, which tells the compiler not to add overflow checks, a small gas saving.
  • if (by != _owner) _spendAllowance(_owner, by, shares); handles the case where someone other than the owner is making the request: in that case the owner must have granted an allowance, the same kind of permission you give an app to spend your tokens.
  • _removeAnySharesFor(_owner, shares); clears the owner's notebook entries, regardless of whether they are locked.
  • _burn(_owner, shares); destroys the shares.
  • LONG.safeTransfer(to, payout); sends the user their share of the LONG.
  • LONG.safeTransfer(treasury, penalty); sends the fee to the treasury.
  • The two emit lines record events on the blockchain, one specific to emergency withdrawals and one standard ERC4626 withdrawal event so that indexers and analytics tools see it too.

In plain words: the emergency exit does not care about the notebook at all. It burns the shares, pays the user minus a fee, and sends the fee to the treasury. The report notes that the default penalty is 10%.

Exploitation: the demonstration step by step

Step 1: deploy and shorten the lock period

The fixture deploys the LONG token and the staking vault, then calls setMinStakePeriod(1) as the owner. This is only to make the test fast; the bug does not depend on the length of the period.

A test that had to wait that long would be impractical, so the owner (who has the authority to change the setting) sets it to one second. The behaviour being tested is the same either way.

Step 2: deposit and observe the stake entry

The depositor approves the vault for 100 LONG and calls deposit(depositAmount, depositor.address). The test then reads balanceOf and stakes(depositor.address, 0) and logs the minted share amount and the recorded timestamp. At this point the depositor has both shares and a matching ledger entry, which is the normal, working case.

The approve call is the depositor granting the vault permission to take their LONG, the same way you authorise a shop to charge your card.

Step 3: transfer the shares

The depositor transfers the entire sLONG balance to the recipient:

TypeScript
    await staking.connect(depositor).transfer(recipient.address, mintedShares);

    await expect(staking.callStatic.stakes(recipient.address, 0)).to.be.reverted;

Line by line:

  • staking.connect(depositor).transfer(recipient.address, mintedShares); acts as the depositor and calls the ordinary ERC20 transfer, sending all the minted shares to the recipient. This is the same action a wallet performs when you send a token.
  • staking.callStatic.stakes(recipient.address, 0) asks the contract for the recipient's first stake entry without changing anything. callStatic means "pretend to run this and tell me the answer, but do not record it".
  • .to.be.reverted asserts that the call fails. A Solidity array getter fails when you ask for an index that does not exist, so this is the test's way of proving the recipient's list is empty.

Why: the transfer is the exact action any user can take with an ERC20 token. The assertion turns "the list is probably empty" into a checked fact. The recipient now holds the shares but has zero stake entries.

Step 4: wait past the lock period and attempt a normal redeem

The test advances time by two seconds and mines a block, so the minimum period of one second is comfortably passed. It then calls a standard redeem:

TypeScript
    await expect(
      staking.connect(recipient).redeem(mintedShares, recipient.address, recipient.address),
    ).to.be.revertedWithCustomError(staking, 'MinStakePeriodNotMet');

Line by line:

  • staking.connect(recipient).redeem(...) acts as the recipient and asks to redeem all the shares, with the LONG going to the recipient and the shares coming from the recipient.
  • await expect(...) wraps the call so the test can check what happens.
  • .to.be.revertedWithCustomError(staking, 'MinStakePeriodNotMet') asserts that the call fails with that specific error name, not just any failure.

Why: this is the heart of the demonstration. The shares were created long enough ago to be unlocked, so the lock period is not the obstacle. The call still fails, and it fails with the lock error, which proves the contract is looking at the empty notebook page rather than at the age of the shares. The lock is not the problem; the missing ledger entry is.

Step 5: emergency redeem and measure the loss

The test reads SCALING_FACTOR, penaltyPercentage and convertToAssets(mintedShares), computes the expected penalty, and records the recipient's and treasury's LONG balances before and after calling emergencyRedeem(mintedShares, recipient.address, recipient.address). It then asserts that the recipient gained exactly the assets minus the penalty, that the treasury gained exactly the penalty, and that the recipient's share balance is now zero.

Reading the balances before and after is how the test proves where the money went: some to the user, some to the treasury.

The example run in the report shows the outcome:

Text
yarn hardhat test test/v2/platform/staking-transfer-poc.test.ts
...
[Setup] Depositor minted 100.0 sLONG shares
[Setup] Stake entry recorded with timestamp 1761366088
[Transfer] Recipient received shares but has zero stake entries
[Redeem Attempt] Normal redeem reverts with MinStakePeriodNotMet
[Emergency] Recipient forced to emergencyRedeem, receiving 90.0 LONG
[Emergency] Treasury collects penalty of 10.0 LONG
✔ proves transferred holders must use penalized emergency exits

Line by line:

  • yarn hardhat test ... is the command that runs the test file. yarn is a package manager that runs the project's scripts, and hardhat test runs the test suite.
  • The [Setup] lines report that 100 sLONG shares were minted and that the stake entry was recorded at a particular timestamp.
  • The [Transfer] line reports that the recipient received the shares but has no stake entries.
  • The [Redeem Attempt] line reports that the normal redeem was refused with MinStakePeriodNotMet.
  • The [Emergency] lines report the outcome: the recipient received 90 LONG and the treasury collected 10 LONG.
  • The final line with a tick mark says the test passed.

A 100 sLONG position exits as 90 LONG to the holder and 10 LONG to the treasury, matching the 10% default penalty.

Root cause

The stake ledger is written only in _deposit and is never reconciled on ERC20 transfers. There is no transfer hook and no override of transfer or transferFrom, so the invariant that a holder's share balance is backed by stake entries of the same total does not survive a transfer. The withdrawal guard trusts the ledger, so a recipient whose balance arrived by transfer has nothing the guard will accept. The emergency path, which exists to let people out regardless of lock status, then becomes the only exit and applies its penalty unconditionally.

In everyday terms: the contract has two records of who owns what, the token balance and the notebook, and it only ever updates one of them when shares move. The guard reads the notebook, the emergency exit ignores it, and nothing in between notices the disagreement.

Impact

Any account that receives sLONG by transfer rather than by depositing is pushed into the emergency exit and permanently loses a fraction of the position equal to penaltyPercentage, with the penalty routed to the treasury. The loss scales with the transferred amount, so it can be arbitrarily large. The report lists auto-stake, rewards routing and third-party transfers as examples of flows that could subject recipients to this. The impact category is griefing: no profit motive is required, and the harm falls on users and the protocol.

In everyday terms: this is not a bug that lets a thief empty the vault. It is a bug that quietly taxes anyone who receives sLONG from someone else. The bigger the transfer, the bigger the tax, and the money does not go to an attacker but to the project's own account.

Fix

It suggests, as design approaches, keeping per-account stake consistency on transfers, for example with hooks that update stakes on transfer, or by migrating stakes on transfer or delegation.

In everyday terms: the fix would be to make the notebook follow the tokens. When shares move, the matching entries should move with them, so the receiver's page reflects what they actually hold.

These are further scenarios worth trying, each described with what a positive result would look like.

  1. Partial transfers. Transfer only part of a balance and check whether the sender's ledger and the recipient's balance diverge in a way that lets either side withdraw more than their entitlement. A positive result is a successful normal withdrawal that consumes stake entries the account no longer economically owns.
  2. Transfer back to the original depositor. Send shares to a fresh account and back, then attempt a normal redeem. If the original entries were consumed or duplicated, the redeem either reverts unexpectedly or succeeds for more shares than held.
  3. Other ERC4626 vaults with per-account lock ledgers. Look for the same pattern: a Stake[]-style array appended on deposit and read on withdraw, with no transfer override. A positive result is a transferred-in holder reverting with the lock error after the lock period has passed.
  4. Penalty parameter changes. Check whether an owner can raise penaltyPercentage after shares have been transferred, which would increase the loss for already-trapped recipients. A positive result is a successful parameter change that increases the penalty applied to an existing transferred position.
  5. Allowance-based emergency exits. Since _emergencyWithdraw spends allowance when the caller is not the owner, test whether a third party with an allowance can force a penalised exit on a transferred holder. A positive result is a successful emergencyWithdraw initiated by another account that burns the holder's shares and sends the penalty to the treasury.

This class of bug hides wherever a token balance and a separate accounting structure are both treated as authoritative. During review, look for mappings or arrays written in deposit or mint hooks and read in withdraw or burn hooks, then check whether the token's transfer functions are overridden or hooked. If they are not, transfers create accounts whose balance and ledger disagree.

The signal is a public getter over a per-user array combined with a custom lock error such as MinStakePeriodNotMet. If the error can be triggered for an account that never deposited, the ledger is not being maintained on transfer.

To show impact, the researcher built a minimal end-to-end test: deposit, transfer, wait past the lock, show the normal redeem reverting, then show the emergency redeem succeeding with a measurable penalty paid to the treasury. The test asserts exact amounts on both sides, which turns a design observation into a concrete, reproducible loss.

In everyday terms: when you review a contract, ask "is there more than one place that records who owns what?" If yes, check whether every action that moves ownership updates all of them. The cheapest way to find out is to try the action as a user who never deposited and see whether the contract complains about a lock that should not apply.

Glossary

  • Address: a user's account identifier on the blockchain, a long string of characters, like an account number.
  • Allowance: a permission a token owner grants to another account to spend a set amount of their tokens.
  • Blockchain: a shared, append-only record of transactions maintained by many computers, where programs called smart contracts run.
  • Block timestamp: the time recorded with each block, used by contracts as a clock.
  • Chai: a testing library that provides readable assertions such as expect(...).to.eq(...).
  • Critical: the highest severity rating in this report, meaning the issue can cause serious loss or break core behaviour.
  • Custom error: a named error a contract can return instead of a plain failure message, for example MinStakePeriodNotMet.
  • Deposit: putting an asset into a vault in exchange for shares.
  • Emergency withdrawal: an exit path that ignores the lock period, burns shares and charges a penalty.
  • ERC20: the common standard for tokens, defining actions such as transfer and balanceOf.
  • ERC4626: a standard for vault share tokens, where shares represent a slice of a pool of an underlying asset.
  • Event: a record a contract writes to the blockchain log so outside tools can see that something happened.
  • Fixture: a reusable setup function in a test that prepares contracts and accounts before each test runs.
  • Griefing: causing harm to users or a protocol without needing to profit from it.
  • Hardhat: a development tool that runs a local pretend blockchain for testing smart contracts.
  • Hook: code that runs automatically at a particular moment, such as during a deposit.
  • Invariant: a rule that should always hold true, for example that a holder's balance matches their ledger entries.
  • Locked / unlocked shares: shares that have not yet passed the minimum stake period (locked) and those that have (unlocked).
  • Mapping: a lookup table inside a contract that maps keys to values.
  • Minimum stake period: the time shares must be held before they can be withdrawn normally.
  • Override: replacing or extending a function inherited from a parent contract.
  • Penalty: a percentage of assets the contract keeps when the emergency exit is used.
  • Proof of concept (PoC): a small demonstration that proves a bug is real and reproducible.
  • Proxy: a contract that forwards calls to another contract, allowing the logic to be upgraded.
  • Redeem: exchanging vault shares back for the underlying asset.
  • Revert: a contract refusing an action and undoing all its effects, returning an error.
  • Scaling factor: a number used to store percentages as whole numbers instead of decimals.
  • Severity: the rating of how serious a finding is.
  • Signer: a test account with a private key, used to act as a particular user.
  • Smart contract: a program deployed on a blockchain that runs the same way for everyone.
  • Staking: locking up tokens in a contract, often to earn rewards or to satisfy a holding requirement.
  • Staking vault: the contract that accepts deposits, issues shares and enforces the lock period.
  • Testnet / local network: a pretend blockchain used for testing rather than real funds.
  • Token: a contract that tracks who owns how much of something.
  • Transfer: sending tokens from one address to another.
  • Treasury: the project's own account, where fees are collected.
  • TypeScript: a programming language used to write the test, a stricter version of JavaScript.
  • Vault share: a token representing a slice of a pool of an underlying asset.
  • Withdrawal: taking the underlying asset back out of a vault by handing in shares.

More from Belong

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.