Skip to content
We manage your security to weather the AI storm →

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
  • 0 Critical
  • 0 High
  • 0 Medium
  • 7 Low
  • 22 Informational

16 resolved · 13 acknowledged

Scope

  • GuardianOrg/mirror-strobelabs-perpcity-contracts 915821ace06e830949c5
26 files in scope · 2,903 nSLOC
FilenSLOCLines
src/AccountingToken.sol584
src/interfaces/IPerp.sol197294
src/interfaces/IWithdrawalController.sol1947
src/libraries/Constants.sol458
src/libraries/Errors.sol5367
src/libraries/PerpAmmLogic.sol302429
src/libraries/PerpFundingLogic.sol4076
src/libraries/PerpLiquidationLogic.sol245427
src/libraries/PerpLogic.sol468959
src/libraries/PerpMakerLogic.sol331413
src/libraries/PerpPreviewLogic.sol49102
src/libraries/PerpUtilizationLogic.sol202253
src/libraries/SafeBeaconIndex.sol1628
src/libraries/SignedFixedPointMathLib.sol1869
src/libraries/Structs.sol161447
src/ModuleRegistry.sol436
src/modules/Fees.sol48260
src/modules/Funding.sol2589
src/modules/MarginRatios.sol93191
src/modules/PriceImpact.sol772
src/modules/Pricing.sol2778
src/Perp.sol346713
src/PerpFactory.sol76171
src/PerpGuardHook.sol10102
src/ProtocolFeeManager.sol1346
src/WithdrawalController.sol144254

Findings 29

Main Review

