Yield withdrawal blocked by zero reward early return
The Distributor contract returns early from distributeRewards when the period reward is zero, so lastUnderlyingBalance is never refreshed after reward distribution ends. Yield that accrues after maxEndTime therefore stays untracked and cannot be withdrawn through withdrawYield.
Originally disclosed on Code4rena
Submitted by KlosMitSoss
Finding Description and Impact
When withdrawing yield, it is calculated as the difference between lastUnderlyingBalance and deposited for the given depositPool. The lastUnderlyingBalance is updated in distributeRewards() to reflect the current token balance, which includes accumulated yield. However, this function returns early when the calculated rewards_ amount for the period between lastCalculatedTimestamp_ and block.timestamp is zero:
uint256 rewards_ = IRewardPool(rewardPool).getPeriodRewards(
rewardPoolIndex_,
lastCalculatedTimestamp_,
uint128(block.timestamp)
);
if (rewards_ == 0) return;
This prevents lastUnderlyingBalance from being updated when rewards_ is zero, causing the accounting system to fail to recognize newly accumulated yield and making it impossible to withdraw.
Rewards are only calculated up to the maxEndTime, which represents when reward distribution for a given pool ends completely. After this point, no more rewards are distributed from that pool.
When getPeriodRewards() returns zero for any period after maxEndTime, it will permanently return zero for all future periods. This means distributeRewards() will always return early without updating lastUnderlyingBalance, creating a permanent lock on any yield that accumulated since lastCalculatedTimestamp_ and any yield that accumulates after the reward distribution period ends.
The problem is particularly severe because:
- Users can remain staked after
maxEndTimeand their tokens continue generating yield - The yield accounting becomes permanently broken once rewards end
- All yield generated after
maxEndTimebecomes permanently inaccessible - This affects the entire deposit pool, not just individual users
If lastCalculatedTimestamp_ == maxEndTime - 100, getPeriodRewards(rewardPoolIndex_, lastCalculatedTimestamp_, maxEndTime) == 0, and yield == 10e18 during that time, this yield amount will be permanently stuck. Any continuing yield accumulation after maxEndTime will also become unwithdrawable.
Recommended Mitigation Steps
Implement functionality that allows withdrawing yield even when no rewards accrue. For example:
- Add a mechanism to update
lastUnderlyingBalanceindependent of reward calculations - Implement a fallback method for yield withdrawal after reward distribution ends
Proof of Concept
Add the following file to ./test/ and run npx hardhat test --grep "should show yield stuck"
import { SignerWithAddress } from '@nomicfoundation/hardhat-ethers/signers';
import { expect } from 'chai';
import { ethers } from 'hardhat';
import {
AavePoolDataProviderMock,
AavePoolMock,
ArbitrumBridgeGatewayRouterMock, // Mock contracts
ChainLinkAggregatorV3Mock,
ChainLinkDataConsumer,
DepositPool,
Distributor,
ERC20Token,
IDepositPool,
IL1SenderV2,
IL2TokenReceiverV2, // Interfaces
IRewardPool,
L1SenderV2,
L2MessageReceiver,
L2TokenReceiverV2,
LayerZeroEndpointV2Mock,
MOR,
MOROFT,
NonfungiblePositionManagerMock,
RewardPool,
StETHMock,
UniswapSwapRouterMock,
WStETHMock,
} from '@/generated-types/ethers';
import { PRECISION, ZERO_ADDR } from '@/scripts/utils/constants';
import { wei } from '@/scripts/utils/utils';
import { getCurrentBlockTime, setNextTime, setTime } from '@/test/helpers/block-helper';
import { Reverter } from '@/test/helpers/reverter';
describe('Morpheus Capital Protocol - POC Test Suite', function () {
// Signers
let owner: SignerWithAddress;
let alice: SignerWithAddress;
let bob: SignerWithAddress;
let charlie: SignerWithAddress;
let treasury: SignerWithAddress;
let referrer1: SignerWithAddress;
let referrer2: SignerWithAddress;
// Core Capital Protocol Contracts
let chainLinkDataConsumer: ChainLinkDataConsumer;
let depositPool: DepositPool;
let distributor: Distributor;
let l1Sender: L1SenderV2;
let l2TokenReceiver: L2TokenReceiverV2;
let rewardPool: RewardPool;
// Mock Contracts and Dependencies
let aavePool: AavePoolMock;
let aavePoolDataProvider: AavePoolDataProviderMock;
let stETH: StETHMock;
let wstETH: WStETHMock;
let depositToken: ERC20Token;
let rewardToken: ERC20Token;
let mor: MOR;
let morOft: MOROFT;
let swapRouter: UniswapSwapRouterMock;
let nonfungiblePositionManager: NonfungiblePositionManagerMock;
let arbitrumBridge: ArbitrumBridgeGatewayRouterMock;
let lzEndpointL1: LayerZeroEndpointV2Mock;
let lzEndpointL2: LayerZeroEndpointV2Mock;
let l2MessageReceiver: L2MessageReceiver;
// Price Feed Mocks
let ethUsdFeed: ChainLinkAggregatorV3Mock;
let btcUsdFeed: ChainLinkAggregatorV3Mock;
let wbtcBtcFeed: ChainLinkAggregatorV3Mock;
// Test Constants
const oneDay = 86400;
const oneHour = 3600;
const publicRewardPoolId = 0;
const privateRewardPoolId = 1;
const l1ChainId = 101;
const l2ChainId = 110;
// Reverter for test isolation
const reverter = new Reverter();
// Enums
enum Strategy {
NONE, // Direct deposit, no yield
NO_YIELD, // No yield strategy (private pools)
AAVE, // Aave yield strategy
}
// Helper Functions
async function deployERC20Token(): Promise<ERC20Token> {
const factory = await ethers.getContractFactory('ERC20Token');
return await factory.deploy();
}
async function deployMocks() {
// Deploy price feed mocks
const aggregatorFactory = await ethers.getContractFactory('ChainLinkAggregatorV3Mock');
ethUsdFeed = await aggregatorFactory.deploy(18);
btcUsdFeed = await aggregatorFactory.deploy(8);
wbtcBtcFeed = await aggregatorFactory.deploy(8);
// Set initial prices
await ethUsdFeed.setAnswerResult(wei(2000, 18)); // $2000/ETH
await btcUsdFeed.setAnswerResult(wei(40000, 8)); // $40000/BTC
await wbtcBtcFeed.setAnswerResult(wei(1, 8)); // 1:1 WBTC/BTC
// Deploy Aave mocks
const aaveDataProviderFactory = await ethers.getContractFactory('AavePoolDataProviderMock');
aavePoolDataProvider = await aaveDataProviderFactory.deploy();
const aavePoolFactory = await ethers.getContractFactory('AavePoolMock');
aavePool = await aavePoolFactory.deploy(aavePoolDataProvider);
// Deploy token mocks
const stETHFactory = await ethers.getContractFactory('StETHMock');
stETH = await stETHFactory.deploy();
const wstETHFactory = await ethers.getContractFactory('WStETHMock');
wstETH = await wstETHFactory.deploy(stETH);
depositToken = await deployERC20Token();
rewardToken = await deployERC20Token();
const morFactory = await ethers.getContractFactory('MOR');
mor = await morFactory.deploy(wei(1000000)); // 1M initial supply
// Deploy swap router mocks
const swapRouterFactory = await ethers.getContractFactory('UniswapSwapRouterMock');
swapRouter = await swapRouterFactory.deploy();
const nftManagerFactory = await ethers.getContractFactory('NonfungiblePositionManagerMock');
nonfungiblePositionManager = await nftManagerFactory.deploy();
// Deploy bridge mocks
const bridgeFactory = await ethers.getContractFactory('ArbitrumBridgeGatewayRouterMock');
arbitrumBridge = await bridgeFactory.deploy();
// Deploy LayerZero mocks
const lzFactory = await ethers.getContractFactory('LayerZeroEndpointV2Mock');
lzEndpointL1 = await lzFactory.deploy(l1ChainId, owner.address);
lzEndpointL2 = await lzFactory.deploy(l2ChainId, owner.address);
// Deploy L2MessageReceiver mock (if needed for L1Sender tests)
const l2MessageReceiverFactory = await ethers.getContractFactory('L2MessageReceiver');
const l2MessageReceiverImpl = await l2MessageReceiverFactory.deploy();
const proxyFactory = await ethers.getContractFactory('ERC1967Proxy');
const l2MessageReceiverProxy = await proxyFactory.deploy(l2MessageReceiverImpl, '0x');
l2MessageReceiver = l2MessageReceiverFactory.attach(l2MessageReceiverProxy) as L2MessageReceiver;
await l2MessageReceiver.L2MessageReceiver__init();
}
async function deployCapitalProtocol() {
// 1. Deploy ChainLinkDataConsumer
const chainLinkFactory = await ethers.getContractFactory('ChainLinkDataConsumer');
const chainLinkImpl = await chainLinkFactory.deploy();
const proxyFactory = await ethers.getContractFactory('ERC1967Proxy');
const chainLinkProxy = await proxyFactory.deploy(await chainLinkImpl.getAddress(), '0x');
chainLinkDataConsumer = chainLinkFactory.attach(await chainLinkProxy.getAddress()) as ChainLinkDataConsumer;
await chainLinkDataConsumer.ChainLinkDataConsumer_init();
// Setup price feeds
await chainLinkDataConsumer.updateDataFeeds(
['ETH/USD', 'wBTC/BTC,BTC/USD'],
[[await ethUsdFeed.getAddress()], [await wbtcBtcFeed.getAddress(), await btcUsdFeed.getAddress()]],
);
// 2. Deploy RewardPool (with library linking)
const linearDistributionLib = await (
await ethers.getContractFactory('LinearDistributionIntervalDecrease')
).deploy();
const rewardPoolFactory = await ethers.getContractFactory('RewardPool', {
libraries: {
LinearDistributionIntervalDecrease: await linearDistributionLib.getAddress(),
},
});
const rewardPoolImpl = await rewardPoolFactory.deploy();
const rewardPoolProxy = await proxyFactory.deploy(await rewardPoolImpl.getAddress(), '0x');
rewardPool = rewardPoolFactory.attach(await rewardPoolProxy.getAddress()) as RewardPool;
const pools: IRewardPool.RewardPoolStruct[] = [
{
payoutStart: oneDay,
decreaseInterval: oneDay,
initialReward: 10000000,
rewardDecrease: 1000000,
isPublic: true,
},
{
payoutStart: oneDay * 20,
decreaseInterval: oneDay * 2,
initialReward: wei(200),
rewardDecrease: wei(1),
isPublic: false,
},
];
await rewardPool.RewardPool_init(pools);
// 3. Deploy L1SenderV2
const l1SenderFactory = await ethers.getContractFactory('L1SenderV2');
const l1SenderImpl = await l1SenderFactory.deploy();
const l1SenderProxy = await proxyFactory.deploy(await l1SenderImpl.getAddress(), '0x');
l1Sender = l1SenderFactory.attach(await l1SenderProxy.getAddress()) as L1SenderV2;
await l1Sender.L1SenderV2__init();
// Configure L1Sender
await l1Sender.setStETh(await stETH.getAddress());
await l1Sender.setArbitrumBridgeConfig({
wstETH: await wstETH.getAddress(),
gateway: await arbitrumBridge.getAddress(),
receiver: treasury.address,
});
await l1Sender.setUniswapSwapRouter(await swapRouter.getAddress());
// 4. Deploy Distributor
const distributorFactory = await ethers.getContractFactory('Distributor');
const distributorImpl = await distributorFactory.deploy();
const distributorProxy = await proxyFactory.deploy(await distributorImpl.getAddress(), '0x');
distributor = distributorFactory.attach(await distributorProxy.getAddress()) as Distributor;
await distributor.Distributor_init(
await chainLinkDataConsumer.getAddress(),
await aavePool.getAddress(),
await aavePoolDataProvider.getAddress(),
await rewardPool.getAddress(),
await l1Sender.getAddress(),
);
// 5. Deploy DepositPool
const lib1 = await (await ethers.getContractFactory('ReferrerLib')).deploy();
const lib2 = await (await ethers.getContractFactory('LockMultiplierMath')).deploy();
const depositPoolFactory = await ethers.getContractFactory('DepositPool', {
libraries: {
ReferrerLib: await lib1.getAddress(),
LockMultiplierMath: await lib2.getAddress(),
},
});
const depositPoolImpl = await depositPoolFactory.deploy();
const depositPoolProxy = await proxyFactory.deploy(await depositPoolImpl.getAddress(), '0x');
depositPool = depositPoolFactory.attach(await depositPoolProxy.getAddress()) as DepositPool;
await depositPool.DepositPool_init(await depositToken.getAddress(), await distributor.getAddress());
// 6. Deploy L2TokenReceiverV2
const l2ReceiverFactory = await ethers.getContractFactory('L2TokenReceiverV2');
const l2ReceiverImpl = await l2ReceiverFactory.deploy();
const l2ReceiverProxy = await proxyFactory.deploy(await l2ReceiverImpl.getAddress(), '0x');
l2TokenReceiver = l2ReceiverFactory.attach(await l2ReceiverProxy.getAddress()) as L2TokenReceiverV2;
await l2TokenReceiver.L2TokenReceiver__init(
await swapRouter.getAddress(),
await nonfungiblePositionManager.getAddress(),
{
tokenIn: await stETH.getAddress(),
tokenOut: await mor.getAddress(),
fee: 500,
sqrtPriceLimitX96: 0,
},
);
// 7. Setup connections
await l1Sender.setDistributor(await distributor.getAddress());
// Add deposit pool to distributor
await distributor.addDepositPool(
publicRewardPoolId,
await depositPool.getAddress(),
await depositToken.getAddress(),
'ETH/USD',
Strategy.NONE,
);
// Complete migration
await depositPool.migrate(publicRewardPoolId);
}
async function mintTokensToUsers() {
const amount = wei(1000);
// Mint deposit tokens
await depositToken.mint(alice.address, amount);
await depositToken.mint(bob.address, amount);
await depositToken.mint(charlie.address, amount);
// Mint stETH
await stETH.mint(alice.address, amount);
await stETH.mint(bob.address, amount);
await stETH.mint(charlie.address, amount);
// Setup approvals
await depositToken.connect(alice).approve(await depositPool.getAddress(), ethers.MaxUint256);
await depositToken.connect(bob).approve(await depositPool.getAddress(), ethers.MaxUint256);
await depositToken.connect(charlie).approve(await depositPool.getAddress(), ethers.MaxUint256);
await stETH.connect(alice).approve(await l1Sender.getAddress(), ethers.MaxUint256);
await stETH.connect(bob).approve(await l1Sender.getAddress(), ethers.MaxUint256);
}
// Test Setup
before(async function () {
// Get signers
[owner, alice, bob, charlie, treasury, referrer1, referrer2] = await ethers.getSigners();
// Deploy all contracts
await deployMocks();
await deployCapitalProtocol();
await mintTokensToUsers();
// Take snapshot for reverting
await reverter.snapshot();
});
afterEach(async function () {
await reverter.revert();
});
describe('POC yield not withdrawable', function () {
it('should show yield stuck', async function () {
await setTime(oneDay * 9);
// Setup reward pool timestamp (required before any staking)
await distributor.setRewardPoolLastCalculatedTimestamp(publicRewardPoolId, oneDay * 7);
// Set minimum rewards distribute period to 1 day
await distributor.setMinRewardsDistributePeriod(1);
const timestamp = await distributor.rewardPoolLastCalculatedTimestamp(publicRewardPoolId);
expect(timestamp).to.eq(604800);
const dp0Before = await distributor.depositPools(publicRewardPoolId, depositPool);
expect(dp0Before.deposited).to.eq(wei(0));
expect(dp0Before.lastUnderlyingBalance).to.eq(wei(0));
// Alice stakes tokens
await depositPool.connect(alice).stake(publicRewardPoolId, wei(100), 0, ZERO_ADDR);
const dp0 = await distributor.depositPools(publicRewardPoolId, depositPool);
expect(dp0.deposited).to.eq(wei(100));
expect(dp0.lastUnderlyingBalance).to.eq(wei(100));
const currentUserRewards = await depositPool.connect(alice).getLatestUserReward(publicRewardPoolId, alice);
expect(currentUserRewards).to.eq(0);
// imitate yield
await depositToken.mint(distributor, wei(100));
expect(await depositToken.balanceOf(distributor)).to.eq(wei(200));
const rewards = await rewardPool.getPeriodRewards(0, oneDay * 9, oneDay * 11);
expect(rewards).to.eq(3000000);
// Fast forward time to maxEndTime
await setTime(oneDay * 11);
// rewards are distributed at that time and yield withdrawn
await distributor.distributeRewards(publicRewardPoolId);
// lastUnderlyingBalance updated
const dp1 = await distributor.depositPools(publicRewardPoolId, depositPool);
expect(dp1.deposited).to.eq(wei(100));
expect(dp1.lastUnderlyingBalance).to.eq(wei(200));
// yield is withdrawn
await distributor.withdrawYield(publicRewardPoolId, depositPool);
expect(await depositToken.balanceOf(distributor)).to.eq(wei(100));
expect(await depositToken.balanceOf(l1Sender)).to.eq(wei(100));
// lastUnderlyingBalance updated
const dp2 = await distributor.depositPools(publicRewardPoolId, depositPool);
expect(dp2.deposited).to.eq(wei(100));
expect(dp2.lastUnderlyingBalance).to.eq(wei(100));
// alice receives rewards
const currentUserRewardsFinal = await depositPool.connect(alice).getLatestUserReward(publicRewardPoolId, alice);
expect(currentUserRewardsFinal).to.be.gt(0);
// Alice withdraws at oneDay * 14
await setTime(oneDay * 14);
// imitate yield that accrues after all reward distributed, they will never be tracked
await depositToken.mint(distributor, wei(100));
// rewards for this period are 0
const rewardsFinal = await rewardPool.getPeriodRewards(0, oneDay * 11, oneDay * 14);
expect(rewardsFinal).to.eq(0);
// lastUnderlyingBalance still the same
const dp3 = await distributor.depositPools(publicRewardPoolId, depositPool);
expect(dp3.deposited).to.eq(wei(100));
expect(dp3.lastUnderlyingBalance).to.eq(wei(100));
await depositPool.connect(alice).withdraw(publicRewardPoolId, wei(100));
expect(await depositToken.balanceOf(distributor)).to.eq(wei(100));
// lastUnderlyingBalance not updated, does not track yield
const dp4 = await distributor.depositPools(publicRewardPoolId, depositPool);
expect(dp4.deposited).to.eq(wei(0));
expect(dp4.lastUnderlyingBalance).to.eq(wei(0));
// yield cannot be withdrawn
await distributor.withdrawYield(publicRewardPoolId, depositPool);
expect(await depositToken.balanceOf(distributor)).to.eq(wei(100));
// l1Sender balance still the same -> no yield withdrawn
expect(await depositToken.balanceOf(l1Sender)).to.eq(wei(100));
});
});
});
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely the early return on a zero reward amount skips the balance refresh that yield withdrawal depends on, and after maxEndTime the reward amount is permanently zero.
Impact
Yield generated after reward distribution ends becomes permanently stuck in the distributor and cannot be withdrawn, affecting the whole deposit pool.
What the attacker needed
Users remain staked past maxEndTime; yield accrues after reward distribution ends
The fix
The contract should update lastUnderlyingBalance independently of reward accrual, for example with a separate refresh function or a fallback yield withdrawal path after rewards end.
How it was found
- Set the reward pool's last calculated timestamp and a minimum distribution period.
- Stake tokens into the deposit pool so deposited and lastUnderlyingBalance are recorded.
- Mint extra tokens to the distributor to imitate yield and advance time to maxEndTime.
- Call distributeRewards and withdrawYield while rewards are still non-zero to show normal operation.
- Advance past maxEndTime, mint more tokens as new yield, and confirm getPeriodRewards returns zero.
- Withdraw the stake and call withdrawYield; the extra tokens remain in the distributor.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
A smart contract tracks how much money users put in and how much extra it has earned. It only updates that 'extra' figure when it also pays out a separate reward, and once the reward programme finishes it stops updating. Any extra money earned after that point is invisible to the contract, so nobody can take it out.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.