Security review · November 2026
PerpCity Contracts Updates for Perp City
Guardian's review of PerpCity Contracts Updates for Perp City, published November 2026. The report records 29 findings across 2 review rounds, including 7 low and 22 informational.
See how Guardian runs a perp DEX smart contract audit.
- Published
- Review window
- October 19 to November 9, 2026
- Rounds
- Main Review, Remediation Review
- Language
- Solidity
- Chains
- Arbitrum
- Sector
- Perpetuals
- 0 Critical
- 0 High
- 0 Medium
- 7 Low
- 22 Informational
Scope
-
GuardianOrg/mirror-strobelabs-perpcity-contracts
915821ace06e830949c5
26 files in scope · 2,903 nSLOC
| File | nSLOC | Lines |
|---|---|---|
src/AccountingToken.sol | 5 | 84 |
src/interfaces/IPerp.sol | 197 | 294 |
src/interfaces/IWithdrawalController.sol | 19 | 47 |
src/libraries/Constants.sol | 4 | 58 |
src/libraries/Errors.sol | 53 | 67 |
src/libraries/PerpAmmLogic.sol | 302 | 429 |
src/libraries/PerpFundingLogic.sol | 40 | 76 |
src/libraries/PerpLiquidationLogic.sol | 245 | 427 |
src/libraries/PerpLogic.sol | 468 | 959 |
src/libraries/PerpMakerLogic.sol | 331 | 413 |
src/libraries/PerpPreviewLogic.sol | 49 | 102 |
src/libraries/PerpUtilizationLogic.sol | 202 | 253 |
src/libraries/SafeBeaconIndex.sol | 16 | 28 |
src/libraries/SignedFixedPointMathLib.sol | 18 | 69 |
src/libraries/Structs.sol | 161 | 447 |
src/ModuleRegistry.sol | 4 | 36 |
src/modules/Fees.sol | 48 | 260 |
src/modules/Funding.sol | 25 | 89 |
src/modules/MarginRatios.sol | 93 | 191 |
src/modules/PriceImpact.sol | 7 | 72 |
src/modules/Pricing.sol | 27 | 78 |
src/Perp.sol | 346 | 713 |
src/PerpFactory.sol | 76 | 171 |
src/PerpGuardHook.sol | 10 | 102 |
src/ProtocolFeeManager.sol | 13 | 46 |
src/WithdrawalController.sol | 144 | 254 |
Findings 29
Main Review
26 findings · October 19 to November 2, 2026-
L-01 Low No in-place release path for excess insurance Suggestion Acknowledged
Description
The updated utilization accounting routes fees attributable to open interest above in-band maker closing capacity into a reserve. On taker settlement,
PerpLogic.realizeReserveuses that amount to repay bad debt first and credits the remainder tofeeFund.insurance. In the current implementation,accountBadDebtis the only path that debits the insurance bucket, and it does so only to cover a realized loss.If a healthy market accumulates insurance materially above its desired loss buffer, the excess cannot be redistributed to traders or LPs through the current interface. It remains reserved, uses TVL-cap headroom, and can be consumed only by future bad debt and can therefore become some type of stucked tokens if the insurance funds grows bigger than reasonable. This is a conditional capital-efficiency limitation.
Recommendation
Be aware and document this behavior or consider to implement a way to release excess insurance funds if ever necessary.
-
L-02 Low MakerMoved does not index
posIdEvents ResolvedDescription
MakerMovedincludesposId, but it is not markedindexedlike other maker lifecycle events. An indexer cannot filter move logs for one position by topic and must fetch and decode allMakerMovedlogs to find that position.Recommendation
Be aware of and document this behavior or consider marking
posIdasindexedinMakerMoved. -
L-03 Low Maker liquidation lifecycle events report zero liquidity delta event-accounting Resolved
Description
PerpLiquidationLogic.liquidateMaker()emitsMakerAdjusted,MakerConvertedandMakerClosedwithliquidityDelta = 0despite removing nonzero liquidity, while the voluntary path reports the actual signed change.Consumers replaying lifecycle liquidity deltas can retain incorrect maker liquidity.
Recommendation
Emit the actual negative removed liquidity in each liquidation lifecycle event.
-
L-04 Low Phantom close reserve underpays terminal short liquidators logic-error Resolved
Description
A terminal short liquidation may leave an unfillable rounding remainder that is written off at mark before the position is deleted. The reward calculation nevertheless subtracts a hypothetical remainder-close reserve from the equity cap. No subsequent close is required, so this unnecessarily reduces the keeper's reward and increases the owner's payout
Recommendation
Compute the remainder close reserve only for nonterminal liquidations.
- if (netDelta.amount0() != 0) { + if (!terminal && netDelta.amount0() != 0) { (uint256 sqrtMin, uint256 sqrtMax) = s.modules.priceImpact .sqrtPriceBounds( snap.spots.ammPrice, snap.spots.index, snap.emas.ammPrice, snap.emas.index, snap.markPrice ); reserve = takerCloseReserve( netDelta.amount0(), valAfter, sqrtMin, sqrtMax, s.modules.fees.maxSwapFee() + MAX_PROTOCOL_FEE ); } -
L-05 Low Deferred flip fee debit under-haircuts second-hop fee claims Business logic errors Resolved
Description
PerpLogic.adjustTaker()executes a position flip by closing the existing side and opening the opposite side through two consecutivePerpAmmLogic.swap()calls.SwapResult memory closeSr = PerpAmmLogic.swap(s, poolId, -int256(oldPerpBalance), snap, false); closeQuote = closeSr.delta.amount1(); (snap.tick, snap.sqrtAmmPrice,) = PerpAmmLogic.poolState(poolId); sr = PerpAmmLogic.swap(s, poolId, newPerpBalance, snap, false); sr = _addSwapResults(closeSr, sr);Each call immediately runs
PerpAmmLogic.accrueSwapFees(). This socializes the protocol and creator fees againstbadDebtand credits the surviving protocol, creator, and insurance fees toFeeFund.However, the first swap's
feeFundFeeAmtremains included intotalMarginuntil both swaps are combined:int256 netMargin = preSettledMargin + p.marginDelta - sr.totalFeeAmt; removeSwapFeesFromMargin(s, sr);When
badDebtremains after the first swap, the second swap calculates its fee haircut using an overstatedtotalMargin. It therefore applies a smaller haircut and credits excess fees toFeeFund. The later aggregate debit correctstotalMargin, but it does not correct the excess fee claim or the remainingbadDebt.The PoC uses the deployed fee schedule and measures 9,733 USDC atoms of excess fee claims per flip in a large synthetic debt scenario. These claims leave the same amount of additional
badDebtand reduce the backing available for later payouts.Recommendation
Remove the first swap's
feeFundFeeAmtfromtotalMarginbefore executing the second swap. After the second swap, remove only its newly createdfeeFundFeeAmt. Preserve the aggregateSwapResultfields used by the adjustment event and add a regression test against a per-hop accounting reference. -
L-06 Low Split maker liquidations can overpay rewards Gaming Acknowledged
Description
PerpLiquidationLogic.liquidateMaker()calculates the liquidation reward withPerpLogic.makerMarkLiqFeeBase():uint256 markFeeBase = PerpLogic.makerMarkLiqFeeBase(pos.delta, sqrtPl, sqrtPu, oldLiquidity, liquidityAmount, snap.markPrice);PerpLogic.makerMarkLiqFeeBase()assumes that the liquidity is removed at the mark price:(uint256 perps, uint256 usd) = LiquidityAmounts.getAmountsForLiquidity(sqrtMark, sqrtPriceL, sqrtPriceU, liquidityAmount); Delta afterDelta = delta + toBalanceDelta(perps.toInt128(), usd.toInt128());The actual removal happens at the AMM price and the returned tokens are added to
pos.delta:Delta delta = PerpAmmLogic.modifyLiquidity(posId, maker.tickLower, maker.tickUpper, -liquidityAmount.toInt128()); int256 marginBeforeLiqFee = pos.margin.toInt256() + lpFees.toInt256() - funding; pos.delta = pos.delta + delta;After a partial liquidation, the hypothetical mark-priced result is discarded. The next liquidation calculates its reward from the actual AMM-settled
pos.delta. When the mark and AMM prices differ, splitting the same removal can therefore change the total reward.Example:
- The maker is liquidatable while the mark and AMM prices remain unchanged
- Removing
2,612,000,000liquidity in one call pays13.590887 USDC - The position is reset to the same starting snapshot
- Removing
2,369,000,000and then243,000,000liquidity pays14.423248 USDC - Both calls remain liquidatable and pass
healthImproved() - Splitting the removal pays the liquidator an additional
0.832361 USDC, or approximately6.12%
This comparison only applies when the external state remains unchanged. Liquidations after a mark-price change, AMM swap, funding accrual, or another position action may correctly produce different rewards.
The previous finding, “Split maker liquidations repeatedly charge unchanged residual notional,” had a different cause. The old formula charged a proportional share of the whole position value for every chunk. This repeatedly included the same residual exposure.
The previous fix changed the fee base to
valBefore - valAfter. The previous chunk’svalAfterbecame the next chunk’svalBefore, so split fees added up to the one-shot fee.The later mark-pricing change protected the fee from AMM price manipulation. However, the hypothetical
afterDeltais not stored, so it does not become the next chunk’s starting state. This reintroduced split overpayment through a different accounting path.Recommendation
Store a per-position maker liquidation fee correction containing both token amounts, a fixed episode start timestamp, and a fixed episode start mark price.
For each partial maker liquidation:
- Reset an existing correction if a certain time interval has elapsed since the episode started or the mark has deviated by more than a given threshold from the episode start mark.
- Calculate the reward from
pos.delta + correction. - Execute the removal and update both correction amounts by
markDelta - actualDelta. - Set the episode timestamp and mark only when starting a new episode. Do not roll either value after later chunks.
- Continue using the real
pos.deltafor settlement, health, funding, and PnL. - Clear the correction when the resulting maker is no longer liquidation-eligible, after a repair restores health, after
PerpLiquidationLogic.backstopMaker(), and when the maker closes or converts into a taker. - Preserve the correction across liquidity adjustments that merely improve an unhealthy maker without ending the liquidation episode. Apply their actual token delta equally to the real and fee-accounting states.
-
L-07 Low Dynamic LP fee depends on swap partitioning Gaming Acknowledged
Description
_accrueSwapSegmentFees()obtains the LP fee fromfees()using the pre-swap AMM spot price and applies that rate to all volume executed by the external swap. The LP fee grows with the squared deviation between the AMM spot price and its EMA.When a taker trades toward the EMA, they can split one intended swap between
openTaker()and subsequentadjustTaker()calls. Each later call begins closer to the EMA and is charged a lower LP fee, whereas a single swap over the same price path applies the higher initial rate to all volume. The resulting position exposure and AMM price are the same, apart from expected rounding.The included PoC uses the deployment-script fee curve and 2% price-impact bound. Splitting a swap into ten calls reduces LP fees by
717USDC atoms, while improving the taker’s net margin by702USDC atoms after per-call rounding. The effect requires a pre-existing spot/EMA divergence and is small under the intended configuration, but it makes LP fee revenue depend on execution partitioning rather than only the traded price path.Recommendation
If partition-independent dynamic fees are desired, calculate the dynamic LP fee over each executed price interval rather than applying an entry-price quote to all volume. Extend the fee-module interface to return the fee amount over a constant-liquidity
sqrtPriceinterval using the shared EMA reference. The price-dependent component should be integrated over the executed path, such that concatenating adjacent paths yields the same fee as executing their union in one swap, subject only to rounding.Alternatively, if allowing traders to select the lower-cost execution mode when moving toward the EMA is acceptable, acknowledge this behavior and document it as an intended fee-model property in
TRUST_ASSUMPTIONS.md. -
I-01 Informational Unused
MoveMakerParamsimport remains inPerpLogicSuperfluous Code ResolvedDescription
PerpLogicimportsMoveMakerParams, but never references the type. The move-maker entry point and parameter handling are implemented inPerp.solandPerpMakerLogic.sol, so this import is stale.Recommendation
Be aware and consider to remove unused code.
-
I-02 Informational Negative settled cash blocks solvent zero-residual maker closes DoS Resolved
Description
When a maker owes accrued funding,
adjustMakerdeducts it from cash collateral:preSettledMargin = pos.margin + lpFees - funding(line 127). WithmarginDelta = 0, this signed cash balance can be negative. A full liquidity removal can leave zero residual perps (amount0 == 0) and a positive quote balance (amount1) large enough to cover the cash deficit and leave positive final equity. The quote balance is the offsetting value; funding is the debit.However, line 130 casts
preSettledMargin + marginDeltatouint256before adding the removal delta topos.deltaat line 131 and before the zero-perp close branch at lines 230-249 addsamount1to cash and pays out. Negative cash therefore revertsOverflow()even if final equity is positive. A maker that remains above the liquidation and backstop thresholds cannot use either path to exit and must add USDC to bring cash nonnegative before closing.Recommendation
Be aware and consider to document this needed top up or to rewrite this logic to allow closes in that case and avoid the overflow.
-
I-03 Informational MarginTransferred can be emitted without a USDC transfer Events Resolved
Description
transferMarginemitsMarginTransferredeven whenmarginDelta == 0. A successfuladjustMakerormoveMakercall with zero margin delta reaches this path, so the event can appear without moving USDC or changingtotalMargin. Log consumers should not treat the event alone as proof that funds moved.Recommendation
Be aware of and document the zero-transfer case.
-
I-04 Informational Redundant tick-change check before event emission Gas Optimization Resolved
Description
_crossTicksAndAccrueSwapFees()returns early wheneversnap.tick == endingTick. Therefore, execution reaching theTicksCrossedevent is guaranteed to satisfysnap.tick != endingTick, making the additional condition redundant and adding unnecessary bytecode and runtime gas.if (snap.tick != endingTick) emit IPerp.TicksCrossed(snap.tick, endingTick, zeroForOne);Recommendation
Remove the redundant condition and emit
TicksCrossedunconditionally after the traversal loop. -
I-05 Informational Extreme reduce-only deltas revert with an arithmetic panic Error Resolved
Description
adjustTakercalls_checkReduceOnlywhenreduceOnlyis true._checkReduceOnlyadds the caller-suppliedint256 deltato the existingint128position balance before checking whether the request reduces exposure. For an existing long,delta = type(int256).maxoverflows that addition; for an existing short,delta = type(int256).minunderflows it. Both revert with SolidityPanic(0x11)beforeErrors.ReduceOnlyViolated().These are invalid requests and each revert is atomic. The effect is an inconsistent revert selector for integrations that recognize a reduce-only violation by its custom error; no valid reduction or market state was shown to be affected.
Recommendation
Be aware and consider to check whether
deltalies in the reduction interval for the current position before adding it and reject with a custom error instead to follow best practices. -
I-06 Informational Widening the price-impact band can make later utilization accrual exceed transaction gas limits Informational Acknowledged
Description
setPriceImpactModuleaccrues utilization under the existing cached price-impact band before installing the replacement module and caching its new band. After time passes, utilization rewards are distributed across initialized ticks in that cached band. Widening can therefore make a later accrual much more expensive than the module update itself.For example:
- Taker open interest exists, and makers add many narrow ranges outside the current band but inside a proposed wider band.
- The governor installs the wider module. The update accrues against the old narrow band, then caches the wider band and completes.
- After time passes,
touch()or a position action must distribute rewards across the newly included ticks. If the band admits enough initialized ticks, that accrual can exceed the transaction gas limit. - Replacing the wide module with a narrow one also accrues against the cached wide band first, so an ordinary rollback can fail for the same reason.
Part of this is known in the trust assumptions therefore this risk is only pointed out as info.
Recommendation
Be aware and consider enforcing a tighter maximum band width.
-
I-07 Informational Zero-liquidity maker adjustments perform an unnecessary Uniswap call Gas Optimization Resolved
Description
adjustMaker()callsPerpAmmLogic.modifyLiquidity()even whenp.liquidityDelta == 0. This performs an unnecessary Uniswap V4 unlock, hook authorization, position update, and settlement cycle. PerpCity independently settles its custom LP fees, while native Uniswap fee growth andfeeDeltaare expected to remain zero, so the zero-liquidity call has no useful effect.Recommendation
Skip
PerpAmmLogic.modifyLiquidity()whenp.liquidityDelta == 0and use a zeroDeltawhile continuing the protocol’s funding, fee, margin, checkpoint, and health accounting. -
I-08 Informational OpenInterestUpdated can be emitted without an open-interest change Events Resolved
Description
adjustTakeracceptsperpDelta == 0for a margin-only adjustment. The zero-swap path leaves the taker's perp balance unchanged, yet_applyTakerSwapStatestill rewrites the same open interest and emitsOpenInterestUpdated. Log consumers should not treat this event alone as proof that open interest changed.Recommendation
Be aware of and document the unchanged-open-interest case.
-
I-09 Informational Market creation logs omit the initial governor Events Resolved
Description
createPerptakes an initialgovernor, andPerp.initializestores it, but neither initialization norPerpCreatedemits that address. A log-only monitor cannot identify a market's initial governor without reading creation calldata or historical state.Recommendation
Consider including the initial governor in
PerpCreatedor emittingSetGovernorduring initialization. -
I-10 Informational Utilization can be increased via matched positions Gaming Acknowledged
Description
PerpLogic.refreshRatesAndEmas()derives long and short utilization independently from grossoi.longandoi.short. A participant can open approximately matched opposing positions and increase both utilization rates.The second swap can restore the AMM price, utilization capacity, and the stored
physicalCapclose to their original values throughrotatePhysicalCapacity(). The matched positions nevertheless remain recorded as gross open interest. Consequently, subsequent calls toPerpLogic.accrue()charge higher utilization fees to all takers, whilePerpUtilizationLogic.accrue()andsplit()distribute the eligible portion to makers. A participant controlling a sufficiently large share of eligible maker liquidity can therefore recover much of the fees paid by their matched taker positions and receive a share of the additional fees paid by unrelated takers.Recommendation
Document that utilization is intentionally based on gross, independently maintained long and short OI, including the resulting behavior for matched opposing positions. Monitor matched gross OI and eligible maker concentration.
-
I-11 Informational
PerpMakerLogic.moveMaker()allows positions below floor Documentation AcknowledgedDescription
PerpMakerLogic.moveMaker()permits a maker’s resulting settled margin to remain belowMIN_OPENING_MARGINwhenevermarginDelta >= 0. The resulting position must still satisfy the maker initial margin ratio because the function callsPerpLogic.checkActionHealth()withrepairEligibleset tofalse. This matches the conditional floor applied byPerpMakerLogic.adjustMaker()andPerpLogic.adjustTaker(). However, section 4.13 ofTRUST_ASSUMPTIONS.mdexplicitly documents this behavior only forPerpMakerLogic.adjustMaker()andPerpLogic.adjustTaker(), omittingPerpMakerLogic.moveMaker().Recommendation
Update section 4.13 of
TRUST_ASSUMPTIONS.mdto includePerpMakerLogic.moveMaker()and clarify that existing positions must retainMIN_OPENING_MARGINonly when withdrawing margin, while risk-increasing actions remain governed by the applicable initial margin ratio.Alternatively, modify the check in
PerpMakerLogic.moveMaker()so it always requires the floor to be satisfied. -
I-12 Informational Overlapping liquidation constraints create a temporary taker no-action window Trust Assumptions Acknowledged
Description
TRUST_ASSUMPTIONS.mdseparately accepts that partial taker liquidations can revert withNegativeMargin, full liquidations can revert withPriceImpactTooHigh, and backstopping starts only below the backstop ratio. These constraints can overlap and temporarily leave an unhealthy position with no executable liquidation or repair path.Funding and utilization can make
settledMarginnegative while favorable PnL keeps full equity positive.PerpLiquidationLogic.liquidateTaker()checks the cash-onlynetMarginbefore checking whether a partial liquidation improves health:require(netMargin >= 0, Errors.NegativeMargin());PerpLogic.adjustTaker()applies the same check beforePerpLogic.checkActionHealth(). A holder reduction that improves full-equity health still reverts unless the holder first clears the entire cash deficit.A full liquidation does not use this cash floor, but it must close through
PerpAmmLogic.swap(). It reverts when the close moves the AMM outside the mark-relative price-impact band.PerpLiquidationLogic.backstopTaker()is unavailable while the position remains above the lower backstop ratio.Example:
- Funding and utilization reduce settled cash to approximately
-0.72 USDC - Favorable PnL leaves approximately
+2.92 USDCfull equity on40 USDCnotional - The position is below the liquidation ratio but above the backstop ratio
- Band-fillable partial liquidations and no-withdrawal holder reductions revert with
NegativeMargin - Full liquidation reverts with
PriceImpactTooHigh - Backstopping reverts with
NotLiquidatable
Recommendation
TRUST_ASSUMPTIONS.md:134-163describes the no-action window in the finding, but it doesn't mention the negative cash as a reason, only the health check. Acknowledge the finding if this behavior is acceptable. - Funding and utilization reduce settled cash to approximately
-
I-13 Informational
reduceOnlydocumentation implies strict exposure reduction Documentation ResolvedDescription
Perp._checkReduceOnly()permits unchanged exposure whendelta == 0, allowing margin-only adjustments. However, its documentation states that it checks whether the delta reduces the position, which may lead integrators to expect a strict exposure reduction.Recommendation
Document that
reduceOnlyprevents increasing or flipping exposure but permits unchanged exposure and margin-only adjustments. -
I-14 Informational Missing taker position-state bounds let partial liquidation alter pending flips and backstop terms Frontrunning Resolved
Description
Perp.adjustTaker()appliesAdjustTakerParams.perpDeltato the position’s live exposure.amt1Limit,maxTotalFee, anddeadlinelimit execution price, fees, and time, but do not limit the starting or resulting exposure.A previous remediation added
reduceOnly. This protects reductions and closes becausePerp._checkReduceOnly()reverts if the transaction crosses zero. It does not protect an intentional flip because every flip must setreduceOnlytofalse.A permissionless
PerpLiquidationLogic.liquidateTaker()call can therefore reduce the position before a pending flip executes. The unchangedperpDeltacloses the smaller remaining position and opens a larger opposite position than the holder intended.Example:
- A holder has a
5,000,000atom long and submitsperpDelta = -5,000,001to open a one-atom short - Without a liquidation, the position ends at
-1 - A liquidator first closes
1,000,000atoms - The same pending
perpDeltanow leaves a-1,000,001atom short - After the index moves from $46 to $50, the intended one-atom short remains healthy and realizes
8.455040USDC - The enlarged short becomes liquidatable and returns only
2.957831USDC to the holder
Perp.backstopTaker()has the same missing state commitment. A backstopper commits to a fixedmarginIn, but cannot require minimum remaining exposure, minimum acquired equity, or an expected position state. A partial taker liquidation can consume equity and reduce exposure before the pending backstop executes. If the originalmarginInstill satisfies the live health check, the backstopper pays the same amount for the changed position.Recommendation
Add an expected current exposure or position-state nonce to
AdjustTakerParamsand reject the transaction if the position changed before execution. KeepreduceOnlyfor reductions and closes.Acknowledge the
Perp.backstopTaker()case the same way the backstopMaker one was. - A holder has a
-
I-15 Informational Partial liquidation leaves unfillable short dust DoS Acknowledged
Description
It is an intended behavior that a successful partial liquidation may reduce exposure enough to make the residual position healthy, after which further liquidation attempts revert with
NotLiquidatable.The
TRUST_ASSUMPTIONS.mdalso record that V4 rounding can make reported short-closing capacity slightly exceed executable sell-side liquidity. Voluntary closes remain all-or-nothing, residual open interest can reserve maker capacity, and operations may need to supply replacement liquidity.These behaviors can be combined through the caller-selected
perpAmountinPerpLiquidationLogic.liquidateTaker(). Consider an unhealthy short for which a full liquidation would succeed:PerpAmmLogic.swap()would buy the available perp, verify that the unfilled amount does not exceed the capacity ledger’s pre-existing overstatement, settle that remainder at the mark, and close the position.Instead, a permissionless liquidator can request a near-full partial liquidation equal to the amount the AMM can execute. The partial trade fills exactly and consumes the remaining sell-side liquidity, but leaves a rounding-sized short. Because most exposure was removed while margin remains, the residue can become healthy.
The two accepted constraints then form a no-action state:
- Further liquidation reverts with
NotLiquidatablebecause the residue is healthy. - The owner’s close through
Perp.adjustTaker()reverts withInsufficientLiquidityToFillbecause voluntary closes require an exact fill. - The residual short open interest can prevent the final maker from removing all liquidity.
The distinct behavior is therefore not either constraint individually, but that a permissionless partial liquidation can transform a position that was terminally closable into the already accepted liquidity-rescue state.
Recommendation
Be aware of the combinations of these two behaviors and the discrepancy they cause between a full and partial liquidation.
- Further liquidation reverts with
-
I-16 Informational Relaxed convergence paths can exceed the transaction gas limit denial-of-service Acknowledged
Description
The protocol recognizes that swap gas grows with the number of initialized ticks crossed, but assumes that the configured price-impact band and fixed tick spacing bound this cost. Fixed tick spacing only bounds tick density within a given price interval. The interval itself can become substantially larger when the AMM is outside the ordinary price-impact band.
PerpAmmLogic.swap()obtains the normalsqrtMinandsqrtMaxbounds and then relaxes whichever bound excludes the pre-swapsnap.sqrtAmmPrice. If the AMM is below the band, the effective interval becomes[snap.sqrtAmmPrice, sqrtMax]; if it is above the band, it becomes[sqrtMin, snap.sqrtAmmPrice]. A convergence-direction swap can therefore traverse the entire displacement between the stranded AMM and the band, in addition to part or all of the ordinary band.This exposure is shared by every sufficiently large convergence-direction call to
PerpAmmLogic.swap(). It therefore applies to taker opens throughPerpLogic.openTaker(), increases, reductions, closes, and flips throughPerpLogic.adjustTaker(), and liquidations throughPerpLiquidationLogic.liquidateTaker(). These paths execute the V4 swap and replay the crossed ticks for protocol accounting. A terminal short liquidation additionally scans the path throughPerpAmmLogic._topOfBook(), making liquidation the most expensive and consequential affected flow.Permissionless makers can populate the expanded convergence interval with minimum-margin narrow ranges and make taker operations exceed the maximum transaction gas budget.
Recommendation
If this is accepted behavior, update
TRUST_ASSUMPTIONS.mdto document that convergence relaxation can makePerpAmmLogic.swap()traverse every initialized tick between an out-of-band AMM price and the relaxed band edge.Operators can monitor both this price gap and the number of initialized candidate ticks along the corrective path, using benchmarked thresholds for a gas-safe traversal.
-
I-17 Informational Principal rounding can make mark health overstate immediate closeability Informational Acknowledged
Description
V4 rounds base input up and quote output down for every segment crossed by an exact-input long close.
PerpLogic.openTaker()checks initial health using the mark value fromPerpLogic.valPnl()without accounting for this closing cost.In the PoC, a healthy 36-atom long opened across 36 ranges at a $500,000 mark costs 17,164,454 quote atoms. Immediately closing it returns only 8,813,863 quote atoms. The loss exceeds its 5,396,075 settled margin and the close reverts with
NegativeEquity. The same position closes successfully against continuous liquidity.The reverted transaction leaves the position open. The owner must add collateral or wait for liquidity or prices to change.
Recommendation
Document in
TRUST_ASSUMPTIONS.mdthat mark health is not an executable close quote and that fragmented V4 rounding can add approximately one base atom of closing loss per crossed range. Position previews and integrations should estimate the full close and warn when its expected cost exceeds the available collateral. -
I-18 Informational Healthy maker liquidation attempts modify liquidity before reverting Gas Optimization Resolved
Description
PerpLiquidationLogic.liquidateMaker()callsPerpAmmLogic.modifyLiquidity()and updates accounting before checking eligibility throughPerpLogic.isHealthy(). Since all eligibility inputs are already available, healthy attempts perform unnecessary PoolManager and accounting work before reverting.Recommendation
Move the eligibility check before
PerpAmmLogic.modifyLiquidity(), aligning the flow withPerpLiquidationLogic.liquidateTaker(). -
I-19 Informational Full maker exits use a redundant refresh flag Best Practices Resolved
Description
The zero-liquidity branch in
PerpMakerLogic.adjustMaker()calls the six-parameterrefreshRatesAndEmas()overload withp.liquidityDelta != 0aspoolMutated. BecausePerp.adjustMaker()requires existing maker liquidity to be nonzero, reaching this branch meansp.liquidityDeltanecessarily removed all liquidity and modified the pool. The expression is therefore alwaystrueand obscures this invariant.Recommendation
Continue using the six-parameter
refreshRatesAndEmas()overload, but passtruedirectly forpoolMutated. This preservessnap.markPrice, avoids an additional pricing-module call, and makes the full-removal invariant explicit.
Remediation Review
3 findings · November 7 to 9, 2026-
I-01 Informational Taker flips settle swap fees per leg but utilization reserve per action Unexpected Behavior Acknowledged
Description
When
PerpLogic.adjustTaker()flips a taker position from long to short or vice versa, it executes a closing swap followed by an opening swap. The function finalizes each leg’s fee-fund claims separately by callingPerpLogic.removeSwapFeesFromMargin()after eachPerpAmmLogic.swap():if (oldPerpBalance != 0 && newPerpBalance != 0 && (oldPerpBalance < 0) != (newPerpBalance < 0)) { // Close first to realize the old side's exact quote, then open the new side from the post-close pool. // Both legs quote rates from the pre-trade prices but round fees independently. The second leg's // price-impact anchor advances to the intermediate pool price. SwapResult memory closeSr = PerpAmmLogic.swap(s, poolId, -int256(oldPerpBalance), snap, false); closeQuote = closeSr.delta.amount1(); // Finalize the close leg's fee claims so the open leg's haircut does not count them as active collateral. removeSwapFeesFromMargin(s, closeSr); (snap.tick, snap.sqrtAmmPrice,) = PerpAmmLogic.poolState(poolId); sr = PerpAmmLogic.swap(s, poolId, newPerpBalance, snap, false); removeSwapFeesFromMargin(s, sr); sr = _addSwapResults(closeSr, sr);However, the old position’s pending utilization reserve is realized only after both swap legs have completed:
(int256 accruedFees, int256 funding, uint256 util) = takerFeesAccrued(s, taker, pos); uint256 reserveCredit = realizeReserve(s, p.posId, taker, pos.delta.amount0()); int256 preSettledMargin = pos.margin.toInt256() - accruedFees; int256 netMargin = preSettledMargin + p.marginDelta - sr.totalFeeAmt; removeReserveFromMargin(s, reserveCredit);Consequently, the operation uses two different settlement boundaries: swap fees are finalized per leg, while utilization reserve is finalized once per complete adjustment. Insurance credit and bad-debt repayment attribution can consequently depend on whether the taker flips atomically or uses two actions.
Recommendation
Document that the current ordering prioritizes preserving/rebuilding insurance by imposing losses on protocol and creator fee claims, even when pending reserve would have been sufficient to cover the debt if realized first.
-
I-02 Informational Atomic taker flips retain equity outside the withdrawal-controller path Documentation Acknowledged
Description
PerpLogic.adjustTaker()implements a side flip by executing a closing swap followed immediately by an opening swap while retaining the existing position and its margin:if (oldPerpBalance != 0 && newPerpBalance != 0 && (oldPerpBalance < 0) != (newPerpBalance < 0)) { // Close first to realize the old side's exact quote, then open the new side from the post-close pool. // Both legs quote rates from the pre-trade prices but round fees independently. The second leg's // price-impact anchor advances to the intermediate pool price. SwapResult memory closeSr = PerpAmmLogic.swap(s, poolId, -int256(oldPerpBalance), snap, false); closeQuote = closeSr.delta.amount1(); // Finalize the close leg's fee claims so the open leg's haircut does not count them as active collateral. removeSwapFeesFromMargin(s, closeSr); (snap.tick, snap.sqrtAmmPrice,) = PerpAmmLogic.poolState(poolId); sr = PerpAmmLogic.swap(s, poolId, newPerpBalance, snap, false); removeSwapFeesFromMargin(s, sr); sr = _addSwapResults(closeSr, sr);In contrast, performing the same economic transition as a complete close followed by a new open first routes the closed position’s remaining equity through
PerpLogic.closeTaker():/// @dev Pays remaining equity and deletes the position and taker checkpoints. function closeTaker(PerpStorage storage s, address equityRecipient, uint256 posId, uint256 equity) internal { transferMargin(s, -equity.toInt128(), equityRecipient); delete s.positions[posId]; delete s.takers[posId]; }The outgoing
PerpLogic.transferMargin()call applies any outstanding bad-debt haircut and routes the resulting USDC payout through the withdrawal controller. Depending on controller capacity and configuration, the payout may be transferred immediately or escrowed as a delayed claim. The user may therefore need additional external capital before opening the replacement position.An atomic flip does not create an external payout, so it neither consumes withdrawal-controller capacity nor creates an escrowed claim. It also retains the position’s nominal equity internally instead of realizing the bad-debt haircut that a complete close would apply.
Additionally, the new documentation for GA-29 advises users to first close their position and then reopen it if they want to avoid an in-between liquidation resulting in an increased exposure. However, they may need to provide additional funds if the rate limiter cannot satisfy their closing request.
Recommendation
Document that an atomic taker flip retains collateral within the market and does not invoke the withdrawal controller, while a standalone close routes equity through the controller before a subsequent open and keep in mind the
GA-29behavior. Frontends and integrations comparing the two paths should account for possible payout escrow, withdrawal capacity, and bad-debt haircuts. No change to the flip implementation is required. -
I-03 Informational Funding correction is split by raw liquidity Accounting Acknowledged
Description
PerpFundingLogic.accrue()charges funding on the rounding gap between raw perp balances and maker inventory, and shares the offsetting correction across all makers by raw liquidity:int256 totalCorrectionX128 = (-exposureX96).sFullMulDiv(fundingAccruedX96, 1 << 64, true); cumls.fundingCorrectionX128 += totalCorrectionX128.sFullMulDiv(1, state.makerLiquidity, true);A range entirely below the current price holds no perp inventory but still counts in
state.makerLiquidity. NearMIN_TICKsuch liquidity is almost free, so a maker postingMIN_OPENING_MARGINcan hold nearly all of it and collect nearly all of the correction while funding is negative. The sign of the correction follows the sign of funding, which is observable on-chain: the maker can open the range while the correction is a credit and close it before funding turns positive.The maker receives the share that would otherwise go to the other makers. The maker is credited while
emas.ammPriceis belowemas.index. With nearly the whole correction captured, the amount taken is:|gap| × |fundingPerDay| × days open fundingPerDay = clamp((emas.ammPrice − emas.index) × fundingRateMultiplier, ± markPrice × maxFundingPerDayPercent)gapisbaseX96 + inventoryX96in perp atoms. It grows by up to about one atom per liquidity change or initialized tick crossed, and never clears. It can also be grown at another maker’s expense. Each partialPerpLiquidationLogic.liquidateMaker()call floors the perps returned, so a caller who slices a liquidatable maker into removals holding under one perp atom moves that amount from the maker into the gap on every call.The spread and the cap are both price amounts, so for the same percentage spread a higher-priced market yields a proportionally larger amount. A 150-atom gap at a price of 5,000 with funding at 2% per day for 30 days yields about 0.45 USDC.
The spread has no hard limit, but funding is capped at
maxFundingPerDayPercentof the mark, 5% in the deployment script. If arbitrage keeps the pool at the mark, the spread settles withinmaxPremiumRatio, 2% in the deployment script. Traders collecting funding should narrow it further, which shrinks the credit without turning it into a charge. That happens only if the spread turns positive, and the maker can observe the EMAs and close the range first.The linked PoC runs the production configuration at a price of 100,000 with the pool at the mark and a 0.5% spread. Over 30 days the out-of-range range collects 2.26 USDC, which is exactly what the in-range makers stop receiving.
A second PoC shows a worst case, on a market where the price is
MAX_INDEX_X96, valuing one perp atom at ~1 USDC. There, 1,000 liquidity resizes leave a gap of about 1,000 USDC notional, more than the market's own inventory. With funding held at the premium clamp for 440 days, the maker collects 8,005 USDC. The charged maker cannot be liquidated because its residual exceeds the available close depth, so the loss reaches other makers' collateral.Recommendation
TRUST_ASSUMPTIONS.mdalready states that the funding correction is socialized across makers. If this is accepted, consider adding that the share follows raw liquidity, so a range holding no perp inventory can collect most of it, and that the amount grows with the price per perp atom.
No findings match.
More from Perp City
Put your code through the same review.
This review started with a conversation about scope. Tell us what you are building and we will plan yours with you.