26 findings · October 19 to November 2, 2026
  1. L-01 Low No in-place release path for excess insurance Suggestion Acknowledged
    Location
    src/libraries/PerpLogic.sol:1046
    Round
    Main Review

    Description

    The updated utilization accounting routes fees attributable to open interest above in-band maker closing capacity into a reserve. On taker settlement, PerpLogic.realizeReserve uses that amount to repay bad debt first and credits the remainder to feeFund.insurance. In the current implementation, accountBadDebt is 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.

  2. L-02 Low MakerMoved does not index posId Events Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/interfaces/IPerp.sol#L130-L132
    Round
    Main Review

    Description

    MakerMoved includes posId, but it is not marked indexed like other maker lifecycle events. An indexer cannot filter move logs for one position by topic and must fetch and decode all MakerMoved logs to find that position.

    Recommendation

    Be aware of and document this behavior or consider marking posId as indexed in MakerMoved.

  3. L-03 Low Maker liquidation lifecycle events report zero liquidity delta event-accounting Resolved
    Location
    packages/mirror-strobelabs-perpcity-contracts/src/libraries/PerpLiquidationLogic.sol:L119-L170
    Round
    Main Review

    Description

    PerpLiquidationLogic.liquidateMaker() emits MakerAdjusted, MakerConverted and MakerClosed with liquidityDelta = 0 despite 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.

  4. L-04 Low Phantom close reserve underpays terminal short liquidators logic-error Resolved
    Location
    packages/mirror-strobelabs-perpcity-contracts/src/libraries/PerpLiquidationLogic.sol:liquidateTaker:L299-L309
    Round
    Main Review

    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
                );
            }
    
  5. L-05 Low Deferred flip fee debit under-haircuts second-hop fee claims Business logic errors Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs/perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLogic.sol#L286-L310 https://github.com/GuardianOrg/mirror-strobelabs/perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpAmmLogic.sol#L175-L195
    Round
    Main Review

    Description

    PerpLogic.adjustTaker() executes a position flip by closing the existing side and opening the opposite side through two consecutive PerpAmmLogic.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 against badDebt and credits the surviving protocol, creator, and insurance fees to FeeFund.

    However, the first swap's feeFundFeeAmt remains included in totalMargin until both swaps are combined:

            int256 netMargin = preSettledMargin + p.marginDelta - sr.totalFeeAmt;
            removeSwapFeesFromMargin(s, sr);
    

    When badDebt remains after the first swap, the second swap calculates its fee haircut using an overstated totalMargin. It therefore applies a smaller haircut and credits excess fees to FeeFund. The later aggregate debit corrects totalMargin, but it does not correct the excess fee claim or the remaining badDebt.

    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 badDebt and reduce the backing available for later payouts.

    Recommendation

    Remove the first swap's feeFundFeeAmt from totalMargin before executing the second swap. After the second swap, remove only its newly created feeFundFeeAmt. Preserve the aggregate SwapResult fields used by the adjustment event and add a regression test against a per-hop accounting reference.

  6. L-06 Low Split maker liquidations can overpay rewards Gaming Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLiquidationLogic.sol#L53-L68 https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLogic.sol#L541-L559
    Round
    Main Review

    Description

    PerpLiquidationLogic.liquidateMaker() calculates the liquidation reward with PerpLogic.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:

    1. The maker is liquidatable while the mark and AMM prices remain unchanged
    2. Removing 2,612,000,000 liquidity in one call pays 13.590887 USDC
    3. The position is reset to the same starting snapshot
    4. Removing 2,369,000,000 and then 243,000,000 liquidity pays 14.423248 USDC
    5. Both calls remain liquidatable and pass healthImproved()
    6. Splitting the removal pays the liquidator an additional 0.832361 USDC, or approximately 6.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’s valAfter became the next chunk’s valBefore, 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 afterDelta is 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:

    1. 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.
    2. Calculate the reward from pos.delta + correction.
    3. Execute the removal and update both correction amounts by markDelta - actualDelta.
    4. Set the episode timestamp and mark only when starting a new episode. Do not roll either value after later chunks.
    5. Continue using the real pos.delta for settlement, health, funding, and PnL.
    6. 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.
    7. 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.
  7. L-07 Low Dynamic LP fee depends on swap partitioning Gaming Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpAmmLogic.sol#L288-L300
    Round
    Main Review

    Description

    _accrueSwapSegmentFees() obtains the LP fee from fees() 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 subsequent adjustTaker() 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 717 USDC atoms, while improving the taker’s net margin by 702 USDC 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 sqrtPrice interval 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.

  8. I-01 Informational Unused MoveMakerParams import remains in PerpLogic Superfluous Code Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLogic.sol#L32-L40
    Round
    Main Review

    Description

    PerpLogic imports MoveMakerParams, but never references the type. The move-maker entry point and parameter handling are implemented in Perp.sol and PerpMakerLogic.sol, so this import is stale.

    Recommendation

    Be aware and consider to remove unused code.

  9. I-02 Informational Negative settled cash blocks solvent zero-residual maker closes DoS Resolved
    Location
    src/libraries/PerpMakerLogic.sol:130
    Round
    Main Review

    Description

    When a maker owes accrued funding, adjustMaker deducts it from cash collateral: preSettledMargin = pos.margin + lpFees - funding (line 127). With marginDelta = 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 + marginDelta to uint256 before adding the removal delta to pos.delta at line 131 and before the zero-perp close branch at lines 230-249 adds amount1 to cash and pays out. Negative cash therefore reverts Overflow() 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.

  10. I-03 Informational MarginTransferred can be emitted without a USDC transfer Events Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLogic.sol#L1055-L1068
    Round
    Main Review

    Description

    transferMargin emits MarginTransferred even when marginDelta == 0. A successful adjustMaker or moveMaker call with zero margin delta reaches this path, so the event can appear without moving USDC or changing totalMargin. Log consumers should not treat the event alone as proof that funds moved.

    Recommendation

    Be aware of and document the zero-transfer case.

  11. I-04 Informational Redundant tick-change check before event emission Gas Optimization Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpAmmLogic.sol#L400
    Round
    Main Review

    Description

    _crossTicksAndAccrueSwapFees() returns early whenever snap.tick == endingTick. Therefore, execution reaching the TicksCrossed event is guaranteed to satisfy snap.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 TicksCrossed unconditionally after the traversal loop.

  12. I-05 Informational Extreme reduce-only deltas revert with an arithmetic panic Error Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/Perp.sol#L707
    Round
    Main Review

    Description

    adjustTaker calls _checkReduceOnly when reduceOnly is true. _checkReduceOnly adds the caller-supplied int256 delta to the existing int128 position balance before checking whether the request reduces exposure. For an existing long, delta = type(int256).max overflows that addition; for an existing short, delta = type(int256).min underflows it. Both revert with Solidity Panic(0x11) before Errors.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 delta lies in the reduction interval for the current position before adding it and reject with a custom error instead to follow best practices.

  13. I-06 Informational Widening the price-impact band can make later utilization accrual exceed transaction gas limits Informational Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpUtilizationLogic.sol#L81-L85
    Round
    Main Review

    Description

    setPriceImpactModule accrues 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.

  14. I-07 Informational Zero-liquidity maker adjustments perform an unnecessary Uniswap call Gas Optimization Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpMakerLogic.sol#L117
    Round
    Main Review

    Description

    adjustMaker() calls PerpAmmLogic.modifyLiquidity() even when p.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 and feeDelta are expected to remain zero, so the zero-liquidity call has no useful effect.

    Recommendation

    Skip PerpAmmLogic.modifyLiquidity() when p.liquidityDelta == 0 and use a zero Delta while continuing the protocol’s funding, fee, margin, checkpoint, and health accounting.

  15. I-08 Informational OpenInterestUpdated can be emitted without an open-interest change Events Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLogic.sol#L731-L737
    Round
    Main Review

    Description

    adjustTaker accepts perpDelta == 0 for a margin-only adjustment. The zero-swap path leaves the taker's perp balance unchanged, yet _applyTakerSwapState still rewrites the same open interest and emits OpenInterestUpdated. 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.

  16. I-09 Informational Market creation logs omit the initial governor Events Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/interfaces/IPerpFactory.sol#L27-L38
    Round
    Main Review

    Description

    createPerp takes an initial governor, and Perp.initialize stores it, but neither initialization nor PerpCreated emits 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 PerpCreated or emitting SetGovernor during initialization.

  17. I-10 Informational Utilization can be increased via matched positions Gaming Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLogic.sol#L449-L456
    Round
    Main Review

    Description

    PerpLogic.refreshRatesAndEmas() derives long and short utilization independently from gross oi.long and oi.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 physicalCap close to their original values through rotatePhysicalCapacity(). The matched positions nevertheless remain recorded as gross open interest. Consequently, subsequent calls to PerpLogic.accrue() charge higher utilization fees to all takers, while PerpUtilizationLogic.accrue() and split() 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.

  18. I-11 Informational PerpMakerLogic.moveMaker() allows positions below floor Documentation Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpMakerLogic.sol#L286
    Round
    Main Review

    Description

    PerpMakerLogic.moveMaker() permits a maker’s resulting settled margin to remain below MIN_OPENING_MARGIN whenever marginDelta >= 0. The resulting position must still satisfy the maker initial margin ratio because the function calls PerpLogic.checkActionHealth() with repairEligible set to false. This matches the conditional floor applied by PerpMakerLogic.adjustMaker() and PerpLogic.adjustTaker(). However, section 4.13 of TRUST_ASSUMPTIONS.md explicitly documents this behavior only for PerpMakerLogic.adjustMaker() and PerpLogic.adjustTaker(), omitting PerpMakerLogic.moveMaker().

    Recommendation

    Update section 4.13 of TRUST_ASSUMPTIONS.md to include PerpMakerLogic.moveMaker() and clarify that existing positions must retain MIN_OPENING_MARGIN only 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.

  19. I-12 Informational Overlapping liquidation constraints create a temporary taker no-action window Trust Assumptions Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLiquidationLogic.sol#L312-L315 https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLogic.sol#L329-L338 https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpAmmLogic.sol#L124-L127
    Round
    Main Review

    Description

    TRUST_ASSUMPTIONS.md separately accepts that partial taker liquidations can revert with NegativeMargin, full liquidations can revert with PriceImpactTooHigh, 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 settledMargin negative while favorable PnL keeps full equity positive. PerpLiquidationLogic.liquidateTaker() checks the cash-only netMargin before checking whether a partial liquidation improves health:

    require(netMargin >= 0, Errors.NegativeMargin());
    

    PerpLogic.adjustTaker() applies the same check before PerpLogic.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:

    1. Funding and utilization reduce settled cash to approximately -0.72 USDC
    2. Favorable PnL leaves approximately +2.92 USDC full equity on 40 USDC notional
    3. The position is below the liquidation ratio but above the backstop ratio
    4. Band-fillable partial liquidations and no-withdrawal holder reductions revert with NegativeMargin
    5. Full liquidation reverts with PriceImpactTooHigh
    6. Backstopping reverts with NotLiquidatable

    Recommendation

    TRUST_ASSUMPTIONS.md:134-163 describes 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.

  20. I-13 Informational reduceOnly documentation implies strict exposure reduction Documentation Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/Perp.sol#L705-L717
    Round
    Main Review

    Description

    Perp._checkReduceOnly() permits unchanged exposure when delta == 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 reduceOnly prevents increasing or flipping exposure but permits unchanged exposure and margin-only adjustments.

  21. I-14 Informational Missing taker position-state bounds let partial liquidation alter pending flips and backstop terms Frontrunning Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/Structs.sol#L414-L421 https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/Perp.sol#L423-L430 https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/Perp.sol#L448-L455 https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLiquidationLogic.sol#L375-L392
    Round
    Main Review

    Description

    Perp.adjustTaker() applies AdjustTakerParams.perpDelta to the position’s live exposure. amt1Limit, maxTotalFee, and deadline limit execution price, fees, and time, but do not limit the starting or resulting exposure.

    A previous remediation added reduceOnly. This protects reductions and closes because Perp._checkReduceOnly() reverts if the transaction crosses zero. It does not protect an intentional flip because every flip must set reduceOnly to false.

    A permissionless PerpLiquidationLogic.liquidateTaker() call can therefore reduce the position before a pending flip executes. The unchanged perpDelta closes the smaller remaining position and opens a larger opposite position than the holder intended.

    Example:

    1. A holder has a 5,000,000 atom long and submits perpDelta = -5,000,001 to open a one-atom short
    2. Without a liquidation, the position ends at -1
    3. A liquidator first closes 1,000,000 atoms
    4. The same pending perpDelta now leaves a -1,000,001 atom short
    5. After the index moves from $46 to $50, the intended one-atom short remains healthy and realizes 8.455040 USDC
    6. The enlarged short becomes liquidatable and returns only 2.957831 USDC to the holder

    Perp.backstopTaker() has the same missing state commitment. A backstopper commits to a fixed marginIn, 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 original marginIn still 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 AdjustTakerParams and reject the transaction if the position changed before execution. Keep reduceOnly for reductions and closes.

    Acknowledge the Perp.backstopTaker() case the same way the backstopMaker one was.

  22. I-15 Informational Partial liquidation leaves unfillable short dust DoS Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-GuardianOrg-mirror-strobelabs-perpcity-contracts-1cac74c3f2a1eb19d711e47b0d68638f/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLiquidationLogic.sol#L279-L328 https://github.com/GuardianOrg/mirror-GuardianOrg-mirror-strobelabs-perpcity-contracts-1cac74c3f2a1eb19d711e47b0d68638f/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpAmmLogic.sol#L102-L138
    Round
    Main Review

    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.md also 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 perpAmount in PerpLiquidationLogic.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 NotLiquidatable because the residue is healthy.
    • The owner’s close through Perp.adjustTaker() reverts with InsufficientLiquidityToFill because 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.

  23. I-16 Informational Relaxed convergence paths can exceed the transaction gas limit denial-of-service Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpAmmLogic.sol#L86-L130
    Round
    Main Review

    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 normal sqrtMin and sqrtMax bounds and then relaxes whichever bound excludes the pre-swap snap.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 through PerpLogic.openTaker(), increases, reductions, closes, and flips through PerpLogic.adjustTaker(), and liquidations through PerpLiquidationLogic.liquidateTaker(). These paths execute the V4 swap and replay the crossed ticks for protocol accounting. A terminal short liquidation additionally scans the path through PerpAmmLogic._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.md to document that convergence relaxation can make PerpAmmLogic.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.

  24. I-17 Informational Principal rounding can make mark health overstate immediate closeability Informational Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLogic.sol#L238-L265
    Round
    Main Review

    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 from PerpLogic.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.md that 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.

  25. I-18 Informational Healthy maker liquidation attempts modify liquidity before reverting Gas Optimization Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpLiquidationLogic.sol#L65-L104
    Round
    Main Review

    Description

    PerpLiquidationLogic.liquidateMaker() calls PerpAmmLogic.modifyLiquidity() and updates accounting before checking eligibility through PerpLogic.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 with PerpLiquidationLogic.liquidateTaker().

  26. I-19 Informational Full maker exits use a redundant refresh flag Best Practices Resolved
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/libraries/PerpMakerLogic.sol#L193-L235 https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/915821ace0cd08841c207a5055aba7a59064cd3c/src/Perp.sol#L366-L371
    Round
    Main Review

    Description

    The zero-liquidity branch in PerpMakerLogic.adjustMaker() calls the six-parameter refreshRatesAndEmas() overload with p.liquidityDelta != 0 as poolMutated. Because Perp.adjustMaker() requires existing maker liquidity to be nonzero, reaching this branch means p.liquidityDelta necessarily removed all liquidity and modified the pool. The expression is therefore always true and obscures this invariant.

    Recommendation

    Continue using the six-parameter refreshRatesAndEmas() overload, but pass true directly for poolMutated. This preserves snap.markPrice, avoids an additional pricing-module call, and makes the full-removal invariant explicit.

