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

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
Chains
Arbitrum, Avalanche, Solana
  • 2 Critical
  • 15 High
  • 52 Medium
  • 30 Low
  • 22 Informational

8 resolved · 2 acknowledged · 15 reported · 96 pending

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
FilenSLOCLines
contracts/adl/AdlUtils.sol136292
contracts/bank/Bank.sol53105
contracts/bank/StrictBank.sol2665
contracts/callback/CallbackUtils.sol246379
contracts/callback/IDepositCallbackReceiver.sol414
contracts/callback/IGasFeeCallbackReceiver.sol48
contracts/callback/IGlvDepositCallbackReceiver.sol413
contracts/callback/IGlvWithdrawalCallbackReceiver.sol414
contracts/callback/IOrderCallbackReceiver.sol514
contracts/callback/IShiftCallbackReceiver.sol48
contracts/callback/IWithdrawalCallbackReceiver.sol413
contracts/chain/ArbGasInfo.sol37
contracts/chain/ArbSys.sol39
contracts/chain/Chain.sol3356
contracts/chain/ChainReader.sol3650
contracts/claim/ClaimEventUtils.sol73141
contracts/claim/ClaimHandler.sol232325
contracts/claim/ClaimUtils.sol6685
contracts/claim/ClaimVault.sol511
contracts/config/AutoCancelSyncer.sol6176
contracts/config/Config.sol468622
contracts/config/ConfigSyncer.sol118172
contracts/config/ConfigTimelockController.sol6177
contracts/config/ConfigUtils.sol325420
contracts/config/IRiskOracle.sol1317
contracts/config/TimelockConfig.sol428544
contracts/data/DataStore.sol237513
contracts/data/Keys.sol14682409
contracts/data/Keys2.sol75167
contracts/deposit/Deposit.sol145210
contracts/deposit/DepositEventUtils.sol90116
contracts/deposit/DepositStoreUtils.sol247325
contracts/deposit/DepositUtils.sol170224
contracts/deposit/DepositVault.sol511
contracts/deposit/ExecuteDepositUtils.sol412584
contracts/deposit/IDepositUtils.sol2138
contracts/deposit/IExecuteDepositUtils.sol2531
contracts/error/Errors.sol391545
contracts/error/ErrorUtils.sol3756
contracts/event/EventEmitter.sol79130
contracts/event/EventUtils.sol423507
contracts/exchange/AdlHandler.sol101145
contracts/exchange/BaseHandler.sol5059
contracts/exchange/BaseOrderHandler.sol5777
contracts/exchange/DepositHandler.sol133195
contracts/exchange/GlvDepositHandler.sol111143
contracts/exchange/GlvShiftHandler.sol88116
contracts/exchange/GlvWithdrawalHandler.sol116148
contracts/exchange/IDepositHandler.sol712
contracts/exchange/IGlvDepositHandler.sol59
contracts/exchange/IGlvWithdrawalHandler.sol59
contracts/exchange/IJitOrderHandler.sol610
contracts/exchange/IOrderExecutor.sol48
contracts/exchange/IOrderHandler.sol59
contracts/exchange/IShiftHandler.sol610
contracts/exchange/IWithdrawalHandler.sol812
contracts/exchange/JitOrderHandler.sol107133
contracts/exchange/LiquidationHandler.sol5475
contracts/exchange/OrderHandler.sol243394
contracts/exchange/ShiftHandler.sol132164
contracts/exchange/WithdrawalHandler.sol166229
contracts/external/ExternalHandler.sol4168
contracts/external/IExternalHandler.sol36
contracts/feature/FeatureUtils.sol1232
contracts/fee/FeeBatch.sol914
contracts/fee/FeeBatchStoreUtils.sol79108
contracts/fee/FeeDistributor.sol545728
contracts/fee/FeeDistributorUtils.sol100124
contracts/fee/FeeDistributorVault.sol1124
contracts/fee/FeeHandler.sol201273
contracts/fee/FeeSwapUtils.sol95119
contracts/fee/FeeUtils.sol204277
contracts/gas/GasUtils.sol347601
contracts/glv/Glv.sol810
contracts/glv/glvDeposit/ExecuteGlvDepositUtils.sol202237
contracts/glv/glvDeposit/GlvDeposit.sol161235
contracts/glv/glvDeposit/GlvDepositCalc.sol4458
contracts/glv/glvDeposit/GlvDepositEventUtils.sol88113
contracts/glv/glvDeposit/GlvDepositStoreUtils.sol280368
contracts/glv/glvDeposit/GlvDepositUtils.sol246286
contracts/glv/glvDeposit/IGlvDepositUtils.sol2327
contracts/glv/GlvEventUtils.sol3652
contracts/glv/GlvFactory.sol5071
contracts/glv/glvShift/GlvShift.sol5370
contracts/glv/glvShift/GlvShiftEventUtils.sol4666
contracts/glv/glvShift/GlvShiftStoreUtils.sol101133
contracts/glv/glvShift/GlvShiftUtils.sol220266
contracts/glv/GlvStoreUtils.sol80109
contracts/glv/GlvToken.sol1723
contracts/glv/GlvUtils.sol226290
contracts/glv/GlvVault.sol59
contracts/glv/glvWithdrawal/GlvWithdrawal.sol133197
contracts/glv/glvWithdrawal/GlvWithdrawalEventUtils.sol6792
contracts/glv/glvWithdrawal/GlvWithdrawalStoreUtils.sol236311
contracts/glv/glvWithdrawal/GlvWithdrawalUtils.sol314371
contracts/glv/glvWithdrawal/IGlvWithdrawalUtils.sol2125
contracts/gov/GovTimelockController.sol1723
contracts/gov/GovToken.sol5079
contracts/gov/ProtocolGovernor.sol7092
contracts/liquidation/LiquidationUtils.sol60100
contracts/market/Market.sol943
contracts/market/MarketEventUtils.sol430569
contracts/market/MarketFactory.sol6592
contracts/market/MarketPoolValueInfo.sol1737
contracts/market/MarketStoreUtils.sol95131
contracts/market/MarketToken.sol1328
contracts/market/MarketUtils.sol17292942
contracts/market/PositionImpactPoolUtils.sol155205
contracts/multichain/BridgeOutFromControllerUtils.sol185218
contracts/multichain/IMultichainGlvRouter.sol610
contracts/multichain/IMultichainGmRouter.sol711
contracts/multichain/IMultichainOrderRouter.sol48
contracts/multichain/IMultichainProvider.sol1422
contracts/multichain/IMultichainTransferRouter.sol48
contracts/multichain/IOriginator.sol47
contracts/multichain/LayerZeroProvider.sol369538
contracts/multichain/MultichainClaimsRouter.sol77102
contracts/multichain/MultichainEventUtils.sol75115
contracts/multichain/MultichainGlvRouter.sol4157
contracts/multichain/MultichainGmRouter.sol6182
contracts/multichain/MultichainOrderRouter.sol5878
contracts/multichain/MultichainReader.sol189238
contracts/multichain/MultichainReaderUtils.sol1721
contracts/multichain/MultichainRouter.sol7488
contracts/multichain/MultichainSubaccountRouter.sol95126
contracts/multichain/MultichainTransferRouter.sol107149
contracts/multichain/MultichainUtils.sol66112
contracts/multichain/MultichainVault.sol513
contracts/nonce/NonceUtils.sol2448
contracts/oracle/ChainlinkDataStreamProvider.sol104136
contracts/oracle/ChainlinkPriceFeedProvider.sol4365
contracts/oracle/ChainlinkPriceFeedUtils.sol3971
contracts/oracle/EdgeDataStreamProvider.sol6487
contracts/oracle/EdgeDataStreamVerifier.sol89126
contracts/oracle/GmOracleProvider.sol115244
contracts/oracle/GmOracleUtils.sol3755
contracts/oracle/IChainlinkDataStreamVerifier.sol314
contracts/oracle/IOracle.sol610
contracts/oracle/IOracleProvider.sol410
contracts/oracle/IPriceFeed.sol38
contracts/oracle/Oracle.sol251370
contracts/oracle/OracleModule.sol3771
contracts/oracle/OracleStore.sol5284
contracts/oracle/OracleUtils.sol4865
contracts/order/AutoCancelUtils.sol2735
contracts/order/BaseOrderUtils.sol148376
contracts/order/DecreaseOrderExecutor.sol1016
contracts/order/DecreaseOrderUtils.sol270337
contracts/order/ExecuteOrderUtils.sol96136
contracts/order/IBaseOrderUtils.sol3460
contracts/order/IncreaseOrderExecutor.sol1016
contracts/order/IncreaseOrderUtils.sol79100
contracts/order/Order.sol251515
contracts/order/OrderEventUtils.sol171222
contracts/order/OrderStoreUtils.sol324423
contracts/order/OrderUtils.sol344445
contracts/order/OrderVault.sol511
contracts/order/SwapOrderExecutor.sol1016
contracts/order/SwapOrderUtils.sol7794
contracts/position/DecreasePositionCollateralUtils.sol546734
contracts/position/DecreasePositionSwapUtils.sol7487
contracts/position/DecreasePositionUtils.sol249371
contracts/position/IncreasePositionUtils.sol234314
contracts/position/Position.sol116206
contracts/position/PositionEventUtils.sol241287
contracts/position/PositionStoreUtils.sol203268
contracts/position/PositionUtils.sol474746
contracts/price/Price.sol2252
contracts/pricing/ISwapPricingUtils.sol1114
contracts/pricing/PositionPricingUtils.sol394620
contracts/pricing/PricingUtils.sol2596
contracts/pricing/SwapPricingUtils.sol222359
contracts/reader/GlvReader.sol144174
contracts/reader/KeeperReader.sol1840
contracts/reader/Reader.sol191233
contracts/reader/ReaderDepositUtils.sol157187
contracts/reader/ReaderPositionUtils.sol193248
contracts/reader/ReaderPricingUtils.sol207279
contracts/reader/ReaderUtils.sol183232
contracts/reader/ReaderWithdrawalUtils.sol77104
contracts/referral/IGov.sol38
contracts/referral/IReferralStorage.sol311
contracts/referral/ITimelock.sol38
contracts/referral/ReferralEventUtils.sol4658
contracts/referral/ReferralTier.sol714
contracts/referral/ReferralUtils.sol102159
contracts/role/Role.sol23124
contracts/role/RoleModule.sol97197
contracts/role/RoleStore.sol61130
contracts/router/BaseRouter.sol3953
contracts/router/ExchangeRouter.sol223377
contracts/router/GlvRouter.sol84118
contracts/router/IExchangeRouter.sol812
contracts/router/relay/BaseGelatoRelayRouter.sol291410
contracts/router/relay/GelatoRelayRouter.sol6278
contracts/router/relay/IRelayUtils.sol65116
contracts/router/relay/RelayUtils.sol679775
contracts/router/relay/SubaccountGelatoRelayRouter.sol99124
contracts/router/relay/SubaccountRouterUtils.sol5066
contracts/router/Router.sol1129
contracts/router/SubaccountRouter.sol195248
contracts/safe/SafeUtils.sol919
contracts/shift/IShiftUtils.sol1721
contracts/shift/Shift.sol102133
contracts/shift/ShiftEventUtils.sol78102
contracts/shift/ShiftStoreUtils.sol192250
contracts/shift/ShiftUtils.sol300394
contracts/shift/ShiftVault.sol59
contracts/subaccount/SubaccountUtils.sol195251
contracts/swap/ISwapHandler.sol48
contracts/swap/ISwapUtils.sol2545
contracts/swap/SwapHandler.sol1126
contracts/swap/SwapUtils.sol277398
contracts/token/IWNT.sol312
contracts/token/TokenUtils.sol122234
contracts/utils/AccountUtils.sol1724
contracts/utils/Array.sol76172
contracts/utils/BasicMulticall.sol1529
contracts/utils/Bits.sol719
contracts/utils/Calc.sol70173
contracts/utils/Cast.sol4172
contracts/utils/EnumerableValues.sol3785
contracts/utils/GlobalReentrancyGuard.sol2440
contracts/utils/PayableMulticall.sol1533
contracts/utils/Precision.sol84156
contracts/utils/Printer.sol2434
contracts/utils/StringUtils.sol69
contracts/utils/Uint256Mask.sol1725
contracts/withdrawal/ExecuteWithdrawalUtils.sol375480
contracts/withdrawal/IExecuteWithdrawalUtils.sol3036
contracts/withdrawal/IWithdrawalUtils.sol2028
contracts/withdrawal/Withdrawal.sol131195
contracts/withdrawal/WithdrawalEventUtils.sol85111
contracts/withdrawal/WithdrawalStoreUtils.sol225297
contracts/withdrawal/WithdrawalUtils.sol138198
contracts/withdrawal/WithdrawalVault.sol511

