lpEarnings generated in emergency mode become stuck on the contract
When the jackpot enters emergency mode, the runJackpot function is blocked, so lpEarnings for the current drawing are never moved to the accumulator. However, claimWinnings can still be called for previous drawings and credits referral win shares to lpEarnings of the current drawing, leaving those funds permanently stuck in the contract.
BengalCatBalu Follow with 0xDemon, 0xnightswatch and 3 others
Originally disclosed on Code4rena
Submitted by BengalCatBalu, also found by 0xDemon, 0xnightswatch, dan__vinci, montecristo, and rokinot
Finding description and impact
As stated in the contest README, emergency mode is an unrecoverable state. This means that the protocol does not intend to exit emergency mode once it is activated.
This means that once the jackpot enters emergency mode, the current drawing will not be completed, since runJackpot is protected by the noEmergencyMode modifier.
function runJackpot() external payable nonReentrant noEmergencyMode {
This means that the lpEarnings for the current drawing will not be included in the accumulator update (cause there will be no upgrade) and will therefore remain stuck in the protocol.
LP earnings originate from two sources:
- Ticket sales
- Referral win shares distributed when claiming rewards for tickets without referrers
Ticket sales are not counted during emergency mode, since users receive their funds back through emergencyRefundTickets.
However, referral win shares can still be generated in any drawing:
function _payReferrersWinnings(
bytes32 _referralSchemeId,
uint256 _winningAmount,
uint256 _referralWinShare
) internal
returns (uint256)
{
...
uint256 referrerShare = _winningAmount * _referralWinShare / PRECISE_UNIT;
// If referrer scheme is empty then the referrer share goes to LPs so we just add the amount to lpEarnings
// in order to make sure our system accounts for it
if (_referralSchemeId == bytes32(0)) {
drawingState[currentDrawingId].lpEarnings += referrerShare;
emit LpEarningsUpdated(currentDrawingId, referrerShare);
return referrerShare;
}
...
}
Let’s look more closely at the claimWinnings call.
A user can invoke this function to claim rewards from any previous drawing (even on emergency mode).
If a ticket has no referrers, the referral win share (a percentage of the prize) is credited as lpEarnings for the current drawing, as shown in the code.
function claimWinnings(uint256[] memory _userTicketIds) external nonReentrant {
if (_userTicketIds.length == 0) revert JackpotErrors.NoTicketsToClaim();
uint256 totalClaimAmount = 0;
for (uint256 i = 0; i < _userTicketIds.length; i++) {
uint256 ticketId = _userTicketIds[i];
IJackpotTicketNFT.TrackedTicket memory ticketInfo = jackpotNFT.getTicketInfo(ticketId);
uint256 drawingId = ticketInfo.drawingId;
if (IERC721(address(jackpotNFT)).ownerOf(ticketId) != msg.sender) revert JackpotErrors.NotTicketOwner();
if (drawingId >= currentDrawingId) revert JackpotErrors.TicketFromFutureDrawing();
DrawingState memory winningDrawingState = drawingState[drawingId];
uint256 tierId = _calculateTicketTierId(ticketInfo.packedTicket, winningDrawingState.winningTicket, winningDrawingState.ballMax);
jackpotNFT.burnTicket(ticketId);
uint256 winningAmount = payoutCalculator.getTierPayout(drawingId, tierId);
uint256 referrerShare = _payReferrersWinnings( // @audit lp earnings distributions here
ticketInfo.referralScheme,
winningAmount,
winningDrawingState.referralWinShare
);
totalClaimAmount += winningAmount - referrerShare;
emit TicketWinningsClaimed(
msg.sender,
drawingId,
ticketId,
tierId / 2, // matches
(tierId % 2) == 1, // bonusball match
winningAmount - referrerShare
);
}
usdc.safeTransfer(msg.sender, totalClaimAmount);
}
Thus, during emergency mode, the claimWinnings function continues generating lpEarnings, but these amounts will never be accounted for going forward. They simply remain stuck in the protocol.
Recommended mitigation steps
Add a dedicated function that allows withdrawing the stuck funds while the protocol is in emergency mode.
Expand for detailed Proof of Concept
Proof of Concept
import { ethers } from "hardhat";
import DeployHelper from "@utils/deploys";
import { getWaffleExpect, getAccounts } from "@utils/test/index";
import { ether, usdc } from "@utils/common";
import { Account } from "@utils/test";
import { PRECISE_UNIT } from "@utils/constants";
import {
GuaranteedMinimumPayoutCalculator,
Jackpot,
JackpotBridgeManager,
JackpotLPManager,
JackpotTicketNFT,
MockDepository,
ReentrantUSDCMock,
ScaledEntropyProviderMock,
} from "@utils/contracts";
import {
Address,
JackpotSystemFixture,
RelayTxData,
Ticket,
} from "@utils/types";
import { deployJackpotSystem } from "@utils/test/jackpotFixture";
import {
calculatePackedTicket,
calculateTicketId,
generateClaimTicketSignature,
generateClaimWinningsSignature,
} from "@utils/protocolUtils";
import { ADDRESS_ZERO, ONE_DAY_IN_SECONDS } from "@utils/constants";
import {
takeSnapshot,
SnapshotRestorer,
time,
} from "@nomicfoundation/hardhat-toolbox/network-helpers";
const expect = getWaffleExpect();
describe("C4", () => {
let owner: Account;
let user: Account;
let buyerOne: Account;
let buyerTwo: Account;
let referrerOne: Account;
let referrerTwo: Account;
let referrerThree: Account;
let solver: Account;
let jackpotSystem: JackpotSystemFixture;
let jackpot: Jackpot;
let jackpotNFT: JackpotTicketNFT;
let jackpotLPManager: JackpotLPManager;
let payoutCalculator: GuaranteedMinimumPayoutCalculator;
let usdcMock: ReentrantUSDCMock;
let entropyProvider: ScaledEntropyProviderMock;
let snapshot: SnapshotRestorer;
let jackpotBridgeManager: JackpotBridgeManager;
let mockDepository: MockDepository;
const drawingDurationInSeconds: bigint = ONE_DAY_IN_SECONDS;
const entropyFee: bigint = ether(0.00005);
const entropyBaseGasLimit: bigint = BigInt(1000000);
const entropyVariableGasLimit: bigint = BigInt(250000);
beforeEach(async () => {
[
owner,
user,
buyerOne,
buyerTwo,
referrerOne,
referrerTwo,
referrerThree,
solver,
] = await getAccounts();
jackpotSystem = await deployJackpotSystem();
jackpot = jackpotSystem.jackpot;
jackpotNFT = jackpotSystem.jackpotNFT;
jackpotLPManager = jackpotSystem.jackpotLPManager;
payoutCalculator = jackpotSystem.payoutCalculator;
usdcMock = jackpotSystem.usdcMock;
entropyProvider = jackpotSystem.entropyProvider;
await jackpot
.connect(owner.wallet)
.initialize(
usdcMock.getAddress(),
await jackpotLPManager.getAddress(),
await jackpotNFT.getAddress(),
entropyProvider.getAddress(),
await payoutCalculator.getAddress(),
);
await jackpot.connect(owner.wallet).initializeLPDeposits(usdc(10000000));
await usdcMock
.connect(owner.wallet)
.approve(jackpot.getAddress(), usdc(1000000));
await jackpot.connect(owner.wallet).lpDeposit(usdc(1000000));
await jackpot
.connect(owner.wallet)
.initializeJackpot(
BigInt(await time.latest()) +
BigInt(jackpotSystem.deploymentParams.drawingDurationInSeconds),
);
jackpotBridgeManager =
await jackpotSystem.deployer.deployJackpotBridgeManager(
await jackpot.getAddress(),
await jackpotNFT.getAddress(),
await usdcMock.getAddress(),
"MegapotBridgeManager",
"1.0.0",
);
mockDepository = await jackpotSystem.deployer.deployMockDepository(
await usdcMock.getAddress(),
);
snapshot = await takeSnapshot();
});
beforeEach(async () => {
await snapshot.restore();
});
describe("POC", async () => {
let subjectRandomNumbers: bigint[][];
let subjectCaller: Account;
let isJackpotRun: boolean = true;
beforeEach(async () => {
await usdcMock.connect(owner.wallet).transfer(buyerOne.address, usdc(1));
await usdcMock.connect(buyerOne.wallet).approve(jackpot.getAddress(), usdc(1));
await jackpot.connect(buyerOne.wallet).buyTickets(
[
{
normals: [BigInt(1), BigInt(2), BigInt(3), BigInt(4), BigInt(5)],
bonusball: BigInt(6)
} as Ticket,
],
buyerOne.address,
[],
[],
ethers.encodeBytes32String("test")
);
if (isJackpotRun) {
await time.increase(drawingDurationInSeconds);
const drawingState = await jackpot.getDrawingState(1);
await jackpot.runJackpot({ value: entropyFee + ((entropyBaseGasLimit + entropyVariableGasLimit * drawingState.bonusballMax) * BigInt(1e10)) });
}
subjectRandomNumbers = [[BigInt(1), BigInt(2), BigInt(3), BigInt(4), BigInt(5)], [BigInt(6)]];
subjectCaller = buyerOne;
});
async function subject(): Promise<any> {
return await entropyProvider.connect(subjectCaller.wallet).randomnessCallback(subjectRandomNumbers);
}
it("POC", async () => {
await subject();
const expectedTicketIdOne = calculateTicketId(1, 1, calculatePackedTicket({
normals: [BigInt(1), BigInt(2), BigInt(3), BigInt(4), BigInt(5)],
bonusball: BigInt(6)
} as Ticket, BigInt(30)));
await jackpot.connect(owner.wallet).enableEmergencyMode();
await jackpot.connect(buyerOne.wallet).claimWinnings([expectedTicketIdOne]);
const currentDrawingId = await jackpot.currentDrawingId();
const drawingStateAfter = await jackpot.getDrawingState(currentDrawingId);
console.log("LP EARNINGS: ", drawingStateAfter.lpEarnings);
expect(drawingStateAfter.lpEarnings).to.be.gt(0);
});
});
});
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 claimWinnings function does not check for emergency mode and continues to add referral win shares to the current drawing's lpEarnings, which can never be processed because runJackpot is disabled.
Impact
Referral win shares generated during emergency mode become permanently stuck in the contract, as the protocol does not intend to exit emergency mode.
What the attacker needed
Emergency mode is enabled; user has a winning ticket from a previous drawing; ticket has no referrer
The fix
Add a dedicated function that allows withdrawing the stuck funds while the protocol is in emergency mode.
How it was found
- A user buys a ticket and the jackpot is run normally, producing a winning drawing.
- The owner enables emergency mode.
- The user calls claimWinnings for their winning ticket from the previous drawing.
- The referral win share is added to the current drawing's lpEarnings, which remains stuck.
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.
The jackpot contract has an emergency mode that stops the normal draw from completing. Even in that mode, users can still claim prizes from earlier draws, and a small cut of those prizes is meant to go to the people who provide liquidity (the pool of money). That cut is recorded as earnings for the current draw, but because the draw never finishes, the money is never paid out and stays locked in the contract.
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.