Remediation Review

3 findings · November 7 to 9, 2026
  1. I-01 Informational Taker flips settle swap fees per leg but utilization reserve per action Unexpected Behavior Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/6e830949c5e3c0fc417cd1f9a2ab56ace4df8a8e/src/libraries/PerpLogic.sol#L136-L162
    Round
    Remediation Review

    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 calling PerpLogic.removeSwapFeesFromMargin() after each PerpAmmLogic.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.

  2. I-02 Informational Atomic taker flips retain equity outside the withdrawal-controller path Documentation Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/6e830949c5e3c0fc417cd1f9a2ab56ace4df8a8e/src/libraries/PerpLogic.sol#L136-L147 https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/6e830949c5e3c0fc417cd1f9a2ab56ace4df8a8e/src/libraries/PerpLogic.sol#L219-L221
    Round
    Remediation Review

    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-29 behavior. 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.

  3. I-03 Informational Funding correction is split by raw liquidity Accounting Acknowledged
    Location
    https://github.com/GuardianOrg/mirror-strobelabs-perpcity-contracts/blob/6e830949c5e3c0fc417cd1f9a2ab56ace4df8a8e/src/libraries/PerpFundingLogic.sol#L108-L109
    Round
    Remediation Review

    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. Near MIN_TICK such liquidity is almost free, so a maker posting MIN_OPENING_MARGIN can 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.ammPrice is below emas.index. With nearly the whole correction captured, the amount taken is:

    |gap| × |fundingPerDay| × days open
    fundingPerDay = clamp((emas.ammPrice − emas.index) × fundingRateMultiplier, ± markPrice × maxFundingPerDayPercent)
    

    gap is baseX96 + inventoryX96 in 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 partial PerpLiquidationLogic.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 maxFundingPerDayPercent of the mark, 5% in the deployment script. If arbitrage keeps the pool at the mark, the spread settles within maxPremiumRatio, 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.md already 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.

More from Perp City

  1. Protocol Review

    202 findings4 critical · 32 high 202 findings: 4 critical, 32 high, 55 medium, 49 low, 62 informational

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.

Get a quote