Findings 121

Main Review

98 findings · January 19 to June 12, 2026
  1. C-01 Critical Reserve check dangerously blocks decrease flows Logical Error Pending
    Location
    PositionUtils.sol, MarketUtils.sol
    Round
    Main Review

    Description

    When sizeDeltaUsd < 0, PositionUtils.updateOpenInterest performs 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, reserveFactor and openInterestReserveFactor are greater than 100%. That means the protocol explicitly allows positions to be opened while reservedUsd is well above poolUsd, as long as reservedUsd remains below the configured reserve-factor ceilings. However, once a user later tries to reduce position size, the transaction must satisfy the stricter reservedUsd <= poolUsd rule. 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 = \$100m
    • reserveFactor = 200%, so validateReserve allows up to \$200m
    • a user opens or increases positions while market-wide reservedUsd = \$150m
    • this state is valid for entry, because \$150m <= \$200m Now a user later attempts a routine partial close. Assume the decrease lowers market-wide reservedUsd from \$150m to \$149m. This reverts because \$149m > \$100m, so the additional absolute reservedUsd > poolUsd check 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 to reservedUsd <= poolUsd. So, whenever reserveUsd > 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.

  2. C-02 Critical factory.call() enables unauthorized transfers Signatures Pending
    Location
    https://github.com/gmx-io/gmx-synthetics-private/blob/release-v2.2c/contracts/router/relay/SignatureUtils.sol#L44-L45
    Round
    Main Review

    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 granted ROUTER_PLUGIN and CONTROLLER privileges 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.

  3. H-01 High GraphQL Injection In /Performance/Annualized Validation Pending
    Location
    subsquidService.ts
    Round
    Main Review

    Description

    User‑controlled address param is interpolated directly into a GraphQL query without validation or escaping. This happens in performance.ts (reads req.query.address) and subsquidService.ts (builds the query string in getAnnualizedPerformance / 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 address before it ever reaches the GraphQL query builder (e.g., require a 0x‑prefixed 40‑hex string and use ethers.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.

  4. H-02 High Keeper May Miss Liquidations On Losing Trades Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/domain/position/positionUtils.ts#L454-L455
    Round
    Main Review

    Description

    Liquidation keeper uses uses usdDelta = -sizeInTokens * midPrice instead of sizeInUSD for 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.

    1. Long, price down (P < entryPrice) sizeInTokens*P < sizeInUsd Keeper 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)
    2. Long, price up (P > entryPrice) sizeInTokens*P > sizeInUsd Keeper 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)
    3. Short, price down (P < entryPrice) sizeInTokens*P < sizeInUsd Short 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)
    4. Short, price up (P > entryPrice) sizeInTokens*P > sizeInUsd Keeper 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.sizeInUsd for price impact calculations

  5. H-03 High Rebalancing Via Pool Value Cap Is Broken Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-fuzz-1768892153850/blob/master/src/worker/executors/glv/glvRebalancer_getPairs.ts#L58
    Round
    Main Review

    Description

    In getPairsByCaps, the code uses sub(-1) instead of mul(-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 use sub(-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 -5000 to 5000), while sub(-1) adds one (converting -5000 to -4999). Since the result stays negative, the gt(minShiftUsd) check always fails and getMax returns 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) with mul(-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));
    
  6. H-04 High Unbounded Metrics Cardinality To DoS DoS Pending
    Location
    src/domain/ui/uiService.ts- src/lib/metrics/metrics.ts- src/lib/metrics/metrics.ts
    Round
    Main Review

    Description

    Even if the variable TIMING_SAMPLE_SIZE is correctly limiting the number of objects inside each key inside _storage.timings, _storage.counters and _storage.gauges. The code is not limiting the number of keys inside _storage.timings, _storage.counters and _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:

    1. Public ingestion endpoint accepts user fields/ui/batch_report (also /report/ui/batch_report) allows clients to submit items with user-controlled event, customFields, and abFlags.Location: src/routes/ui.ts
    2. UI service turns those fields into metric name + tagslogCounter / logTiming build the metric name from event in the code metrics.timing(uiReport.\${event}, time, tags); (note how \${event} is a string part of the json body sent by the user) and include customFields/abFlags inside tags.Location: src/domain/ui/uiService.ts
    3. Metric key is derived from full tag objectThe metrics store computes a key as \${name}:\${_valueToConsistentKey(tags)}, and _valueToConsistentKey JSON-stringifies the full nested object. Note how the name and the tags contains custom values from the user Location: src/lib/metrics/metrics.ts
    4. Metrics are kept in memory until periodic flushThe metrics store keeps entries in _storage and only flushes every 10 minutes.Location: src/lib/metrics/metrics.ts Scale example: With /ui/batch_report at 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 event names, customFields names and abFlags names in tags with the goal of ensuring that the number of keys inside the objects _storage.timings, _storage.counters and _storage.gauges are 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.counters and _storage.gauges to ensure that possible issues like this one are not repeated.

  7. H-05 High Keeper uses position price impact without pending impact, causing ADL and frozen limit/stop order misclassification Logical Error Pending
    Location
    src/domain/position/positionUtils.ts:385
    Round
    Main Review

    Description

    The keeper’s generic price impact helper, getPositionPriceImpactUsd(), does not include position.pendingImpactAmount in 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() through getSizeDeltaForAdl(), so the keeper can estimate the wrong post-ADL market state and choose an incorrect sizeDeltaUsd.
    • Frozen limit/stop order validation uses getPositionPriceImpactUsd() through validateExecutionPrice(), 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.

  8. H-06 High depositReferralRewards Call Would Always Revert Rounding Pending
    Location
    https://github.com/GuardianOrg/gmx-functions-team1-1769575982199/blob/007d7b8e9391fb53ac3e27e501d5e7d08faa210d/fee-automation-workflow/domain/fee/feeDistributionService.ts#L983-L984
    Round
    Main Review

    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 to floor(sum(x_i) / d). Each individual division can lose up to wntPrice - 1 in remainder. With N affiliates and traders, the total difference can be up to N * (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) = 177423742242951297
    

    Off-chain sum: 354847484485902594 + 709694968971805188 + 177423742242951297 = 1241966195700659079 On-chain: floor(3500 * 10^30 / 2818733868580000) = 1241966195700659081 Difference: 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.

  9. H-07 High Wrong Operation Order Cause Reward Loss Logical Error Pending
    Location
    https://github.com/gmx-io/gmx-synthetics-private/blob/fee-automation/contracts/fee/FeeDistributor.sol#L618
    Round
    Main Review

    Description

    In FeeDistributor._distributeFees(), updateLastDistributionTime() is called before setTokensPerInterval():

    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:

    1. updateLastDistributionTime() sets lastDistributionTime = block.timestamp
    2. setTokensPerInterval() internally calls IRewardTracker(rewardTracker).updateRewards()
    3. updateRewards() calls _updateRewards() which calls IRewardDistributor(distributor).distribute()
    4. distribute() calls pendingRewards(), which computes:

    uint256 timeDiff = block.timestamp.sub(lastDistributionTime); return tokensPerInterval.mul(timeDiff); ``` Since lastDistributionTime was already set to block.timestamp in step 1, timeDiff == 0, and pendingRewards() returns 0. 5. distribute() early-returns with 0 — 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 because setTokensPerInterval() already triggers the full distribution flow: setTokensPerInterval() → updateRewards() → distribute(), and distribute() internally sets lastDistributionTime = block.timestamp after 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 after setTokensPerInterval() so that pending rewards are distributed first:

    - IRewardDistributor(distributor).updateLastDistributionTime();
      IRewardDistributor(distributor).setTokensPerInterval(feeAmountGmx / 1 weeks);
    + IRewardDistributor(distributor).updateLastDistributionTime();
    
  10. H-08 High pendingImpactAmount Overwritten In Keeper Logical Error Pending
    Round
    Main Review

    Description

    On-chain pendingImpactAmount is cumulative across increases: IncreasePositionUtils adds the new priceImpactAmount to the existing pending value. However, the PositionIncrease event emits only the delta (pendingPriceImpactAmount = priceImpactAmount). The keeper’s processPositionIncrease writes 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 pendingImpactAmount to the current value in the DB instead of replacing it.

  11. H-09 High Single-Sided Market State Double-Adjustment Logical Error Pending
    Location
    Keepers (Global)
    Round
    Main Review

    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.

  12. H-10 High Non-Determinism Issues In Chainlink CRE Workflow Logical Error Pending
    Location
    gmx-functions (global)
    Round
    Main Review

    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 Problem The 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 timestamp fee-automation-workflow/utils/date.ts:4 — getRecentWednesdayStartOfDay() uses new Date() to compute the weekly period for all subgraph queries. The CRE trigger already provides a deterministic payload.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. Missing orderBy in all 6 subgraph queries fee-automation-workflow/domain/fee/feeDistributionService.ts — Every query lacks orderBy:

    • getAffiliatesTierQuery (line 231) — affiliates
    • getReferralsQuery (lines 252, 268, 283) — affiliateStats, referralStats
    • getFeeStatsV1Query (line 724) — feeStats
    • getFeeStatsV2Query (line 744) — positionFeesInfoWithPeriods, swapFeesInfoWithPeriods The queries use first: 1000, skip: N pagination. Without orderBy, pagination is undefined, producing different aggregate totals (totalRebateUsd, totalEsGmxRewards, v1Fees, v2Fees).
    1. Record<string, T> with Object.entries()/Object.values() iteration fee-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 recommend Map over plain objects — CRE nodes may run different JS engine versions with different iteration behavior.

    2. Unsorted output arrays and batch calldata The output.affiliates (line 522) and output.referrals (line 593) arrays are populated via Object.values() and never sorted. These feed directly into processReferralRewardsCalls() (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

    1. Use trigger timestamp — replace `new Date()` with payload.scheduledExecutionTime or block timestamp
    2. Add orderBy + orderDirection to all subgraph queries
    3. Use Map instead of Record for aggregation structures, or sort inputs before building Records
    4. Sort output arrays by account address before returning from processDistributionData() and before batch processing in `processReferralRewardsCalls()`
  13. H-11 High Keeper Misprices Virtual Inventory Math Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/domain/position/positionUtils.ts#L204
    Round
    Main Review

    Description

    The keeper always calculates the virtual inventory based on the virtualInventoryForPositions value and not based on the virtualInventoryForPositionsInTokens value in it's isPositionLiquidatable check. As the USE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCE param on chain is true this calculation is wrong. This can lead to the keeper ignoring liquidatable positions.

    Recommendation

    Use virtualInventoryForPositionsInTokens to calculate the value of the inventory instead.

  14. H-12 High Reserve checks can block liquidations and ADLs Logical Error Pending
    Location
    PositionUtils.sol, DecreasePositionUtils.sol
    Round
    Main Review

    Description

    PositionUtils.updateOpenInterest re-runs validateReserve and validateOpenInterestReserve after applying a negative open interest delta. DecreasePositionUtils routes 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 = \$100m
    • reserveFactor = 200%, so validateReserve allows up to \$200m
    • openInterestReserveFactor = 200%, so validateOpenInterestReserve allows up to \$200m
    • current reservedUsd = \$210m (due to upward price movement in a popular market) Now suppose an ADL or liquidation reduces exposure and moves reservedUsd down to \$205m. This is a reserve-improving action, but it still reverts:
    • \$205m > \$200m, so validateReserve fails
    • \$205m > \$200m, so validateOpenInterestReserve fails The same issue applies to liquidations. Liquidation orders fully close the targeted position, but they still revert if the residual market-wide reservedUsd remains 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

    1. If governance lowers maxOpenInterest, reserveFactor, or openInterestReserveFactor below 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.
    2. 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() in DecreasePositionCollateralUtils.sol:630. However, after collateral processing completes, the execution now continues through DecreasePositionUtils.sol:303, which invokes the same market-wide validations through PositionUtils.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 global maxOpenInterest or 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.
  15. H-13 High StaticOracleProvider returns min/max inverted DoS Pending
    Location
    https://github.com/gmx-io/gmx-synthetics-private/blob/3bd5f61d3953fe9286ef2f50c78d00561997340a/contracts/oracle/StaticOracleProvider.sol#L46-L47
    Round
    Main Review

    Description

    The StaticOracleProvider returns the min price as max price and the other way around. This likely leads to DoS in the _setPrimaryPrice function.

    Recommendation

    Return the min price as min price and the max price as max price.

  16. M-01 Medium Incompatible Gas Assumptions On MegaEVM Configuration Acknowledged
    Location
    https://github.com/GuardianOrg/gmx-synthetics-team1-1768586730346/blob/256a058fa996d8da5bea9eb617557e323d7379da/contracts/gas/GasUtils.sol#L293-L313
    Round
    Main Review

    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)

  17. M-02 Medium RBAC Signatures Are Replayable Signatures Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/lib/rbac.ts#L10-L11
    Round
    Main Review

    Description

    signRequest only signs METHOD|PATH|RBAC_SALT (rbac.ts (line 10)), and rbacMiddleware verifies 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.

  18. M-03 Medium Lack Of Effective Rate Limits Best Practices Pending
    Location
    rateLimitByUserMiddleware.ts
    Round
    Main Review

    Description

    The rateLimitByUser middleware 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 spoofing X‑Forwarded‑For to influence req.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 /apy endpoint to try to cause a DoS. Moreover, during testing, a script was used that repeatedly requested /apy with 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"
    done
    

    Recommendation

    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.

  19. M-04 Medium ADL Size Delta Overestimation Due To Full PnL Logical Error Pending
    Location
    adlUtils.ts: 24-44
    Round
    Main Review

    Description

    The getSizeDeltaForAdl binary search calculates an oversized sizeDeltaUsd because getNextMarketAfterAdl simulates 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, causing PnlOvercorrected reverts 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 sizeDelta in getNextMarketAfterAdl.

  20. M-05 Medium GraphQL Injection In /intract/task_2 Validation Pending
    Location
    src/domain/subgraph/subgraphService.ts
    Round
    Main Review

    Description

    User‑controlled address is interpolated directly into a GraphQL query without validation or escaping. This happens in intract.ts (reads req.query/req.body), intractService.ts (passes the raw account), and subgraphService.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.

  21. M-06 Medium Vulnerable Dependencies Best Practices Pending
    Location
    package.json
    Round
    Main Review

    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
    • @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.

  22. M-07 Medium validateGlvShiftMaxLoss Uses Post-Shift Input Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-team1-1768586730346/blob/updates/contracts/glv/glvShift/GlvShiftUtils.sol#L236
    Round
    Main Review

    Description

    The validateGlvShiftMaxLoss check in executeGlvShift prices the input and output using post-shift pool values and supply. The shift is executed first, then getPoolValueInfo and getMarketTokenSupply are 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 from fromMarket.

    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 glvShiftMaxLossFactor to 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 fromMarket pool value and market token supply before executing the shift and use those pre-shift values for marketTokensUsd. Keep receivedMarketTokensUsd based on post-shift state, or reuse the withdrawal/deposit valuation inputs to ensure a consistent pre/post comparison.

  23. M-08 Medium Source-Map Fetch Abuse By Regex Bypass Best Practices Pending
    Location
    src/domain/ui/uiService.ts - src/domain/ui/sourceMapResolver.ts - src/domain/ui/sourceMapResolver.ts
    Round
    Main Review

    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:

    1. Public ingestion endpoint accepts error stacks/ui/batch_report accepts "event" items and forwards the payload to logEvent, which later processes customFields.errorStack.Main code: logEvent(logger, item.payload, ...)Location: src/routes/ui.ts
    2. Source-map resolution is triggeredprepareEventPayload checks uiSourceMapsEnabled and customFields.errorStack, then calls getMappedStackTrace(...).Main code: if (uiSourceMapsEnabled && errorStack) { getMappedStackTrace(errorStack) }Location: src/domain/ui/uiService.ts
    3. 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
    4. 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" ); ``` If assetsPath is https://www.production.com/assets, the unescaped dots allow matches like https://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 URLgetSourceMap transforms filePath into <filePath>.map and calls fetch(url) with default redirect-following (up to 20 redirects in node-fetch v2).Main code: const url = filePath.replace(".js", ".js.map"); await fetch(url);Location: src/domain/ui/sourceMapResolver.ts 6. No explicit timeoutfetch(url) is called without AbortController/timeout; hanging hosts can consume sockets/concurrency.Location: src/domain/ui/sourceMapResolver.ts

    Recommendation

    • 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.
  24. M-09 Medium Funding Rate Swap Logic Swaps Wrong Entries Logical Error Pending
    Location
    fundingRate.ts: 235
    Round
    Main Review

    Description

    The updateFundingRate flow tries to reorder updates when next min funding exceeds the current max, but the swap logic swaps the last two entries in the change list, which are fundingIncreaseRate and fundingDecreaseRate. As a result, minFundingRate can still be applied before maxFundingRate. Onchain validateRange checks min <= current max per setUint, 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, validateRange rejects, multicall reverts. Impact
    • Multicall reverts when minFundingRate is 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 minFundingRate and maxFundingRate changes and swap those specific entries, or build the payload in deterministic order so maxFundingRate is always applied before minFundingRate when both update. This ensures onchain range checks pass.

  25. M-10 Medium Risk Free Trades For Malicious Keeper Validation Acknowledged
    Location
    https://github.com/GuardianOrg/gmx-synthetics-team1-1768586730346/blob/256a058fa996d8da5bea9eb617557e323d7379da/contracts/config/Config.sol#L615
    Round
    Main Review

    Description

    In case the LIMITED_CONFIG_KEEPER acts 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_INTEREST key so that the order can't be executed

    Recommendation

    Carefully set the allowed keys the LIMITED_CONFIG_KEEPER should be able to update to not open up any potential attack vectors.

  26. M-11 Medium Event Lookup Across Batch Can Cause Failures DoS Pending
    Location
    https://github.com/GuardianOrg/gmx-functions-team1-1769575982199/blob/007d7b8e9391fb53ac3e27e501d5e7d08faa210d/fee-automation-workflow/main.ts#L186-L187
    Round
    Main Review

    Description

    In main.ts, callFeeDistributor captures fromBlock using the latest header before submitting the transaction, then queries logs from that block onward and expects exactly one matching log. During batched depositReferralRewards execution, a later batch can query a range that still includes prior batch logs (or other matching logs in the same range), causing logs.length > 1 and a hard failure even though the current transaction succeeded.

    Recommendation

    Consider making log selection transaction-specific instead of range-unique

  27. M-12 Medium Buyback Flow Swap Failure Handling Logical Error Pending
    Location
    buyback.ts, openOceanService.ts: 258
    Round
    Main Review

    Description

    In openOceanService.swapTokens if the swap transaction fails, it only logs a warning and continues. The function returns true unless success && 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 failure
    

    Impact:

    • In the pre-buyback swap (native -> buyback token): If it silently fails, the flow still calls feeHandler.buyback without 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 negative totalPnlUsd even though the flow did not complete correctly. This may trigger the BUYBACK_LOSS_TOO_HIGH guard 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 swapTokens to 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");
        }
    
  28. M-13 Medium Trigger Equality Skipped For Limit/Stop Orders Logical Error Pending
    Location
    orderUtils.ts, signedPriceModel.ts, BaseOrderUtils.sol
    Round
    Main Review

    Description

    The keeper limit/stop order flow treats the trigger condition as strictly crossed, not reached. validateOrderTriggerPrice uses < or > and getSignedPricesForFrozenOrder rejects prices that are exactly equal to triggerPrice. 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 _searchSignedPriceByTriggerPrice to 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.

  29. M-14 Medium ADL Sizing Uses Inconsistent PnL Values Logical Error Pending
    Location
    adlUtils.ts
    Round
    Main Review

    Description

    The getNextMarketAfterAdl function computes an adjustedPositionPnl to 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 unadjusted positionPnl.

    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 adjustedPositionPnl to determine which branch to take. However, both branches compute pnlTokenAmountForPool using the unadjusted positionPnl instead of adjustedPositionPnl. This inconsistency causes incorrect pool amount estimation in the simulated nextMarket state. The pnlTokenAmountForPool value directly affects the pool amount in the returned market state, which is then used by getSizeDeltaForAdl to iteratively compute the optimal ADL size. When positionPnl is positive and priceImpactDiffUsd is also positive, the pool deduction is overestimated because the full positionPnl is used rather than the reduced adjustedPositionPnl. 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 PnlOvercorrected errors 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 > 0 and priceImpactDiffUsd > 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 adjustedPositionPnl consistently for both the branching condition and the value calculation.

  30. M-15 Medium Missed Liquidations: Missing Position Fee Logical Error Pending
    Location
    positionUtils.ts: 112
    Round
    Main Review

    Description

    The getRemainingCollateralUsdForLiquidation (BigNumber version) double-counts the position fee when checking if positions are liquidatable. position.totalFeesUsd is fetched from the contract's reader.getPositionInfo() which returns totalCostAmount — this already includes positionFeeAmount (along with borrowing fees, funding fees, UI fees, etc.). The BigNumber version then subtracts getPositionFee() 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 getPositionFee subtraction from getRemainingCollateralUsdForLiquidation to match the BigInt version.

  31. M-16 Medium Reorg Replay Causes pendingImpactAmount Drift Logical Error Pending
    Location
    positions.ts
    Round
    Main Review

    Description

    The processPositionDecrease function has reorg protection for realizedPnl but not for pendingImpactAmount. When a chain reorganization occurs and the same PositionDecrease event is replayed, the pendingImpactAmount calculation 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 different blockHash, it marks the log with isReorg: true and 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 check
    

    The realizedPnl calculation checks isReorg and skips the addition if true. The pendingImpactAmount calculation has no such check and always recomputes based on current database values, which were already modified by the first processing. Consider a position with sizeInUsd = 1000 and pendingImpactAmount = -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 of pendingImpactAmount. For negative values (unfavorable impact), this makes the value less negative than it should be. The pendingImpactAmount feeds into getPositionPriceImpactUsdForLiquidation, which calculates remainingCollateralUsd for liquidation checks. If pendingImpactAmount drifts less negative, the position appears healthier than it actually is.

    Recommendation

    Apply the same reorg protection pattern used for realizedPnl. Skip the pendingImpactAmount adjustment when isReorg is true, since the value was already correctly computed during the first processing.

  32. M-17 Medium Missing Position Null Check Causes Batch Abort DoS Pending
    Location
    positions.ts
    Round
    Main Review

    Description

    The processPositionDecrease function 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 null
    

    Other callers in the codebase correctly check for null before accessing properties, but processPositionDecrease does not. A position may not exist in the keeper database in several scenarios:

    • The corresponding PositionIncrease event 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 PositionIncrease in an orphaned block while the PositionDecrease remains in the canonical chain When the error is thrown, it propagates through processLogs to the enclosing knex.transaction call, 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.

  33. M-18 Medium V2 Keeper Costs Can Underflow Calculations DoS Pending
    Location
    https://github.com/gmx-io/gmx-synthetics-private/blob/9ece3c109e6d7ef2700ef999c94b6b7143b12569/contracts/fee/FeeDistributor.sol#L659
    Round
    Main Review

    Description

    In _calculateChainlinkAndTreasuryAmounts, the treasury amount is calculated by subtracting keeperCostsV2 from the V2 portion of WNT. However, there is no validation that keeperCostsV2 fits within the available V2 allocation. If V2 keeper costs exceed chainlinkTreasuryWntAmount - 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 keeperCostsV2 value 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 _finalizeWntForTreasury that 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 -> REVERT This causes a DoS on distribute, halting the automated weekly fee distribution across all chains, disrupting protocol operations.

    Recommendation

    Options include:

    1. Cap keeperCostsV2 to the available V2 allocation (partial top-up)
    2. Allow V2 keeper costs to also draw from the treasury allocation when the V2 portion is insufficient, mirroring the V1 fallback logic.
  34. M-19 Medium maxPositiveImpactFactor Not Capped In Keeper Validation Pending
    Round
    Main Review

    Description

    In the on chain code if the maxPositiveImpactFactor exceeds the maxNegativeImpactFactor it is capped at the maxNegativeImpactFactor. 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 maxPositiveImpactFactor at the maxNegativeImpactFactor in the keeper code.

  35. M-20 Medium Keeper Can Underset Skew From OI Basis Mismatch Math Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/worker/executors/fundingRate.ts#L477-L478
    Round
    Main Review

    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 of openInterestInTokens * indexPrice. And since USE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCE is 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 (especially minFundingFactorPerSecond behavior). 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

  36. M-21 Medium Stop-Loss Orders Skipped Before Liquidation Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/master/src/worker/executors/liquidations.ts#L208
    Round
    Main Review

    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:

    1. Discarding the signedPriceTokens output (e.g. ETH) and only keeping priceFeedTokens (e.g. USDC),
    2. Not passing signedPriceTokens to getSignedPricesForFrozenOrder, and passing in tokens (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 validateSignedPrices checks 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, the limitStopOrders.ts code (standard path) handles this correctly:

    const [signedPriceTokens, priceFeedTokens] = separatePriceFeedTokens(tokens, realtimeFeedMapping);
    
    signedPrices = getSignedPricesForFrozenOrder(order, signedPriceTokens, latestSignedPrices); // signedPriceTokens correctly passed in
    

    Impact: Users are liquidated instead of having their stop-loss executed, resulting in additional liquidation penalties.

    Recommendation

    Update executeStopLossOrders to pass signedPriceTokens into getSignedPricesForFrozenOrder.

  37. M-22 Medium Keeper Applies Wrong Position Impact Cap Validation Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/domain/position/positionUtils.ts#L407-L410
    Round
    Main Review

    Description

    In the getPositionPriceImpactUsd the 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 out
    

    This leads to the keeper skipping the execution of executable orders.

    Recommendation

    Do only apply this cap in case of decrease orders.

  38. M-23 Medium Nonce Race Condition DoS Pending
    Location
    src/domain/blockchain/blockchain.ts:340-344
    Round
    Main Review

    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.

    1. The WalletPool locks a wallet for a single transaction and refuses to issue the next until the previous one is either mined or times out.
    2. 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.
    3. 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:
    4. Rejection: If Tx B gas < 1.1x Tx A gas, the node rejects it. Result: Liquidation 2 is dropped.
    5. 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 WalletPool to enable parallel transaction issuance, and establish a separate background service to monitor and replace stuck transactions with higher gas fees as needed.

  39. M-24 Medium MegaETH RPC Gas Cap Can Block Liquidations Warning Pending
    Location
    liquidations.ts, positionService.ts, adlService.ts
    Round
    Main Review

    Description

    MegaETH caps both eth_call and eth_estimateGas at 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, the eth_estimateGas binary search and eth_call simulation 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:

    1. Before sending a liquidation TX, the keeper simulates the full executeLiquidation call via eth_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
    }
    
    1. The liquidation executor passes useEstimatedGas: true, forcing eth_estimateGas with no fallback to executionBaseGasLimit:
    // liquidations.ts
    sendTransaction(handler.populateTransaction.executeLiquidation(...), label, {
      useEstimatedGas: true,  // forces eth_estimateGas, no fallback
    });
    
    // txUtils.ts — _getGasByEstimatedGasOrExecutionBaseGasLimit()
    const estimatedGas = await estimatedGasPromise;  // throws if cap hit
    

    If eth_estimateGas fails, sendTransaction throws and the liquidation is not submitted.

    Recommendation

    1. Add a try-catch fallback in the eth_estimateGas path that falls back to a calibrated executionBaseGasLimit when estimation fails, rather than throwing.
    2. Configure MegaETH chain in chains.ts with appropriate gas limits.
    3. Add distinct error detection in isPositionLiquidatable() for gas-cap failures so they are not silently treated as "not liquidatable."
  40. M-25 Medium Secondary keeper auto-reenable can stall Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/master/src/domain/keeper/keeperService.ts#L181
    Round
    Main Review

    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 disableSecondaryMode relies on enableSecondaryModeTimeout to track a pending 15 minute timer when initialIsSecondaryMode is true. When enableSecondaryMode is called manually, it cancels the timer with clearTimeout but does not reset enableSecondaryModeTimeout to null. A subsequent call to disableSecondaryMode sees 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 initialIsSecondaryMode true and calls disableSecondaryMode, scheduling a 15 minute re-enable timer.
    • An operator calls enableSecondaryMode before the timer fires, which clears the timer but leaves enableSecondaryModeTimeout truthy.
    • Later, disableSecondaryMode runs 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, set enableSecondaryModeTimeout = null.

  41. M-26 Medium Decrease validation uses wrong size denominator Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/master/src/domain/position/positionUtils.ts#L1081
    Round
    Main Review

    Description

    The validateDecreasePosition function reduces position.sizeInUsd before calculating sizeDeltaInTokens, causing the denominator to be the remaining size rather than the original size. This results in an inflated token delta and an incorrectly reduced sizeInTokens for 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 sizeDeltaInTokens using the original sizeInUsd as the denominator (PositionUtils.sol#L227). Consider a position with sizeInUsd = 1000, sizeInTokens = 10, and a decrease of sizeDeltaUsd = 200:

    • On-chain: sizeDeltaInTokens = 10 * 200 / 1000 = 2, remaining tokens = 8
    • Keeper: sizeInUsd reduced to 800 first, then sizeDeltaInTokens = 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 subsequent validatePosition call 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 validateLimitStopOrder when deciding whether to execute frozen limit decrease or stop-loss orders. If validation fails, the order is skipped:
    • limitStopOrders.ts calls validateLimitStopOrder
    • validateLimitStopOrder calls validateDecreasePosition for decrease orders
    • validateDecreasePosition calls validatePosition with the incorrect simulated position
    • validatePosition calls isPositionLiquidatable
    • If the position appears liquidatable, validation fails and the order is not executed

    Recommendation

    Calculate sizeDeltaInTokens before reducing position.sizeInUsd, using the original size as the denominator to match on-chain behavior.

  42. M-27 Medium Keeper Works With Stale positionImpactPoolAmount Validation Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/domain/position/positionUtils.ts#L407-L410
    Round
    Main Review

    Description

    The keeper uses the the positionImpactPoolAmount in the getPositionPriceImpactUsd to cap the price impact. This value is likely stale as it ignores the pendingPositionImpactPoolDistributionAmount. 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 positionImpactPoolAmount by the pendingPositionImpactPoolDistributionAmount.

  43. M-28 Medium Stale Fees Can Lead To Missed Liquidations Validation Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/worker/pullers/positions.ts#L255-L300
    Round
    Main Review

    Description

    Keeper liquidation candidate selection uses cached totalFeesUsd from DB when computing remaining collateral. That fee value is refreshed asynchronously by the pullPositionFees function, 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.

  44. M-29 Medium Keeper Always Uses Liquidation Collateral Factor Validation Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/domain/position/positionUtils.ts#L854
    Round
    Main Review

    Description

    The validatePosition function in the keeper bot always uses minCollateralFactorForLiquidation, while on-chain order execution for normal increase/decrease paths validates with minCollateralFactor (higher). This creates false positives off-chain: keeper tries executing frozen orders that can never pass on-chain leverage checks.

    Recommendation

    Add a forLiquidation flag in keeper validation and use minCollateralFactor for normal order execution checks.

  45. M-30 Medium Keeper Price Impact Simulation Ignores Prices Math Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/domain/adl/adlUtils.ts#L20
    Round
    Main Review

    Description

    However, on chain the USE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCE parameter 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 via getSizeDeltaForAdl, which repeatedly simulates post-ADL market state (getNextMarketAfterAdl). That simulation depends on getPositionPriceImpactUsd, currently called with usdDelta = -sizeDeltaUsd in keeper ADL flow. Because keeper ADL simulation skips this conversion, priceImpactDiffUsd is miscomputed, so projected nextPnlToPoolFactor is 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 usdDelta with the current token price.

  46. M-31 Medium Atomic Oracle Providers Enable Price Picking Logical Error Pending
    Location
    Oracle.sol
    Round
    Main Review

    Description

    On live deployments (Arbitrum, Avalanche, Botanix), both ChainlinkPriceFeedProvider and ChainlinkDataStreamProvider were 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 providers
    

    As 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 bridgeOut flow is wrapped with withRelay, which sets prices via setPricesForAtomicAction from user-supplied relayParams.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.

  47. M-32 Medium GLV market token deposits bypass expiry Logical Error Pending
    Location
    https://github.com/gmx-io/gmx-synthetics-private/blob/updates/contracts/glv/glvDeposit/ExecuteGlvDepositUtils.sol#L192
    Round
    Main Review

    Description

    GLV deposits where isMarketTokenDeposit == true do 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 ExecuteDepositUtils timestamp 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.

    Recommendation

    Consider adding request-relative timestamp validation at the start of ExecuteGlvDepositUtils.executeGlvDeposit(...) (or immediately before market-token early return).

    Resolution

    Guardian: Commit 9bc91653 was intended to fix M-32, but it only added the lower-bound oracle timestamp check to the GLV isMarketTokenDeposit branch. The normal deposit path also enforces oracle.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

  48. M-33 Medium Edge data stream decimals are not validated Validation Pending
    Location
    EdgeDataStreamProvider.sol: 74-L80
    Round
    Main Review

    Description

    EdgeDataStreamProvider.getOraclePrice uses edgeDataStreamTokenDecimalsKey(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 example 0), output prices can be mis-scaled by orders of magnitude. In comparison, ChainlinkDataStreamProvider scales by dataStreamMultiplierKey(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, LINEA e.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:   0
    

    Recommendation

    1. In EdgeDataStreamProvider.getOraclePrice, revert if token decimals are unset.
    2. This issue should have been mitigated operationally because TimelockConfig.signalSetEdgeDataStream sets both edgeDataStreamId and edgeDataStreamTokenDecimals in the same scheduled batch. This issue was only expected if: a. Timelock admin explicitly passes 0 for edgeDataStreamTokenDecimals during signalSetEdgeDataStream (governance/operator error), or b. A controller writes directly to DataStore and bypasses the intended timelock config path. Double check why the misconfiguration was allowed to slip through.
  49. M-34 Medium Missing Chainlink ref price feeds for tokens Configuration Pending
    Location
    Oracle.sol
    Round
    Main Review

    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)), getPriceFeedPrice returns (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, and priceFeedHeartbeatDurationKey in the DataStore for all tokens where a Chainlink price feed exists on the deployed chain.

  50. M-35 Medium Account-unbound hashes allow digest collisions Signatures Pending
    Location
    BaseGelatoRelayRouter.sol, RelayUtils.sol
    Round
    Main Review

    Description

    Multichain actions use global replay protection keyed only by digest, while many multichain struct hashes do not bind account. This lets two different users produce the same digest for the same payload shape. _validateCall burns digest before 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 bridgeOut payload P.
    • Alice copies P, signs as Alice, and submits first.
    • Alice tx succeeds, consumes digest(P).
    • Bob tx reverts with InvalidUserDigest. Affected actions:
    • claimFundingFees, claimCollateral, claimAffiliateRewards
    • bridgeOut
    • createDeposit, createWithdrawal, createShift
    • createGlvDeposit, createGlvWithdrawal
    • setTraderReferralCode, registerCode
    • non-subaccount createOrder, updateOrder, cancelOrder, batch struct variants use account = address(0) in hash derivation Not affected:
    • updateOrder and cancelOrder Economic 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 bridgeOut and claim actions, where attacker can execute the same payload shape against own balances, causing victim failure and forced re-sign/retry.

    Recommendation

    Include account in every multichain struct hash that currently omits it, including claims and referral actions. Keep the digest unique per user action.

  51. M-36 Medium Disabled markets block accrued funds DoS Pending
    Location
    MarketUtils.sol
    Round
    Main Review

    Description

    claimFundingFees and claimCollateral now both end with validateMarketTokenBalance after transferring funds out of the market token contract. In both flows, market is passed as an address, so Solidity resolves to the overload that first calls getEnabledMarket. That helper reverts with DisabledMarket whenever 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 claimableCollateralAmount or accrued funding fees recorded for that market from a prior decrease or settlement flow.
    • The user calls claimCollateral or claimFundingFees.
    • 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.

  52. M-37 Medium Deposit reader overquotes capped positive impact Unexpected Behavior Pending
    Location
    ReaderDepositUtils: 166, ExecuteDepositUtils: 409
    Round
    Main Review

    Description

    ReaderDepositUtils.getDepositAmountOutForSingleToken does not model capped positive deposit price impact the same way as on-chain deposit execution. Execution only uses the tokenOut impact pool:

    if (_params.priceImpactUsd > 0) {
        (int256 positiveImpactAmount, /* cappedDiffUsd */) = MarketUtils.applySwapImpactWithCap(...);
        mintAmount += MarketUtils.usdToMarketTokenAmount(
            positiveImpactAmount.toUint256() * _params.tokenOutPrice.max,
            poolValue,
            marketTokensSupply
        );
    }
    

    If tokenOut cannot cover the full positive impact, execution ignores the capped remainder. The reader does more. It falls back to the tokenIn impact pool and increases amountIn:

    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 SwapUtils for swaps, but not in ExecuteDepositUtils for deposits. As a result, Reader.getDepositAmountOut can return a mint amount that no real deposit can receive. Illustrative example:

    • A deposit earns \$100 of positive impact.
    • The tokenOut impact pool can only cover \$60.
    • The tokenIn impact pool still has enough value to cover the remaining \$40.
    • Reader.getDepositAmountOut quotes minting based on the full \$100.
    • Actual deposit execution only mints based on the \$60 available from the tokenOut side. Impact:
    • Frontends, integrations and users can set minMarketTokens from an inflated quote and revert unexpectedly

    Recommendation

    Remove the tokenIn fallback from ReaderDepositUtils so the reader only quotes value that deposit execution can actually mint

  53. M-38 Medium Relay Fee Atomic Swap Extraction Oracle Pending
    Location
    BaseGelatoRelayRouter.sol, SubaccountGelatoRelayRouter.sol
    Round
    Main Review

    Description

    Relay fee handling exposes an atomic swap path before the wrapped action-specific logic executes. _handleRelayFee pulls feeToken from the user and swaps it into WNT through GMX using AtomicSwap pricing 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);
    }
    

    swapFeeTokens is a real protocol swap. It uses swapPricingType = 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 -> WNT swap 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 removeSubaccount is just the cleanest same-chain trigger for this. It can be made into a semantic no-op because DataStore.removeAddress does not require the address to exist in the set first. If the chosen subaccount was 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 / WNT conversion 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 removeSubaccount that uses SOL -> USDC -> WETH as the relay fee path. Assume the true market is:
    • SOL = $200
    • WETH = $2,000 So 1,000 SOL should be worth 100 WETH. Now assume the attacker chooses atomic providers such that the fee swap uses:
    • SOL min = $210
    • WETH max = $1,980 GMX computes output from tokenInPrice.min / tokenOutPrice.max, so the protocol computes: amountOut ~= 1,000 * 210 / 1,980 = 106.06 WETH Using current Arbitrum atomic fees for this path:
    • SOL-USDC atomic swap fee: 1.50%
    • WETH-USDC atomic swap fee: 2.25% After atomic fees: 106.06 * (1 - 0.015) * (1 - 0.0225) ~= 102.08 WETH If negative price impact consumes 0.30 WETH and the actual relay fee is 0.05 WETH, the attacker still receives: 102.08 - 0.30 - 0.05 = 101.73 WETH At the true market price, 101.73 WETH is worth about $203,460. The attacker started with 1,000 SOL worth $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

  54. M-39 Medium Market-Order Sync Guard Fail-Open in DB Desync DoS Pending
    Location
    src/domain/log/logStatusService.ts
    Round
    Main Review

    Description

    isSynced(keys) returns false when 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:

    1. Pullers in subscribeToLogs(...) continuously process logs.
    2. Each polling cycle fetches logs, parses/processes them, writes entities/raw logs, and updates logs_status.last_block_number.
    3. _processLogs(...) and updateLogStatusIfSameBlock(...) run in the same DB transaction.
    4. If the cycle fails/aborts/timeouts, transaction rolls back.
    5. Repeated rollbacks stall last_block_number while chain head advances, so isSynced=false. Moreover, is isSynced is false this generates other vulnerabilities:
    6. Missing await in batch path (src/worker/executors/marketOrders.ts, ~303):
    if (!logStatusService.isSynced(["orders", "oracle"])) return;
    

    isSynced() returns Promise<boolean> and promise is truthy, so guard never blocks, so the current check would never trigger.

    1. 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

    1. Add await in batch market-order sync check (executeMarketOrders):
    if (!(await logStatusService.isSynced(["orders", "oracle"]))) {
      return;
    }
    
    1. 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 blocksBehind starts 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.
  55. L-01 Low RateLimit Middleware To DoS Access Control Pending
    Location
    rateLimitMiddleware.ts
    Round
    Main Review

    Description

    The rateLimit middleware 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 cause 429 responses 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 rateLimit middleware 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) with rateLimitByUser, 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.

  56. L-02 Low minAmountOut Ignored In BridgeOut Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-team1-1768586730346/blob/updates/contracts/multichain/LayerZeroProvider.sol#L315
    Round
    Main Review

    Description

    LayerZeroProvider.prepareSend overwrites the user‑provided minAmountOut with Stargate’s quoted amountReceivedLD, 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.
    • prepareSend replaces minAmountLD with receipt.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.

  57. L-03 Low Unbounded Time Range Queries Trust Assumptions Pending
    Location
    src/routes/intract.ts & src/routes/apy.ts
    Round
    Main Review

    Description

    Multiple public endpoints accept user‑controlled startTimestamp/endTimestamp without validation of size, ordering, or maximum range. These values are forwarded to subsquid/subgraph queries, potentially causing expensive scans over large datasets. /apy is 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, endTimestamp
    • GET /intract/task_2?startTimestamp=...&endTimestamp=...
    • POST /intract/task_2 with JSON body containing startTimestamp, endTimestamp Basic 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.
  58. L-04 Low Unhandled Input Parsing Errors Leading To 500 Best Practices Pending
    Location
    - \`src/routes/admin.ts\` - \`src/routes/candles.ts\` - \`src/routes/signedPrices.ts\` - \`src/domain/signedPrice/signedPriceModel.ts\` - \`src/routes/apy.ts\` - \`src/routes/performance.ts\` - \`src/domain/subsquid/subsquidService.ts\` - \`src/domain/glv/glvModel.ts\` - \`src/domain/market/marketService.ts\`
    Round
    Main Review

    Description

    Multiple endpoints accept user‑controlled parameters without strict validation. Invalid values can trigger unhandled exceptions (e.g., BigNumber.from on 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 endpoints

    • GET /admin/glv/price_loss — params: glv, from, amount
      • issue: invalid amount or unknown glv/from
    • GET /admin/glv/shift — params: glv, from, to, amount, staticCall, secret
      • issue: invalid amount or unknown glv/from/to
    • 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 bad sourceUrl
    • GET /signed_prices/search — params: blockNumber, createdAfter, createdBefore, after, before, limit, asc
      • issue: NaN values → limit/to_timestamp
    • 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: address issue: invalid address → GraphQL parse error

    Recommendation

    • Validate all numeric inputs with Number.isFinite and return 400 on invalid.
    • Validate addresses with ethers.utils.getAddress and return 400 on invalid.
    • Guard BigNumber.from with try/catch → return 400.
    • Require arrays (logs, metrics) with Array.isArray.
    • Add missing return after error responses.
    • Consider centralized validation middleware.
  59. L-05 Low GLV Oracle Count Mismatch Causes Keeper Loss Gas Griefing Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-team1-1768586730346/blob/updates/contracts/glv/glvDeposit/GlvDepositUtils.sol#L159
    Round
    Main Review

    Description

    GLV deposit creation validates execution fees assuming glvTokenPriceUsed is false, yielding an oraclePriceCount of 2 + marketCount + swapsCount. However, keepers typically provide a GLV oracle price during execution, resulting in glvTokenPriceUsed being true and an oraclePriceCount of 4 + 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 oraclePriceCount of 4 but capped to the execution fee collected for 3. The keeper loses EXECUTION_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);
    
  60. L-06 Low Zero-Division Can Halt GLV Rebalancer Unexpected Behavior Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-fuzz-1768892153850/blob/master/src/domain/glv/glvRebalancerUtils.ts#L1301
    Round
    Main Review

    Description

    The rebalancer divides by zero in multiple places. capShiftSizeByMaxAmounts divides by currentFromShortUsd and currentFromTotalUsd. If a single short pool is empty, the division by 0 causes the rebalancer to revert and stop rebalancing for all markets. Similarly, getTargetPoolSize divides by targetUtilization (0 when all markets have zero reserved OI), and getProportionalShiftSizeUsd divides 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.

  61. L-07 Low Missing Spread Validation For Impact Factor Validation Pending
    Location
    riskOracle.ts(executor)
    Round
    Main Review

    Description

    The risk oracle executor validates that positivePositionImpactFactor is strictly less than negativePositionImpactFactor, but does not enforce any minimum spread between these values. PricingUtils.sol explicitly 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%).

  62. L-08 Low Sync Lacks Parameter/baseKey Binding Validation Pending
    Location
    ConfigSyncer.sol
    Round
    Main Review

    Description

    In ConfigSyncer.sol, the sync function trusts the additionalData baseKey and 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 different baseKey than 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 parameter to an expected baseKey and 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.

  63. L-09 Low Public Log Ingestion Endpoints Best Practices Pending
    Location
    src/routes/ui.ts: 14 - src/lib/middlewares/rateLimitByUserMiddleware.ts: 8 - src/lib/userHash.ts: 10 - src/app.ts: 26
    Round
    Main Review

    Description

    The public endpoints: /ui/batch_report and /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.

  64. L-10 Low Unbounded IP Set Access Control Pending
    Location
    src/app.ts: 26 - src/lib/middlewares/loggerMiddleware.ts: 32
    Round
    Main Review

    Description

    uniqueUsers is a global in-memory Set that stores every distinct req.ip observed by loggerMiddlewareEnd. There is no eviction or TTL, so the set grows for the lifetime of the process. In src/app.ts, trust proxy is enabled (server.set("trust proxy", true)), which makes Express accept the client IP from X-Forwarded-For rather than the direct socket IP. If the service is reachable without a strictly configured trusted proxy list, a client can spoof X-Forwarded-For and generate an unbounded stream of unique IPs, causing unbounded growth of the set and distorting the “unique users” metric.

    Recommendation

    Replace the Set with an LRU/TTL cache (or an approximate counter such as HyperLogLog), and configure trust proxy with a strict allow-list of trusted proxies. If proxy trust cannot be locked down, validate or ignore X-Forwarded-For so untrusted clients cannot spoof req.ip.

  65. L-11 Low Validation Bug In Admin Metrics Ingestion Pending
    Location
    src/routes/admin.ts: 627
    Round
    Main Review

    Description

    /admin/write_metrics accepts an array of metric objects and validates each entry. The validation intends to require a value for all methods except increment, but the check is implemented as if (key !== "increment" && value === undefined) instead of checking the method. This means the value requirement is tied to the metric name rather than the metric method. As a result, a metric with method gauge, histogram, or distribution can omit value if 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 (not key) and enforce value for gauge, histogram, and distribution.

  66. L-12 Low Empty Funding Data Silently Skips Updates Unexpected Behavior Pending
    Location
    fundingRate.ts: 482
    Round
    Main Review

    Description

    getNextFundingRate assumes there is at least one aggregated funding sample per market after exchange filtering. If aggFundingRates is empty, getMedian returns undefined, which is then used in Math.abs and Math.max. This produces NaN targets and diffs, and the update check silently falls through without setting shouldUpdate. The result is missed funding updates with confusing logs, rather than a clear error or fallback. Scenarios that produce an empty aggFundingRates include:

    • exchange filters that exclude all sources ((e.g., config uses binance but ingested rows are labeled binance_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 aggFundingRates and log a clear warning, or fallback to a safe default. A minimal fix is to return shouldUpdate: false with an explicit log when aggFundingRates.length === 0 before computing medians.

  67. L-13 Low Tier Change Could Cause Reverts For Fee Workflow Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-functions-team1-1769575982199/blob/007d7b8e9391fb53ac3e27e501d5e7d08faa210d/fee-automation-workflow/domain/fee/feeDistributionService.ts#L983-L984
    Round
    Main Review

    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.

  68. L-14 Low Over-Broad OFT Trigger For BRIDGED_GMX_RECEIVED Configuration Pending
    Location
    https://github.com/GuardianOrg/gmx-functions-team1-1769575982199/blob/007d7b8e9391fb53ac3e27e501d5e7d08faa210d/fee-automation-workflow/main.ts#L418-L419
    Round
    Main Review

    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.

  69. L-15 Low OrderUpdated Drops autoCancel Sync Warning Pending
    Location
    order.ts
    Round
    Main Review

    Description

    The on-chain OrderUpdated event includes the autoCancel flag, and OrderHandler.updateOrder updates the on-chain auto-cancel list. However, the keeper’s processOrderUpdated path does not persist autoCancel in the database. This leaves the DB out of sync with on-chain order state. The keeper later uses DB auto_cancel in getAutoCancelOrdersByPositionKey to 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 autoCancel from OrderUpdated into the DB, and optionally clear skipReason when skip is reset.

  70. L-16 Low Docker Hardening Recommendations Best Practices Pending
    Location
    Dockerfile
    Round
    Main Review

    Description

    The following critical vulnerabilities were identified in the container and infrastructure configuration of the application:

    1. Global SSL Validation Disabled The docker:run script in package.json explicitly sets the environment variable NODE_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).
    2. Container Runs as Root The Dockerfile fails to switch to a non-privileged user (e.g., USER node) and runs the application as root. 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.
    3. Weak Database Security The docker-compose.yml configuration 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.
    4. Production Image Bloat & Attack Surface The Dockerfile installs powerful system and debugging tools—including gdb, 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:

    1. Enable SSL Validation:
      • Immediate Action: Remove NODE_TLS_REJECT_UNAUTHORIZED=0 from package.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.
    2. Run as Non-Privileged User:
      • Modify the Dockerfile to include USER node after the installation and build steps are complete. This ensures the application process runs with the limited permissions of the node user.
    3. Secure Database Configuration:
      • Password: Use Docker secrets or environment variables to inject credentials. Do not hardcode passwords in docker-compose.yml. At a minimum, ensure POSTGRES_PASSWORD is set to a long, complex, and random string.
      • Port Exposure: Remove the ports mapping (5432:5432) in production configurations. The application interface should communicate with the database solely via the internal Docker network.
    4. Minimize Container Image:
      • Use multi-stage builds in the Dockerfile. Perform installation and building in a builder stage, then copy only the necessary artifacts (e.g., dist/, package.json, production node_modules) to a final runner stage.
      • Avoid installing unnecessary tools (vim, gdb, strace) in the final stage. Consider using minimal base images like node:alpine or gcr.io/distroless/nodejs to further reduce the attack surface.
  71. L-17 Low Keeper ADL DoS If factor == max factor Validation Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/worker/executors/adl.ts#L90
    Round
    Main Review

    Description

    The keeper thinks that ADL is required if the pnlToPoolFactor >= maxPnlFactorForAdl while on the contract side ADL is only executed if pnlToPoolFactor > 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.

  72. L-18 Low Lack of Slippage Sanity Checks in Swap Execution Frontrunning Pending
    Location
    src/domain/swap/swapUtils.ts
    Round
    Main Review

    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 function getSwapPathAmountOut from src/domain/swap/swapUtils.ts is the primary simulation engine. It returns null (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, in src/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).
    1. Reconnaissance: Attacker monitors the pending orders pool (or mempool) for GMX Swap orders with minOutputAmount set to 0.
    2. 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).
    3. Victim Execution:
      • The Keeper processes the user's order.
      • It calculates amountOut in getSwapPathAmountOut.
      • Due to the pool imbalance created by the attacker, amountOut includes 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.
    4. 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, in getSwapPathAmountOut, calculate the theoretical "fair" amount out based on oracle price (as if impact was 0). Then, compare the calculated amountOut with the fair amount. Finally, if the deviation exceeds the safety threshold, log a warning and skip execution, even if amountOut > minOutputAmount. A different option would be to use frontrun resistant RPC if keeper finds minOutputAmount is too low. they can

  73. L-19 Low Incorrect priority config for shift execution Configuration Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/domain/shift/shiftService.ts#L72-L73
    Round
    Main Review

    Description

    Normal shift transactions currently read the GLV shift priority key. This can cause suboptimal queue ordering when shiftExecutionPriority and glvShiftExecutionPriority differ, leading to minor scheduling/latency inconsistencies under load.

    Recommendation

    In shiftService.ts, change: keeperConfig.get("glvShiftExecutionPriority", 0) to keeperConfig.get("shiftExecutionPriority", 0).

  74. L-20 Low Missing Swap Validation In Keeper Validation Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/worker/executors/limitSwapOrders.ts#L185-L192
    Round
    Main Review

    Description

    Keeper frozen limit-swap execution validates mainly amountOut >= minOutputAmount off-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.

  75. L-21 Low Protocol-Unfavorable Rounding Review Rounding Pending
    Location
    DecreasePositionCollateralUtils.sol, PositionPricingUtils.sol
    Round
    Main Review

    Description

    1. In payForCost, when remaining costs are paid using secondaryOutputToken, 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 remainingCostUsd is later set to 0, marking fees as fully paid. DecreasePositionCollateralUtils.sol:611

    1. Borrowing fee tokenization uses floor division:
    borrowingFees.borrowingFeeAmount = borrowingFeeUsd / collateralTokenPrice.min
    

    Tokenized borrowing fees can be slightly lower than intended USD-equivalent fees. PositionPricingUtils.sol:477

    1. UI fee tokenization uses floor division:
    uiFees.uiFeeAmount = Precision.applyFactor(sizeDeltaUsd, uiFees.uiFeeReceiverFactor) / collateralTokenPrice.min
    

    UI fee amounts can be slightly under-collected in token terms. PositionPricingUtils.sol:526

    1. Position fee tokenization uses floor division:
    fees.positionFeeAmount = Precision.applyFactor(sizeDeltaUsd, fees.positionFeeFactor) / collateralTokenPrice.min
    

    Protocol 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.

  76. L-22 Low Unsigned prices control median in GMOracle Oracle Pending
    Location
    GMOracleProvider.sol
    Round
    Main Review

    Description

    GmOracleProvider.getOraclePrice decodes a report from caller-supplied data and derives signers from report.signerInfo. Both the sorting check and the signature validation iterate only signers.length times, but the median price computation operates over the full price arrays. There is no check that these array lengths equal signers.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.getMedian picks 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: Assume MIN_ORACLE_SIGNERS = 3 and the three legitimate signers report valid min prices [100, 200, 300]. A malicious keeper constructs a report with:

    • signerInfo encoding 3 signers
    • signatures: 3 valid signatures (+ any padding)
    • minPrices: [100, 200, 300, 999999, 999999, 999999, 999999] Result:
    1. Sorting check passes — only validates [100, 200, 300].
    2. Signature check passes — only validates first 3 entries against valid signers.
    3. getMedian picks arr[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
        );
    }
    
  77. L-23 Low Subaccounts can self-deal fee-routing fields Validation Pending
    Location
    SubaccountUtils.sol
    Round
    Main Review

    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 receiver and cancellationReceiver:

    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 referralCode set to a code it owns and uiFeeReceiver set to its own address.
    • The order still passes subaccount validation because only receiver and cancellationReceiver are checked.
    • Alice's order executes normally, but part of the fee flow is credited to the bot's uiFeeReceiver.
    • Since setTraderReferralCode only 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.

  78. L-24 Low Equal max impact caps remove safety margin Configuration Pending
    Location
    markets.ts, DecreasePositionCollateralUtils.sol
    Round
    Main Review

    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 negative to keep capped round trips unprofitable. On increase, positive position impact is capped by capPositiveImpactUsdByMaxPositionImpact:

    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 positiveMaxPositionImpactFactor strictly below negativeMaxPositionImpactFactor for SOL [SOL-SOL].

  79. L-25 Low TWAP tranche splits strand vault dust Rounding Pending
    Location
    OrderUtils.sol
    Round
    Main Review

    Description

    createTwapOrder splits the total collateral and execution fee across twapCount orders 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 the test_replay_TWAP_EQ_03 replay: the TWAP path and the equivalent individual path end with identical sizeInUsd and sizeInTokens, but the TWAP path reports 2 fewer units of collateral because the split rounds down during tranche creation. As a result, small dust amounts can remain in OrderVault after 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 OrderVault across repeated TWAP usage

    Recommendation

    Track and handle the TWAP split remainder explicitly. A simple fix is to assign the remainder to the final tranche.

  80. L-26 Low SUI and WAVAX retain impact-pool drips Configuration Pending
    Location
    Global
    Round
    Main Review

    Description

    The Arbitrum SUI [WETH-USDC] market and the Avalanche WAVAX [WAVAX-USDC] market are configured with nonzero positionImpactPoolDistributionRate values even though the surrounding peer markets use 0. 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:   141000000000000000000
    

    distributePositionImpactPool is 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 positionImpactPoolDistributionRate for SUI and WAVAX to 0 if 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.

  81. L-27 Low GLV rebalancer can abort entire rebalance cycle Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/worker/executors/glv/glvRebalancer.ts#L67-L68
    Round
    Main Review

    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.

  82. L-28 Low minUtililization not enforced in GLV rebalancer Configuration Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/config/glvs.ts#L54-L55
    Round
    Main Review

    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 minUtililization is 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.

  83. I-01 Informational Outdated Comments In updateAdlState Documentation Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-team1-1768586730346/blob/updates/contracts/adl/AdlUtils.sol#L68-L69
    Round
    Main Review

    Description

    The comments in updateAdlState state that the isAdlEnabled flag is used to "avoid having to repeatedly validate whether auto-deleveraging is required." However, the actual implementation in executeAdl always re-validates the PnL factor by calling isPnlFactorExceeded regardless of the flag state. The flag only provides early revert when isAdlEnabled is 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.

  84. I-02 Informational GMX Signed Prices Use maxPrice For minPriceFull Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/worker/pullers/pricesFromGmx.ts#L119-L120
    Round
    Main Review

    Description

    For GMX signed price derivation, minPriceFull is derived from p.maxPrice instead of p.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 minPriceFull from p.minPrice.

  85. I-03 Informational Redundant Index Price Fetch In Withdrawal Gas Optimization Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-team1-1768586730346/blob/updates/contracts/withdrawal/ExecuteWithdrawalUtils.sol#L457
    Round
    Main Review

    Description

    _getOutputAmounts calls params.oracle.getPrimaryPrice for the index token even though prices.indexTokenPrice is already available from getMarketPrices. This duplicates the oracle read and introduces an unnecessary dependency on a second call.

    Recommendation

    Use the existing prices.indexTokenPrice when calling getPoolValueInfo to keep price usage consistent and reduce redundant oracle reads.

  86. I-04 Informational Unsanitized Parameters Used In SQL Queries Best Practices Pending
    Location
    admin.ts: 510-527 - signedPriceModel.ts: 330-410 - lockModel.ts: 23-40 - db/index.ts: 38-45 - db/index.ts: 344 - candleModel.ts: 175-235 - positionModel.ts: 186-205 - marketModel.ts: 175-190 - db/index.ts: 110-120 - db/index.ts: 126-134 - db/index.ts: 148-179
    Round
    Main Review

    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:

    1. 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 validation
    2. signedPriceModel.ts:330-410 - getDataForCandlesPerMinute()Injected: Token addresses concatenated into IN clausePattern: tokenAddresses.map((a) => \'${a}'`).join(",")in WHERE Source: Config viatokensConfig.getTokens()`
    3. lockModel.ts:23-40 - tryAcquireLock()Injected: ttlSeconds into INTERVALPattern: INTERVAL '\${ttlSeconds} seconds'Source: Function param
    4. db/index.ts:38-45 - pool.afterCreateInjected: statementTimeout, idleInTransactionSessionTimeoutPattern: SET statement_timeout = '\${statementTimeout}ms'Source: Config values
    5. db/index.ts:344 - getStuckQueries()Injected: threshold into INTERVALPattern: NOW() - INTERVAL '\${threshold} seconds'Source: Internal monitoring param
    6. candleModel.ts:175-235 - createOrUpdateCandles()Injected: Query objects joined as stringsPattern: rawQueries.map(q => q.toString()).join(";")Source: Internal candle data
    7. positionModel.ts:186-205 - updatePositions()Injected: Position update queriesPattern: sql.push(query.toString()); trx.raw(sql.join(";"))Source: Internal position data
    8. marketModel.ts:175-190 - updateMarkets()Injected: CASE expression fragmentsPattern: trx.raw(\CASE address ${cases} ELSE...`)`Source: Internal market data
    9. db/index.ts:110-120 - testReset()Injected: Table names in DELETEPattern: tables.map(t => \DELETE FROM ${t}`)`
    10. db/index.ts:126-134 - testCreateTemplateDatabase()Injected: Database name in DDLPattern: DROP/CREATE DATABASE \${templateName}
    11. 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.

  87. I-05 Informational Incorrect CRE Network/Config Values Configuration Pending
    Location
    https://github.com/GuardianOrg/gmx-functions-team1-1769575982199/blob/007d7b8e9391fb53ac3e27e501d5e7d08faa210d/fee-automation-workflow/configArbitrum.json#L2-L3
    Round
    Main Review

    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.

  88. I-06 Informational Fee Rewards Manipulation Via Snapshot Inflation Gaming Pending
    Location
    https://github.com/gmx-io/gmx-synthetics-private/blob/updates/contracts/fee/FeeDistributor.sol#L121
    Round
    Main Review

    Description

    initiateDistribute() determines each chain's share of GMX rewards by reading spot totalSupply() from the extendedGmxTracker on each chain. This snapshot is stored and used throughout the rest of the distribution cycle to calculate requiredGmxAmount:

    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

  89. I-07 Informational Implementation mismatch for forceCalculation Documentation Pending
    Location
    GlvUtils.sol:37
    Round
    Main Review

    Description

    GlvUtils.getGlvValue comments state there is a forceCalculation option 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 when oracle.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 forceCalculation in getGlvValue and thread it through relevant call sites. Or remove/update comments to reflect current behavior (no override available).

  90. I-08 Informational pnlAfterPriceImpactUsd Calculated Twice Superfluous Code Pending
    Location
    https://github.com/gmx-io/gmx-synthetics-private/blob/a1abe07e19f8a86e57e633080709f2419ccbab61/contracts/reader/ReaderPositionUtils.sol#L259-L272
    Round
    Main Review

    Description

    pnlAfterPriceImpactUsd is calculated twice in the getPositionInfo function.

    Recommendation

    Consider to remove one of the two calculations.

  91. I-09 Informational Market TWAP Orders Always Revert Logical Error Pending
    Location
    OrderUtils.sol
    Round
    Main Review

    Description

    createTwapOrder always assigns a nonzero validFromTime to every slice after the first one. Since _createOrder explicitly forbids market orders with a nonzero validFromTime, any TWAP request using a market order type and twapCount >= 2 will 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 validFromTime restriction.

  92. I-10 Informational Missing Multichain TwapOrder Functionality Logical Error Pending
    Location
    GLOBAL
    Round
    Main Review

    Description

    The createTwapOrder function takes a srcChainId as param but can only be used on the local chain.

    Recommendation

    Consider to let multichain users create TwapOrders or to remove this param.

  93. I-11 Informational External-driven max funding cap can lag GMX Logical Error Pending
    Location
    https://github.com/GuardianOrg/gmx-synthetics-keeper-team1-1768892132004/blob/02688b85e664531640cc50abeaef3cc74899143f/src/worker/executors/fundingRate.ts#L506-L507
    Round
    Main Review

    Description

    The keeper computes a target maxFundingRate from 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 as MAX_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.

  94. I-12 Informational TWAP orders inherit fixed creation price bounds Logical Error Pending
    Location
    Global
    Round
    Main Review

    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:
    1. Too strict
    • acceptablePrice or minOutputAmount becomes unfillable
    • slices fail, freeze, or remain unexecuted
    1. 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.
  95. I-13 Informational TWAP orders inherit fixed creation price bounds Logical Error Pending
    Location
    Global
    Round
    Main Review

    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:
    1. Too strict
    • acceptablePrice or minOutputAmount becomes unfillable
    • slices fail, freeze, or remain unexecuted
    1. 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.

  96. I-14 Informational TWAP bypasses tightening of creation validations Logical Error Pending
    Location
    Global
    Round
    Main Review

    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.

  97. I-15 Informational Cross-Collateral Review Concerns Informational Pending
    Round
    Main Review

    Description

    1. Withdrawal fairness and redeemability

    Market NAV would include cross-collateral poolAmount, while LP withdrawals would still be paid only in longToken and shortToken. 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 / pnlToken model. 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 SwapRequest and 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.

  98. I-16 Informational Cross-Margin Review Concerns Informational Pending
    Round
    Main Review

    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 Settlement changes core position semantics

    0002.e resets sizeInUsd while keeping sizeInTokens unchanged. In the current engine, sizeInUsd is 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 sizeInUsd changes 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.f leaves 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
  1. H-01 High StrictVault Not Synced In Buyback Flow Logical Error Reported
    Location
    https://github.com/GuardianOrg/gmx-synthetics-private-team1-1769494159874/blob/b34275f43f9f07988c3f0ea77953ce20b2bbcc38/contracts/fee/FeeHandler.sol#L178
    Round
    Remediation Review 1

    Description

    The buyback flow does no sync the GMX or WNT amount in the FeeVault. This can lead to an inflated withdrawableBuybackTokenAmount:

    • Eve calls claimFees to increase the buybackAvailableFeeAmount of USDC by $500 and the FeeVault is synced via recordTransferIn to hold $500 USDC
    • Eve calls buyback to swap $100 WNT to USDC this will decrease the synced USDC amount of the FeeVault as transferOut is called but will not sync the WNT balance of the FeeVault as recordTransferIn is not used
      • It will also decrease buybackAvailableFeeAmount by the USDC amount that Eve will receive and increase the withdrawableBuybackTokenAmount by the received WNT tokens
    • Eve calls claimFees again but this time with WNT as the feeToken which will call recordTransferIn to get the amount of unsynced tokens in the FeeVault that equal the current claimable tokens + the WNT received during the last buyback call (that were not synced)
      • Now the withdrawableBuybackTokenAmount is increased not only by the claimed amount but also again by the received WNT tokens from the buyback call 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.

    Recommendation

    Call recordTransferIn in the buyback flow to keep the FeeVault synced.

  2. M-01 Medium M-32 and M-33 fixes introduce build errors Error Reported
    Location
    ExecuteGlvDepositUtils.sol, TimelockConfig.sol
    Round
    Remediation Review 1

    Description

    Two recent fixes introduce compile-time regressions. First, 9bc91653 adds a new check in ExecuteGlvDepositUtils, but references deposit.updatedAtTime() before deposit is declared. In this branch, the only in-scope request object is glvDeposit.

    if (glvDeposit.isMarketTokenDeposit()) {
        if (params.oracle.minTimestamp() < deposit.updatedAtTime()) {
            revert Errors.OracleTimestampsAreSmallerThanRequired(
                params.oracle.minTimestamp(),
                glvDeposit.updatedAtTime()
            );
        }
    }
    

    Second, 436e2901 changes InvalidEdgeDataStreamDecimals to take two arguments in Errors, but TimelockConfig still 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() with glvDeposit.updatedAtTime() in ExecuteGlvDepositUtils. Update the TimelockConfig revert to pass both required arguments to InvalidEdgeDataStreamDecimals, for example token and edgeDataStreamTokenDecimals.

  3. M-02 Medium GLV market token deposits bypass max expiry Logical Error Reported
    Location
    ExecuteGlvDepositUtils.sol
    Round
    Remediation Review 1

    Description

    Commit 9bc91653 was intended to fix M-32, but it only added the lower-bound oracle timestamp check to the GLV isMarketTokenDeposit branch. The normal deposit path also enforces oracle.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

  4. M-03 Medium Missing init bricks relay fee swaps Configuration Reported
    Location
    BaseGelatoRelayRouter.sol, config/general.ts
    Round
    Remediation Review 1

    Description

    7b6f71e7de1e30e19b0ae6e62d3b1f384e80b221 adds a new global guard in BaseGelatoRelayRouter that rejects any relay fee swap whose USD value exceeds MAX_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_USD remains at the DataStore default value of 0 unless operators manually seed it out-of-band. Any relay action that uses feeSwapPath will then revert as soon as relayFeeUsd > 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_USD in their setup.

    Recommendation

    Add MAX_RELAY_FEE_SWAP_USD to the standard general-config path and initialize it during deployment or migration, instead of relying on manual post-deploy writes. At minimum:

    • add a maxRelayFeeSwapUsd field to config/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
  5. M-04 Medium Relay TWAP flow inherits the M-35 hash flaw DoS Reported
    Location
    GelatoRelayRouter.sol, RelayUtils.sol, BaseGelatoRelayRouter.sol
    Round
    Remediation Review 1

    Description

    M-35 identified that non-subaccount relay actions can share the same globally consumed digest because replay protection is keyed only by digest, while some struct hashes do not bind account. The new non-subaccount createTwapOrder flow added in 17c104fa inherits the same issue. GelatoRelayRouter.createTwapOrder builds its digest with RelayUtils.getCreateTwapOrderStructHash(relayParams, params, twapCount, interval), and that overload hardcodes account = 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, _validateCall still 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 createTwapOrder payload P.
    • 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 createTwapOrder Include account in the non-subaccount getCreateTwapOrderStructHash path so the digest is unique per user action.

  6. M-05 Medium Zero saved funding biases longs at min Logical Error Reported
    Location
    MarketUtils.sol
    Round
    Remediation Review 1

    Description

    Introduced in commit 8dc3041, the adaptive funding path getNextFundingFactorPerSecond now treats nextSavedFundingFactorPerSecond == 0 as 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 0 neutral. It does not. The final min-bound call uses Calc.boundMagnitude, which gives zero a positive sign and upgrades it to +min whenever 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 if longOpenInterest == shortOpenInterest. For example:

    • fundingIncreaseFactorPerSecond != 0
    • savedFundingFactorPerSecond = 0
    • longOpenInterest == shortOpenInterest
    • minFundingFactorPerSecondKey(market, true) > 0 The function does not early return. It selects the long-side bounds because 0 >= 0, then boundMagnitude turns 0 into +minLong. The returned result is longsPayShorts = true even though the market is balanced.

    Recommendation

    Treat nextSavedFundingFactorPerSecond == 0 as neutral rather than implicitly long.

  7. L-01 Low Buyback info script reads stale fee holder Configuration Reported
    Location
    printBuybackInfo.ts
    Round
    Remediation Review 1

    Description

    printBuybackInfo still assumes that buyback inventory is physically held by FeeHandler. After the fee custody refactor, that assumption is no longer true: claimFees, buyback, and withdrawFees all move assets through FeeVault instead. The script now reads withdrawableBuybackTokenAmount from DataStore but compares it against the token balance of feeHandler.address. On deployments that actually use FeeVault, 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.ts to read balances from FeeVault instead of FeeHandler.

  8. I-01 Informational Legacy funding key callers write dead slots Configuration Reported
    Location
    AdaptiveFunding.ts, Config.ts, Keys.sol, keys.ts
    Round
    Remediation Review 1

    Description

    The funding bound keys were changed from a market-scoped layout to a per-side layout by adding isLong to minFundingFactorPerSecondKey and maxFundingFactorPerSecondKey. 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 slots
    

    The 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 minFundingFactorPerSecondKey and maxFundingFactorPerSecondKey calls to pass isLong
    • replace legacy encodeData(["address"], [market]) writes with encodeData(["address", "bool"], [market, isLong])
    • where the same bound should apply to both sides, write the true and false keys explicitly
  9. I-02 Informational Variable Name Inconsistency Informational Reported
    Location
    https://github.com/GuardianOrg/gmx-synthetics-private-team1-1769494159874/blob/b34275f43f9f07988c3f0ea77953ce20b2bbcc38/contracts/router/relay/RelayUtils.sol#L43-L50
    Round
    Remediation Review 1

    Description

    The CREATE_TWAP_ORDER_TYPE ends with _TYPE while all the others end with _PARAMS.

    Recommendation

    Consider to use a consistent variable name scheme to follow best practices.

  10. I-03 Informational Missing Batch TWAP functionality Informational Reported
    Location
    GLOBAL
    Round
    Remediation Review 1

    Description

    The batch functions do not allow TWAP orders.

    Recommendation

    Consider to implement TWAP orders into the batch flows, but be aware that for subaccount actions this would require to sum up the twapCount.

  11. I-04 Informational Unresolved findings from main review Informational Reported
    Location
    Global
    Round
    Remediation Review 1

    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
  1. H-01 High StaticOracle freeze affects other live markets Logical Error Resolved
    Location
    Config.sol, StaticOracleProvider.sol
    Round
    Remediation Review 2

    Description

    StaticOracleProvider is 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, and shortToken from 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.

  2. M-01 Medium V2 keeper top-ups can DoS distribution DoS Resolved
    Location
    FeeDistributor.sol
    Round
    Remediation Review 2

    Description

    FeeDistributor.distribute can 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 cap keeperCostsV2 or 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 keeperCostsV2 branch, the function returns the whole non-Chainlink V2 bucket as wntForTreasury while keeperCostsV2 is still paid in full later through wntForKeepers. This can overcommit the same totalWntBalance. 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 / feesV2Usd split.
    • wntForChainlink = 1 WNT.
    • V2 keepers require a 95 WNT top-up.
    • _calculateChainlinkAndTreasuryAmounts returns wntForTreasury = 9 WNT in the high-cost branch.
    • _finalizeWntForTreasury computes 100 - 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 block distribute. Since distribute is 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: If keeperCostV2 exceeds totalWntBalance , this issue is also triggered.

    Recommendation

    Make the V2 keeper shortfall handling explicit and ensure the WNT allocation cannot exceed totalWntBalance.

  3. M-02 Medium Static prices unusable when ref price diverge Logical Error Resolved
    Location
    Oracle.sol, StaticOracleProvider.sol
    Round
    Remediation Review 2

    Description

    StaticOracleProvider is 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. StaticOracleProvider explicitly reports that it is not a Chainlink on-chain provider:

    function isChainlinkOnChainProvider() external pure returns (bool) {
        return false;
    }
    

    As a result, Oracle._validatePrices applies 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_FACTOR of 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 with MaxRefPriceDeviationExceeded. 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 calling lastRoundData on the chainlink feed will lead to a revert.

    Recommendation

    Do not apply the live Chainlink reference-price deviation check to explicitly frozen static prices.

  4. M-03 Medium Static oracle unusable as oracle is not enabled Logical Error Resolved
    Location
    Config.sol, updateOracleProviders.ts
    Round
    Remediation Review 2

    Description

    Config.setStaticPriceForToken is intended to activate the static oracle flow for closed-market freezes. It sets the frozen token price, then routes the token to StaticOracleProvider. In the current deployment configuration, StaticOracleProvider is deployed and passed into Config, but it is not enabled as an oracle provider. updateOracleProviders.ts only enables the live providers:

    const providersToAdd = [
      chainlinkPriceFeedProvider.address,
      chainlinkDataStreamProvider.address,
      edgeDataStreamProvider.address,
    ];
    

    Therefore, calling setStaticPriceForToken reverts when it tries to assign staticOracleProvider through _setOracleProviderForToken which 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, otherwise setStaticPriceForToken reverts with InvalidOracleProvider(staticOracleProvider).

    Recommendation

    An immediate fix would be to enable StaticOracleProvider. However, consider if the setStaticPriceForToken should call isOracleProviderEnabledKey(staticOracleProvider) in the first place as the static oracle is not a normal live provider.

  5. M-04 Medium EIP6492_DEPLOYER Address Not Set Configuration Resolved
    Location
    GLOBAL
    Round
    Remediation Review 2

    Description

    deployEIP6492Deployer.ts deploys EIP6492Deployer, but skips setting EIP6492_DEPLOYER in DataStore on existing mainnet deployments because the deployer account cannot call Config.setAddress. The generic config helper can support this update, and EIP6492_DEPLOYER is 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_DEPLOYER address through the existing config flow after deployment.

  6. M-05 Medium Static freeze only works with atomic price Logical Error Resolved
    Location
    Config.sol
    Round
    Remediation Review 2

    Description

    Config.setStaticPriceForToken is 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 through setStaticPriceForToken unless 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, setStaticPriceForToken reverts with NonAtomicOracleProvider; 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.

  7. L-01 Low MIN_CHANGE_DELAY Can DoS Static Oracle Updates DoS Resolved
    Location
    https://github.com/gmx-io/gmx-synthetics-private/blob/a8d8375cd5e3d00bbebc01f384fc2f9189b5643a/contracts/config/Config.sol#L163
    Round
    Remediation Review 2

    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_DELAY needs to pass.

    Recommendation

    Consider to skip the ORACLE_PROVIDER_MIN_CHANGE_DELAY in case of the StaticOracleProvider.

  8. I-01 Informational GMOracle Code Remains After Provider Removal Superfluous Code Resolved
    Location
    GLOBAL
    Round
    Remediation Review 2

    Description

    GmOracleProvider was removed, but GM oracle-specific production code remains in the codebase:

    • GmOracleUtils still exists and is only used in a test file: OracleModuleTest.
    • Errors.sol still contains GM oracle-specific errors such as GmEmptySigner

    Recommendation

    Consider to remove unused code.

Remediation Review 3

4 findings · May 22, 2026
  1. M-01 Medium ADL Nets Losing Positions Against Pool Liability Math Reported
    Location
    https://github.com/gmx-io/gmx-synthetics-private/blob/fd095157acda26c7e394bebd6d8b54f3b5a157df/contracts/market/MarketUtils.sol#L523-L582
    Round
    Remediation Review 3

    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 getPositivePnl function 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 liability But 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.

  2. M-02 Medium uiFeeFactor Not Snapshotted Everywhere Logical Error Reported
    Location
    GLOBAL
    Round
    Remediation Review 3

    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 uiFeeFactor everywhere.

  3. M-03 Medium Reference-price Deviation Checks Are Disabled Oracle Reported
    Location
    GLOBAL
    Round
    Remediation Review 3

    Description

    Oracle.sol now requires !provider.isChainlinkOnChainProvider() && provider.shouldCheckRefPrice(). ChainlinkDataStreamProvider and EdgeDataStreamProvider return false on shouldCheckRefPrice. This makes MAX_ORACLE_REF_PRICE_DEVIATION_FACTOR effectively dead for production providers.

    Recommendation

    Return true for live off-chain providers, and exempt only ChainlinkPriceFeedProvider, static and mock providers.

  4. I-01 Informational Scripts still reference removed GmOracleProvider Superfluous Code Reported
    Location
    GLOBAL
    Round
    Remediation Review 3

    Description

    GmOracleProvider was removed from contracts but some scripts still reference to it.

    Recommendation

    Consider to remove unused code completly.

More from GMX

All 51 reports
  1. Morpho Liquidation Module

    3 findings 3 findings: 3 informational
  2. RewardRouterV3 & RewardRouterUtils

    20 findings1 high 20 findings: 1 high, 8 low, 11 informational
  3. V2.2.1 Review

    102 findings8 high 102 findings: 8 high, 37 medium, 49 low, 8 informational
  4. 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.

Get a quote