Security review · June 2026
V2 for GMX
Guardian's review of V2 for GMX, published June 2026. The report records 121 findings across 4 review rounds, including 2 critical and 15 high.
See how Guardian runs a perp DEX smart contract audit.
- Published
- Review window
- January 19 to June 12, 2026
- Rounds
- Main Review, Remediation Review 1, Remediation Review 2, Remediation Review 3
- Language
- Solidity
- Sector
- Perpetuals
- 2 Critical
- 15 High
- 52 Medium
- 30 Low
- 22 Informational
Scope
- gmx-io/gmx-synthetics 256a058fa9
-
gmx-io/gmx-synthetics-private
9ece3c109eb34275f43fa8d8375cd5fd095157ac -
GuardianOrg/gmx-functions-team1-1769575982199
007d7b8e93 -
GuardianOrg/gmx-synthetics-keeper-team1-1768892132004
02688b85e6
236 files in scope · 27,805 nSLOC
| File | nSLOC | Lines |
|---|---|---|
contracts/adl/AdlUtils.sol | 136 | 292 |
contracts/bank/Bank.sol | 53 | 105 |
contracts/bank/StrictBank.sol | 26 | 65 |
contracts/callback/CallbackUtils.sol | 246 | 379 |
contracts/callback/IDepositCallbackReceiver.sol | 4 | 14 |
contracts/callback/IGasFeeCallbackReceiver.sol | 4 | 8 |
contracts/callback/IGlvDepositCallbackReceiver.sol | 4 | 13 |
contracts/callback/IGlvWithdrawalCallbackReceiver.sol | 4 | 14 |
contracts/callback/IOrderCallbackReceiver.sol | 5 | 14 |
contracts/callback/IShiftCallbackReceiver.sol | 4 | 8 |
contracts/callback/IWithdrawalCallbackReceiver.sol | 4 | 13 |
contracts/chain/ArbGasInfo.sol | 3 | 7 |
contracts/chain/ArbSys.sol | 3 | 9 |
contracts/chain/Chain.sol | 33 | 56 |
contracts/chain/ChainReader.sol | 36 | 50 |
contracts/claim/ClaimEventUtils.sol | 73 | 141 |
contracts/claim/ClaimHandler.sol | 232 | 325 |
contracts/claim/ClaimUtils.sol | 66 | 85 |
contracts/claim/ClaimVault.sol | 5 | 11 |
contracts/config/AutoCancelSyncer.sol | 61 | 76 |
contracts/config/Config.sol | 468 | 622 |
contracts/config/ConfigSyncer.sol | 118 | 172 |
contracts/config/ConfigTimelockController.sol | 61 | 77 |
contracts/config/ConfigUtils.sol | 325 | 420 |
contracts/config/IRiskOracle.sol | 13 | 17 |
contracts/config/TimelockConfig.sol | 428 | 544 |
contracts/data/DataStore.sol | 237 | 513 |
contracts/data/Keys.sol | 1468 | 2409 |
contracts/data/Keys2.sol | 75 | 167 |
contracts/deposit/Deposit.sol | 145 | 210 |
contracts/deposit/DepositEventUtils.sol | 90 | 116 |
contracts/deposit/DepositStoreUtils.sol | 247 | 325 |
contracts/deposit/DepositUtils.sol | 170 | 224 |
contracts/deposit/DepositVault.sol | 5 | 11 |
contracts/deposit/ExecuteDepositUtils.sol | 412 | 584 |
contracts/deposit/IDepositUtils.sol | 21 | 38 |
contracts/deposit/IExecuteDepositUtils.sol | 25 | 31 |
contracts/error/Errors.sol | 391 | 545 |
contracts/error/ErrorUtils.sol | 37 | 56 |
contracts/event/EventEmitter.sol | 79 | 130 |
contracts/event/EventUtils.sol | 423 | 507 |
contracts/exchange/AdlHandler.sol | 101 | 145 |
contracts/exchange/BaseHandler.sol | 50 | 59 |
contracts/exchange/BaseOrderHandler.sol | 57 | 77 |
contracts/exchange/DepositHandler.sol | 133 | 195 |
contracts/exchange/GlvDepositHandler.sol | 111 | 143 |
contracts/exchange/GlvShiftHandler.sol | 88 | 116 |
contracts/exchange/GlvWithdrawalHandler.sol | 116 | 148 |
contracts/exchange/IDepositHandler.sol | 7 | 12 |
contracts/exchange/IGlvDepositHandler.sol | 5 | 9 |
contracts/exchange/IGlvWithdrawalHandler.sol | 5 | 9 |
contracts/exchange/IJitOrderHandler.sol | 6 | 10 |
contracts/exchange/IOrderExecutor.sol | 4 | 8 |
contracts/exchange/IOrderHandler.sol | 5 | 9 |
contracts/exchange/IShiftHandler.sol | 6 | 10 |
contracts/exchange/IWithdrawalHandler.sol | 8 | 12 |
contracts/exchange/JitOrderHandler.sol | 107 | 133 |
contracts/exchange/LiquidationHandler.sol | 54 | 75 |
contracts/exchange/OrderHandler.sol | 243 | 394 |
contracts/exchange/ShiftHandler.sol | 132 | 164 |
contracts/exchange/WithdrawalHandler.sol | 166 | 229 |
contracts/external/ExternalHandler.sol | 41 | 68 |
contracts/external/IExternalHandler.sol | 3 | 6 |
contracts/feature/FeatureUtils.sol | 12 | 32 |
contracts/fee/FeeBatch.sol | 9 | 14 |
contracts/fee/FeeBatchStoreUtils.sol | 79 | 108 |
contracts/fee/FeeDistributor.sol | 545 | 728 |
contracts/fee/FeeDistributorUtils.sol | 100 | 124 |
contracts/fee/FeeDistributorVault.sol | 11 | 24 |
contracts/fee/FeeHandler.sol | 201 | 273 |
contracts/fee/FeeSwapUtils.sol | 95 | 119 |
contracts/fee/FeeUtils.sol | 204 | 277 |
contracts/gas/GasUtils.sol | 347 | 601 |
contracts/glv/Glv.sol | 8 | 10 |
contracts/glv/glvDeposit/ExecuteGlvDepositUtils.sol | 202 | 237 |
contracts/glv/glvDeposit/GlvDeposit.sol | 161 | 235 |
contracts/glv/glvDeposit/GlvDepositCalc.sol | 44 | 58 |
contracts/glv/glvDeposit/GlvDepositEventUtils.sol | 88 | 113 |
contracts/glv/glvDeposit/GlvDepositStoreUtils.sol | 280 | 368 |
contracts/glv/glvDeposit/GlvDepositUtils.sol | 246 | 286 |
contracts/glv/glvDeposit/IGlvDepositUtils.sol | 23 | 27 |
contracts/glv/GlvEventUtils.sol | 36 | 52 |
contracts/glv/GlvFactory.sol | 50 | 71 |
contracts/glv/glvShift/GlvShift.sol | 53 | 70 |
contracts/glv/glvShift/GlvShiftEventUtils.sol | 46 | 66 |
contracts/glv/glvShift/GlvShiftStoreUtils.sol | 101 | 133 |
contracts/glv/glvShift/GlvShiftUtils.sol | 220 | 266 |
contracts/glv/GlvStoreUtils.sol | 80 | 109 |
contracts/glv/GlvToken.sol | 17 | 23 |
contracts/glv/GlvUtils.sol | 226 | 290 |
contracts/glv/GlvVault.sol | 5 | 9 |
contracts/glv/glvWithdrawal/GlvWithdrawal.sol | 133 | 197 |
contracts/glv/glvWithdrawal/GlvWithdrawalEventUtils.sol | 67 | 92 |
contracts/glv/glvWithdrawal/GlvWithdrawalStoreUtils.sol | 236 | 311 |
contracts/glv/glvWithdrawal/GlvWithdrawalUtils.sol | 314 | 371 |
contracts/glv/glvWithdrawal/IGlvWithdrawalUtils.sol | 21 | 25 |
contracts/gov/GovTimelockController.sol | 17 | 23 |
contracts/gov/GovToken.sol | 50 | 79 |
contracts/gov/ProtocolGovernor.sol | 70 | 92 |
contracts/liquidation/LiquidationUtils.sol | 60 | 100 |
contracts/market/Market.sol | 9 | 43 |
contracts/market/MarketEventUtils.sol | 430 | 569 |
contracts/market/MarketFactory.sol | 65 | 92 |
contracts/market/MarketPoolValueInfo.sol | 17 | 37 |
contracts/market/MarketStoreUtils.sol | 95 | 131 |
contracts/market/MarketToken.sol | 13 | 28 |
contracts/market/MarketUtils.sol | 1729 | 2942 |
contracts/market/PositionImpactPoolUtils.sol | 155 | 205 |
contracts/multichain/BridgeOutFromControllerUtils.sol | 185 | 218 |
contracts/multichain/IMultichainGlvRouter.sol | 6 | 10 |
contracts/multichain/IMultichainGmRouter.sol | 7 | 11 |
contracts/multichain/IMultichainOrderRouter.sol | 4 | 8 |
contracts/multichain/IMultichainProvider.sol | 14 | 22 |
contracts/multichain/IMultichainTransferRouter.sol | 4 | 8 |
contracts/multichain/IOriginator.sol | 4 | 7 |
contracts/multichain/LayerZeroProvider.sol | 369 | 538 |
contracts/multichain/MultichainClaimsRouter.sol | 77 | 102 |
contracts/multichain/MultichainEventUtils.sol | 75 | 115 |
contracts/multichain/MultichainGlvRouter.sol | 41 | 57 |
contracts/multichain/MultichainGmRouter.sol | 61 | 82 |
contracts/multichain/MultichainOrderRouter.sol | 58 | 78 |
contracts/multichain/MultichainReader.sol | 189 | 238 |
contracts/multichain/MultichainReaderUtils.sol | 17 | 21 |
contracts/multichain/MultichainRouter.sol | 74 | 88 |
contracts/multichain/MultichainSubaccountRouter.sol | 95 | 126 |
contracts/multichain/MultichainTransferRouter.sol | 107 | 149 |
contracts/multichain/MultichainUtils.sol | 66 | 112 |
contracts/multichain/MultichainVault.sol | 5 | 13 |
contracts/nonce/NonceUtils.sol | 24 | 48 |
contracts/oracle/ChainlinkDataStreamProvider.sol | 104 | 136 |
contracts/oracle/ChainlinkPriceFeedProvider.sol | 43 | 65 |
contracts/oracle/ChainlinkPriceFeedUtils.sol | 39 | 71 |
contracts/oracle/EdgeDataStreamProvider.sol | 64 | 87 |
contracts/oracle/EdgeDataStreamVerifier.sol | 89 | 126 |
contracts/oracle/GmOracleProvider.sol | 115 | 244 |
contracts/oracle/GmOracleUtils.sol | 37 | 55 |
contracts/oracle/IChainlinkDataStreamVerifier.sol | 3 | 14 |
contracts/oracle/IOracle.sol | 6 | 10 |
contracts/oracle/IOracleProvider.sol | 4 | 10 |
contracts/oracle/IPriceFeed.sol | 3 | 8 |
contracts/oracle/Oracle.sol | 251 | 370 |
contracts/oracle/OracleModule.sol | 37 | 71 |
contracts/oracle/OracleStore.sol | 52 | 84 |
contracts/oracle/OracleUtils.sol | 48 | 65 |
contracts/order/AutoCancelUtils.sol | 27 | 35 |
contracts/order/BaseOrderUtils.sol | 148 | 376 |
contracts/order/DecreaseOrderExecutor.sol | 10 | 16 |
contracts/order/DecreaseOrderUtils.sol | 270 | 337 |
contracts/order/ExecuteOrderUtils.sol | 96 | 136 |
contracts/order/IBaseOrderUtils.sol | 34 | 60 |
contracts/order/IncreaseOrderExecutor.sol | 10 | 16 |
contracts/order/IncreaseOrderUtils.sol | 79 | 100 |
contracts/order/Order.sol | 251 | 515 |
contracts/order/OrderEventUtils.sol | 171 | 222 |
contracts/order/OrderStoreUtils.sol | 324 | 423 |
contracts/order/OrderUtils.sol | 344 | 445 |
contracts/order/OrderVault.sol | 5 | 11 |
contracts/order/SwapOrderExecutor.sol | 10 | 16 |
contracts/order/SwapOrderUtils.sol | 77 | 94 |
contracts/position/DecreasePositionCollateralUtils.sol | 546 | 734 |
contracts/position/DecreasePositionSwapUtils.sol | 74 | 87 |
contracts/position/DecreasePositionUtils.sol | 249 | 371 |
contracts/position/IncreasePositionUtils.sol | 234 | 314 |
contracts/position/Position.sol | 116 | 206 |
contracts/position/PositionEventUtils.sol | 241 | 287 |
contracts/position/PositionStoreUtils.sol | 203 | 268 |
contracts/position/PositionUtils.sol | 474 | 746 |
contracts/price/Price.sol | 22 | 52 |
contracts/pricing/ISwapPricingUtils.sol | 11 | 14 |
contracts/pricing/PositionPricingUtils.sol | 394 | 620 |
contracts/pricing/PricingUtils.sol | 25 | 96 |
contracts/pricing/SwapPricingUtils.sol | 222 | 359 |
contracts/reader/GlvReader.sol | 144 | 174 |
contracts/reader/KeeperReader.sol | 18 | 40 |
contracts/reader/Reader.sol | 191 | 233 |
contracts/reader/ReaderDepositUtils.sol | 157 | 187 |
contracts/reader/ReaderPositionUtils.sol | 193 | 248 |
contracts/reader/ReaderPricingUtils.sol | 207 | 279 |
contracts/reader/ReaderUtils.sol | 183 | 232 |
contracts/reader/ReaderWithdrawalUtils.sol | 77 | 104 |
contracts/referral/IGov.sol | 3 | 8 |
contracts/referral/IReferralStorage.sol | 3 | 11 |
contracts/referral/ITimelock.sol | 3 | 8 |
contracts/referral/ReferralEventUtils.sol | 46 | 58 |
contracts/referral/ReferralTier.sol | 7 | 14 |
contracts/referral/ReferralUtils.sol | 102 | 159 |
contracts/role/Role.sol | 23 | 124 |
contracts/role/RoleModule.sol | 97 | 197 |
contracts/role/RoleStore.sol | 61 | 130 |
contracts/router/BaseRouter.sol | 39 | 53 |
contracts/router/ExchangeRouter.sol | 223 | 377 |
contracts/router/GlvRouter.sol | 84 | 118 |
contracts/router/IExchangeRouter.sol | 8 | 12 |
contracts/router/relay/BaseGelatoRelayRouter.sol | 291 | 410 |
contracts/router/relay/GelatoRelayRouter.sol | 62 | 78 |
contracts/router/relay/IRelayUtils.sol | 65 | 116 |
contracts/router/relay/RelayUtils.sol | 679 | 775 |
contracts/router/relay/SubaccountGelatoRelayRouter.sol | 99 | 124 |
contracts/router/relay/SubaccountRouterUtils.sol | 50 | 66 |
contracts/router/Router.sol | 11 | 29 |
contracts/router/SubaccountRouter.sol | 195 | 248 |
contracts/safe/SafeUtils.sol | 9 | 19 |
contracts/shift/IShiftUtils.sol | 17 | 21 |
contracts/shift/Shift.sol | 102 | 133 |
contracts/shift/ShiftEventUtils.sol | 78 | 102 |
contracts/shift/ShiftStoreUtils.sol | 192 | 250 |
contracts/shift/ShiftUtils.sol | 300 | 394 |
contracts/shift/ShiftVault.sol | 5 | 9 |
contracts/subaccount/SubaccountUtils.sol | 195 | 251 |
contracts/swap/ISwapHandler.sol | 4 | 8 |
contracts/swap/ISwapUtils.sol | 25 | 45 |
contracts/swap/SwapHandler.sol | 11 | 26 |
contracts/swap/SwapUtils.sol | 277 | 398 |
contracts/token/IWNT.sol | 3 | 12 |
contracts/token/TokenUtils.sol | 122 | 234 |
contracts/utils/AccountUtils.sol | 17 | 24 |
contracts/utils/Array.sol | 76 | 172 |
contracts/utils/BasicMulticall.sol | 15 | 29 |
contracts/utils/Bits.sol | 7 | 19 |
contracts/utils/Calc.sol | 70 | 173 |
contracts/utils/Cast.sol | 41 | 72 |
contracts/utils/EnumerableValues.sol | 37 | 85 |
contracts/utils/GlobalReentrancyGuard.sol | 24 | 40 |
contracts/utils/PayableMulticall.sol | 15 | 33 |
contracts/utils/Precision.sol | 84 | 156 |
contracts/utils/Printer.sol | 24 | 34 |
contracts/utils/StringUtils.sol | 6 | 9 |
contracts/utils/Uint256Mask.sol | 17 | 25 |
contracts/withdrawal/ExecuteWithdrawalUtils.sol | 375 | 480 |
contracts/withdrawal/IExecuteWithdrawalUtils.sol | 30 | 36 |
contracts/withdrawal/IWithdrawalUtils.sol | 20 | 28 |
contracts/withdrawal/Withdrawal.sol | 131 | 195 |
contracts/withdrawal/WithdrawalEventUtils.sol | 85 | 111 |
contracts/withdrawal/WithdrawalStoreUtils.sol | 225 | 297 |
contracts/withdrawal/WithdrawalUtils.sol | 138 | 198 |
contracts/withdrawal/WithdrawalVault.sol | 5 | 11 |
Findings 121
Main Review
98 findings · January 19 to June 12, 2026-
C-01 Critical Reserve check dangerously blocks decrease flows Logical Error Pending
Description
When
sizeDeltaUsd < 0,PositionUtils.updateOpenInterestperforms an additional absolute backing check:if (sizeDeltaUsd < 0) { uint256 poolUsd = MarketUtils.getPoolUsdWithoutPnl(...); uint256 reservedUsd = MarketUtils.getReservedUsd(...); if (reservedUsd > poolUsd) { revert Errors.InsufficientReserve(reservedUsd, poolUsd); } }This check is much stricter than the configured reserve-factor gates used elsewhere in the system. In all markets checked,
reserveFactorandopenInterestReserveFactorare greater than 100%. That means the protocol explicitly allows positions to be opened whilereservedUsdis well abovepoolUsd, as long asreservedUsdremains below the configured reserve-factor ceilings. However, once a user later tries to reduce position size, the transaction must satisfy the stricterreservedUsd <= poolUsdrule. This is a direct inconsistency: the protocol accepts one reserve invariant on entry, then enforces a different and stricter invariant on exit. Example scenario:poolUsd = \$100mreserveFactor = 200%, sovalidateReserveallows up to\$200m- a user opens or increases positions while market-wide
reservedUsd = \$150m - this state is valid for entry, because
\$150m <= \$200mNow a user later attempts a routine partial close. Assume the decrease lowers market-widereservedUsdfrom\$150mto\$149m. This reverts because\$149m > \$100m, so the additional absolutereservedUsd > poolUsdcheck fails As a result, the protocol admits exposure into a state that it later refuses to let users manage through normal decrease flows unless the same transaction restores the market all the way back toreservedUsd <= poolUsd. So, wheneverreserveUsd > poolUsd, an acceptable state for markets: - Users are blocked from routine decrease flows
- Liquidations and ADLs are also blocked
Recommendation
Consider removing this newly introduced check entirely.
-
C-02 Critical factory.call() enables unauthorized transfers Signatures Pending
Description
SignatureUtils.validateSignature()supports EIP-6492 by executing attacker-controlled calldata during signature validation in SignatureUtils.sol:154 and SignatureUtils.sol:167. This path is reachable from relay authorization in BaseGelatoRelayRouter.sol:391. The call is executed by the relay router itself, and the relay routers are grantedROUTER_PLUGINandCONTROLLERprivileges in deployGelatoRelayRouter.ts:23, deploySubaccountGelatoRelayRouter.ts:30, and roles.ts:62. As a result, an attacker can supply factory and factoryCalldata that invoke privileged protocol functions during signature validation, before authentication is completed. Root Cause For EIP-6492 signatures,_validateEIP6492Signature()decodes(factory, factoryCalldata, originalSignature)and performs:(bool success, ) = factory.call(factoryCalldata);for undeployed-wallet deployment and again for the deployed-wallet retry path. There is no restriction that:- factory is an approved deployment factory
- factoryCalldata is a deployment call
- the call is side-effect-free
- the call cannot target privileged protocol contracts
This is unsafe because the caller of
factory.call(...)is the relay router, not the user. Impact An attacker can execute arbitrary privileged actions as the relay router during signature validation. The most direct consequence is unauthorized token theft from arbitrary users who previously approved Router, because Router.pluginTransfer:26 is restricted only by ROUTER_PLUGIN, and the relay routers have that role. This turns signature validation into a privilege-escalation primitive. Why Validation Success Does Not Make This Safe A valid signature only proves the attacker controls the expectedSigner. It does not justify executing arbitrary side effects from a privileged protocol contract during the validation process.
Recommendation
Do not allow arbitrary calls during signature validation.
-
H-01 High GraphQL Injection In /Performance/Annualized Validation Pending
Description
User‑controlled
addressparam is interpolated directly into a GraphQL query without validation or escaping. This happens inperformance.ts(readsreq.query.address) andsubsquidService.ts(builds the query string ingetAnnualizedPerformance/getPerformanceSnapshots). Basic example curl to break the query:curl "https://arbitrum-api.gmxinfra.io/performance/annualized?period=90d&address=%22%7D%20bad%20%7B%20" That payload injects a " and } to break the query syntax.This could be used to cause a DoS or depending on the exact information kept in the GraphQL, be used to read sensitive information or even modify information.
Recommendation
Validate and normalize
addressbefore it ever reaches the GraphQL query builder (e.g., require a 0x‑prefixed 40‑hex string and useethers.utils.getAddress), and reject anything that isn’t a valid address. Then stop interpolating raw strings into GraphQL; instead, use GraphQL variables or a safe query builder to avoid injection entirely. This also prevents cache‑key abuse with arbitrary strings and reduces backend load from malformed requests. -
H-02 High Keeper May Miss Liquidations On Losing Trades Logical Error Pending
Description
Liquidation keeper uses uses
usdDelta = -sizeInTokens * midPriceinstead ofsizeInUSDfor calculating price impact. When current mark price deviates from entry price which is extremely likely for any trade, these diverge and change the negative price‑impact deduction in remaining collateral. Assume sizeInUsd = entryPrice * sizeInTokens. Let P = midPrice.- Long, price down (P < entryPrice)
sizeInTokens*P < sizeInUsdKeeper computes a smaller negative price impact. Remaining collateral looks higher than on‑chain. Impact: keeper can skip liquidation even though the contract would liquidate. (False negative) - Long, price up (P > entryPrice)
sizeInTokens*P > sizeInUsdKeeper computes a larger negative price impact. Remaining collateral looks lower than on‑chain. Impact: keeper may attempt liquidation that the contract will reject. (False positive; blocked by on‑chain pre‑check) - Short, price down (P < entryPrice)
sizeInTokens*P < sizeInUsdShort PnL is positive; contract impact still based on sizeInUsd. Keeper’s mid‑price sizing makes negative impact smaller. Remaining collateral looks higher than on‑chain. Impact: keeper can skip liquidation when it should execute. (False negative) - Short, price up (P > entryPrice)
sizeInTokens*P > sizeInUsdKeeper computes larger negative impact. Remaining collateral looks lower than on‑chain. Impact: keeper may attempt liquidation that is rejected on‑chain. (False positive)Net effect:Down‑moves for longs and shorts (cases 1 & 3) create the highest risk: missed liquidations. Up‑moves (cases 2 & 4) cause extra attempts, but on‑chain checks prevent wrong liquidations.
Recommendation
Consider using
position.sizeInUsdfor price impact calculations - Long, price down (P < entryPrice)
-
H-03 High Rebalancing Via Pool Value Cap Is Broken Logical Error Pending
Description
In
getPairsByCaps, the code usessub(-1)instead ofmul(-1)when converting negative remaining values to positive for pool value cap checks. This completely disables pool value cap enforcement in the GLV rebalancer. The pool value caps incorrectly usesub(-1):if (cap.remainingLongUsd.sub(-1).gt(minShiftUsd)) { recordExceedingCap({ ... }); } maxExceedingUsd = getMax(maxExceedingUsd, cap.remainingLongUsd.sub(-1), cap.remainingShortUsd.sub(-1));In contrast, the token balance caps correctly use
mul(-1):if (cap.remainingUsd.mul(-1).gt(minShiftUsd)) { recordExceedingCap({ ... }); } maxExceedingUsd = getMax(maxExceedingUsd, cap.remainingUsd.mul(-1));The difference:
mul(-1)negates the value (converting-5000to5000), whilesub(-1)adds one (converting-5000to-4999). Since the result stays negative, thegt(minShiftUsd)check always fails andgetMaxreturns 0, causing the market to be skipped entirely. Pool value caps are a risk management mechanism to limit exposure to individual markets. Without proper rebalancing, GLV could become overexposed to a single market causing LPs concentrated losses during market volatility.Recommendation
Replace
sub(-1)withmul(-1)in the pool value caps block:if (cap.remainingLongUsd.mul(-1).gt(minShiftUsd)) { ... } if (cap.remainingShortUsd.mul(-1).gt(minShiftUsd)) { ... } maxExceedingUsd = getMax(maxExceedingUsd, cap.remainingLongUsd.mul(-1), cap.remainingShortUsd.mul(-1)); -
H-04 High Unbounded Metrics Cardinality To DoS DoS Pending
Description
Even if the variable
TIMING_SAMPLE_SIZEis correctly limiting the number of objects inside each key inside_storage.timings,_storage.countersand_storage.gauges. The code is not limiting the number of keys inside_storage.timings,_storage.countersand_storage.gauges. An attacker could send different metric events names that will generate different arrays under the temporary log storage in memory that could be abused to cause a DoS of the server by sending hundreds of thousands of events and to increase telemetry backend costs (datadog). Note that this could also be accidentally abused if a big amount of users use the platform at the same time. Step-by-step code explanation:- Public ingestion endpoint accepts user fields
/ui/batch_report(also/report/ui/batch_report) allows clients to submititemswith user-controlledevent,customFields, andabFlags.Location:src/routes/ui.ts - UI service turns those fields into metric name + tags
logCounter/logTimingbuild the metric name fromeventin the codemetrics.timing(uiReport.\${event}, time, tags);(note how\${event}is a string part of the json body sent by the user) and includecustomFields/abFlagsinsidetags.Location:src/domain/ui/uiService.ts - Metric key is derived from full tag objectThe metrics store computes a key as
\${name}:\${_valueToConsistentKey(tags)}, and_valueToConsistentKeyJSON-stringifies the full nested object. Note how the name and the tags contains custom values from the user Location:src/lib/metrics/metrics.ts - Metrics are kept in memory until periodic flushThe metrics store keeps entries in
_storageand only flushes every 10 minutes.Location:src/lib/metrics/metrics.tsScale example: With/ui/batch_reportat 60 requests/minute and 300kb max per request, a single user can send ~18 MB/minute of telemetry payload. Over 10 minutes (the default flush interval), that is ~180 MB of incoming data and up to 60,000 items (if 100 items per request). If 1,000 users (or an attacker mimicking 1,000 users) do this concurrently, the service could ingest ~180 GB of telemetry payloads per 10 minutes and create up to ~60 million unique metric keys, far exceeding memory/CPU budgets due to unbounded cardinality.
Recommendation
It's recommended to create an allow-list of possible
eventnames,customFieldsnames andabFlagsnames in tags with the goal of ensuring that the number of keys inside the objects_storage.timings,_storage.countersand_storage.gaugesare limited. As extra check, apart from the allow-lists, it would be recommended to also limit the total number of keys inside_storage.timings,_storage.countersand_storage.gaugesto ensure that possible issues like this one are not repeated. - Public ingestion endpoint accepts user fields
-
H-05 High Keeper uses position price impact without pending impact, causing ADL and frozen limit/stop order misclassification Logical Error Pending
Description
The keeper’s generic price impact helper,
getPositionPriceImpactUsd(), does not includeposition.pendingImpactAmountin its calculation. However, the liquidation-specific helpers do include pending impact, and the contract-side logic also accounts for it. This creates a keeper/onchain mismatch for flows that rely on the generic helper. In particular:- ADL sizing uses
getPositionPriceImpactUsd()throughgetSizeDeltaForAdl(), so the keeper can estimate the wrong post-ADL market state and choose an incorrectsizeDeltaUsd. - Frozen limit/stop order validation uses
getPositionPriceImpactUsd()throughvalidateExecutionPrice(), so the keeper can incorrectly decide an order is executable when onchain execution would fail, or skip an order that is actually executable. Because pending impact is part of the real effective price impact onchain, omitting it can lead to delayed execution, false negatives, and avoidable reverted transactions.
Recommendation
Consider updating
getPositionPriceImpactUsd()to incorporate position.pendingImpactAmount using the same pricing direction logic already used in the liquidation helpers / contract logic. - ADL sizing uses
-
H-06 High depositReferralRewards Call Would Always Revert Rounding Pending
Description
In distribute(), the on-chain contract computes a single aggregate WNT amount and stores it:
// FeeDistributor.sol line 679-680 uint256 scaledWntPrice = _getUint(Keys2.FEE_DISTRIBUTOR_WNT_PRICE) * Precision.FLOAT_PRECISION; uint256 wntForReferralRewards = Precision.toFactor(wntReferralRewardsInUsd, scaledWntPrice); This is effectively floor(totalRebateUsd / wntPrice) — one division on the aggregate.In the subsequent depositReferralRewards step, the off-chain code re-queries the subgraph and computes per-affiliate and per-trader amounts individually:
// feeDistributionService.ts line 935 const amount = rebateUsd / wntPrice; // per affiliate // feeDistributionService.ts line 974 const amount = discountUsd / wntPrice; // per trader Then validates the sum against the on-chain stored value: // feeDistributionService.ts line 983 if (totalWntAmount !== wntAmount) { throw new Error(...) }Due to integer division,
sum(floor(x_i / d))is always less than or equal tofloor(sum(x_i) / d). Each individual division can lose up towntPrice - 1in remainder. With N affiliates and traders, the total difference can be up toN * (wntPrice - 1). Example: 3 affiliates, wntPrice = 2818733868580000 (ETH at $2818.73, 12 extra decimals):Affiliate A: \$1000 rebate → floor(1000 * 10^30 / 2818733868580000) = 354847484485902594 Affiliate B: \$2000 rebate → floor(2000 * 10^30 / 2818733868580000) = 709694968971805188 Affiliate C: \$500 rebate → floor(500 * 10^30 / 2818733868580000) = 177423742242951297Off-chain sum:
354847484485902594 + 709694968971805188 + 177423742242951297 = 1241966195700659079On-chain:floor(3500 * 10^30 / 2818733868580000) = 1241966195700659081Difference: 2 wei With only 3 affiliates the difference is 2 wei. In production with hundreds of affiliates and traders, the cumulative truncation loss grows proportionally. This issue is not about this 2 wei of difference, thats negligible, its about the the strict equality check at line 983 which will revert on any non-zero difference.if (totalWntAmount !== wntAmount) { throw new Error( `The totalWntAmount to be deposited (\${formatAmount( totalWntAmount, )}) doesn't equal the wntAmount recorded on-chain for this week (\${formatAmount( wntAmount, )})`, ); }Recommendation
Consider applying division on the sum like its done in first step of the distribute or Replace the strict equality check with a tolerance-based comparison that accounts for the maximum possible truncation loss.
-
H-07 High Wrong Operation Order Cause Reward Loss Logical Error Pending
Description
In
FeeDistributor._distributeFees(),updateLastDistributionTime()is called beforesetTokensPerInterval():IRewardDistributor(distributor).updateLastDistributionTime(); // sets lastDistributionTime = block.timestamp IRewardDistributor(distributor).setTokensPerInterval(feeAmountGmx / 1 weeks);This ordering causes pending rewards from the previous interval to be silently lost. The call chain is:
updateLastDistributionTime()setslastDistributionTime = block.timestampsetTokensPerInterval()internally callsIRewardTracker(rewardTracker).updateRewards()updateRewards()calls_updateRewards()which callsIRewardDistributor(distributor).distribute()distribute()callspendingRewards(), which computes:
uint256 timeDiff = block.timestamp.sub(lastDistributionTime); return tokensPerInterval.mul(timeDiff); ``` Since
lastDistributionTimewas already set toblock.timestampin step 1,timeDiff == 0, andpendingRewards()returns0. 5.distribute()early-returns with0— no rewards are transferred. As a result, all accrued rewards from the previous interval (since the last distribution) are lost and never distributed to stakers.Recommendation
Remove the
updateLastDistributionTime()call entirely. It is redundant becausesetTokensPerInterval()already triggers the full distribution flow:setTokensPerInterval()→updateRewards()→distribute(), anddistribute()internally setslastDistributionTime = block.timestampafter transferring pending rewards.- IRewardDistributor(distributor).updateLastDistributionTime(); IRewardDistributor(distributor).setTokensPerInterval(feeAmountGmx / 1 weeks);If retaining the explicit
updateLastDistributionTime()call is considered important, it should be moved aftersetTokensPerInterval()so that pending rewards are distributed first:- IRewardDistributor(distributor).updateLastDistributionTime(); IRewardDistributor(distributor).setTokensPerInterval(feeAmountGmx / 1 weeks); + IRewardDistributor(distributor).updateLastDistributionTime(); -
H-08 High pendingImpactAmount Overwritten In Keeper Logical Error Pending
Description
On-chain
pendingImpactAmountis cumulative across increases:IncreasePositionUtilsadds the newpriceImpactAmountto the existing pending value. However, thePositionIncreaseevent emits only the delta (pendingPriceImpactAmount = priceImpactAmount). The keeper’sprocessPositionIncreasewrites this delta directly into the DB, overwriting any existing pending impact for that position. After multiple increases, the keeper under‑tracks negative pending impact, which leads to wrong remaining collateral estimations and therefore liquidatable positions might be ignored. For example:- Position starts with pendingImpactAmount = 0
- Increase #1: priceImpactAmount = -5.
- On‑chain pending becomes -5
- Event emits -5
- Keeper writes -5 into the DB (ok)
- Increase #2: priceImpactAmount = -3.
- On‑chain pending becomes -8
- Event emits -3
- Keeper writes -3 into the DB (loses -5)
Recommendation
Add the
pendingImpactAmountto the current value in the DB instead of replacing it. -
H-09 High Single-Sided Market State Double-Adjustment Logical Error Pending
Description
For single-sided markets
(longToken == shortToken), keeper market state normalization and arithmetic apply anti-double-counting twice. During pulls, the keeper zeroes short-collateral OI and pool fields for single-sided markets:marketService.ts (line 190) marketService.ts (line 195) marketService.ts (line 746)Later, keeper helpers still divide by 2 when
longToken == shortToken:marketUtils.ts (line 188) marketUtils.ts (line 456) marketUtils.ts (line 201)This results in understated local token OI and pool values (approximately 50%). The contracts do not use this exact “zero one side, then divide” combination. Instead, they read both collateral-token views and apply divisor logic to those reads:
MarketUtils.sol (line 2232) MarketUtils.sol (line 2254) MarketUtils.sol (line 2284)Impact: <This impacts ADLs, GLVs, Liquidations, due to pnl to pool factors and OI calculations, still trying to understand all impacts, will be back>
Recommendation
Consider using either divisor or zero one-side adjustment, but not both.
-
H-10 High Non-Determinism Issues In Chainlink CRE Workflow Logical Error Pending
Description
Chainlink CRE runs workflows across multiple nodes that must reach consensus. All nodes execute the same code and must produce identical results. If any node produces a different output, consensus fails and the workflow doesn't execute. Reference: https://docs.chain.link/cre/concepts/non-determinism-ts
The ProblemThe workflow has multiple sources of non-determinism that cascade into consensus failure:new Date() → different query time ranges per node ↓ No orderBy on subgraph queries → different/unordered results per node ↓ Record<string,T> + Object.values() iteration → different processing order ↓ Unsorted output arrays → different affiliate/referral ordering ↓ Different batch calldata encoded → consensus failure ↓ No fees distributed. No referral rewards deposited.**Sources of Non-Determinism
**1.
new Date()instead of trigger timestampfee-automation-workflow/utils/date.ts:4—getRecentWednesdayStartOfDay()usesnew Date()to compute the weekly period for all subgraph queries. The CRE trigger already provides a deterministicpayload.scheduledExecutionTime(main.ts:201) but it is never used. If nodes execute across a Wednesday midnight UTC boundary, they compute different weekly periods and query entirely different data: <table header-row="true"> <tr> <td>Node</td> <td>new Date()</td> <td>Computed Wednesday</td> </tr> <tr> <td>Node A</td> <td>Wed Jan 8 00:00:00</td> <td>Jan 8</td> </tr> <tr> <td>Node B</td> <td>Tue Jan 7 23:59:59</td> <td>Jan 1 (previous week)</td> </tr> </table> 2. MissingorderByin all 6 subgraph queriesfee-automation-workflow/domain/fee/feeDistributionService.ts— Every query lacksorderBy:getAffiliatesTierQuery(line 231) —affiliatesgetReferralsQuery(lines 252, 268, 283) —affiliateStats,referralStatsgetFeeStatsV1Query(line 724) —feeStatsgetFeeStatsV2Query(line 744) —positionFeesInfoWithPeriods,swapFeesInfoWithPeriodsThe queries usefirst: 1000, skip: Npagination. WithoutorderBy, pagination is undefined, producing different aggregate totals (totalRebateUsd,totalEsGmxRewards,v1Fees,v2Fees).
-
Record<string, T>withObject.entries()/Object.values()iterationfee-automation-workflow/domain/fee/feeDistributionService.ts— Three Records are built from unordered subgraph data and iterated in insertion order: <table header-row="true"> <tr> <td>Line</td> <td>Variable</td> <td>Iterated at</td> </tr> <tr> <td>337</td> <td>affiliatesTiers: Record<string, number></td> <td>line 345</td> </tr> <tr> <td>373</td> <td>affiliatesRebatesData: Record<string, AffiliateData></td> <td>lines 424, 434, 460, 510</td> </tr> <tr> <td>540</td> <td>referralDiscountData: Record<string, ReferralDiscountAggregate></td> <td>lines 566, 583</td> </tr> </table> Chainlink docs explicitly recommendMapover plain objects — CRE nodes may run different JS engine versions with different iteration behavior. -
Unsorted output arrays and batch calldata The
output.affiliates(line 522) andoutput.referrals(line 593) arrays are populated viaObject.values()and never sorted. These feed directly intoprocessReferralRewardsCalls()(line 900), which chunks them into batches of 150 and encodes on-chain calldata. Different ordering = different calldata bytes = consensus rejection.
Recommendation
Consider following all best practices mentioned here https://docs.chain.link/cre/concepts/non-determinism-ts
- Use trigger timestamp — replace `new Date()` with
payload.scheduledExecutionTimeor block timestamp - Add orderBy + orderDirection to all subgraph queries
- Use Map instead of Record for aggregation structures, or sort inputs before building Records
- Sort output arrays by account address before returning from
processDistributionData()and before batch processing in `processReferralRewardsCalls()`
-
H-11 High Keeper Misprices Virtual Inventory Math Pending
Description
The keeper always calculates the virtual inventory based on the
virtualInventoryForPositionsvalue and not based on thevirtualInventoryForPositionsInTokensvalue in it'sisPositionLiquidatablecheck. As theUSE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCEparam on chain is true this calculation is wrong. This can lead to the keeper ignoring liquidatable positions.Recommendation
Use
virtualInventoryForPositionsInTokensto calculate the value of the inventory instead. -
H-12 High Reserve checks can block liquidations and ADLs Logical Error Pending
Description
PositionUtils.updateOpenInterestre-runsvalidateReserveandvalidateOpenInterestReserveafter applying a negative open interest delta.DecreasePositionUtilsroutes all decreases through this helper, and both liquidation orders and ADL orders execute through the same decrease-order path. As a result, stressed reductions are not allowed merely because they improve reserve usage. They are only allowed if the entire post-transaction market state is brought fully back within the configured reserve-factor bounds in a single transaction. This is especially relevant because reserve factors can be configured above 100%. In that configuration, a market can remain fully backed in absolute terms while still violating the configured reserve-factor caps. If a liquidation or ADL reduces exposure but the post-state remains above those caps, the transaction still reverts.function updateOpenInterest( PositionUtils.UpdatePositionParams memory params, int256 sizeDeltaUsd, int256 sizeDeltaInTokens, MarketUtils.MarketPrices memory prices ) internal { if (sizeDeltaUsd != 0) { MarketUtils.applyDeltaToOpenInterest(...); MarketUtils.applyDeltaToOpenInterestInTokens(...); MarketUtils.validateOpenInterest(...); MarketUtils.validateReserve(...); MarketUtils.validateOpenInterestReserve(...); if (sizeDeltaUsd < 0) { ... } } }Illustrative scenario:
poolUsd = \$100mreserveFactor = 200%, sovalidateReserveallows up to\$200mopenInterestReserveFactor = 200%, sovalidateOpenInterestReserveallows up to\$200m- current
reservedUsd = \$210m(due to upward price movement in a popular market) Now suppose an ADL or liquidation reduces exposure and movesreservedUsddown to\$205m. This is a reserve-improving action, but it still reverts: \$205m > \$200m, sovalidateReservefails\$205m > \$200m, sovalidateOpenInterestReservefails The same issue applies to liquidations. Liquidation orders fully close the targeted position, but they still revert if the residual market-widereservedUsdremains above the configured reserve-factor thresholds after that liquidation. Impact:- ADL and liquidations can be blocked even when it is reducing stressed exposure in the intended direction.
Other Impacts From The Same Root Cause
- If governance lowers
maxOpenInterest,reserveFactor, oropenInterestReserveFactorbelow the current market state, then even a risk-reducing decrease can revert unless that single transaction alone restores the entire side below the configured threshold. - Neutralization of the protocol’s insolvent-close escape hatch.
The decrease flow is intentionally designed to allow certain stressed or insolvent closes to continue via
handleEarlyReturn()inDecreasePositionCollateralUtils.sol:630. However, after collateral processing completes, the execution now continues throughDecreasePositionUtils.sol:303, which invokes the same market-wide validations throughPositionUtils.sol:635. As a result, even if the position-level logic explicitly allows the close because it reduces toxic exposure, the transaction can still revert on globalmaxOpenInterestor reserve-factor checks if the residual market state remains above threshold. This matters separately because it defeats an intentional liveness mechanism for stressed exits.
Recommendation
First reconsider if having these validations is important, if they are then Consider
- Only enforcing these absolute checks on positive open-interest deltas.
- For negative deltas, enforce a monotonic rule:
- post-state violation must be <= pre-state violation
- and the relevant quantities (openInterest, reservedUsd) must strictly improve
- If they want stricter behavior, at minimum exempt liquidation / ADL / full close flows.
-
H-13 High StaticOracleProvider returns min/max inverted DoS Pending
Description
The
StaticOracleProviderreturns the min price as max price and the other way around. This likely leads to DoS in the_setPrimaryPricefunction.Recommendation
Return the min price as min price and the max price as max price.
-
M-01 Medium Incompatible Gas Assumptions On MegaEVM Configuration Acknowledged
Description
MegaETH’s gas model is not singular like EVM. It is multidimensional, with separate costs for compute and storage. Because of this difference, MegaETH recommends using their API for gas estimation instead of relying on standard EVM-style gas calculations. However, the current implementation uses EVM-based assumptions for gas estimation, which may not accurately reflect actual execution costs on MegaEVM. This affects both keepers and on-chain contract logic. For example, gas constants and estimations are defined in: https://github.com/GuardianOrg/gmx-synthetics-team1-1768586730346/blob/256a058fa996d8da5bea9eb617557e323d7379da/contracts/gas/GasUtils.sol#L293-L313 Or configs around max data length, like data list length. Megaeth also uses 98/100 rule for gas forwarding instead of 63/64 rule of vanilla EVM.
This could lead to: Underpriced transactions that revert due to insufficient gas Unexpected keeper failures or degraded protocol reliability on MegaEVM
Recommendation
Gas value constants configured for EVM should not be assumed to be valid on MegaEVM. Since MegaEVM does not currently expose a local Forge environment for testing, we recommend deploying to the MegaETH testnet and empirically validating all gas-related constants and estimations. Where possible, integrate MegaETH’s recommended gas estimation API for production usage. (Keepers)
-
M-02 Medium RBAC Signatures Are Replayable Signatures Pending
Description
signRequestonly signsMETHOD|PATH|RBAC_SALT(rbac.ts (line 10)), andrbacMiddlewareverifies only that string (rbacMiddleware.ts (line 27)). There is no timestamp/nonce or request‑body binding, so any leaked X-Gmx-Signature header can be replayed indefinitely for the same method+path, enabling repeated privileged actions tied to that role.Recommendation
Consider adding a timestamp/nonce to the signed message and enforce a short TTL on the server, and for write endpoints include a hash of the request body/query in the signed payload.
-
M-03 Medium Lack Of Effective Rate Limits Best Practices Pending
Description
The
rateLimitByUsermiddleware keys requests by a hash of req.ip plus the User-Agent. Because User-Agent is fully client‑controlled, an attacker can bypass the limiter simply by rotating that header (and, when trust proxy is enabled, potentially also by spoofingX‑Forwarded‑Forto influencereq.ip). This makes the rate limit ineffective as an abuse control: the “user” identity is not stable, so the limiter becomes a per‑header throttle that can be reset on every request. This would allow attackers to easily abuse endpoints that perform heavy computations like the/apyendpoint to try to cause a DoS. Moreover, during testing, a script was used that repeatedly requested/apywith a custom time range (startTimestamp/endTimestamp) and observed the HTTP status codes. Despite sending multiple rapid requests in sequence, the endpoint returned 200 every time and no 429 responses were seen, confirming that the rate limit might not even be enabled in production. The script used was:URL="https://arbitrum-api.gmxinfra.io/apy?startTimestamp=1769179466000&endTimestamp=1769185466000" for i in {1..50}; do curl -s -o /dev/null -w "%{http_code}\n" \ -H "User-Agent: ratelimit-test" \ -H "X-Forwarded-For: 1.2.3.4" \ "\$URL" doneRecommendation
Use a shared, server‑side rate limiter keyed on stable identities (API key/user ID) and trusted client IPs, not spoofable headers. Enforce limits at the edge (gateway/WAF or Redis‑backed) so they apply across all instances and add stricter caps for expensive endpoints.
-
M-04 Medium ADL Size Delta Overestimation Due To Full PnL Logical Error Pending
Description
The
getSizeDeltaForAdlbinary search calculates an oversizedsizeDeltaUsdbecausegetNextMarketAfterAdlsimulates pool impact using the position's full PnL rather than proportional PnL (based on the fraction being closed). This causes the simulation to overestimate the pool impact, making the loop break early and returning a larger size than appropriate. On-chain execution uses proportional PnL, causingPnlOvercorrectedreverts when the actual impact exceeds the minimum threshold. Current hotfix: Line 74 divides result by 2 to mitigate, however this results in inefficient delayed ADLs.Recommendation
Consider using proportional PnL to
sizeDeltaingetNextMarketAfterAdl. -
M-05 Medium GraphQL Injection In /intract/task_2 Validation Pending
Description
User‑controlled address is interpolated directly into a GraphQL query without validation or escaping. This happens in
intract.ts(readsreq.query/req.body),intractService.ts(passes the raw account), andsubgraphService.ts(builds the query string in getGmTokenBalances). An attacker can inject quotes/braces to break out of the account: "..." clause, potentially altering the query, causing heavy queries (DoS), or reading additional fields depending on subgraph schema and permissions. Basic example curl to break the query:curl "https://botanix-api.gmxinfra.io/intract/task_2?address=%22%7D%20bad%20%7B%20"Recommendation
Validate and normalize address before it reaches the GraphQL builder (e.g., require 0x‑prefixed 40‑hex and use
ethers.utils.getAddress, reject invalid). Then stop interpolating raw strings into GraphQL; use GraphQL variables or a safe query builder to avoid injection entirely. Consider bounding startTimestamp/endTimestamp too, to reduce backend load from malformed requests. -
M-06 Medium Vulnerable Dependencies Best Practices Pending
Description
Several dependencies with known vulnerabilities were found used in by this project. These are the known vulnerabilities in dependencies that should be fixed asap because they are probably affecting the used code:
- body-parser (high) - CVEs: CVE-2024-45590 - Remediation: Upgrade to version 1.20.3 or later
- express (medium) - CVEs: CVE-2024-29041, CVE-2024-43796 - Remediation: Upgrade to version 4.19.2 or later
- lodash (medium) - CVEs: CVE-2025-13465 - Remediation: Upgrade to version 4.17.23 or later
- ws (high) - CVEs: CVE-2024-37890 - Remediation: Upgrade to version 7.5.10 or 8.17.1 or later
- https://github.com/advisories/GHSA-3h5v-q93c-6h6q These are other dependencies used with known vulnerabilities that even if they are probably not affecting the current code, they should still be fixed:
- @babel/helpers (medium): update to >=7.26.10.
- @babel/runtime (medium): update to >=7.26.10.
- @babel/runtime-corejs3 (medium): update to >=7.26.10.
- @babel/traverse (critical): update to >=7.23.2.
- brace-expansion (low): update to >=2.0.2
- braces (high): update to >=3.0.3.
- cookie (low): update to >=0.7.0.
- cross-spawn (high): update to >=7.0.5.
- diff (medium): update to >=5.2.2.
- elliptic (critical): update to >=6.6.1.
- es5-ext (low): update to >=0.10.63.
- esbuild (moderate): update to >=0.25.0.
- eslint (medium): update to 9.26.0.
- form-data (critical): update to >=4.0.4.
- get-func-name (high): update to >=2.0.1.
- got (medium): update to >=11.8.5.
- inflight (medium): update to a patched version.
- js-yaml (medium): update to >=4.1.1.
- micromatch (medium): update to >=4.0.8.
- nanoid (medium): update to >=3.3.8.
- path-to-regexp (high): update to >=0.1.12.
- qs (high): update to >=6.14.1.
- request (moderate): update to a patched version.
- semver (high): update to >=7.5.2.
- send (low): update to >=0.19.0.
- serialize-javascript (medium): update >=6.0.2.
- serve-static (low): update to >=1.16.0.
- tmp (medium): update to >=0.2.4.
- tough-cookie (medium): update to >=4.1.3.
- webpack (medium): update to >=5.94.0.
Recommendation
It's recommended to upgrade all the dependencies to their latest versions to prevent unnecessary security risks.
-
M-07 Medium
validateGlvShiftMaxLossUses Post-Shift Input Logical Error PendingDescription
The
validateGlvShiftMaxLosscheck inexecuteGlvShiftprices the input and output using post-shift pool values and supply. The shift is executed first, thengetPoolValueInfoandgetMarketTokenSupplyare queried for both markets. This makes the input side (marketTokensUsd) reflect the post-shift price, which can be lower after adverse impact, understating the true cost of tokens removed fromfromMarket.cache.marketTokensUsd = MarketUtils.marketTokenAmountToUsd( glvShift.marketTokenAmount(), cache.fromMarketPoolValueInfo.poolValue.toUint256(), // using post-shift values cache.fromMarketTokenSupply ); validateGlvShiftMaxLoss(params.dataStore, glvShift.glv(), cache.marketTokensUsd, cache.receivedMarketTokensUsd);Illustrative example:
- Pre-shift fromMarket: pool value $1000, supply 100 → $10/GM. GLV shifts 50 GM, so the true cost is $500.
- The shift worsens pool balance, post-shift pool value drops to $400 while supply is 50 → $8/GM.
- If you price the input using post-shift values, those 50 GM look like $400, not $500.
- If you received $350 on the other side, loss looks 12.5% ($50/$400) instead of 30% ($150/$500).
Impact: the max-loss guardrail can be bypassed in edge cases because the computed loss is smaller than the pre-shift loss, allowing shifts that exceed
glvShiftMaxLossFactorto pass validation. The keeper rebalancer compounds this by estimating price loss with the same post-shift pool value/supply assumptions, so shifts that would fail a pre-shift loss check are still selected and submitted:
// glvRebalancerUtils.ts (line 989) const toMarketSupplyAfterShift = toAmount.add(toMarket.totalSupply); const toMarketPoolValueAfterShift = BigNumber.from(toMarket.poolValueMax).add(toUsd); const receivedMarketTokensUsd = toAmount.mul(toMarketPoolValueAfterShift).div(toMarketSupplyAfterShift); const fromMarketPoolValueAfterShift = BigNumber.from(fromMarket.poolValueMax).sub(fromUsd); const fromMarketSupplyAfterShift = BigNumber.from(fromMarket.totalSupply).sub(fromAmount); const marketTokensUsd = fromAmount.mul(fromMarketPoolValueAfterShift).div(fromMarketSupplyAfterShift);Recommendation
Snapshot the
fromMarketpool value and market token supply before executing the shift and use those pre-shift values formarketTokensUsd. KeepreceivedMarketTokensUsdbased on post-shift state, or reuse the withdrawal/deposit valuation inputs to ensure a consistent pre/post comparison. -
M-08 Medium Source-Map Fetch Abuse By Regex Bypass Best Practices Pending
Description
It's possible to abuse the source-map fetch functionality to fetch an attacker's controller web page. Then, the attack could delay the response enough from his domain to try to exhaust resources of the server trying to cause a DoS. Step by step issue:
- Public ingestion endpoint accepts error stacks
/ui/batch_reportaccepts"event"items and forwards the payload tologEvent, which later processescustomFields.errorStack.Main code:logEvent(logger, item.payload, ...)Location:src/routes/ui.ts - Source-map resolution is triggered
prepareEventPayloadchecksuiSourceMapsEnabledandcustomFields.errorStack, then callsgetMappedStackTrace(...).Main code:if (uiSourceMapsEnabled && errorStack) { getMappedStackTrace(errorStack) }Location:src/domain/ui/uiService.ts - Stack traces are parsed with a regexThe regex is built from
frontendConfig.get("assetsPath")but only escapes the first/, leaving.as regex wildcards.Main code:new RegExp(\(?${assetsPath}\/...), "g")Location:src/domain/ui/sourceMapResolver.ts - Regex bypass detail
The currenlty used regex is:
const ERROR_STACK_SOURCE_REGEXP = new RegExp(
(?<filePath>\${(frontendConfig.get("assetsPath") as string).replace( "/", "\\/" )}\\/(?<filename>[-a-zA-Z0-9@:%._\\+~#=]+)):(?<line>\\d+):(?<column>\\d+), "g" ); ``` IfassetsPathishttps://www.production.com/assets, the unescaped dots allow matches likehttps://wwwAproduction.com/assets/...because.in regex matches any character. This lets attacker-crafted stack traces point to non-exact hosts while still matching the regex. 5. Source maps are fetched from the matched URLgetSourceMaptransformsfilePathinto<filePath>.mapand callsfetch(url)with default redirect-following (up to 20 redirects innode-fetchv2).Main code:const url = filePath.replace(".js", ".js.map"); await fetch(url);Location:src/domain/ui/sourceMapResolver.ts6. No explicit timeoutfetch(url)is called without AbortController/timeout; hanging hosts can consume sockets/concurrency.Location:src/domain/ui/sourceMapResolver.tsRecommendation
- Parse and validate URLs explicitly: build the URL from a trusted base, then enforce exact hostname/port/scheme matches (not regex).
- Limit redirects (or set
redirect: "manual"), and enforce a redirect allow-list. - Add a strict fetch timeout + max response size; abort slow or large responses.
- Cap traces per request and add a global concurrency limit for source-map fetches.
- Public ingestion endpoint accepts error stacks
-
M-09 Medium Funding Rate Swap Logic Swaps Wrong Entries Logical Error Pending
Description
The
updateFundingRateflow tries to reorder updates whennextmin funding exceeds the current max, but the swap logic swaps the last two entries in the change list, which arefundingIncreaseRateandfundingDecreaseRate. As a result,minFundingRatecan still be applied beforemaxFundingRate. OnchainvalidateRangechecksmin <= current maxpersetUint, so applying min first can revert the entire multicall. This blocks all funding config updates in that payload, leaving min/max and increase/decrease rates stale.if (resultMax.shouldUpdate) { changes.push({ type: "maxFundingRate", ... }); changes.push({ type: "fundingIncreaseRate", ... }); changes.push({ type: "fundingDecreaseRate", ... }); } if (resultMin.shouldUpdate && resultMax.shouldUpdate && resultMin.next > resultMax.current) { [changes[changes.length - 1], changes[changes.length - 2]] = [changes[changes.length - 2], changes[changes.length - 1]]; }Example scenario:
- Current max: 0.5%/hr, current min: 0.1%/hr.
- Computed next min: 0.6%/hr, next max: 0.8%/hr.
- Min is applied first due to incorrect swap,
validateRangerejects, multicall reverts. Impact - Multicall reverts when
minFundingRateis applied above current max. - All funding configuration updates for the run fail, not just the affected market.
- Funding parameters can remain stale during high volatility, affecting fee accuracy and market balance.
Recommendation
Track the positions of the
minFundingRateandmaxFundingRatechanges and swap those specific entries, or build the payload in deterministic order somaxFundingRateis always applied beforeminFundingRatewhen both update. This ensures onchain range checks pass. -
M-10 Medium Risk Free Trades For Malicious Keeper Validation Acknowledged
Description
In case the
LIMITED_CONFIG_KEEPERacts maliciously it is able to perform risk free trades in the following way:- Create multiple orders with a lot of collateral and a lot of leverage
- Look out if any order would be in instant profit if executed => if so let it go through
- Otherwise update the
MAX_OPEN_INTERESTkey so that the order can't be executed
Recommendation
Carefully set the allowed keys the
LIMITED_CONFIG_KEEPERshould be able to update to not open up any potential attack vectors. -
M-11 Medium Event Lookup Across Batch Can Cause Failures DoS Pending
Description
In
main.ts,callFeeDistributorcapturesfromBlockusing the latest header before submitting the transaction, then queries logs from that block onward and expects exactly one matching log. During batcheddepositReferralRewardsexecution, a later batch can query a range that still includes prior batch logs (or other matching logs in the same range), causinglogs.length > 1and a hard failure even though the current transaction succeeded.Recommendation
Consider making log selection transaction-specific instead of range-unique
-
M-12 Medium Buyback Flow Swap Failure Handling Logical Error Pending
Description
In
openOceanService.swapTokensif the swap transaction fails, it only logs a warning and continues. The function returnstrueunlesssuccess && output < minOutputAmount. A failed tx is therefore treated as success.const [success, failReason] = await waitForTransactionResult(txHash, ...); if (!success) { logger.warn("swap tx %s receipt failed: %s", txHash, failReason); } ... if (tokenOutBalanceDiff.lt(minOutputAmount)) { ... if (success) { return [false, "OUTPUT_AMOUNT"]; } } return [true, undefined]; // <--- returns true even on failureImpact:
- In the pre-buyback swap (native -> buyback token): If it silently fails, the flow still calls
feeHandler.buybackwithout actually holding the required buyback tokens, which will revert and waste gas. - In the post‑buyback conversion (fee token → buyback token): If it silently fails, the buyback already happened, but the keeper keeps fee tokens instead of converting. This can later trigger an extra hop: feeToken → native (cleanup) and native → buyback on a later run, incurring extra fees/slippage.
- Logs indicate swaps/buybacks proceeded even when they failed.
- PnL is derived from wallet balance deltas for native, feeToken, and buybackToken after the flow completes (
buyback.ts: L611). If a swap fails but is treated as success, the wallet can spend gas and not receive output tokens, yielding a negativetotalPnlUsdeven though the flow did not complete correctly. This may trigger theBUYBACK_LOSS_TOO_HIGHguard and disable buyback despite no real protocol loss.
Recommendation
Treat the pre‑buyback swap as a hard prerequisite for the on‑chain buyback. If the keeper needs to acquire buyback tokens, require
swapTokensto return success before proceeding to buyback. When the swap fails, return early (or retry with a bounded backoff) and emit a distinct warning that the buyback was skipped due to insufficient buyback tokens. Furthermore, in the post-buyback swap logs, avoid the "skip buyback" wording for the second swap, and emit a distinct "post-buyback conversion failed" signal:// buyback.ts: L599-601 if (!swapSuccess && swapError === "ESTIMATED_MIN_AMOUNT_OUT") { logger.warn("swap failed with estimated min amount out, skip buyback"); } - In the pre-buyback swap (native -> buyback token): If it silently fails, the flow still calls
-
M-13 Medium Trigger Equality Skipped For Limit/Stop Orders Logical Error Pending
Description
The keeper limit/stop order flow treats the trigger condition as strictly crossed, not reached.
validateOrderTriggerPriceuses<or>andgetSignedPricesForFrozenOrderrejects prices that are exactly equal totriggerPrice. The signed-price search also filters with a strict operator in_searchSignedPriceByTriggerPrice. On-chain validation accepts equality for all limit/stop triggers, so a price that equals the trigger is executable on-chain but ignored by the keeper.// validateOrderTriggerPrice() const price = useGt ? priceRange.maxPrice : priceRange.minPrice; if (useGt) { return price.gt(order.triggerPrice); } return price.lt(order.triggerPrice);// _searchSignedPriceByTriggerPrice() const priceOperator = useGt ? ">" : "<"; ... .andWhere(firstFilterPriceProp, priceOperator, triggerPrice.toString()) ...This mismatch means the keeper can miss executions when the oracle touches the trigger and reverses without a strict cross. The impact varies by order type:
- StopLossDecrease: protection failure. The trigger condition is met on-chain, but the keeper does not execute. If the next signed price is away from the trigger, the stop remains open and risk increases.
- LimitDecrease: missed take-profit. The user loses a profit exit if the only eligible price equals the trigger.
- StopIncrease: missed stop-entry. This is usually an opportunity cost, but can be material for momentum strategies.
- LimitIncrease: missed entry at the user’s price, typically opportunity cost. Example scenario (StopLossDecrease):
- A trader longs ETH at 3000 with a stop-loss at 2900.
- Oracle min price prints exactly 2900, then rebounds to 2910 on the next update.
- The contract would allow execution at 2900, but the keeper requires
< 2900, so it does nothing. - Price later drops to 2700 before any strict-cross price is observed; the stop still sits open and the trader absorbs the extra 200 loss that the stop was intended to prevent.
Recommendation
Align the keeper’s trigger checks with on-chain semantics by using inclusive comparisons. Update
validateOrderTriggerPrice,getSignedPricesForFrozenOrder, and_searchSignedPriceByTriggerPriceto allow equality (>=/<=) and to use inclusive operators in the SQL filters. Consider adding a regression test for each order type to ensure equality triggers are executable. -
M-14 Medium ADL Sizing Uses Inconsistent PnL Values Logical Error Pending
Description
The
getNextMarketAfterAdlfunction computes anadjustedPositionPnlto account for capped price impact but fails to use it consistently. The adjusted value is only used for the branching condition while the actual pool delta calculation uses the unadjustedpositionPnl.const positionPnl = getPositionPnl(position, market, prices); let adjustedPositionPnl = positionPnl; if (adjustedPositionPnl.gt(0) && priceImpactDiffUsd.gt(0)) { if (adjustedPositionPnl.gt(priceImpactDiffUsd)) { adjustedPositionPnl = adjustedPositionPnl.sub(priceImpactDiffUsd); } else { adjustedPositionPnl = bigNumberify(0); } } let pnlTokenAmountForPool: BigNumber; if (adjustedPositionPnl.lt(0)) { pnlTokenAmountForPool = positionPnl.mul(-1).div(collateralTokenPrice); } else { pnlTokenAmountForPool = positionPnl.mul(-1).div(pnlTokenPrice); }The condition check on line 37 uses
adjustedPositionPnlto determine which branch to take. However, both branches computepnlTokenAmountForPoolusing the unadjustedpositionPnlinstead ofadjustedPositionPnl. This inconsistency causes incorrect pool amount estimation in the simulatednextMarketstate. ThepnlTokenAmountForPoolvalue directly affects the pool amount in the returned market state, which is then used by getSizeDeltaForAdl to iteratively compute the optimal ADL size. WhenpositionPnlis positive andpriceImpactDiffUsdis also positive, the pool deduction is overestimated because the fullpositionPnlis used rather than the reducedadjustedPositionPnl. Consider the following scenario:positionPnl= 1000 USD (trader profit)priceImpactDiffUsd= 300 USD (capped impact)adjustedPositionPnl= 700 USD (computed but unused)- Pool deduction uses 1000 USD instead of 700 USD (30% error) The impact includes:
- Incorrect PnL-to-pool factor calculation in
getSizeDeltaForAdl - Oversized ADL executions that may trigger
PnlOvercorrectederrors on-chain - Undersized ADL executions requiring multiple iterations to bring PnL-to-pool below threshold
- Wasted gas from failed or repeated ADL transactions
The bug triggers when both
positionPnl > 0andpriceImpactDiffUsd > 0, which occurs during ADL of profitable positions with capped price impact. The iterative algorithm with 18 iterations and a final division by 2 provides some tolerance, but significant estimation errors can still propagate through.
Recommendation
Use
adjustedPositionPnlconsistently for both the branching condition and the value calculation. -
M-15 Medium Missed Liquidations: Missing Position Fee Logical Error Pending
Description
The
getRemainingCollateralUsdForLiquidation(BigNumber version) double-counts the position fee when checking if positions are liquidatable.position.totalFeesUsdis fetched from the contract'sreader.getPositionInfo()which returns totalCostAmount — this already includes positionFeeAmount (along with borrowing fees, funding fees, UI fees, etc.). The BigNumber version then subtractsgetPositionFee()again explicitly. Location: positionUtils.ts:130-146 BigNumber version (buggy):const positionFee = getPositionFee(market, position.isLong, bigNumberify(position.sizeInUsd).mul(-1)); const remainingCollateralUsd = collateralUsd .add(positionPnlUsd) .sub(position.totalFeesUsd) // totalFeesUsd already includes positionFee .sub(positionFee) // <-- double-subtracted here .add(priceImpactUsd);Recommendation
Consider removing the redundant
getPositionFeesubtraction fromgetRemainingCollateralUsdForLiquidationto match the BigInt version. -
M-16 Medium Reorg Replay Causes
pendingImpactAmountDrift Logical Error PendingDescription
The
processPositionDecreasefunction has reorg protection forrealizedPnlbut not forpendingImpactAmount. When a chain reorganization occurs and the samePositionDecreaseevent is replayed, thependingImpactAmountcalculation reads from already-updated database state, causing cumulative drift with each replay. The keeper detects reorgs by comparing log content (txHash,data,topics) against stored logs. If the same content appears with a differentblockHash, it marks the log withisReorg: trueand re-processes it.const currentRealizedPnl = bigNumberify(position?.realizedPnl ?? 0); const nextRealizedPnl = log.isReorg ? currentRealizedPnl // Protected: skip if reorg : currentRealizedPnl.add(eventData.uncappedBasePnlUsd); const sizeInUsd = BigNumber.from(position.sizeInUsd); // Reads already-updated DB const pendingImpactAmount = BigNumber.from(position.pendingImpactAmount); // Reads already-updated DB const proportionalPendingImpactAmount = sizeInUsd.eq(0) ? BigNumber.from(0) : mulDiv(pendingImpactAmount, eventData.sizeDeltaUsd, sizeInUsd, pendingImpactAmount.lt(0)); const nextPendingImpactAmount = pendingImpactAmount.sub(proportionalPendingImpactAmount); // No reorg checkThe
realizedPnlcalculation checksisReorgand skips the addition if true. ThependingImpactAmountcalculation has no such check and always recomputes based on current database values, which were already modified by the first processing. Consider a position withsizeInUsd= 1000 andpendingImpactAmount= -100. A decrease event closes 20% (sizeDeltaUsd= 200):- First processing: proportional = -100 * 200 / 1000 = -20, next = -80
- DB updated:
sizeInUsd= 800,pendingImpactAmount= -80 - Reorg replay: reads
sizeInUsd= 800,pendingImpactAmount= -80 from DB - Recalculates: proportional = -80 * 200 / 800 = -20, next = -60
- DB updated:
pendingImpactAmount= -60 (should remain -80) Each reorg replay reduces the magnitude ofpendingImpactAmount. For negative values (unfavorable impact), this makes the value less negative than it should be. ThependingImpactAmountfeeds intogetPositionPriceImpactUsdForLiquidation, which calculatesremainingCollateralUsdfor liquidation checks. IfpendingImpactAmountdrifts less negative, the position appears healthier than it actually is.
Recommendation
Apply the same reorg protection pattern used for
realizedPnl. Skip thependingImpactAmountadjustment whenisReorgis true, since the value was already correctly computed during the first processing. -
M-17 Medium Missing Position Null Check Causes Batch Abort DoS Pending
Description
The
processPositionDecreasefunction retrieves a position from the database but has inconsistent null handling. If the position does not exist in the database, the function throws a TypeError, which aborts the entire log processing batch and prevents all subsequent events in that transaction from being applied.async function processPositionDecrease( log: LogWithDescription, eventData: PositionDecreaseEventData, trx: Knex.Transaction ) { const key = eventData.positionKey; const position = await positionModel.getPositionByKey(trx, key); const currentRealizedPnl = bigNumberify(position?.realizedPnl ?? 0); // handles null const nextRealizedPnl = log.isReorg ? currentRealizedPnl : currentRealizedPnl.add(eventData.uncappedBasePnlUsd); const sizeInUsd = BigNumber.from(position.sizeInUsd); // throws if null const pendingImpactAmount = BigNumber.from(position.pendingImpactAmount); // throws if null ... metadata: { values: { positionKey: position.key, // throws if nullOther callers in the codebase correctly check for null before accessing properties, but
processPositionDecreasedoes not. A position may not exist in the keeper database in several scenarios:- The corresponding
PositionIncreaseevent was missed due to WebSocket disconnection, RPC provider failure, or gaps in polling - The database was reset or migrated while the keeper was running
- A chain reorg placed the
PositionIncreasein an orphaned block while thePositionDecreaseremains in the canonical chain When the error is thrown, it propagates throughprocessLogsto the enclosingknex.transactioncall, causing a rollback. On the next iteration, the same logs are fetched and the same error can recur until the missing row is repaired or skipped, preventing forward progress. Impact: - Keeper can become stuck and cannot process any events in the affected batch
- Liquidations, order executions, and other time-sensitive operations are delayed or missed
- The keeper requires manual intervention to recover, such as database seeding or skipping the problematic block range
Recommendation
Add a guard to check if the position exists before accessing its properties. If the position is missing, log a warning and skip processing that event so the rest of the batch can proceed, and trigger a full position sync (or enqueue a resync) to reconcile state. An alternative approach is to enqueue a full position sync from the chain when a missing position is detected, ensuring the keeper eventually reconciles its state.
- The corresponding
-
M-18 Medium V2 Keeper Costs Can Underflow Calculations DoS Pending
Description
In
_calculateChainlinkAndTreasuryAmounts, the treasury amount is calculated by subtractingkeeperCostsV2from the V2 portion of WNT. However, there is no validation thatkeeperCostsV2fits within the available V2 allocation. If V2 keeper costs exceedchainlinkTreasuryWntAmount - wntForChainlink, the subtraction will underflow and revert, blocking the entire weekly fee distribution.function _calculateChainlinkAndTreasuryAmounts( uint256 totalWntBalance, uint256 feesV1Usd, uint256 feesV2Usd, uint256 keeperCostsV2 ) internal view returns (uint256, uint256) { // ... // @audit underflow if keeperCostsV2 > chainlinkTreasuryWntAmount - wntForChainlink uint256 wntForTreasury = chainlinkTreasuryWntAmount - wntForChainlink - keeperCostsV2; return (wntForChainlink, wntForTreasury); }The
keeperCostsV2value is calculated in calculateKeeperCosts based on the difference between each V2 keeper's target balance and their current native balance. Unlike V1 costs which have a fallback mechanism in_finalizeWntForTreasurythat can tap into the treasury allocation or pull from the treasury wallet, V2 keeper costs have no such safety mechanism. Example scenario:- V1 fees dominate:
feesV1Usd = 900k,feesV2Usd = 100k - V2 portion is 10% of total WNT, e.g. 30 ETH
- Chainlink factor takes 10%, leaving 27 ETH for treasury + V2 keepers
- V2 keepers have spent heavily and need 50 ETH top-up
- Calculation:
27 - 50 = underflow -> REVERTThis causes a DoS on distribute, halting the automated weekly fee distribution across all chains, disrupting protocol operations.
Recommendation
Options include:
- Cap
keeperCostsV2to the available V2 allocation (partial top-up) - Allow V2 keeper costs to also draw from the treasury allocation when the V2 portion is insufficient, mirroring the V1 fallback logic.
- V1 fees dominate:
-
M-19 Medium maxPositiveImpactFactor Not Capped In Keeper Validation Pending
Description
In the on chain code if the
maxPositiveImpactFactorexceeds themaxNegativeImpactFactorit is capped at themaxNegativeImpactFactor. This does not happen in the keeper. So in that case the keeper will cap the positive price impact not strictly enough and could therefore ignore a liquidatable position.Recommendation
Cap the
maxPositiveImpactFactorat themaxNegativeImpactFactorin the keeper code. -
M-20 Medium Keeper Can Underset Skew From OI Basis Mismatch Math Pending
Description
Keeper funding update logic always uses USD open interest to gate target selection. However, contracts, when
USE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCE=true, compute it on basis ofopenInterestInTokens*indexPrice. And sinceUSE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCEis currently set as true, this mismatch allows keeper to classify a market as balanced/low-skew while contract-side economic intent sees material skew, causing under-aggressive funding config updates (especiallyminFundingFactorPerSecondbehavior). Example: Price moves significantly. Opposite-side positions open at new price. USD OI appears balanced, but token notional remains imbalanced. Keeper updates funding params as if skew is low. Funding pressure is weaker than intended, slowing skew mean reversion. ETH at 5,000: long 10,000 USD (2 ETH) ETH at 8,000: short 10,000 USD (1.25 ETH) USD OI: 10k vs 10k (looks balanced) Token-basis exposure at 8,000: Long = 2 * 8000 = 16,000 Short = 1.25 * 8000 = 10,000 True skew = +6,000 longs Keeper can under-set funding pressure despite real skew.Recommendation
Consider comparing open interests using tokens * price, if
USE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCE = True -
M-21 Medium Stop-Loss Orders Skipped Before Liquidation Logical Error Pending
Description
Before liquidating a position, the keeper checks if the user has any stop-loss orders that could close the position instead. This is beneficial because stop-loss avoids liquidation penalty fees. However, a bug in the validation of prices causes all stop loss orders (with price feed tokens involved) to be skipped. In
executeStopLossOrders(liquidations.ts), the code separates tokens into signed price tokens and price feed tokens, and makes two errors:- Discarding the
signedPriceTokensoutput (e.g. ETH) and only keepingpriceFeedTokens(e.g. USDC), - Not passing
signedPriceTokenstogetSignedPricesForFrozenOrder, and passing intokens(all tokens) instead:
const tokens = getOrderTokens(order, markets); // ALL tokens const [, priceFeedTokens] = separatePriceFeedTokens(tokens, realtimeFeedMapping); // ← Did not keep signedPriceTokens output which needs validation const signedPrices = getSignedPricesForFrozenOrder(order, tokens, signedPricesByToken); // Passes ALL tokens // ... if (!validateSignedPrices({ // ... signedPrices, // ← Includes priceFeedTokens (e.g. USDC) which fail validateExistForAllTokens // ... })) { continue; // Stop-loss SKIPPED! }When
validateSignedPriceschecks if all tokens have signed prices, stablecoins are missing (as they use price feed instead of signed prices), causing validation to fail. This ultimately leads to the skipped execution of stop loss orders. In contrast, thelimitStopOrders.tscode (standard path) handles this correctly:const [signedPriceTokens, priceFeedTokens] = separatePriceFeedTokens(tokens, realtimeFeedMapping); signedPrices = getSignedPricesForFrozenOrder(order, signedPriceTokens, latestSignedPrices); // signedPriceTokens correctly passed inImpact: Users are liquidated instead of having their stop-loss executed, resulting in additional liquidation penalties.
Recommendation
Update
executeStopLossOrdersto passsignedPriceTokensintogetSignedPricesForFrozenOrder. - Discarding the
-
M-22 Medium Keeper Applies Wrong Position Impact Cap Validation Pending
Description
In the
getPositionPriceImpactUsdthe keeper caps the positive price impact by the amount in the price impact pool. However this should only happen on decrease orders as on chain comments explain:// note that the positive priceImpactUsd is not capped by the position impact pool here // this is to prevent cases where for new markets, user A opens a position with negative // price impact and user B does not have any incentive to open a position to balance the pool // because the price impact pool is empty until user A closes // the positive price impact will still be capped during position decrease when the positive // price impact is actually paid outThis leads to the keeper skipping the execution of executable orders.
Recommendation
Do only apply this cap in case of decrease orders.
-
M-23 Medium Nonce Race Condition DoS Pending
Description
The Keeper's logic for managing transaction nonces and wallet locks contains a race condition that leads to nonce collisions and severe throughput degradation under network congestion. The core issue is that the bot paralyzes itself by strictly coupling its transaction loop to the state of the blockchain, rather than maintaining its own local state.
- The
WalletPoollocks a wallet for a single transaction and refuses to issue the next until the previous one is either mined or times out. - When it finally does wake up (after timeout), it asks the RPC
getTransactionCount(..., "latest"). This query ignores the bot's own pending transactions in the mempool. - The Collision Loop:
- T=0s: Keeper locks Wallet A, sends Tx A (Liquidation 1, Nonce 100).
- Network Condition: Congestion delays mining. Tx A sits in mempool.
- T=10s: Code forces a specific timeout unlock.
- T=11s: Keeper attempts Liquidation 2. It grabs Wallet A.
- T=11.1s: Keeper asks RPC for nonce. RPC sees Nonce 99 mined, so it returns 100 again (ignoring the pending Tx A).
- T=11.2s: Keeper broadcasts Tx B with Nonce 100. When Nonce 100 is reused, the behavior is destructive:
- Rejection: If Tx B gas < 1.1x Tx A gas, the node rejects it. Result: Liquidation 2 is dropped.
- Overwrite: If Tx B gas > 1.1x Tx A gas, Tx B replaces Tx A. Result: Liquidation 1 is cancelled. If the bot correctly used Nonce 101 for Tx B, both transactions would exist in the mempool.
- Scenario 1 (Tx A Reverts): Even if Tx A fails execution on-chain (e.g., position already closed), it consumes the nonce. The miner immediately picks up Tx B (Nonce 101) in the same block. Zero throughput loss.
- Scenario 2 (Tx A Stuck): Even if Tx A is waiting for gas, Tx B is queued behind it, ready to go the moment A is processed. This might have financial impact because sending transactions 1 by 1 is too slow to handle high-volatility events effectively. In a "Black Thursday" scenario where hundreds of positions become undercollateralized simultaneously, the current architecture limits the bot to roughly 4 liquidations per minute per wallet, taking over 12 minutes to process a batch of 50. A competitor using correct nonce pipelining could process the same batch in under 2 seconds. This massive latency gap means the protocol will likely incur bad debt on the later positions before this bot can even attempt to liquidate them.
Recommendation
Refactor the transaction management system to decouple transaction submission from confirmation. Implement a local nonce tracker for each wallet that increments the nonce immediately after broadcasting a transaction, allowing subsequent transactions to be queued in the mempool without waiting for prior confirmation. Additionally, remove the blocking lock in
WalletPoolto enable parallel transaction issuance, and establish a separate background service to monitor and replace stuck transactions with higher gas fees as needed. - The
-
M-24 Medium MegaETH RPC Gas Cap Can Block Liquidations Warning Pending
Description
MegaETH caps both
eth_callandeth_estimateGasat 10,000,000 gas per RPC call (https://docs.megaeth.com/rpc). The keeper's liquidation flow depends on both of these methods, and neither has a fallback when the cap is hit. On-chain liquidation transactions on Arbitrum typically consume ~5M gas. While this is under 10M for standard cases, theeth_estimateGasbinary search andeth_callsimulation allocate headroom beyond actual usage, and edge cases (positions with many associated orders to auto-cancel, callback contracts, or collateral swaps) can push gas consumption higher. There is no hard guarantee that all liquidation simulations stay below 10M, especially with MegaETH's Multidimensional Gas Model. The liquidation flow hits the cap at two points:- Before sending a liquidation TX, the keeper simulates the full
executeLiquidationcall viaeth_call. If the simulation exceeds the 10M cap, it reverts. The catch block returns[false, <error>]and the position is silently skipped as "not liquidatable":
// positionService.ts — isPositionLiquidatable() const result = await providerPool.call({ to: handler.address, data: handler.interface.encodeFunctionData("executeLiquidation", [...]), from: walletPool.getAddresses()[0], }, blockTag); // on exception: return [false, extractReasonFromException(ex)]// liquidations.ts — caller silently skips on failure const [isLiquidatableOnchain, reason] = await positionService.isPositionLiquidatable(position, oracleParams); if (!isLiquidatableOnchain) { return; // silently dropped }- The liquidation executor passes
useEstimatedGas: true, forcingeth_estimateGaswith no fallback toexecutionBaseGasLimit:
// liquidations.ts sendTransaction(handler.populateTransaction.executeLiquidation(...), label, { useEstimatedGas: true, // forces eth_estimateGas, no fallback });// txUtils.ts — _getGasByEstimatedGasOrExecutionBaseGasLimit() const estimatedGas = await estimatedGasPromise; // throws if cap hitIf
eth_estimateGasfails,sendTransactionthrows and the liquidation is not submitted.Recommendation
- Add a try-catch fallback in the
eth_estimateGaspath that falls back to a calibratedexecutionBaseGasLimitwhen estimation fails, rather than throwing. - Configure MegaETH chain in
chains.tswith appropriate gas limits. - Add distinct error detection in
isPositionLiquidatable()for gas-cap failures so they are not silently treated as "not liquidatable."
- Before sending a liquidation TX, the keeper simulates the full
-
M-25 Medium Secondary keeper auto-reenable can stall Logical Error Pending
Description
The keeper runs in either primary or secondary mode to avoid duplicate execution. Secondary mode uses delays and promotes itself to primary based on successful executions when it detects the primary is down. For keepers that start in secondary mode, there is a 15-min timer that auto re-enables secondary mode after it has been manually disabled. The auto-reenable logic in
disableSecondaryModerelies onenableSecondaryModeTimeoutto track a pending 15 minute timer wheninitialIsSecondaryModeis true. WhenenableSecondaryModeis called manually, it cancels the timer withclearTimeoutbut does not resetenableSecondaryModeTimeoutto null. A subsequent call todisableSecondaryModesees the stale handle and returns early, skipping scheduling the re-enable timer. The keeper can then remain in non-secondary mode indefinitely unless manually toggled. Example sequence:- Keeper starts with
initialIsSecondaryModetrue and callsdisableSecondaryMode, scheduling a 15 minute re-enable timer. - An operator calls
enableSecondaryModebefore the timer fires, which clears the timer but leavesenableSecondaryModeTimeouttruthy. - Later,
disableSecondaryModeruns again and exits early due to the stale handle, so no new timer is scheduled. - Auto re-enable never runs, leaving the keeper in non-secondary mode. Impact:
- Reduces redundancy by preventing automatic fallback to secondary mode after manual toggles.
- Can keep a backup keeper in primary mode longer than intended, increasing operational risk when other primary keepers exist.
export function enableSecondaryMode() { if (enableSecondaryModeTimeout) { logger.warn("clear disable secondary mode timeout"); clearTimeout(enableSecondaryModeTimeout); //BUG: Missing `enableSecondaryModeTimeout = null;` here! } ... }Recommendation
After
clearTimeout, setenableSecondaryModeTimeout = null. - Keeper starts with
-
M-26 Medium Decrease validation uses wrong size denominator Logical Error Pending
Description
The
validateDecreasePositionfunction reducesposition.sizeInUsdbefore calculatingsizeDeltaInTokens, causing the denominator to be the remaining size rather than the original size. This results in an inflated token delta and an incorrectly reducedsizeInTokensfor the simulated post-decrease position.position.sizeInUsd = bigNumberify(position.sizeInUsd).sub(sizeDeltaUsd).toString(); if (position.sizeInUsd === "0") { return true; } const sizeDeltaInTokens = bigNumberify(position.sizeInTokens).mul(sizeDeltaUsd).div(position.sizeInUsd); position.sizeInTokens = bigNumberify(position.sizeInTokens).sub(sizeDeltaInTokens).toString();In contrast, the on-chain contract calculates
sizeDeltaInTokensusing the originalsizeInUsdas the denominator (PositionUtils.sol#L227). Consider a position withsizeInUsd= 1000,sizeInTokens= 10, and a decrease ofsizeDeltaUsd= 200:- On-chain:
sizeDeltaInTokens= 10 * 200 / 1000 = 2, remaining tokens = 8 - Keeper:
sizeInUsdreduced to 800 first, thensizeDeltaInTokens= 10 * 200 / 800 = 2.5, remaining tokens = 7.5 The keeper calculates 7.5 remaining tokens when the correct value is 8. This affects the subsequentvalidatePositioncall which checks if the post-decrease position would be liquidatable. For a long position at $100 per token: - Correct PnL: 8 * 100 - 800 = 0
- Keeper PnL: 7.5 * 100 - 800 = -50
The position appears to have negative PnL when it should have zero, making it seem less healthy than it actually is.
The function is called from
validateLimitStopOrderwhen deciding whether to execute frozen limit decrease or stop-loss orders. If validation fails, the order is skipped: limitStopOrders.tscallsvalidateLimitStopOrdervalidateLimitStopOrdercallsvalidateDecreasePositionfor decrease ordersvalidateDecreasePositioncallsvalidatePositionwith the incorrect simulated positionvalidatePositioncallsisPositionLiquidatable- If the position appears liquidatable, validation fails and the order is not executed
Recommendation
Calculate
sizeDeltaInTokensbefore reducingposition.sizeInUsd, using the original size as the denominator to match on-chain behavior. - On-chain:
-
M-27 Medium Keeper Works With Stale positionImpactPoolAmount Validation Pending
Description
The keeper uses the the
positionImpactPoolAmountin thegetPositionPriceImpactUsdto cap the price impact. This value is likely stale as it ignores thependingPositionImpactPoolDistributionAmount. This leads to the keeper trying to execute orders that are not executable and therefore the keeper will run into DoS and wastes gas.Recommendation
Decrease the
positionImpactPoolAmountby thependingPositionImpactPoolDistributionAmount. -
M-28 Medium Stale Fees Can Lead To Missed Liquidations Validation Pending
Description
Keeper liquidation candidate selection uses cached
totalFeesUsdfrom DB when computing remaining collateral. That fee value is refreshed asynchronously by thepullPositionFeesfunction, not in the liquidation loop itself. Fee refresh is chunked (PULL_POSITION_FEES_CHUNK_COUNT= 20) and periodic (positionFeesPullInterval= 60_000 by default), so a given position may wait around 20 minutes for refresh in normal operation. Because liquidation is a threshold check, even moderate staleness can cause false negatives for near-boundary positions: keeper marks position as healthy and skips it, so it never reaches on-chain liquidation simulation in that cycle. This can delay liquidation and worsen bad-debt risk during volatile periods. Be aware that stale fees can also lead to issues in other keeper flows.Recommendation
Consider if off-chain result is not liquidatable but close to boundary to still run on-chain liquidation simulation to make sure the position is healthy.
-
M-29 Medium Keeper Always Uses Liquidation Collateral Factor Validation Pending
Description
The
validatePositionfunction in the keeper bot always usesminCollateralFactorForLiquidation, while on-chain order execution for normal increase/decrease paths validates withminCollateralFactor(higher). This creates false positives off-chain: keeper tries executing frozen orders that can never pass on-chain leverage checks.Recommendation
Add a
forLiquidationflag in keeper validation and useminCollateralFactorfor normal order execution checks. -
M-30 Medium Keeper Price Impact Simulation Ignores Prices Math Pending
Description
However, on chain the
USE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCEparameter is true and therefore the raw USD delta is not used. Instead it calculates it based on the current token price. Description The keeper computes ADL size viagetSizeDeltaForAdl, which repeatedly simulates post-ADL market state (getNextMarketAfterAdl). That simulation depends ongetPositionPriceImpactUsd, currently called withusdDelta = -sizeDeltaUsdin keeper ADL flow. Because keeper ADL simulation skips this conversion,priceImpactDiffUsdis miscomputed, so projectednextPnlToPoolFactoris wrong. This directly distorts ADL search output (sizeDeltaUsd). Impact:- Keeper can choose an oversized ADL amount that reverts on-chain.
- Keeper can choose an undersized ADL amount, reducing PnL factor too little and requiring extra ADL rounds. Risking further imbalance in the market during volatile times. The same issue arises in the order execution flow. Only in the liquidation flow it is handled correctly.
Recommendation
Always calculate
usdDeltawith the current token price. -
M-31 Medium Atomic Oracle Providers Enable Price Picking Logical Error Pending
Description
On live deployments (Arbitrum, Avalanche, Botanix), both
ChainlinkPriceFeedProviderandChainlinkDataStreamProviderwere found to be enabled as atomic providers despite code comments warning against this:// Oracle.sol#L269 since for atomic actions, any atomic provider can be used, it is recommended that only one atomic provider is configured per token otherwise there is a risk that if there is a difference in pricing between atomic oracle providers for a token, a user could use that to gain a profit by alternating actions between the two atomic providersAs a result, users can select the provider that gives them a more favorable price at withdrawal, extracting value from the pool. Furthermore, if the difference in pricing between the two providers is large enough, users can cycle deposits and atomic withdrawals, selecting the favorable provider on each withdrawal and resulting in repeatable profit. Additionally, the
bridgeOutflow is wrapped withwithRelay, which sets prices via setPricesForAtomicActionfrom user-suppliedrelayParams.oracleParams. Users can pick whichever provider yields a more favorable swap rate for the relay fee conversion, reducing their effective relay fee input and shifting the economic loss onto GMX swap liquidity / impact pools over repeated use.Recommendation
Enforce exactly one atomic oracle provider per token at validation time (same strictness as non-atomic path), or disallow mixed atomic providers globally.
-
M-32 Medium GLV market token deposits bypass expiry Logical Error Pending
Description
GLV deposits where
isMarketTokenDeposit == truedo not enforce per-request oracle timestamp bounds:minTimestamp >= updatedAtTime maxTimestamp <= updatedAtTime + REQUEST_EXPIRATION_TIME- A GLV deposit request stores
updatedAtTime. - For non-market-token GLV deposits:
- Execution follows the synthetic Deposit flow.
- This path inherits
ExecuteDepositUtilstimestamp and expiration checks.
- For market-token GLV deposits:
- Execution enters
_processMarketDeposit(). - The function returns immediately after moving GM → GLV.
- As a result, request-time oracle freshness checks are skipped. A keeper can execute a market-token GLV deposit using oracle timestamps that would be considered invalid under normal request-level freshness rules. This creates an inconsistency between market-token and non-market-token GLV deposit validation and may allow execution with stale or out-of-bounds oracle data.
- Execution enters
Recommendation
Consider adding request-relative timestamp validation at the start of
ExecuteGlvDepositUtils.executeGlvDeposit(...)(or immediately before market-token early return).Resolution
Guardian: Commit
9bc91653was intended to fix M-32, but it only added the lower-bound oracle timestamp check to the GLVisMarketTokenDepositbranch. The normal deposit path also enforcesoracle.maxTimestamp <= updatedAtTime + REQUEST_EXPIRATION_TIME, while the GLV market-token shortcut still returns before applying that expiry check.if (glvDeposit.isMarketTokenDeposit()) { if (params.oracle.minTimestamp() < glvDeposit.updatedAtTime()) { revert Errors.OracleTimestampsAreSmallerThanRequired( params.oracle.minTimestamp(), glvDeposit.updatedAtTime() ); } // missing: maxTimestamp <= updatedAtTime + REQUEST_EXPIRATION_TIME glvVault.transferOut(glvDeposit.market(), glvDeposit.glv(), glvDeposit.marketTokenAmount()); return glvDeposit.marketTokenAmount(); }As a result, an old GLV market-token deposit can still execute after expiry as long as the keeper supplies fresh-enough prices for
minTimestamp. The equivalent normal deposit would revert.Recommendation Complete the M-32 fix by validating that
oracle.maxTimestamp <= glvDeposit.updatedAtTime() + REQUEST_EXPIRATION_TIME - A GLV deposit request stores
-
M-33 Medium Edge data stream decimals are not validated Validation Pending
Description
EdgeDataStreamProvider.getOraclePriceusesedgeDataStreamTokenDecimalsKey(token)to scale prices, but does not validate this value before applying:uint256 tokenDecimals = dataStore.getUint(Keys.edgeDataStreamTokenDecimalsKey(token)); int256 floatMultiplier = int256(30) - int256(tokenDecimals) + report.expo; uint256 adjustedBidPrice = report.bid * 10 ** (uint256(floatMultiplier));If
edgeDataStreamTokenDecimalsKey(token)is misconfigured (for example0), output prices can be mis-scaled by orders of magnitude. In comparison,ChainlinkDataStreamProviderscales bydataStreamMultiplierKey(token)which explicitly reverts when unset:uint256 multiplier = dataStore.getUint(Keys.dataStreamMultiplierKey(token)); if (multiplier == 0) { revert Errors.EmptyDataStreamMultiplier(token); }This misconfiguration was found in live deployments for these tokens:
ZORA, KTA, XPL, ASTER, 0G, AVNT, LINEAe.g.ZORA (0xc5ff0eB026dB972F95DF3dfF04e697d8b660092a) Provider: ChainlinkDataStreamProvider (0xE1d5a068c5b75E0c7Ea1A9Fe8EA056f9356C6fFD) Oracle Type: 0x0000000000000000000000000000000000000000000000000000000000000000 Price Feed: (none) Data Stream ID: 0x000318ed7a378324925d265f0dd2908a3802241fed9a3317da12b53ec8ecc399 Data Stream Multiplier:1000000000000000000000000 Spread Reduction: 500000000000000000000000000000 Edge Stream ID: 0x569e75fc77c1a856f6daaf9e69d8a9566ca34aa47f9133711ce065a571af0cfd Edge Token Decimals: 0Recommendation
- In
EdgeDataStreamProvider.getOraclePrice, revert if token decimals are unset. - This issue should have been mitigated operationally because
TimelockConfig.signalSetEdgeDataStreamsets bothedgeDataStreamIdandedgeDataStreamTokenDecimalsin the same scheduled batch. This issue was only expected if: a. Timelock admin explicitly passes0foredgeDataStreamTokenDecimalsduringsignalSetEdgeDataStream(governance/operator error), or b. A controller writes directly toDataStoreand bypasses the intended timelock config path. Double check why the misconfiguration was allowed to slip through.
- In
-
M-34 Medium Missing Chainlink ref price feeds for tokens Configuration Pending
Description
Oracle.sol implements a defense-in-depth mechanism where, for non-Chainlink-on-chain providers (i.e.
ChainlinkDataStreamProvider,EdgeDataStreamProvider,GmOracleProvider), it cross-validates the provider's returned price against a Chainlink on-chain price feed:if (!provider.isChainlinkOnChainProvider()) { (bool hasRefPrice, uint256 refPrice) = ChainlinkPriceFeedUtils.getPriceFeedPrice(dataStore, token); if (hasRefPrice) { _validateRefPrice(token, validatedPrice.min, refPrice, maxRefPriceDeviationFactor); _validateRefPrice(token, validatedPrice.max, refPrice, maxRefPriceDeviationFactor); } }If a price feed is not configured (
priceFeedKey(token) == address(0)),getPriceFeedPricereturns(false, 0)and the validation is silently skipped. This means the primary oracle provider's price is accepted without any secondary sanity check. An on-chain configuration audit found 9 tokens that have Chainlink price feeds deployed and active on Arbitrum, but are not configured in GMX's DataStore:XRP, LTC, SHIB, STX, POL, SUI, SEI, APT, TON. Avalanche and Botanix were also audited. No additional tokens with available-but-unconfigured Chainlink feeds were found on those chains. The reference price check bounds how far the primary provider's price can deviate before the transaction reverts. Without it, a manipulated data stream, compromised keeper, or provider scaling bug would be accepted unconditionally.Recommendation
Configure
priceFeedKey,priceFeedMultiplierKey, andpriceFeedHeartbeatDurationKeyin the DataStore for all tokens where a Chainlink price feed exists on the deployed chain. -
M-35 Medium Account-unbound hashes allow digest collisions Signatures Pending
Description
Multichain actions use global replay protection keyed only by
digest, while many multichain struct hashes do not bindaccount. This lets two different users produce the samedigestfor the same payload shape._validateCallburnsdigestbefore signature validation:bytes32 digest = ECDSA.toTypedDataHash(domainSeparator, structHash); _validateDigest(digest); // consumed globally RelayUtils.validateSignature(domainSeparator, digest, relayParams.signature, account, "call");For multiple multichain actions, the struct hash omits
account, e.g.getBridgeOutStructHash:return keccak256( abi.encode( BRIDGE_OUT_TYPEHASH, params.token, params.amount, params.minAmountOut, params.provider, keccak256(abi.encodePacked(params.data)), _getRelayParamsHash(relayParams) // no account binding ) );Illustrative example:
- Bob submits signed
bridgeOutpayloadP. - Alice copies
P, signs as Alice, and submits first. - Alice tx succeeds, consumes
digest(P). - Bob tx reverts with
InvalidUserDigest. Affected actions: claimFundingFees,claimCollateral,claimAffiliateRewardsbridgeOutcreateDeposit,createWithdrawal,createShiftcreateGlvDeposit,createGlvWithdrawalsetTraderReferralCode,registerCode- non-subaccount
createOrder,updateOrder,cancelOrder,batchstruct variants useaccount = address(0)in hash derivation Not affected: updateOrderandcancelOrderEconomic feasibility:- Not economically feasible for most affected create-flows, because attacker usually must spend or lock own funds while outputs/refunds are routed by victim payload values.
- Economically feasible grief exists for
bridgeOutand claim actions, where attacker can execute the same payload shape against own balances, causing victim failure and forced re-sign/retry.
Recommendation
Include
accountin every multichain struct hash that currently omits it, including claims and referral actions. Keep the digest unique per user action. - Bob submits signed
-
M-36 Medium Disabled markets block accrued funds DoS Pending
Description
claimFundingFeesandclaimCollateralnow both end withvalidateMarketTokenBalanceafter transferring funds out of the market token contract. In both flows,marketis passed as anaddress, so Solidity resolves to the overload that first callsgetEnabledMarket. That helper reverts withDisabledMarketwhenever the market has been disabled.function claimFundingFees( DataStore dataStore, EventEmitter eventEmitter, address market, address token, address account, address receiver ) internal returns (uint256) { // ... decrement claimable amount and transfer tokens out ... MarketToken(payable(market)).transferOut(token, receiver, claimableAmount); // `market` is an address here, so this resolves to the address overload validateMarketTokenBalance(dataStore, market); } function validateMarketTokenBalance( DataStore dataStore, address _market ) public view { // this reverts if the market is disabled Market.Props memory market = getEnabledMarket(dataStore, _market); validateMarketTokenBalance(dataStore, market); } function getEnabledMarket(DataStore dataStore, address marketAddress) public view returns (Market.Props memory) { Market.Props memory market = MarketStoreUtils.get(dataStore, marketAddress); validateEnabledMarket(dataStore, market); return market; }Illustrative example:
- A market is disabled as an emergency response to oracle issues or operational instability.
- A user already has
claimableCollateralAmountor accrued funding fees recorded for that market from a prior decrease or settlement flow. - The user calls
claimCollateralorclaimFundingFees. - The transaction reverts with
DisabledMarket, so the user cannot withdraw the already-accrued claim while the market remains disabled. Impact: - Users can be frozen out of withdrawing already-accrued claimable collateral and funding fees.
Recommendation
Do not require a market to be enabled when validating post-claim token balances for passive withdrawals.
-
M-37 Medium Deposit reader overquotes capped positive impact Unexpected Behavior Pending
Description
ReaderDepositUtils.getDepositAmountOutForSingleTokendoes not model capped positive deposit price impact the same way as on-chain deposit execution. Execution only uses thetokenOutimpact pool:if (_params.priceImpactUsd > 0) { (int256 positiveImpactAmount, /* cappedDiffUsd */) = MarketUtils.applySwapImpactWithCap(...); mintAmount += MarketUtils.usdToMarketTokenAmount( positiveImpactAmount.toUint256() * _params.tokenOutPrice.max, poolValue, marketTokensSupply ); }If
tokenOutcannot cover the full positive impact, execution ignores the capped remainder. The reader does more. It falls back to thetokenInimpact pool and increasesamountIn:if (params.priceImpactUsd > 0) { (int256 positiveImpactAmount, uint256 cappedDiffUsd) = MarketUtils.getSwapImpactAmountWithCap(...); if (cappedDiffUsd != 0) { (int256 tokenInPriceImpactAmount, /* cappedDiffUsd */) = MarketUtils.getSwapImpactAmountWithCap(...); amountIn += tokenInPriceImpactAmount.toUint256(); } }This fallback exists in
SwapUtilsfor swaps, but not inExecuteDepositUtilsfor deposits. As a result,Reader.getDepositAmountOutcan return a mint amount that no real deposit can receive. Illustrative example:- A deposit earns
\$100of positive impact. - The
tokenOutimpact pool can only cover\$60. - The
tokenInimpact pool still has enough value to cover the remaining\$40. Reader.getDepositAmountOutquotes minting based on the full\$100.- Actual deposit execution only mints based on the
\$60available from thetokenOutside. Impact: - Frontends, integrations and users can set
minMarketTokensfrom an inflated quote and revert unexpectedly
Recommendation
Remove the
tokenInfallback fromReaderDepositUtilsso the reader only quotes value that deposit execution can actually mint - A deposit earns
-
M-38 Medium Relay Fee Atomic Swap Extraction Oracle Pending
Description
Relay fee handling exposes an atomic swap path before the wrapped action-specific logic executes.
_handleRelayFeepullsfeeTokenfrom the user and swaps it into WNT through GMX usingAtomicSwappricing under user-supplied atomic oracle params.if (relayParams.fee.feeSwapPath.length != 0) { _sendTokens(account, relayParams.fee.feeToken, address(contracts.orderVault), relayParams.fee.feeAmount, srcChainId); RelayUtils.swapFeeTokens(contracts, eventEmitter, oracle, relayParams.fee); }swapFeeTokensis a real protocol swap. It usesswapPricingType = AtomicSwap, and sends the WNT output to the relay router itself. After the wrapped action returns, the router pays only the actual relay fee and refunds the remaining WNT back to the user.uint256 residualFeeAmount = ERC20(contracts.wnt).balanceOf(address(this)); relayFee = GasUtils.payGelatoRelayFee(..., residualFeeAmount); residualFeeAmount -= relayFee; if (residualFeeAmount > 0) { _transferResidualFee(contracts.wnt, account, residualFeeAmount, srcChainId); }The crux is:
- the attacker chooses stale or mispriced atomic oracle prices to used for the fee conversion
- the protocol executes a real
feeToken -> WNTswap using those prices - the resulting WNT is refunded back to the attacker except for the true relay fee
- there is no general cap on relay fee swap size for this path, so if a favorable oracle mispricing occurs the attacker can scale the swapped notional to maximize extraction
removeSubaccountis just the cleanest same-chain trigger for this. It can be made into a semantic no-op becauseDataStore.removeAddressdoes not require the address to exist in the set first. If the chosensubaccountwas never added, the removal silently succeeds and the fee swap still executes. Impact: - exposes a same-chain standalone path to monetize attacker-chosen atomic pricing
- lets the attacker capture the favorable
feeToken / WNTconversion through the refund path - allows the attacker to exploit a favorable mispricing at the largest notional permitted by wallet balance and pool liquidity
- extracts value from GMX swap liquidity / impact pools while only paying the true relay fee
For example:
Attacker calls
removeSubaccountthat usesSOL -> USDC -> WETHas the relay fee path. Assume the true market is: SOL = $200WETH = $2,000So1,000 SOLshould be worth100 WETH. Now assume the attacker chooses atomic providers such that the fee swap uses:SOL min = $210WETH max = $1,980GMX computes output fromtokenInPrice.min / tokenOutPrice.max, so the protocol computes:amountOut ~= 1,000 * 210 / 1,980 = 106.06 WETHUsing current Arbitrum atomic fees for this path:SOL-USDCatomic swap fee:1.50%WETH-USDCatomic swap fee:2.25%After atomic fees:106.06 * (1 - 0.015) * (1 - 0.0225) ~= 102.08 WETHIf negative price impact consumes0.30 WETHand the actual relay fee is0.05 WETH, the attacker still receives:102.08 - 0.30 - 0.05 = 101.73 WETHAt the true market price,101.73 WETHis worth about$203,460. The attacker started with1,000 SOLworth$200,000, so the net profit is about$3,460. Practical constraints: Several factors reduce the likelihood of profitable exploitation under normal conditions:- atomic swap fees are charged on each hop of the relay fee path
- negative price impact further reduces output
- non-onchain atomic providers are checked against the configured Chainlink ref price when a ref feed exists
- data stream spread reduction can compress bid / ask divergence These constraints mean the issue may not be profitable during ordinary market conditions even though the extraction path exists. However, the risk is still real if a favorable oracle dislocation occurs. The Oct 10 move is a concrete example. At block 70101253, the submitted WAVAX oracle price was $11.99 while Trader Joe spot was $17.35, a deviation of -30.88%, exposing a path for profitable extraction.
Recommendation
Considering that relay swap is a quality-of-life feature, we would recommend removing the feature entirely. If removal is not feasible, considering implementing swap size caps and setting higher atomic swap fees
-
M-39 Medium Market-Order Sync Guard Fail-Open in DB Desync DoS Pending
Description
isSynced(keys)returnsfalsewhen DB log status is ~5 minutes behind chain head (diff > 300000 / blockInterval). Code:src/domain/log/logStatusService.ts.if (diff > 300000 / blockInterval) return false;DB desync mechanism:
- Pullers in
subscribeToLogs(...)continuously process logs. - Each polling cycle fetches logs, parses/processes them, writes entities/raw logs, and updates
logs_status.last_block_number. _processLogs(...)andupdateLogStatusIfSameBlock(...)run in the same DB transaction.- If the cycle fails/aborts/timeouts, transaction rolls back.
- Repeated rollbacks stall
last_block_numberwhile chain head advances, soisSynced=false. Moreover, is isSynced isfalsethis generates other vulnerabilities: - Missing
awaitin batch path (src/worker/executors/marketOrders.ts, ~303):
if (!logStatusService.isSynced(["orders", "oracle"])) return;isSynced()returnsPromise<boolean>and promise is truthy, so guard never blocks, so the current check would never trigger.- DoS of executors that DO stop when unsynced:
executeAdl,executeDeposits,executeWithdrawals,executeShifts,executeLimitSwapOrders,executeLimitStopOrders,executeLiquidations,executeGlvDeposits,executeGlvWithdrawals,executeGlvShifts,executeGlvRebalancer,executeRiskOracleUpdates. Potential impacts:
- Fail-open sync safety for market orders during desync.
- Inconsistent behavior: most executors pause, market orders continue.
- More stale/low-value candidate processing during lag windows.
- Possible extra gas/ops costs from failed or stale attempts.
- Higher latency/availability degradation risk under sustained desync + order flow.
Recommendation
- Add
awaitin batch market-order sync check (executeMarketOrders):
if (!(await logStatusService.isSynced(["orders", "oracle"]))) { return; }- Add one anti-desync safeguard pack (simple practical version):
- Break big work into small work: if a cycle receives too many logs, do smaller batches instead of trying everything in one heavy cycle.
- Cap queue growth: if incoming logs are faster than processing, limit the queue and apply backpressure so memory/DB do not collapse.
- Alert early: trigger alerts when
blocksBehindstarts rising fast (not only when it is already very high). - Auto-pause affected executors: if a key is clearly desynced, pause only jobs depending on that key to avoid wasting gas and noise.
- Auto-recovery checks: before re-enabling, verify lag is back under threshold and pullers are succeeding again.
- Pullers in
-
L-01 Low RateLimit Middleware To DoS Access Control Pending
Description
The
rateLimitmiddleware is global per process, not per user. It uses a single in-memory buffer for each route, so one noisy client can consume the entire quota and cause429responses for everyone else hitting the same instance. This makes it easy to DoS these endpoints for all users on that instance. The affected endpoints are:/performance/annualized,/performance/snapshots,/intract/task_1(GET/POST),/intract/task_2(GET/POST),/ui/batch_report, and/ui/feedback. Because these endpoints only return public data (performance analytics, intract task results) or telemetry ingestion (UI batch report/feedback), this is rated low severity, despite being a viable DoS vector.Recommendation
Stop using the global
rateLimitmiddleware for these public endpoints, since it enables a single client to exhaust the quota for everyone. Instead, enforce limits per user (or per API key) withrateLimitByUser, but harden it by keying on stable identities (API key/user ID) and trusted client IPs, and back it with shared storage (Redis/edge gateway) so limits apply across instances. -
L-02 Low
minAmountOutIgnored InBridgeOutLogical Error PendingDescription
LayerZeroProvider.prepareSendoverwrites the user‑providedminAmountOutwith Stargate’s quotedamountReceivedLD, effectively disabling user slippage protection for bridge‑out operations:// prepareSend sendParam = SendParam({ dstEid: _dstEid, to: Cast.toBytes32(receiver), amountLD: amount, minAmountLD: minAmountOut, extraOptions: bytes(""), composeMsg: bytes(""), oftCmd: "" }); (, , receipt) = stargate.quoteOFT(sendParam); sendParam.minAmountLD = receipt.amountReceivedLD;For example:
- User submits a signed bridge‑out with
minAmountOut = X. prepareSendreplacesminAmountLDwithreceipt.amountReceivedLD.- The call proceeds even if
receipt.amountReceivedLD < X, which is contrary to the signed intent. As a result, users (and controller flows) cannot enforce a minimum received amount on bridge‑out.
Recommendation
Consider removing this param or document the risk for users.
- User submits a signed bridge‑out with
-
L-03 Low Unbounded Time Range Queries Trust Assumptions Pending
Description
Multiple public endpoints accept user‑controlled
startTimestamp/endTimestampwithout validation of size, ordering, or maximum range. These values are forwarded to subsquid/subgraph queries, potentially causing expensive scans over large datasets./apyis especially susceptible because custom periods are explicitly not cached. This could lead to increased backend load and latency, enabling low‑effort DoS via repeated large‑range queries. Affected endpoints:GET /apy?startTimestamp=...&endTimestamp=...GET /intract/task_1?startTimestamp=...&endTimestamp=...POST /intract/task_1 with JSON body containing startTimestamp, endTimestampGET /intract/task_2?startTimestamp=...&endTimestamp=...POST /intract/task_2 with JSON body containing startTimestamp, endTimestampBasic example curl (large period):
curl "https://botanix-api.gmxinfra.io/apy?startTimestamp=1262304000000&endTimestamp=1769462400000" curl "https://botanix-api.gmxinfra.io/intract/task_2?address=0x0000000000000000000000000000000000000000&startTimestamp=2010-01-01T00:00:00Z&endTimestamp=2026-01-27T00:00:00Z"Recommendation
- Validate timestamps (must be numeric/ISO; reject invalid).
- Enforce maximum range (e.g., ≤ 90 days) and require
start <= end. - For
/apy, either cap custom ranges or cache them to avoid repeated expensive queries. - Return 400 for out‑of‑bounds requests.
-
L-04 Low Unhandled Input Parsing Errors Leading To 500 Best Practices Pending
Description
Multiple endpoints accept user‑controlled parameters without strict validation. Invalid values can trigger unhandled exceptions (e.g.,
BigNumber.fromon non‑numeric input, invalid address lookups,limit(NaN),to_timestamp(NaN)), resulting in 500 responses. These errors can be spammed to generate operational noise or load and become more serious if RBAC is compromised. Affected endpointsGET /admin/glv/price_loss— params:glv,from,amount- issue: invalid
amountor unknownglv/from
- issue: invalid
GET /admin/glv/shift— params:glv,from,to,amount,staticCall,secret- issue: invalid
amountor unknownglv/from/to
- issue: invalid
POST /admin/buyback/execute— params:buybackTokenSymbol,feeTokenSymbol- issue: invalid symbols
POST /admin/write_logs— params:logs[]- issue: missing/non-array logs
POST /admin/write_metrics— params:metrics[]- issue: missing/non-array metrics
POST /admin/db/vacuum/:table— param:table- issue: invalid table name → DB error
POST /admin/db/vacuum_full/:table— param:table- issue: invalid table name → DB error
POST /admin/markets/:key/pull_data— param:key- issue: unknown market address
POST /prices/candles/prefill— params:source,sourceUrl,tokenSymbol,period,limit- issue: invalid
source(no early return) or badsourceUrl
- issue: invalid
GET /signed_prices/search— params:blockNumber,createdAfter,createdBefore,after,before,limit,asc- issue: NaN values →
limit/to_timestamp
- issue: NaN values →
GET /apy— params:startTimestamp,endTimestamp- issue: NaN timestamps → downstream errors
GET /performance/annualized— param:address- issue: invalid address → GraphQL parse error
GET /performance/snapshots— param:addressissue: invalid address → GraphQL parse error
Recommendation
- Validate all numeric inputs with
Number.isFiniteand return 400 on invalid. - Validate addresses with
ethers.utils.getAddressand return 400 on invalid. - Guard
BigNumber.fromwith try/catch → return 400. - Require arrays (
logs,metrics) withArray.isArray. - Add missing
returnafter error responses. - Consider centralized validation middleware.
-
L-05 Low GLV Oracle Count Mismatch Causes Keeper Loss Gas Griefing Pending
Description
GLV deposit creation validates execution fees assuming
glvTokenPriceUsedis false, yielding anoraclePriceCountof2 + marketCount + swapsCount. However, keepers typically provide a GLV oracle price during execution, resulting inglvTokenPriceUsedbeing true and anoraclePriceCountof4 + swapsCount. For GLVs with exactly 1 market, the creation estimate (3) is lower than the execution value (4).// Creation - always assumes false uint256 oraclePriceCount = GasUtils.estimateGlvDepositOraclePriceCount( marketCount, swapPathLength, false );// Execution - uses actual value cache.oraclePriceCount = GasUtils.estimateGlvDepositOraclePriceCount( cache.marketCount, swapPathLength, cache.glvTokenPriceUsed // true when keeper provides GLV price ); GasUtils.payExecutionFee(..., cache.oraclePriceCount, ...);On every execution of a single-market GLV deposit, keeper payment is calculated using
oraclePriceCountof 4 but capped to the execution fee collected for 3. The keeper losesEXECUTION_GAS_FEE_PER_ORACLE_PRICE(250,000 gas) worth of compensation on every single-market GLV deposit execution, regardless of success or failure.Recommendation
In
GlvDepositUtils.createGlvDeposit, use the maximum of both oracle price count calculations during fee validation:uint256 oraclePriceCount = GasUtils.estimateGlvDepositOraclePriceCount( marketCount, params.addresses.longTokenSwapPath.length + params.addresses.shortTokenSwapPath.length, false // <-- This should use max of both ); GasUtils.validateExecutionFee(dataStore, estimatedGasLimit, params.executionFee, oraclePriceCount); -
L-06 Low Zero-Division Can Halt GLV Rebalancer Unexpected Behavior Pending
Description
The rebalancer divides by zero in multiple places.
capShiftSizeByMaxAmountsdivides bycurrentFromShortUsdandcurrentFromTotalUsd. If a single short pool is empty, the division by 0 causes the rebalancer to revert and stop rebalancing for all markets. Similarly,getTargetPoolSizedivides bytargetUtilization(0 when all markets have zero reserved OI), andgetProportionalShiftSizeUsddivides by total pool USD (0 when both pools are empty).const ratio = currentFromLongUsd.mul(FLOAT).div(currentFromShortUsd); const currentFromTotalUsd = currentFromLongUsd.add(currentFromShortUsd); const availableLongUsd = shiftUsd.mul(currentFromLongUsd.mul(FLOAT).div(currentFromTotalUsd)).div(FLOAT); const availableShortUsd = shiftUsd.mul(currentFromShortUsd.mul(FLOAT).div(currentFromTotalUsd)).div(FLOAT);Recommendation
Add guards before each division. If inputs are 0, return 0 or skip the cap calculation to keep the rebalancer running.
-
L-07 Low Missing Spread Validation For Impact Factor Validation Pending
Description
The risk oracle executor validates that
positivePositionImpactFactoris strictly less thannegativePositionImpactFactor, but does not enforce any minimum spread between these values.PricingUtils.solexplicitly warns: "This risk will also be present if the positive and negative price impact values are similar."if (positiveValue[allowEqual ? "gt" : "gte"](negativeValue)) { invalidUpdates.push({ positive, negative }); continue; }Values like positive = 0.00000099 and negative = 0.00000100 pass validation despite being nearly identical. This weakens the manipulation disincentive since traders rebalancing the pool receive almost the same rebate as the penalty for imbalancing it.
Recommendation
Add a configurable minimum ratio check, requiring positive to be at most some percentage of negative (e.g. 50%).
-
L-08 Low Sync Lacks Parameter/baseKey Binding Validation Pending
Description
In ConfigSyncer.sol, the
syncfunction trusts theadditionalData baseKeyand does not verify that it matches the parameter string used to fetch the oracle update. The keeper enforces this mapping off‑chain, but the on‑chain contract does not. If a bad oracle update is emitted, a direct sync can apply a differentbaseKeythan the parameter label implies.IRiskOracle.RiskParameterUpdate memory u = IRiskOracle(riskOracle).getLatestUpdateByParameterAndMarket(parameter, market); (bytes32 baseKey, bytes memory data) = abi.decode(u.additionalData, (bytes32, bytes)); _validateMarketInData(baseKey, market, data); _validateKey(baseKey); config.setUint(baseKey, data, Cast.bytesToUint256(u.newValue));Example scenario:
- parameter =
maxOpenInterestForLongs - additionalData =
(baseKey = POSITION_IMPACT_FACTOR, data = abi.encode(market, true)) - parameter does not match baseKey!
- Result: position impact factor set to a very large value, enabling impact pool drain (see comments MarketUtils.sol#L898)
Recommendation
Bind
parameterto an expectedbaseKeyand data format on‑chain, and revert if the decoded baseKey or data schema does not match the parameter. This preserves the off‑chain intent even if sync is called directly. - parameter =
-
L-09 Low Public Log Ingestion Endpoints Best Practices Pending
Description
The public endpoints:
/ui/batch_reportand/ui/feedback(also mounted under/report/ui/*) have rate limiting relies on a per-user hash. Supposing it's not posisble to bypas the rate limits(although at the moment it's as explained in anothre issue), the rate limit still allows users to send a bast amount of logs:/ui/batch_report: 5 requests per 5 seconds per user ⇒ 60 requests/minute. Each request allows up to 100 items and 300kb body size ⇒ up to 6,000 items/minute and ~18 MB/minute per user./ui/feedback: 10 requests per 60 seconds per user ⇒ 10 requests/minute. 100kb body size ⇒ up to ~1 MB/minute per user. Therefore attackers can spam logs/metrics, skew dashboards, trigger alerts, and increase monitoring costs.
Recommendation
Fix the per user rate limit functionality and implement stronger rate limits in these endpoints.
-
L-10 Low Unbounded IP Set Access Control Pending
Description
uniqueUsersis a global in-memorySetthat stores every distinctreq.ipobserved byloggerMiddlewareEnd. There is no eviction or TTL, so the set grows for the lifetime of the process. Insrc/app.ts,trust proxyis enabled (server.set("trust proxy", true)), which makes Express accept the client IP fromX-Forwarded-Forrather than the direct socket IP. If the service is reachable without a strictly configured trusted proxy list, a client can spoofX-Forwarded-Forand generate an unbounded stream of unique IPs, causing unbounded growth of the set and distorting the “unique users” metric.Recommendation
Replace the
Setwith an LRU/TTL cache (or an approximate counter such as HyperLogLog), and configuretrust proxywith a strict allow-list of trusted proxies. If proxy trust cannot be locked down, validate or ignoreX-Forwarded-Forso untrusted clients cannot spoofreq.ip. -
L-11 Low Validation Bug In Admin Metrics Ingestion Pending
Description
/admin/write_metricsaccepts an array of metric objects and validates each entry. The validation intends to require avaluefor all methods exceptincrement, but the check is implemented asif (key !== "increment" && value === undefined)instead of checking themethod. This means thevaluerequirement is tied to the metric name rather than the metric method. As a result, a metric with methodgauge,histogram, ordistributioncan omitvalueif its key happens to be"increment", and a method"increment"metric can still be forced to provide a value if the key is not"increment". This can allow invalid or inconsistent metrics to be accepted and forwarded to Datadog, which may skew telemetry, cause confusing dashboards, or trigger downstream errors depending on how the backend handles missing values. While RBAC-protected, it is still a correctness and integrity issue for admin-triggered monitoring.Recommendation
Validate based on
method(notkey) and enforcevalueforgauge,histogram, anddistribution. -
L-12 Low Empty Funding Data Silently Skips Updates Unexpected Behavior Pending
Description
getNextFundingRateassumes there is at least one aggregated funding sample per market after exchange filtering. IfaggFundingRatesis empty,getMedianreturnsundefined, which is then used inMath.absandMath.max. This producesNaNtargets and diffs, and the update check silently falls through without settingshouldUpdate. The result is missed funding updates with confusing logs, rather than a clear error or fallback. Scenarios that produce an emptyaggFundingRatesinclude:- exchange filters that exclude all sources ((e.g., config uses
binancebut ingested rows are labeledbinance_futures, so the filter drops everything) - or a funding data ingestion outage.
aggFundingRates = [...aggFundingRates].sort((a, b) => b.avgRate - a.avgRate).slice(0, 3); const aggAvgRate = getMedian(aggFundingRates.map((item) => item.avgRate))!; ... const absAvgRate = Math.abs(aggRate); ... if (Math.abs(diff) > config.updateThresholdAbs || (diffPercent && diffPercent > config.updateThresholdPercent)) { shouldUpdate = config.updatesEnabled; }Impact
- Funding updates can be skipped for a market even when they should change.
- The failure is silent, making operational detection harder.
- Prolonged stale parameters can lead to mispriced funding during volatile periods.
Recommendation
Guard against empty
aggFundingRatesand log a clear warning, or fallback to a safe default. A minimal fix is to returnshouldUpdate: falsewith an explicit log whenaggFundingRates.length === 0before computing medians. - exchange filters that exclude all sources ((e.g., config uses
-
L-13 Low Tier Change Could Cause Reverts For Fee Workflow Logical Error Pending
Description
The tier query in getAffiliatesTierQuery (feeDistributionService.ts line 231) has no time filter — it queries current on-chain tier assignments: affiliates(where: { tierId_in: ["2", "1"] }) Both distribute and depositReferralRewards call getDistributionData(), which runs this query independently. Since tier assignments can change on-chain at any time, if an affiliate's tier is updated between the two steps, the recalculation in depositReferralRewards will produce different totals than what distribute stored on-chain. Validation checks fail:
- totalEsGmxAmount !== esGmxAmount (feeDistributionService.ts line 958) → revert
- totalWntAmount !== wntAmount (feeDistributionService.ts line 983) → revert
Recommendation
Consider snapshotting the tier data during the distribute step or modify subgraph to consider time period for tier returns.
-
L-14 Low Over-Broad OFT Trigger For BRIDGED_GMX_RECEIVED Configuration Pending
Description
The workflow listens for OFTReceived on the GMX adapter and routes to bridgedGmxReceived. This can trigger on any qualifying OFT receipt matching the filter, not strictly the fee-distribution bridge hop. A third party may be able to cause extra trigger executions by sending bridge traffic that satisfies the filter. Impact: If CRE charges per trigger/run, this can become a meaningful cost/griefing vector. If trigger cost is negligible and handler exits cheaply, impact is lower.
Recommendation
Tighten trigger constraints to distribution-specific contex.
-
L-15 Low OrderUpdated Drops autoCancel Sync Warning Pending
Description
The on-chain
OrderUpdatedevent includes theautoCancelflag, andOrderHandler.updateOrderupdates the on-chain auto-cancel list. However, the keeper’sprocessOrderUpdatedpath does not persistautoCancelin the database. This leaves the DB out of sync with on-chain order state. The keeper later uses DBauto_cancelingetAutoCancelOrdersByPositionKeyto estimate gas for full-close executions. A stale value can cause gas limit misestimation and execution delays.await orderModel.updateOrder(trx, key, { ... ... // does not update autoCancel });Recommendation
Persist
autoCancelfromOrderUpdatedinto the DB, and optionally clearskipReasonwhenskipis reset. -
L-16 Low Docker Hardening Recommendations Best Practices Pending
Description
The following critical vulnerabilities were identified in the container and infrastructure configuration of the application:
- Global SSL Validation Disabled
The
docker:runscript inpackage.jsonexplicitly sets the environment variableNODE_TLS_REJECT_UNAUTHORIZED=0. Impact: This would disable SSL certificate verification for the Node.js process. The application becomes highly susceptible to Man-in-the-Middle (MITM) attacks, as it will trust any server certificate, including malicious ones, for all outgoing HTTPS requests (e.g., to RPC nodes or external APIs). - Container Runs as Root
The
Dockerfilefails to switch to a non-privileged user (e.g.,USER node) and runs the application asroot. Impact: In the event of a Remote Code Execution (RCE) compromise, the attacker gains root privileges inside the container. This significantly lowers the barrier for container escapes, privilege escalation, and lateral movement within the underlying infrastructure. - Weak Database Security
The
docker-compose.ymlconfiguration uses the default, weak password (POSTGRES_PASSWORD: postgres) and exposes the database port (5432) directly to the host network. Impact: An attacker with network access to the host can easily authenticate to the database. Even if the port is not exposed effectively, if an attacker gains access to the container network, the weak credentials provide immediate data access. - Production Image Bloat & Attack Surface
The
Dockerfileinstalls powerful system and debugging tools—includinggdb,strace,vim,curl,net-tools—and leaves them in the final production image. Impact: These tools serve as "living off the land" binaries (LOLBins). A threat actor who gains initial access can use them to inspect memory, modify files, and tunnel traffic, greatly simplifying post-exploitation activities and reconnaissance.
Recommendation
To harden the Docker and infrastructure configuration, implement the following changes:
- Enable SSL Validation:
- Immediate Action: Remove
NODE_TLS_REJECT_UNAUTHORIZED=0frompackage.json. - If self-signed certificates are required for internal services, add the CA certificate to the container's trust store instead of disabling validation globally.
- Immediate Action: Remove
- Run as Non-Privileged User:
- Modify the
Dockerfileto includeUSER nodeafter the installation and build steps are complete. This ensures the application process runs with the limited permissions of thenodeuser.
- Modify the
- Secure Database Configuration:
- Password: Use Docker secrets or environment variables to inject credentials. Do not hardcode passwords in
docker-compose.yml. At a minimum, ensurePOSTGRES_PASSWORDis set to a long, complex, and random string. - Port Exposure: Remove the
portsmapping (5432:5432) in production configurations. The application interface should communicate with the database solely via the internal Docker network.
- Password: Use Docker secrets or environment variables to inject credentials. Do not hardcode passwords in
- Minimize Container Image:
- Use multi-stage builds in the
Dockerfile. Perform installation and building in abuilderstage, then copy only the necessary artifacts (e.g.,dist/,package.json,productionnode_modules) to a finalrunnerstage. - Avoid installing unnecessary tools (
vim,gdb,strace) in the final stage. Consider using minimal base images likenode:alpineorgcr.io/distroless/nodejsto further reduce the attack surface.
- Use multi-stage builds in the
- Global SSL Validation Disabled
The
-
L-17 Low Keeper ADL DoS If factor == max factor Validation Pending
Description
The keeper thinks that ADL is required if the
pnlToPoolFactor >= maxPnlFactorForAdlwhile on the contract side ADL is only executed ifpnlToPoolFactor > maxPnlFactorForAdl. This may lead to a DoS, wasted gas and an alarming revert.Recommendation
Consider to adjust the keeper code to only try to ADL a position if
pnlToPoolFactor > maxPnlFactorForAdl. -
L-18 Low Lack of Slippage Sanity Checks in Swap Execution Frontrunning Pending
Description
If a user submits an order with
minOutputAmount = 0(or a very low value due to UI bugs, bot errors, or misunderstandings), the keeper will execute it even if the realized price is catastrophic (e.g., -90% due to a massive pool imbalance caused by a sandwich attack). The functiongetSwapPathAmountOutfromsrc/domain/swap/swapUtils.tsis the primary simulation engine. It returnsnull(abort execution) only if the calculation is strictly less than the user's defined minimum. It does not check if the price impact is unreasonably high purely based on pool state modification. Then, insrc/domain/pricing/pricingUtils.ts, the pricing logic correctly implements an exponential penalty for unbalancing pools. This mechanism is what attackers manipulate to create the slippage could destroy user value. Attack Scenario:- Prerequisite: A user submits a Swap Order (e.g., USDC -> ETH) with
minOutputAmount = 0(or significantly below market value).
- Reconnaissance: Attacker monitors the pending orders pool (or mempool) for GMX Swap orders with
minOutputAmountset to 0. - Front-run:
- Attacker sees the target order.
- Attacker executes a massive swap (USDC -> ETH) immediately before the keeper executes the user's order.
- Effect: The USDC/ETH pool becomes severely unbalanced (Excess of USDC, scarcity of ETH). The "Price Impact" for buying ETH shoots up (e.g., a 50% penalty).
- Victim Execution:
- The Keeper processes the user's order.
- It calculates
amountOutingetSwapPathAmountOut. - Due to the pool imbalance created by the attacker,
amountOutincludes a massive negative price impact. - Since
amountOut > minOutputAmount (0), the Keeper proceeds and submits the transaction. - The user swaps 1000 USDC but gets only $500 worth of ETH. The rest is absorbed by the pool as value due to the penalty.
- Back-run:
- Attacker executes the reverse swap (ETH -> USDC).
- Since the pool now has even more USDC (from the victim's bad trade), the attacker extracts a profit compared to their initial state.
Recommendation
Define a constant
MAX_AUTO_SLIPPAGE_BPS(e.g., 1000 BPS = 10%). Then, ingetSwapPathAmountOut, calculate the theoretical "fair" amount out based on oracle price (as if impact was 0). Then, compare the calculatedamountOutwith the fair amount. Finally, if the deviation exceeds the safety threshold, log a warning and skip execution, even ifamountOut > minOutputAmount. A different option would be to use frontrun resistant RPC if keeper findsminOutputAmountis too low. they can - Prerequisite: A user submits a Swap Order (e.g., USDC -> ETH) with
-
L-19 Low Incorrect priority config for shift execution Configuration Pending
Description
Normal shift transactions currently read the GLV shift priority key. This can cause suboptimal queue ordering when
shiftExecutionPriorityandglvShiftExecutionPrioritydiffer, leading to minor scheduling/latency inconsistencies under load.Recommendation
In shiftService.ts, change:
keeperConfig.get("glvShiftExecutionPriority", 0)tokeeperConfig.get("shiftExecutionPriority", 0). -
L-20 Low Missing Swap Validation In Keeper Validation Pending
Description
Keeper frozen limit-swap execution validates mainly
amountOut >= minOutputAmountoff-chain, but does not mirror several on-chain swap validations. As a result keeper attempt frozen swap orders that are guaranteed to revert on-chain, consuming execution bandwidth and gas over time. Examples of missing off-chain checks (performed on-chain):- validatePoolAmount
- validateReserve
- validateMaxPnl
- etc.
Recommendation
Keeper should perform full parity validation for frozen swap orders before sending transactions.
-
L-21 Low Protocol-Unfavorable Rounding Review Rounding Pending
Description
- In
payForCost, when remaining costs are paid usingsecondaryOutputToken, required token amount is computed with floor division:
remainingCostInSecondaryOutputToken = remainingCostInOutputToken * collateralTokenPrice.min / secondaryOutputTokenPrice.min.This can round required payment down. In edge cases, the required secondary amount becomes 0 even though a positive USD cost remains, and
remainingCostUsdis later set to 0, marking fees as fully paid. DecreasePositionCollateralUtils.sol:611- Borrowing fee tokenization uses floor division:
borrowingFees.borrowingFeeAmount = borrowingFeeUsd / collateralTokenPrice.minTokenized borrowing fees can be slightly lower than intended USD-equivalent fees. PositionPricingUtils.sol:477
- UI fee tokenization uses floor division:
uiFees.uiFeeAmount = Precision.applyFactor(sizeDeltaUsd, uiFees.uiFeeReceiverFactor) / collateralTokenPrice.minUI fee amounts can be slightly under-collected in token terms. PositionPricingUtils.sol:526
- Position fee tokenization uses floor division:
fees.positionFeeAmount = Precision.applyFactor(sizeDeltaUsd, fees.positionFeeFactor) / collateralTokenPrice.minProtocol position fees can be slightly under-collected in token terms. PositionPricingUtils.sol:568
Recommendation
Consider round-up conversion or accept/document this as intentional dust behavior.
- In
-
L-22 Low Unsigned prices control median in GMOracle Oracle Pending
Description
GmOracleProvider.getOraclePricedecodes areportfrom caller-supplieddataand derivessignersfromreport.signerInfo. Both the sorting check and the signature validation iterate onlysigners.lengthtimes, but the median price computation operates over the full price arrays. There is no check that these array lengths equalsigners.length.// Sorting check — bounded by signers.length for (uint256 i = 0; i < signers.length; i++) { if (i == 0) { continue; } if (report.minPrices[i - 1] > report.minPrices[i]) { revert ...; } if (report.maxPrices[i - 1] > report.maxPrices[i]) { revert ...; } } // Signature validation — bounded by signers.length for (uint256 i = 0; i < signers.length; i++) { uint256 minPrice = report.minPrices[i]; uint256 maxPrice = report.maxPrices[i]; GmOracleUtils.validateSigner(salt, report, token, minPrice, maxPrice, ...); } // Median — uses FULL array length uint256 medianMinPrice = Array.getMedian(report.minPrices) * (10 ** report.precision); uint256 medianMaxPrice = Array.getMedian(report.maxPrices) * (10 ** report.precision);Array.getMedianpicks the middle element of the array it receives. Since the sorting check only covers indices[0, signers.length), elements beyond that are completely unvalidated. Example Scenario: AssumeMIN_ORACLE_SIGNERS = 3and the three legitimate signers report valid min prices[100, 200, 300]. A malicious keeper constructs a report with:signerInfoencoding 3 signerssignatures: 3 valid signatures (+ any padding)minPrices:[100, 200, 300, 999999, 999999, 999999, 999999]Result:
- Sorting check passes — only validates
[100, 200, 300]. - Signature check passes — only validates first 3 entries against valid signers.
getMedianpicksarr[7/2]=arr[3]= 999999 (attacker-controlled). The purpose of requiring N oracle signers is to prevent any single entity (including the keeper) from dictating prices. This vulnerability allows a keeper to fully control the oracle price with only the minimum required valid signatures by padding the price arrays with arbitrary unsigned values.
Recommendation
Add an array length check at the start of
getOraclePrice, after deriving signers:if (report.minPrices.length != signers.length || report.maxPrices.length != signers.length || report.signatures.length != signers.length) { revert Errors.GmInvalidArrayLengths( signers.length, report.minPrices.length, report.maxPrices.length, report.signatures.length ); } -
L-23 Low Subaccounts can self-deal fee-routing fields Validation Pending
Description
The codebase already treats subaccounts as a distinct trust boundary and adds explicit protections where a delegated subaccount could misuse the main account's funds. For example, relay fee swaps are subject to a dedicated subaccount cap because a malicious subaccount could create a value-extracting swap against the main account:
if (relayParams.fee.feeSwapPath.length != 0) { if (isSubaccount) { // a malicious subaccount could create a large swap with a negative price impact // and then execute a personal swap with a positive price impact // to mitigate this, we limit the max relay fee swap size for subaccounts uint256 maxRelayFeeSwapUsd = contracts.dataStore.getUint(Keys.MAX_RELAY_FEE_SWAP_USD_FOR_SUBACCOUNT); ... } }However, subaccount order validation only constrains
receiverandcancellationReceiver:function validateCreateOrderParams( address account, IBaseOrderUtils.CreateOrderParams calldata params ) external pure { if (params.addresses.receiver != account) { revert Errors.InvalidReceiverForSubaccountOrder(params.addresses.receiver, account); } if (params.addresses.cancellationReceiver != address(0) && params.addresses.cancellationReceiver != account) { revert Errors.InvalidCancellationReceiverForSubaccountOrder(params.addresses.cancellationReceiver, account); } // `uiFeeReceiver` and `referralCode` are left unconstrained }The remaining fee-routing fields (uiFeeReceiver and referralCode) are then used as-is when the order is created. This lets a delegated subaccount redirect economic value from the main account's trades to itself. Example:
- Alice authorizes a trading bot as a subaccount.
- The bot submits Alice's first order with
referralCodeset to a code it owns anduiFeeReceiverset to its own address. - The order still passes subaccount validation because only
receiverandcancellationReceiverare checked. - Alice's order executes normally, but part of the fee flow is credited to the bot's
uiFeeReceiver. - Since
setTraderReferralCodeonly sets the code when the trader has none, the bot can also permanently bind Alice's referral relationship to its own affiliate code on the first delegated order.
Recommendation
Extend subaccount-specific validation to cover all value-bearing fee-routing fields, not just token receivers.
-
L-24 Low Equal max impact caps remove safety margin Configuration Pending
Description
The Arbitrum
SOL [SOL-SOL]market is configured with equal max positive and max negative position impact caps.SOL [SOL-SOL] (0xf22CFFA7B4174554FF9dBf7B5A8c01FaaDceA722) maxPosImpact: +=0.50% -=0.50%The codebase and README both rely on
max positive < max negativeto keep capped round trips unprofitable. On increase, positive position impact is capped bycapPositiveImpactUsdByMaxPositionImpact:cache.priceImpactUsd = MarketUtils.capPositiveImpactUsdByMaxPositionImpact( params.contracts.dataStore, params.market.marketToken, cache.priceImpactUsd, params.order.sizeDeltaUsd() );On decrease, negative total impact is capped to the configured max negative value, with the excess moved into
priceImpactDiffUsd:if (values.totalImpactUsd < minPriceImpactUsd) { values.priceImpactDiffUsd = (minPriceImpactUsd - values.totalImpactUsd).toUint256(); values.totalImpactUsd = minPriceImpactUsd; }This means a trader can open a balance-improving position and immediately close it after the market remains skewed, realizing up to the capped positive impact on entry while only paying up to the capped negative impact on exit. When the two caps are equal, the protocol loses the built-in price-impact spread that is meant to make this round trip structurally lossmaking. Illustrative example:
- entry would earn
+0.9%uncapped impact, but is capped to+0.5% - exit would pay
-1.4%uncapped impact, but is capped to-0.5% - net capped price impact becomes
0%before fees Impact: - removes the intended margin of safety against open-then-close impact farming
- makes profitability depend only on fees, discounts, rebates, or future config changes
- weakens the configuration invariant explicitly described in the protocol documentation
Under the current
SOL [SOL-SOL]fee schedule, this does not appear immediately profitable on price impact alone because position fees still apply. The issue is that the market is configured exactly on the unsafe boundary rather than below it.
Recommendation
Set
positiveMaxPositionImpactFactorstrictly belownegativeMaxPositionImpactFactorforSOL [SOL-SOL]. - entry would earn
-
L-25 Low TWAP tranche splits strand vault dust Rounding Pending
Description
createTwapOrdersplits the total collateral and execution fee acrosstwapCountorders using integer division:params.numbers.initialCollateralDeltaAmount = initialCollateralDeltaAmountTwap / twapCount; ... params.numbers.executionFee = wntAmount / twapCount;When either total is not exactly divisible by
twapCount, the remainder is not assigned to any child order. The individual orders are created using only the floored per-tranche amounts, and there is no refund or residual-accounting step for the leftover units. This is visible in thetest_replay_TWAP_EQ_03replay: the TWAP path and the equivalent individual path end with identicalsizeInUsdandsizeInTokens, but the TWAP path reports2fewer units of collateral because the split rounds down during tranche creation. As a result, small dust amounts can remain inOrderVaultafter TWAP order creation. Since that remainder is not tied to any order, it becomes unattributed balance that can accumulate over time. Impact:- users may pay slightly more total collateral or execution fee than the created TWAP orders actually consume
- leftover dust can build up in
OrderVaultacross repeated TWAP usage
Recommendation
Track and handle the TWAP split remainder explicitly. A simple fix is to assign the remainder to the final tranche.
-
L-26 Low SUI and WAVAX retain impact-pool drips Configuration Pending
Description
The Arbitrum
SUI [WETH-USDC]market and the AvalancheWAVAX [WAVAX-USDC]market are configured with nonzeropositionImpactPoolDistributionRatevalues even though the surrounding peer markets use0. Both stand out as exceptions in their respective market sets and may have been left behind after the broader position impact pool distribution settings were disabled for other markets.// Arbitrum Chain SUI [WETH-USDC] (0x6Ecf2133E2C9751cAAdCb6958b9654baE198a797) positionImpactPoolRate/day: 1082.999999 minPositionImpactPoolAmount: 6986000000000 // Avalanche Chain WAVAX [WAVAX-USDC] (0x913C1F46b48b3eD35E7dc3Cf754d4ae8499F31CF) positionImpactPoolRate/day: 143.424000 minPositionImpactPoolAmount: 141000000000000000000distributePositionImpactPoolis called on deposits, withdrawals, and order execution, so any excess SUI or WAVAX in the position impact pool is gradually released back into pool value instead of remaining available to fund future positive position impact. This changes those markets' behavior relative to peers:- positive position impact capacity on SUI and WAVAX decays over time
- GM holders on those markets receive the excess impact-pool value sooner than on zero-rate markets
- traders on those markets face a different realized price impact profile than traders on otherwise similar markets This is not a direct exploit, but it is a live economic asymmetry. If the rates were left enabled unintentionally, SUI and WAVAX users are operating under different rebate and pool-value dynamics than the rest of the market set.
Recommendation
Set
positionImpactPoolDistributionRatefor SUI and WAVAX to0if the intention is to align them with the other Arbitrum and Avalanche markets. Otherwise, document the exceptions explicitly so the different position impact behavior is intentional and reviewable. -
L-27 Low GLV rebalancer can abort entire rebalance cycle Logical Error Pending
Description
The rebalancer intentionally filters out markets with unset reserve factors (0) to avoid using newly listed / not-ready markets (glvRebalancer.ts (line 65)). However, context construction still resolves all glv.markets against the filtered market list (glvRebalancerUtils.ts (line 1133)). If any filtered market is missing, getMarketByAddress throws (marketUtils.ts (line 133)). As a result, a single not-ready market can cause the GLV rebalance execution to fail before pair selection, instead of being ignored. This creates false negatives where valid rebalances among eligible markets are skipped (e.g., A <-> B should rebalance while new market C is ignored).
Recommendation
Consider making market eligibility handling consistent between filtering and context creation: Build rebalance context from only eligible GLV markets (intersection of glv.markets and filtered markets), or Keep all markets in context but mark ineligible markets and exclude them from pairing without throwing.
-
L-28 Low minUtililization not enforced in GLV rebalancer Configuration Pending
Description
minUtililization is defined as a configurable market threshold in glvs.ts (line 54), and its documented intent is to restrict when a market is eligible as a toMarket. However, destination-market selection in getToMarkets (glvRebalancerUtils.ts (line 740)) does not apply any utilization >= minUtililization check. Current filtering only applies disabled flags, reserve-factor readiness, and maxPoolExposureFactor (glvRebalancerUtils.ts (line 753)). This means markets below configured minimum utilization can still be chosen as shift destinations.
Recommendation
First check if
minUtililizationis something you want or is just dead code right now, if its required, consider adding filter based on that as well, otherwise remove the dead code. -
I-01 Informational Outdated Comments In
updateAdlStateDocumentation PendingDescription
The comments in
updateAdlStatestate that theisAdlEnabledflag is used to "avoid having to repeatedly validate whether auto-deleveraging is required." However, the actual implementation inexecuteAdlalways re-validates the PnL factor by callingisPnlFactorExceededregardless of the flag state. The flag only provides early revert whenisAdlEnabledis false, not gas savings on successful ADL execution paths.Recommendation
Update comments to accurately reflect that the flag serves as an early revert mechanism and public coordination signal, not a gas optimization for successful ADL executions.
-
I-02 Informational GMX Signed Prices Use maxPrice For minPriceFull Logical Error Pending
Description
For GMX signed price derivation,
minPriceFullis derived fromp.maxPriceinstead ofp.minPrice, collapsing the min/max range and biasing price bands upward. This can skew trigger checks and any logic that relies on accurate min/max bounds (limit/stop execution, PnL/ADL thresholds). Refs:pricesFromGmx.ts (line 118),pricesFromGmx.ts (line 209).Recommendation
Consider deriving
minPriceFullfromp.minPrice. -
I-03 Informational Redundant Index Price Fetch In Withdrawal Gas Optimization Pending
Description
_getOutputAmountscallsparams.oracle.getPrimaryPricefor the index token even thoughprices.indexTokenPriceis already available fromgetMarketPrices. This duplicates the oracle read and introduces an unnecessary dependency on a second call.Recommendation
Use the existing
prices.indexTokenPricewhen callinggetPoolValueInfoto keep price usage consistent and reduce redundant oracle reads. -
I-04 Informational Unsanitized Parameters Used In SQL Queries Best Practices Pending
Description
Multiple locations use string interpolation/concatenation to inject variables into SQL queries instead of parameterized queries, creating SQL injection surface even when current values are from internal sources. String interpolation bypasses driver parameterization. Variables from configs/internal state can become attack vectors through supply-chain compromise, config manipulation, env injection, compromised admin accounts, or future refactoring. Affected code locations:
admin.ts:510-527-POST /db/vacuum/:table,/db/vacuum_full/:tableInjected:req.params.table(admin URL param, requires db.write RBAC)Pattern:knex.raw(\VACUUM ??`, [table])` - no validationsignedPriceModel.ts:330-410-getDataForCandlesPerMinute()Injected: Token addresses concatenated into IN clausePattern:tokenAddresses.map((a) => \'${a}'`).join(",")in WHERE Source: Config viatokensConfig.getTokens()`lockModel.ts:23-40-tryAcquireLock()Injected:ttlSecondsinto INTERVALPattern:INTERVAL '\${ttlSeconds} seconds'Source: Function paramdb/index.ts:38-45-pool.afterCreateInjected:statementTimeout,idleInTransactionSessionTimeoutPattern:SET statement_timeout = '\${statementTimeout}ms'Source: Config valuesdb/index.ts:344-getStuckQueries()Injected:thresholdinto INTERVALPattern:NOW() - INTERVAL '\${threshold} seconds'Source: Internal monitoring paramcandleModel.ts:175-235-createOrUpdateCandles()Injected: Query objects joined as stringsPattern:rawQueries.map(q => q.toString()).join(";")Source: Internal candle datapositionModel.ts:186-205-updatePositions()Injected: Position update queriesPattern:sql.push(query.toString()); trx.raw(sql.join(";"))Source: Internal position datamarketModel.ts:175-190-updateMarkets()Injected: CASE expression fragmentsPattern:trx.raw(\CASE address ${cases} ELSE...`)`Source: Internal market datadb/index.ts:110-120-testReset()Injected: Table names in DELETEPattern:tables.map(t => \DELETE FROM ${t}`)`db/index.ts:126-134-testCreateTemplateDatabase()Injected: Database name in DDLPattern:DROP/CREATE DATABASE \${templateName}db/index.ts:148-179-testSetup()/testTeardown()Injected: Database names in DDLPattern:DROP/CREATE DATABASE \${database}
Recommendation
Use parameterized queries:
?for values,??for identifiers (with whitelist),knex.raw('SQL', [params]). For IN clauses:knex.raw('WHERE col = ANY(?)', [[array]]). Avoid .toString() concatenation. -
I-05 Informational Incorrect CRE Network/Config Values Configuration Pending
Description
configArbitrum.json is configured with mainnet chain identifiers (e.g., Arbitrum mainnet chain name/id) while isTestnet is set to true, and several addresses appear to be placeholders/same-address values.
Recommendation
Consider reviewing all configs before deployment and correcting whereever required.
-
I-06 Informational Fee Rewards Manipulation Via Snapshot Inflation Gaming Pending
Description
initiateDistribute()determines each chain's share of GMX rewards by reading spottotalSupply()from theextendedGmxTrackeron each chain. This snapshot is stored and used throughout the rest of the distribution cycle to calculaterequiredGmxAmount:uint256 stakedGmx = IERC20(extendedGmxTracker).totalSupply(); _setUint(Keys2.feeDistributorStakedGmxKey(chainId), stakedGmx);Since initiateDistribute() is called on a predictable schedule (Wednesday 0 UTC), an attacker who already holds a stake on a chain can front-run the keeper transaction by temporarily inflating that chain's totalSupply — e.g., via flashloaned GMX — and unstaking immediately after the snapshot is taken. Increasing rewards allocation for their chain, and therby their own stake.
Recommendation
Consider smoothing out the totalSupply consideration by using a time-weighted average over the distribution cycle duration
-
I-07 Informational Implementation mismatch for
forceCalculationDocumentation PendingDescription
GlvUtils.getGlvValuecomments state there is aforceCalculationoption to force basket-based GLV valuation even when a primary GLV oracle price exists. However, the actual function signature has no such parameter, and logic always short-circuits to the GLV oracle path whenoracle.primaryPrices(glv)is present. This creates a spec/implementation mismatch: callers cannot request deterministic basket-based valuation in cases where comments indicate they should be able to.Recommendation
Implement
forceCalculationingetGlvValueand thread it through relevant call sites. Or remove/update comments to reflect current behavior (no override available). -
I-08 Informational pnlAfterPriceImpactUsd Calculated Twice Superfluous Code Pending
Description
pnlAfterPriceImpactUsdis calculated twice in thegetPositionInfofunction.Recommendation
Consider to remove one of the two calculations.
-
I-09 Informational Market TWAP Orders Always Revert Logical Error Pending
Description
createTwapOrderalways assigns a nonzerovalidFromTimeto every slice after the first one. Since_createOrderexplicitly forbids market orders with a nonzerovalidFromTime, any TWAP request using a market order type andtwapCount >= 2will always revert.Recommendation
If TWAP market orders should be supported, introduce a different execution model for market orders. Each slice should be stored in a way that allows delayed execution without relying on the normal market-order
validFromTimerestriction. -
I-10 Informational Missing Multichain TwapOrder Functionality Logical Error Pending
Description
The
createTwapOrderfunction takes asrcChainIdas param but can only be used on the local chain.Recommendation
Consider to let multichain users create TwapOrders or to remove this param.
-
I-11 Informational External-driven max funding cap can lag GMX Logical Error Pending
Description
The keeper computes a target
maxFundingRatefrom reference exchange funding magnitudes, then moves toward that target gradually using a time window, periodic execution, thresholds, and max-change limits(fundingRate.ts (line 50), fundingRate.ts (line 529), fundingRate.ts (line 539)). That target is written on-chain asMAX_FUNDING_FACTOR_PER_SECOND, and the contract then bounds effective funding within configured limits(MarketUtils.sol (line 1666), MarketUtils.sol (line 1672)).f_ps = min(maxFundingFactorPerSecond, x * fundingFactor)If reference venues are relatively balanced while GMX is still meaningfully skewed, the externally derived cap can sit lower than what GMX-local inventory pressure would ideally want. However since keeper pushes max target down toward floor/buffer smoothly (not instant; windowed + rate-limited), the impact here is not that severe.Recommendation
Be aware that calm external funding regimes can suppress GMX skew-correction pressure. Monitor markets that stay skewed for long periods while maxFundingRate is pinned near low floors or conservative caps and intervene if needed.
-
I-12 Informational TWAP orders inherit fixed creation price bounds Logical Error Pending
Description
The TWAP implementation creates all child orders upfront and copies the same pricing fields into every slice:
- triggerPrice
- acceptablePrice
- minOutputAmount Only validFromTime, collateral, and execution fee are adjusted per child. As a result, later slices execute against future market conditions while still using price constraints chosen at t0. Later TWAP slices can become:
- Too strict
- acceptablePrice or minOutputAmount becomes unfillable
- slices fail, freeze, or remain unexecuted
- Too loose
- users widen bounds at t0 to avoid non-execution
- later slices can then execute at materially worse prices than intended This undermines the expected behavior of a TWAP, where each slice should reflect market conditions near its scheduled execution time. Example Assume a user creates a 5-slice TWAP at t0 with:
- interval = 5 minutes
- acceptablePrice = 4900
- minOutputAmount = 1000 If market conditions drift by slice 4:
- current executable price may be outside the stale acceptablePrice
- current output may be below the stale minOutputAmount Even though the user intended to trade over time, slices 4 and 5 are still constrained by bounds chosen 15-20 minutes earlier.
-
I-13 Informational TWAP orders inherit fixed creation price bounds Logical Error Pending
Description
The TWAP implementation creates all child orders upfront and copies the same pricing fields into every slice:
- triggerPrice
- acceptablePrice
- minOutputAmount Only validFromTime, collateral, and execution fee are adjusted per child. As a result, later slices execute against future market conditions while still using price constraints chosen at t0. Later TWAP slices can become:
- Too strict
- acceptablePrice or minOutputAmount becomes unfillable
- slices fail, freeze, or remain unexecuted
- Too loose
- users widen bounds at t0 to avoid non-execution
- later slices can then execute at materially worse prices than intended This undermines the expected behavior of a TWAP, where each slice should reflect market conditions near its scheduled execution time. Example Assume a user creates a 5-slice TWAP at t0 with:
- interval = 5 minutes
- acceptablePrice = 4900
- minOutputAmount = 1000 If market conditions drift by slice 4:
- current executable price may be outside the stale acceptablePrice
- current output may be below the stale minOutputAmount Even though the user intended to trade over time, slices 4 and 5 are still constrained by bounds chosen 15-20 minutes earlier.
Recommendation
Beware of this.
-
I-14 Informational TWAP bypasses tightening of creation validations Logical Error Pending
Description
createTwapOrder()creates all future slices immediately at t0 and stores them as ordinary orders. Each child only waits on its own validFromTime; it is not re-created when its execution window arrives. Because of this, every child is only subject to creation-time validations once, when the TWAP is initially submitted. If governance later tightens configuration that is only checked during order creation, already-created future slices are grandfathered in and remain executable. Creation-only checks include:- swap path length validation: OrderUtils.sol:233
- callback gas limit validation: OrderUtils.sol:267
- max data length validation in handler: OrderHandler.sol:93
- execution fee capping under current gas config: So the issue is specifically that future TWAP slices can bypass later changes to creation-only policy, even though a fresh normal order created at the same future time would revert. Assume:
- MAX_CALLBACK_GAS_LIMIT = 2,000,000 at t0
- user creates a 5-slice TWAP with callbackGasLimit = 1,500,000
- slices are scheduled over the next hour At t1, governance lowers:
- MAX_CALLBACK_GAS_LIMIT = 300,000 Now:
- a new normal order with callbackGasLimit = 1,500,000 would revert at creation
- but the already-created TWAP child scheduled for t2 still exists and can execute later with the old callback gas limit, because that limit was only validated when the child was first stored Users can pre-commit a batch of future orders under a more permissive creation-time config regime and continue to execute them after governance has tightened those policies. This weakens the effectiveness of configuration changes intended to immediately constrain newly submitted orders.
Recommendation
Beware of this.
-
I-15 Informational Cross-Collateral Review Concerns Informational Pending
Description
1. Withdrawal fairness and redeemability
Market NAV would include cross-collateral
poolAmount, while LP withdrawals would still be paid only inlongTokenandshortToken. This can create a first-withdrawer advantage and leave remaining LPs with a larger share of volatile or illiquid cross-collateral exposure.2. Reserve accounting
The ADRs do not clearly specify whether cross-collateral should count toward reserve capacity for open interest.
- If it does not count, market NAV and usable backing diverge.
- If it does count, long / short payout capacity starts depending on unrelated collateral-token liquidity.
3. Funding-fee accounting-level swap
The proposed accounting-level swap for funding fees is not economically neutral. It moves exposure from pool tokens to cross-collateral without a real trade, which can push risk onto LPs if the cross-collateral token is volatile, thinly traded, or hard to unwind.
4. Price-impact settlement
The current engine assumes price impact is tied to the existing position-impact /
pnlTokenmodel. If profit or positive price impact is preferentially paid in cross-collateral, the design needs explicit rules for:- which pool actually funds the payout,
- which asset the cap should apply against,
- how conversion between impact-pool accounting and payout asset is performed. Without this, value transfer between pools can become unclear.
5. PnL cap basis
It is not yet clear whether trader max PnL should remain capped against long / short payout-token liquidity or expand with total market NAV including cross-collateral. This choice affects solvency, trader UX (they still remain exposed to other collateral tokens of the pool due to this), and how conservative the market becomes as cross-collateral grows.
6. Keeper and rebalancing dependence
The design depends on
SwapRequestand active rebalancing to keep cross-collateral inventory under control. If rebalancing is slow, unavailable, or made in illiquid markets, LP withdrawal quality and market composition can degrade even if internal accounting remains correct. This also creates a gap between:- accounting value, based on oracle prices, and
- realizable value, based on actual executable liquidity.
7. Gas and state growth
Pool-value calculation, validation, and bookkeeping would need to handle multiple cross-collateral token types. This creates linear growth in hot paths and likely requires:
- a strict hard cap on token types per market, and
- dust-cleanup rules so token lists can shrink again.
8. GLV exposure and pricing
If market value includes cross-collateral, GLV pricing and risk exposure inherit that complexity. The ADRs acknowledge this, but they do not yet define the full oracle, validation, and exposure-reporting model for GLV once supported markets hold arbitrary collateral assets.
-
I-16 Informational Cross-Margin Review Concerns Informational Pending
Description
Account equity may diverge from realizable settlement value
Current GMX position equity is not just raw mark-to-market PnL. Real execution also depends on PnL caps, price impact, fees, and payout token availability. Cross-margin account equity needs an explicit rule for whether it recognizes:
- capped or uncapped unrealized PnL,
- price impact,
- fee drag,
- token-specific payout limitations. Without this, account-level "safe equity" may overstate what can actually be realized when positions settle.
PnL Settlementchanges core position semantics0002.eresetssizeInUsdwhile keepingsizeInTokensunchanged. In the current engine,sizeInUsdis a core input for:- PnL accounting,
- funding,
- borrowing,
- open interest,
- position history and analytics.
This is not just a bookkeeping optimization. It changes the meaning of the position itself and may create hidden inconsistencies across subsystems that currently assume
sizeInUsdchanges only through increase / decrease operations.
Delayed deposit weakens the current solvency model
In isolated margin, most relevant collateral is already inside the market. In this design, a position can rely on future collateral movement from the provider. That means settlement safety depends on a later transfer succeeding under:
- provider balance constraints,
- cap constraints,
- token-eligibility constraints,
- current market conditions. This is a materially weaker solvency model than current isolated margin, even if the intended user experience is better.
Liquidation ordering is economically significant
0002.fleaves liquidation ordering flexible. This is not only an optimization detail. Different liquidation sequences can produce different:- recovered equity,
- fee outcomes,
- remaining account health,
- LP loss outcomes. If contract-level ordering is too expensive and keeper-level ordering is used instead, correctness and fairness become partially operational rather than purely protocol-defined.
Oracle dependency expands sharply
Cross-margin account health depends on prices for:
- all positions,
- all eligible collateral tokens,
- profit-recognition logic,
- possibly post-swap output tokens. This makes account-level safety more oracle-intensive than current isolated positions. The ADRs mention this, but the design implication is stronger: the more tokens the account can meaningfully depend on, the more ways stale or missing prices can distort account health.
Remediation Review 1
11 findings · April 14 to 16, 2026-
H-01 High StrictVault Not Synced In Buyback Flow Logical Error Reported
Description
The
buybackflow does no sync theGMXorWNTamount in theFeeVault. This can lead to an inflatedwithdrawableBuybackTokenAmount:- Eve calls
claimFeesto increase thebuybackAvailableFeeAmountofUSDCby $500 and theFeeVaultis synced viarecordTransferInto hold $500USDC - Eve calls
buybackto swap $100WNTtoUSDCthis will decrease the syncedUSDCamount of theFeeVaultastransferOutis called but will not sync theWNTbalance of theFeeVaultasrecordTransferInis not used- It will also decrease
buybackAvailableFeeAmountby theUSDCamount thatEvewill receive and increase thewithdrawableBuybackTokenAmountby the receivedWNTtokens
- It will also decrease
- Eve calls
claimFeesagain but this time withWNTas thefeeTokenwhich will callrecordTransferInto get the amount of unsynced tokens in theFeeVaultthat equal the current claimable tokens + theWNTreceived during the lastbuybackcall (that were not synced)- Now the
withdrawableBuybackTokenAmountis increased not only by the claimed amount but also again by the receivedWNTtokens from thebuybackcall which will double count them now This leads to a DoS of the fee distribution flow as it will try to pull more tokens than there are in the Vault.
- Now the
Recommendation
Call
recordTransferInin thebuybackflow to keep theFeeVaultsynced. - Eve calls
-
M-01 Medium M-32 and M-33 fixes introduce build errors Error Reported
Description
Two recent fixes introduce compile-time regressions. First,
9bc91653adds a new check inExecuteGlvDepositUtils, but referencesdeposit.updatedAtTime()beforedepositis declared. In this branch, the only in-scope request object isglvDeposit.if (glvDeposit.isMarketTokenDeposit()) { if (params.oracle.minTimestamp() < deposit.updatedAtTime()) { revert Errors.OracleTimestampsAreSmallerThanRequired( params.oracle.minTimestamp(), glvDeposit.updatedAtTime() ); } }Second,
436e2901changesInvalidEdgeDataStreamDecimalsto take two arguments inErrors, butTimelockConfigstill reverts with only one:error InvalidEdgeDataStreamDecimals(address token, uint256 decimals); ... if (edgeDataStreamTokenDecimals == 0) { revert Errors.InvalidEdgeDataStreamDecimals(token); }These changes make the patched code uncompilable until both call sites are corrected.
Recommendation
Replace
deposit.updatedAtTime()withglvDeposit.updatedAtTime()inExecuteGlvDepositUtils. Update theTimelockConfigrevert to pass both required arguments toInvalidEdgeDataStreamDecimals, for exampletokenandedgeDataStreamTokenDecimals. -
M-02 Medium GLV market token deposits bypass max expiry Logical Error Reported
Description
Commit
9bc91653was intended to fix M-32, but it only added the lower-bound oracle timestamp check to the GLVisMarketTokenDepositbranch. The normal deposit path also enforcesoracle.maxTimestamp <= updatedAtTime + REQUEST_EXPIRATION_TIME, while the GLV market-token shortcut still returns before applying that expiry check.if (glvDeposit.isMarketTokenDeposit()) { if (params.oracle.minTimestamp() < glvDeposit.updatedAtTime()) { revert Errors.OracleTimestampsAreSmallerThanRequired( params.oracle.minTimestamp(), glvDeposit.updatedAtTime() ); } // missing: maxTimestamp <= updatedAtTime + REQUEST_EXPIRATION_TIME glvVault.transferOut(glvDeposit.market(), glvDeposit.glv(), glvDeposit.marketTokenAmount()); return glvDeposit.marketTokenAmount(); }As a result, an old GLV market-token deposit can still execute after expiry as long as the keeper supplies fresh-enough prices for
minTimestamp. The equivalent normal deposit would revert.Recommendation
Complete the M-32 fix by validating that
oracle.maxTimestamp <= glvDeposit.updatedAtTime() + REQUEST_EXPIRATION_TIME -
M-03 Medium Missing init bricks relay fee swaps Configuration Reported
Description
7b6f71e7de1e30e19b0ae6e62d3b1f384e80b221adds a new global guard inBaseGelatoRelayRouterthat rejects any relay fee swap whose USD value exceedsMAX_RELAY_FEE_SWAP_USD. This is intended to cap oracle mispricing extraction for all relay calls, but the commit only updates the runtime check and tests. It does not update the repo's standard general-config plumbing to initialize the new key in production deployments. As a result,MAX_RELAY_FEE_SWAP_USDremains at theDataStoredefault value of0unless operators manually seed it out-of-band. Any relay action that usesfeeSwapPathwill then revert as soon asrelayFeeUsd > 0.if (relayParams.fee.feeSwapPath.length != 0) { uint256 relayFeeUsd = relayParams.fee.feeAmount * oracle.getPrimaryPrice(relayParams.fee.feeToken).max; // New global cap; defaults to 0 unless explicitly configured uint256 maxRelayFeeSwapUsd = contracts.dataStore.getUint(Keys.MAX_RELAY_FEE_SWAP_USD); if (relayFeeUsd > maxRelayFeeSwapUsd) { revert Errors.MaxRelayFeeSwapExceeded(relayFeeUsd, maxRelayFeeSwapUsd); } }The surrounding config scripts still only handle
MAX_RELAY_FEE_SWAP_USD_FOR_SUBACCOUNT, so the new global key is not part of the normal rollout path. Impact:- Breaks all relay calls that rely on swapping fee tokens into WNT until operators manually configure the new key.
- Creates a rollout regression even though tests pass, because the tests explicitly seed
MAX_RELAY_FEE_SWAP_USDin their setup.
Recommendation
Add
MAX_RELAY_FEE_SWAP_USDto the standard general-config path and initialize it during deployment or migration, instead of relying on manual post-deploy writes. At minimum:- add a
maxRelayFeeSwapUsdfield toconfig/general.ts - write the value in
updateGeneralConfigUtils - print and verify the value in
printGeneralConfig - set a non-zero default that is at least large enough for legitimate relay fee swaps and greater than or equal to
MAX_RELAY_FEE_SWAP_USD_FOR_SUBACCOUNT
-
M-04 Medium Relay TWAP flow inherits the M-35 hash flaw DoS Reported
Description
M-35 identified that non-subaccount relay actions can share the same globally consumed
digestbecause replay protection is keyed only bydigest, while some struct hashes do not bindaccount. The new non-subaccountcreateTwapOrderflow added in17c104fainherits the same issue.GelatoRelayRouter.createTwapOrderbuilds its digest withRelayUtils.getCreateTwapOrderStructHash(relayParams, params, twapCount, interval), and that overload hardcodesaccount = address(0):function getCreateTwapOrderStructHash( IRelayUtils.RelayParams calldata relayParams, IBaseOrderUtils.CreateOrderParams memory params, uint256 twapCount, uint256 interval ) external pure returns (bytes32) { return _getCreateTwapOrderStructHash(relayParams, bytes32(0), address(0), params, twapCount, interval); }At the same time,
_validateCallstill burns the digest globally before signature validation:bytes32 digest = ECDSA.toTypedDataHash(domainSeparator, structHash); _validateDigest(digest); SignatureUtils.validateSignature( domainSeparator, digest, relayParams.signature, account, "call", ... );As a result, two different users signing the same non-subaccount TWAP payload shape produce the same digest. If one user submits first, the other user's transaction reverts with
InvalidUserDigest, even though the signatures are for different accounts. Illustrative example:- Bob signs a gasless non-subaccount
createTwapOrderpayloadP. - Alice copies
P, signs it as Alice, and submits first. - Alice's transaction consumes the shared digest.
- Bob's later relay transaction reverts because the digest was already marked as used.
Recommendation
In
createTwapOrderIncludeaccountin the non-subaccountgetCreateTwapOrderStructHashpath so the digest is unique per user action. - Bob signs a gasless non-subaccount
-
M-05 Medium Zero saved funding biases longs at min Logical Error Reported
Description
Introduced in commit
8dc3041, the adaptive funding pathgetNextFundingFactorPerSecondnow treatsnextSavedFundingFactorPerSecond == 0as long-side funding when selecting the per-side min and max bounds:bool isLongFunding = cache.nextSavedFundingFactorPerSecond >= 0; configCache.minFundingFactorPerSecond = dataStore.getUintValueFromDataStore( Keys.minFundingFactorPerSecondKey(market.marketToken, isLongFunding) ); configCache.maxFundingFactorPerSecond = dataStore.getUintValueFromDataStore( Keys.maxFundingFactorPerSecondKey(market.marketToken, isLongFunding) );That would only be a tie-break if the function then kept
0neutral. It does not. The final min-bound call usesCalc.boundMagnitude, which gives zero a positive sign and upgrades it to+minwhenever the selected minimum is non-zero:cache.nextSavedFundingFactorPerSecondWithMinBound = Calc.boundMagnitude( cache.nextSavedFundingFactorPerSecond, configCache.minFundingFactorPerSecond, configCache.maxFundingFactorPerSecond ); return ( cache.nextSavedFundingFactorPerSecondWithMinBound.abs(), cache.nextSavedFundingFactorPerSecondWithMinBound > 0, cache.nextSavedFundingFactorPerSecond );function boundMagnitude(int256 value, uint256 min, uint256 max) internal pure returns (int256) { uint256 magnitude = value.abs(); if (magnitude < min) { magnitude = min; } if (magnitude > max) { magnitude = max; } // Zero is treated as positive here int256 sign = value == 0 ? int256(1) : value / value.abs().toInt256(); return magnitude.toInt256() * sign; }As a result, a neutral saved funding state can be converted into a positive funding regime even when there is no long-side skew. This is reachable in the adaptive branch because equal open interest only early-returns when
fundingIncreaseFactorPerSecond == 0. When adaptive funding is enabled, the function continues even iflongOpenInterest == shortOpenInterest. For example:fundingIncreaseFactorPerSecond != 0savedFundingFactorPerSecond = 0longOpenInterest == shortOpenInterestminFundingFactorPerSecondKey(market, true) > 0The function does not early return. It selects the long-side bounds because0 >= 0, thenboundMagnitudeturns0into+minLong. The returned result islongsPayShorts = trueeven though the market is balanced.
Recommendation
Treat
nextSavedFundingFactorPerSecond == 0as neutral rather than implicitly long. -
L-01 Low Buyback info script reads stale fee holder Configuration Reported
Description
printBuybackInfostill assumes that buyback inventory is physically held byFeeHandler. After the fee custody refactor, that assumption is no longer true:claimFees,buyback, andwithdrawFeesall move assets throughFeeVaultinstead. The script now readswithdrawableBuybackTokenAmountfromDataStorebut compares it against the token balance offeeHandler.address. On deployments that actually useFeeVault, this can report an artificial shortfall even when the buyback inventory is fully backed.const dataStore = await hre.ethers.getContract("DataStore"); const feeHandler = await hre.ethers.getContract("FeeHandler"); const withdrawableAmount = await dataStore.getUint(keys.withdrawableBuybackTokenAmountKey(buybackToken.address)); const contractBalance = await getBalanceOf(buybackToken.address, feeHandler.address); // Stale assumption: the balance now sits in `FeeVault`, not `FeeHandler` if (contractBalance.lt(withdrawableAmount)) { throw new Error(`Insufficient contract balance`); }Recommendation
Update
printBuybackInfo.tsto read balances fromFeeVaultinstead ofFeeHandler. -
I-01 Informational Legacy funding key callers write dead slots Configuration Reported
Description
The funding bound keys were changed from a market-scoped layout to a per-side layout by adding
isLongtominFundingFactorPerSecondKeyandmaxFundingFactorPerSecondKey. This is consistent with the new funding logic, which reads separate long and short bounds. However, some callers still use the legacy one-argument form or still encode config writes with["address"]instead of["address", "bool"]. Those stale callers no longer update the active storage slots. They write a dead key while the protocol continues reading the new per-side keys, so the intended funding bounds remain unchanged.await dataStore.setUint(keys.minFundingFactorPerSecondKey(ethUsdMarket.marketToken), 0); await dataStore.setUint(keys.maxFundingFactorPerSecondKey(ethUsdMarket.marketToken), decimalToFloat(1)); // Legacy helper shape: writes the old slot, not the active per-side slotsThe live funding logic now reads side-specific values:
bool isLongFunding = cache.nextSavedFundingFactorPerSecond >= 0; configCache.minFundingFactorPerSecond = dataStore.getUintValueFromDataStore( Keys.minFundingFactorPerSecondKey(market.marketToken, isLongFunding) ); configCache.maxFundingFactorPerSecond = dataStore.getUintValueFromDataStore( Keys.maxFundingFactorPerSecondKey(market.marketToken, isLongFunding) );There is also a stale config test path that still writes the legacy encoding, resulting in broken tests:
await config.setUint( keys.MAX_FUNDING_FACTOR_PER_SECOND, encodeData(["address"], [ethUsdMarket.marketToken]), 10 ); // Legacy config encoding: the active per-side key expects ["address", "bool"]Recommendation
- update all
minFundingFactorPerSecondKeyandmaxFundingFactorPerSecondKeycalls to passisLong - replace legacy
encodeData(["address"], [market])writes withencodeData(["address", "bool"], [market, isLong]) - where the same bound should apply to both sides, write the
trueandfalsekeys explicitly
- update all
-
I-02 Informational Variable Name Inconsistency Informational Reported
Description
The
CREATE_TWAP_ORDER_TYPEends with_TYPEwhile all the others end with_PARAMS.Recommendation
Consider to use a consistent variable name scheme to follow best practices.
-
I-03 Informational Missing Batch TWAP functionality Informational Reported
Description
The
batchfunctions do not allow TWAP orders.Recommendation
Consider to implement TWAP orders into the
batchflows, but be aware that for subaccount actions this would require to sum up thetwapCount. -
I-04 Informational Unresolved findings from main review Informational Reported
Description
These findings from the main review remain unresolved: H-07: Wrong Operation Order Cause Reward Loss H-13: StaticOracleProvider returns min/max inverted M-17: V2 Keeper Costs Can Underflow Calculations M-31: Atomic Oracle Providers Enable Price Picking M-35: Account-unbound hashes allow digest collisions L-05: GLV Oracle Count Mismatch Causes Keeper Loss L-07: Sync Lacks Parameter/baseKey Binding L-21 to L-26
Recommendation
Resolve the issues or mark them as acknowledged.
Remediation Review 2
8 findings · May 11 to 14, 2026-
H-01 High StaticOracle freeze affects other live markets Logical Error Resolved
Description
StaticOracleProvideris intended to support freezing conditions for a market that is being closed. However, the implemented freeze is not market-scoped. It changes the oracle provider for a token globally.function setStaticPriceForToken() { ... _setOracleProviderForToken(address(oracle), token, staticOracleProvider); ... }There is no per-market static oracle selector. Market pricing reads
indexToken,longToken, andshortTokenfrom the same global oracle. Therefore, freezing WETH, USDC, BTC, or any other shared token for one closed market changes the required oracle provider for all other live markets and flows that use that token. An honest attempt to freeze one closing market can force unrelated live markets to execute with a stale token price.This can misprice pool value, collateral value, etc.Recommendation
Do not freeze shared long/short tokens. Ensure that the to-be-frozen index token, is not used in another market.
Consider additional validation that rejects freezing a token if any enabled market, GLV, or swap path outside the target closure set still depends on that token. Alternatively, consider making static freeze state market-scoped, not token-scoped. Store frozen prices under a market-specific key, such as
(market, token), and only use those prices for that market's close path. -
M-01 Medium V2 keeper top-ups can DoS distribution DoS Resolved
Description
FeeDistributor.distributecan still revert during the final WNT allocation step when V2 keeper top-up costs are larger than the V2-side WNT allocation. The previous remediation avoids the immediate subtraction underflow in_calculateChainlinkAndTreasuryAmounts, but it does not capkeeperCostsV2or give V2 keeper costs the same treasury fallback path used for V1 keeper and referral costs.function _calculateChainlinkAndTreasuryAmounts(...) internal view returns (uint256, uint256) { ... if (keeperCostsV2 > chainlinkTreasuryWntAmount - wntForChainlink) { // avoids the local underflow, but still leaves keeperCostsV2 fully payable return (wntForChainlink, chainlinkTreasuryWntAmount - wntForChainlink); } uint256 wntForTreasury = chainlinkTreasuryWntAmount - wntForChainlink - keeperCostsV2; return (wntForChainlink, wntForTreasury); }In the high
keeperCostsV2branch, the function returns the whole non-Chainlink V2 bucket aswntForTreasurywhilekeeperCostsV2is still paid in full later throughwntForKeepers. This can overcommit the sametotalWntBalance. The overcommit is hit in_finalizeWntForTreasury, before V1 fallback logic can help:function _finalizeWntForTreasury(...) internal returns (uint256) { uint256 wntBeforeV1KeeperCostsAndReferralRewards = totalWntBalance - keeperCostsV2 - wntForChainlink - wntForTreasury; // can still underflow after the remediation ... }Illustrative example:
totalWntBalance = 100 WNT.- V2 receives a 10 WNT allocation based on the
feesV1Usd/feesV2Usdsplit. wntForChainlink = 1 WNT.- V2 keepers require a 95 WNT top-up.
_calculateChainlinkAndTreasuryAmountsreturnswntForTreasury = 9 WNTin the high-cost branch._finalizeWntForTreasurycomputes100 - 95 - 1 - 9, leaving insufficient room for any V1 keeper/referral costs and reverting if the committed amounts exceed the vault balance. As a result, a period with unusually high V2 keeper top-up requirements can blockdistribute. Sincedistributeis the final step that resets the distribution state and transfers weekly rewards, this can halt the automated fee distribution process until balances or keeper target configs are manually adjusted. Note: IfkeeperCostV2exceedstotalWntBalance, this issue is also triggered.
Recommendation
Make the V2 keeper shortfall handling explicit and ensure the WNT allocation cannot exceed
totalWntBalance. -
M-02 Medium Static prices unusable when ref price diverge Logical Error Resolved
Description
StaticOracleProvideris intended to support frozen pricing for markets that are being closed. However, static prices are still validated against the live Chainlink reference price when a reference feed exists for the token.StaticOracleProviderexplicitly reports that it is not a Chainlink on-chain provider:function isChainlinkOnChainProvider() external pure returns (bool) { return false; }As a result,
Oracle._validatePricesapplies the reference-price deviation check to static prices:if (!provider.isChainlinkOnChainProvider()) { (bool hasRefPrice, uint256 refPrice) = ChainlinkPriceFeedUtils.getPriceFeedPrice(dataStore, token); if (hasRefPrice) { _validateRefPrice(token, validatedPrice.min, refPrice, maxRefPriceDeviationFactor); _validateRefPrice(token, validatedPrice.max, refPrice, maxRefPriceDeviationFactor); } }This means a frozen token price remains executable only while it stays within
MAX_ORACLE_REF_PRICE_DEVIATION_FACTORof the current Chainlink feed. If the live Chainlink price moves far enough away from the frozen price, every non-atomic execution requiring that static token price reverts withMaxRefPriceDeviationExceeded. This can leave positions and liquidity stuck or force governance/operators to change oracle configuration again under emergency conditions. This will also lead to reverts if the reason behind shutting down the market is a deprecated chainlink feed as in that case callinglastRoundDataon the chainlink feed will lead to a revert.Recommendation
Do not apply the live Chainlink reference-price deviation check to explicitly frozen static prices.
-
M-03 Medium Static oracle unusable as oracle is not enabled Logical Error Resolved
Description
Config.setStaticPriceForTokenis intended to activate the static oracle flow for closed-market freezes. It sets the frozen token price, then routes the token toStaticOracleProvider. In the current deployment configuration,StaticOracleProvideris deployed and passed intoConfig, but it is not enabled as an oracle provider.updateOracleProviders.tsonly enables the live providers:const providersToAdd = [ chainlinkPriceFeedProvider.address, chainlinkDataStreamProvider.address, edgeDataStreamProvider.address, ];Therefore, calling
setStaticPriceForTokenreverts when it tries to assignstaticOracleProviderthrough_setOracleProviderForTokenwhich rejects any provider that is not globally enabled:if (!dataStore.getBool(Keys.isOracleProviderEnabledKey(provider))) { revert Errors.InvalidOracleProvider(provider); }As a result, the intended static-price freeze path is unusable unless operators first enable
StaticOracleProvider, otherwisesetStaticPriceForTokenreverts withInvalidOracleProvider(staticOracleProvider).Recommendation
An immediate fix would be to enable
StaticOracleProvider. However, consider if thesetStaticPriceForTokenshould callisOracleProviderEnabledKey(staticOracleProvider)in the first place as the static oracle is not a normal live provider. -
M-04 Medium EIP6492_DEPLOYER Address Not Set Configuration Resolved
Description
deployEIP6492Deployer.tsdeploysEIP6492Deployer, but skips settingEIP6492_DEPLOYERinDataStoreon existing mainnet deployments because the deployer account cannot callConfig.setAddress. The generic config helper can support this update, andEIP6492_DEPLOYERis allowlisted in Config, but no committed script currently adds this config item for the deployed address.Recommendation
Consider to add an explicit script or config item that sets the
EIP6492_DEPLOYERaddress through the existing config flow after deployment. -
M-05 Medium Static freeze only works with atomic price Logical Error Resolved
Description
Config.setStaticPriceForTokenis intended to activate the static oracle flow for markets that need to be closed under frozen pricing. However, the function can only initialize the static price from an atomic oracle provider:function setStaticPriceForToken( address token, OracleUtils.SetPricesParams memory pricesParams ) external onlyConfigKeeper nonReentrant withOraclePricesForAtomicAction(pricesParams) { ... }This means the static freeze path is only usable for tokens that have an enabled atomic provider capable of producing the seed price. Tokens whose normal source is a non-atomic provider, such as
ChainlinkDataStreamProvider, cannot be frozen throughsetStaticPriceForTokenunless an additional atomic provider is configured for that token or the data stream provider is marked atomic. This is a practical issue for markets being delisted because static pricing is most valuable when the live oracle source is expected to become unavailable. For example, if a token only has Chainlink Data Streams configured and that stream is deprecated, operators may be unable to initialize static pricing: before deprecation,setStaticPriceForTokenreverts withNonAtomicOracleProvider; after deprecation, there may be no fresh data stream report available to seed the static price.Recommendation
Do not require the freeze seed price to come only from an atomic provider.
-
L-01 Low MIN_CHANGE_DELAY Can DoS Static Oracle Updates DoS Resolved
Description
In case a new token / market is created but a mistake happened or an emergency situation occurs and the config keeper wants to freeze the token price to wind down the market again, it might be DoSed, as the
ORACLE_PROVIDER_MIN_CHANGE_DELAYneeds to pass.Recommendation
Consider to skip the
ORACLE_PROVIDER_MIN_CHANGE_DELAYin case of theStaticOracleProvider. -
I-01 Informational GMOracle Code Remains After Provider Removal Superfluous Code Resolved
Description
GmOracleProviderwas removed, but GM oracle-specific production code remains in the codebase:GmOracleUtilsstill exists and is only used in a test file:OracleModuleTest.Errors.solstill contains GM oracle-specific errors such asGmEmptySigner
Recommendation
Consider to remove unused code.
Remediation Review 3
4 findings · May 22, 2026-
M-01 Medium ADL Nets Losing Positions Against Pool Liability Math Reported
Description
ADL is intended to determine whether the side-specific payout pool can cover profitable traders. For long positions, positive PnL is paid from the market’s longToken pool; for short positions, positive PnL is paid from the shortToken pool. Losing positions, however, repay losses through their collateral token. The current
getPositivePnlfunction change improves the previous behavior by preventing losses from one collateral-token bucket from offsetting profits in another bucket. However, it still computes net PnL inside each collateral bucket before flooring the result at zero. This means losses can still hide actual payout-pool liability when profitable and losing positions use the same collateral token. Example in an ETH/USDC market::- Two ETH long positions use USDC collateral.
- Position A is profitable by $200, so closing it decreases the ETH pool by $200.
- Position B is losing by $150, so closing it increases the USDC pool by $150.
The current ADL accounting nets these positions and reports only $50 of positive PnL:
\$200 profit - \$150 loss = \$50 reported liabilityBut this is not settlement-equivalent. The ETH pool still needs to pay $200; the $150 loss replenishes the USDC pool, not the ETH pool.
Recommendation
A fix would likely require new market variables. If this is not feasible, be aware about that and monitor probably on the keeper side when and which positions to close and adjust the ADL threshold if needed.
-
M-02 Medium uiFeeFactor Not Snapshotted Everywhere Logical Error Reported
Description
Normal GM deposits now snapshot uiFeeFactor when the request is created, so the user pays the fee rate that was active when they signed/submitted the deposit, to avoid unexpected slippage and ui fee attacks. This protection is still missing in all other flows.
Recommendation
Consider to snapshot the
uiFeeFactoreverywhere. -
M-03 Medium Reference-price Deviation Checks Are Disabled Oracle Reported
Description
Oracle.solnow requires!provider.isChainlinkOnChainProvider() && provider.shouldCheckRefPrice().ChainlinkDataStreamProviderandEdgeDataStreamProviderreturn false onshouldCheckRefPrice. This makesMAX_ORACLE_REF_PRICE_DEVIATION_FACTOReffectively dead for production providers.Recommendation
Return true for live off-chain providers, and exempt only
ChainlinkPriceFeedProvider, static and mock providers. -
I-01 Informational Scripts still reference removed GmOracleProvider Superfluous Code Reported
Description
GmOracleProvider was removed from contracts but some scripts still reference to it.
Recommendation
Consider to remove unused code completly.
No findings match.
More from GMX
All 51 reports-
Morpho Liquidation Module
3 findings 3 findings: 3 informational -
RewardRouterV3 & RewardRouterUtils
20 findings1 high 20 findings: 1 high, 8 low, 11 informational -
V2.2.1 Review
102 findings8 high 102 findings: 8 high, 37 medium, 49 low, 8 informational -
Incentives Contracts
17 findings 17 findings: 3 medium, 3 low, 11 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.
