bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 33쪽
e |
| `indexTokenPrice` | `Price.Props` | Index token price range |
| `isLong` | `bool` | Pass `true` for long-side PnL |
| `maximize` | `bool` | Whether to use the maximizing price path |
**Returns:** Long-side or short-side PnL as an `int256`.
### Reader.getOpenInterestWithPnl
```solidity
function getOpenInterestWithPnl(
DataStore dataStore,
Market.Props memory market,
Price.Props memory indexTokenPrice,
bool isLong,
bool maximize
) external view returns (int256)
```
**Parameters:**
| Parameter | Type | Description |
| ----------------- | -------------- | ---------------------------------------- |
| `dataStore` | `address` | Address of the DataStore contract |
| `market` | `Market.Props` | Market to evaluate |
| `indexTokenPrice` | `Price.Props` | Index token price range |
| `isLong` | `bool` | Pass `true` for long-side open interest |
| `maximize` | `bool` | Whether to use the maximizing price path |
**Returns:** Open interest with PnL included, as an `int256`.
### Reader.getPnlToPoolFactor
```solidity
function getPnlToPoolFactor(
DataStore dataStore,
address marketAddress,
MarketUtils.MarketPrices memory prices,
bool isLong,
bool maximize
) external view returns (int256)
```
**Parameters:**
| Parameter | Type | Description |
| --------------- | -------------------------- | ---------------------------------------- |
| `dataStore` | `address` | Address of the DataStore contract |
| `marketAddress` | `address` | Market token address |
| `prices` | `MarketUtils.MarketPrices` | Current prices for the market |
| `isLong` | `bool` | Pass `true` for the long side |
| `maximize` | `bool` | Whether to use the maximizing price path |
**Returns:** Current PnL-to-pool factor as an `int256`.
## Pricing and risk helpers
Use these methods when you need direct swap-impact or ADL diagnostics without calling the larger quote helpers.
### Reader.getSwapPriceImpact
```solidity
function getSwapPriceImpact(
DataStore dataStore,
address marketKey,
address tokenIn,
address tokenOut,
uint256 amountIn,
Price.Props memory tokenInPrice,
Price.Props memory tokenOutPrice
) external view returns (int256, int256, int256)
```
**Parameters:**
| Parameter | Type | Description |
| --------------- | ------------- | --------------------------------- |
| `dataStore` | `address` | Address of the DataStore contract |
| `marketKey` | `address` | Market token address |
| `tokenIn` | `address` | Input token address |
| `tokenOut` | `address` | Output token address |
| `amountIn` | `uint256` | Input token amount |
| `tokenInPrice` | `Price.Props` | Input token price range |
| `tokenOutPrice` | `Price.Props` | Output token price range |
**Returns:** A tuple of swap price impact values as signed integers.
### Reader.getAdlState
```solidity
function getAdlState(
DataStore dataStore,
address market,
bool isLong,
MarketUtils.MarketPrices memory prices
) external view returns (uint256, bool, int256, uint256)
```
**Parameters:**
| Parameter | Type | Description |
| ----------- | -------------------------- | --------------------------------- |
| `dataStore` | `address` | Address of the DataStore contract |
| `market` | `address` | Market token address |
| `isLong` | `bool` | Pass `true` for the long side |
| `prices` | `MarketUtils.MarketPrices` | Current prices for the market |
**Returns:** A tuple describing the ADL state, including the ADL phase, whether ADL is enabled, the PnL factor, and the minimum PnL factor for ADL.
---
## Simulations
The `SimulationRouter` and `GlvRouter` contracts expose public simulation functions that let you dry-run an existing request's execution against supplied prices after request creation and before keeper execution. Running a simulation catches validation errors — such as price impact limits or insufficient output amounts — without spending gas on a failed execution.
For the full `CreateOrderParams` and `CreateDepositParams` structures, see [ExchangeRouter](./exchange-router.md). For contract addresses, see [Contract addresses](./addresses.md).
## How simulations work
Simulation functions use the `withSimulatedOraclePrices` modifier in `OracleModule`. The modifier injects synthetic price data into the oracle, executes the handler logic through the router/controller path, then unconditionally reverts with `EndOfOracleSimulation`. Because the transaction always reverts, no state changes are persisted.
The caller interprets the revert reason: if the error is `EndOfOracleSimulation`, the simulation succeeded and the supplied prices passed validation. Any other revert reason indicates an error that would also occur on-chain. In practice, this is a preflight tool for users and integrators; actual request execution is still performed by keeper-only handler functions.
The five `simulateExecuteLatest...` functions for deposits, withdrawals, shifts, orders, and JIT orders are exposed by `SimulationRouter`. Create the request through `ExchangeRouter` first, wait for that transaction to be included, then run the matching simulation function on `SimulationRouter` as an `eth_call` (for example, with ethers `callStatic`). Do not include the simulation call in the `ExchangeRouter.multicall`.
**Example (TypeScript / ethers):**
```typescript
const createTx = await exchangeRouter.multicall(
[
exchangeRouter.interface.encodeFunctionData("sendWnt", [depositVault.address, executionFee]),
exchangeRouter.interface.encodeFunctionData("sendTokens", [
usdc.address,
depositVault.address,
shortTokenAmount,
]),
exchangeRouter.interface.encodeFunctionData("createDeposit", [depositParams]),
],
{ value: executionFee }
);
await createTx.wait();
const currentTimestamp = (await provider.getBlock("latest")).timestamp;
await expect(
simulationRouter.callStatic.simulateExecuteLatestDeposit({
primaryTokens: [wnt.address, usdc.address],
primaryPrices: [
{ min: wethPrice, max: wethPrice },
{ min: usdcPrice, max: usdcPrice },
],
minTimestamp: currentTimestamp,
maxTimestamp: currentTimestamp,
})
).to.be.revertedWithCustomError(errorsContract, "EndOfOracleSimulation");
```
If the call reverts with `EndOfOracleSimulation`, the simulated execution passed. If it reverts with any other error, treat that as the actual validation error for the supplied prices.
## Available simulation functions
The latest-request helpers use the current global request key. Call the simulation promptly after the request-creation transaction is included. If another request advances the global nonce first, the helper can target that newer request instead.
### SimulationRouter functions
| Function | Action type |
| ------------------------------------------------------------------------------------------- | ----------------------- |
| `simulateExecuteLatestDeposit(SimulatePricesParams)` | GM deposit |
| `simulateExecuteLatestWithdrawal(SimulatePricesParams, SwapPricingType)` | GM withdrawal |
| `simulateExecuteLatestShift(SimulatePricesParams)` | GM pool shift |
| `simulateExecuteLatestOrder(SimulatePricesParams)` | Perpetual or swap order |
| `simulateExecuteLatestJitOrder(GlvShiftUtils.CreateGlvShiftParams[], SimulatePricesParams)` | JIT order |
### GlvRouter functions
| Function | Action type |
| ------------------------------------------------------------- | ------------------------------ |
| `simulateExecuteGlvDeposit(bytes32, SimulatePricesParams)` | GLV deposit by explicit key |
| `simulateExecuteLatestGlvDeposit(SimulatePricesParams)` | Latest GLV deposit |
| `simulateExecuteGlvWithdrawal(bytes32, SimulatePricesParams)` | GLV withdrawal by explicit key |
| `simulateExecuteLatestGlvWithdrawal(SimulatePricesParams)` | Latest GLV withdrawal |
## SimulatePricesParams
```solidity
struct SimulatePricesParams {
address[] primaryTokens; // token addresses to price
Price.Props[] primaryPrices; // { min, max } price for each token
uint256 minTimestamp; // lower bound of the price window
uint256 maxTimestamp; // upper bound of the price window
}
```
Supply current oracle prices for all tokens involved in the action. The `minTimestamp` and `maxTimestamp` fields must bracket the expected execution timestamp; a common pattern is to set both to `block.timestamp + 120`.
### Field notes
| Field | Description |
| --------------- | ------------------------------------------------------------------------------------------------------------- |
| `primaryTokens` | Token addresses to assign simulated prices to. Include every token the action depends on. |
| `primaryPrices` | Simulated oracle prices for each token, in the same order as `primaryTokens`. Each price uses `{ min, max }`. |
| `minTimestamp` | Lower bound for the simulated oracle timestamp window. |
| `maxTimestamp` | Upper bound for the simulated oracle timestamp window. |
---
## GraphQL
GMX provides GraphQL endpoints powered by Subsquid for querying indexed on-chain data on Arbitrum, Avalanche, and MegaETH.
| Network | Status | URL |
| --------------------- | ---------------------------- | ----------------------------------------------------------------------------------- |
| **Arbitrum One** | ✅ Active | <CopyUrl url="https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql" /> |
| **Avalanche C-Chain** | ✅ Active | <CopyUrl url="https://gmx.squids.live/gmx-synthetics-avalanche:prod/api/graphql" /> |
| **MegaETH** | ✅ Active | <CopyUrl url="https://gmx.squids.live/gmx-synthetics-megaeth:prod/api/graphql" /> |
The Botanix endpoint is no longer available because GMX no longer supports Botanix.
## Schema changes
### 2026-09-01 — GLV market allocation snapshots added
The indexed schema now records how each GLV vault's value is split across its GM markets, once per hour. Query the new `GlvMarketAllocationSnapshot` entity through `glvMarketAllocationSnapshots`, `glvMarketAllocationSnapshotById`, and `glvMarketAllocationSnapshotsConnection`. Each row covers one GLV vault and one of its markets for one hour, with the `id` `glvAddress:marketAddress:snapshotTimestamp`.
| Field | What it holds |
| ----- | ------------- |
| `snapshotTimestamp` | Start of the hour, in Unix seconds |
| `glvAddress`, `marketAddress` | The GLV vault and the GM market |
| `blockNumber`, `blockTimestamp` | Block the values were read at |
| `marketTokenBalanceAmount` | GM tokens of the market held by the GLV vault (18 decimals) |
| `marketTokenBalanceUsd` | That balance valued at the GM token's max price, as GMX values a GLV vault (30 decimals) |
| `glvValue` | Sum of `marketTokenBalanceUsd` across the markets valued in that hour (30 decimals) |
| `marketTokenBalancePerGlvValue` | The market's share of `glvValue`: `marketTokenBalanceUsd / glvValue`, scaled by `1e30` |
| `marketTokenMaxPrice`, `marketTokenMinPrice` | GM token prices used for the snapshot |
| `marketTokenSupply`, `marketPoolValue` | Total GM token supply of the market (18 decimals) and that supply valued at the max price, that is, the whole market in USD (30 decimals) |
When an hour has no indexed events, the indexer repeats the previous hour's rows under the new `snapshotTimestamp` but keeps their original `blockNumber` and `blockTimestamp`. Compare `blockTimestamp` with `snapshotTimestamp` to tell a carried-over row from a fresh read. A market without a price or market info at snapshot time is skipped, so `glvValue` covers only the markets valued in that hour.
### 2026-08-18 — Funding history and trade-action coverage expanded
The indexed schema now exposes additional hourly funding inputs and identifies funding-fee settlement executions in trade history.
| Surface | Change |
| ------- | ------ |
| `FundingBalanceOiSnapshot` | New hourly entity available through `fundingBalanceOiSnapshots` and `fundingBalanceOiSnapshotById`. It shares its `id` with the corresponding `FundingRateSnapshot` and exposes raw USD and token open interest, collateral-token splits, index-token price inputs, the open interest used for funding balance, and signed and absolute net exposure. |
| Pure-swap `TradeAction` fields | `swapImpactUsd` and `swapFeeUsd` now aggregate the complete swap path. `executionAmountOut` is populated from the final swap event. If a required swap event is missing, the affected fields remain `null`; a genuine zero remains `0`. |
| `FundingRateSnapshot` and `marketsNetRatesByPeriod` | Pre-v2.2c history now falls back to the legacy single min/max funding-factor keys when both per-side keys are unset. Legacy configuration events apply the value to both sides. |
| `TradeAction.isFundingFeeSettle` | New indexed boolean. Funding-fee settlement executions now create `TradeAction` rows with this field set to `true`; older rows can be `null`. |
### 2026-07-21 — Referral flow and positive funding PnL clarified
Affiliate analytics now distinguish traders who leave an affiliate because they graduated to a GMX direct-discount code from traders who were otherwise lost.
| Surface | Change |
| ------- | ------ |
| `AffiliateTraderStatsByHour` | Added `tradersGraduated` |
| `affiliateStats` points | Added `tradersGraduated` |
| `affiliateStats` summary | Added `tradersGraduated` and `tradersGraduatedDelta` |
`tradersNet` is calculated as `tradersGained - tradersGraduated - tradersLost`. The `AccountStat.positiveFundingFeesUsd` field is the signed PnL contribution from funding received through `ClaimableFundingUpdated`, whether claimed or not. It is excluded from `realizedFees`, so add it to PnL once rather than treating it as another realized fee.
### 2026-07-17 — TWAP grouping metadata migrated
The indexer now reads TWAP grouping metadata from the first valid `gmxo` entry in `Order.dataList`. It falls back to decoding the legacy synthetic `uiFeeReceiver` format for older orders. The public `numberOfParts` and `twapGroupId` fields remain the integration surface; you don't need to decode either metadata format yourself.
### 2026-07-15 — Order UI fee snapshots added
`Order` and `TradeAction` now expose `uiFeeFactor`, the factor snapshotted when the order was created. The field is nullable because historical rows created before the snapshot was added don't contain it. Treat `null` as unavailable historical data, not as a zero factor.
### 2026-07-14 — GLV user earnings added
The schema now tracks GLV fee earnings by account and exposes a public `glvUserEarnings(account: String!)` resolver.
| Entity or resolver | Added surface |
| ------------------ | ------------- |
| `Glv` | `glvTokenSupply`, `cumulativeFeeUsdPerGlvToken` |
| `CollectedFeesInfo` | `cumulativeFeeUsdPerGlvToken` |
| `GlvTokenBalance` | Current balance, realized cumulative income, and entry snapshot for one account and GLV |
| `GlvTokenBalanceChange` | Ordered balance-change history used to reconstruct the 7-day window |
| `glvUserEarnings` | `glvAddress`, `lifetimeFeeUsd`, and `recent7dFeeUsd` for each GLV held by an account |
The resolver calculates lifetime earnings from realized income plus the account's unrealized share of the current fee accumulator. Its 7-day value uses hourly snapshots at the window edge and clamps a negative result to zero.
### 2026-06-23 — Referral code update support
The GraphQL schema now includes the referral entities needed to evaluate GMX-managed protocol referral code updates. These additions support the backend workflow that moves eligible traders to organic volume-discount codes or graduated direct-discount codes.
**Expanded referral fields.**
| Entity | Added fields |
| ------ | ------------ |
| `TraderReferralTradeStatsByHour` | `affiliateRewardsUsd` |
**Additional referral entities.**
| Entity | What it provides |
| ------ | ---------------- |
| `TraderFirstReferral` | First-assignment timestamp for a trader and referral code pair |
| `ReferralTier` | Tier configuration with `totalRebate` and `discountShare` |
| `ReferrerTier` | Current tier id for a referrer address |
The private `referralCodeUpdates` resolver is used by GMX-maintained services and is not a public integration surface. Public referral dashboards should continue to use `affiliateStats`, `traderReferralStats`, and the referral entities described below.
### 2026-05-28 — Trade PnL, market info, and funding snapshots expanded
The GraphQL schema and indexer-derived analytics now expose a more detailed split between realized PnL, swap fees, discounts, market funding state, and hourly rate snapshots.
**Expanded fields.**
| Entity | Added fields |
| ------ | ------------ |
| `AccountStat` | `realizedSwapFees`, `realizedSwapImpact` |
| `PositionChange` | `swapFeeUsd` |
| `TradeAction` | `swapFeeUsd`, `traderDiscountAmount` |
| `PositionFeesEntity` | `traderDiscountAmount` |
| `MarketInfo` | `minCollateralFactorForLiquidation`, `savedFundingFactorPerSecond`, `fundingUpdatedAt`, `useOpenInterestInTokensForBalance` |
The account PnL summary server extension also includes a fuller debug breakdown for fees, price impact, discounts, and swap impact. Use these fields when you need to distinguish base realized PnL from fee and impact components instead of treating trade-history PnL as one all-in number.
Hourly rate snapshots now replay the funding formula from indexed market state, including `MarketInfo`, `savedFundingFactorPerSecond`, `fundingUpdatedAt`, open interest, and relevant `DataStore` settings. They are still historical indexer snapshots, not realtime market state.
### 2026-03-31 — Referral analytics added
The GraphQL schema now exposes referral analytics for both affiliates and traders. Five new entities track referral code ownership and hourly trade statistics, and two new query resolvers aggregate that data into time-windowed summaries with period-over-period comparisons.
**New entities.**
| Entity | What it provides |
| ------ | ---------------- |
| `ReferralCodeOwner` | Maps a referral code to its `owner` address, with `updatedAtTimestamp`, `updatedAtBlock`, and `updatedTxnHash` |
| `TraderReferral` | Records which `referralCode` and `affiliate` a trader is associated with, plus update metadata |
| `AffiliateReferralTradeStatsByHour` | Hourly trade stats for an affiliate: `volumeUsd`, `tradesCount`, and `rebatesUsd` |
| `TraderReferralTradeStatsByHour` | Hourly trade stats for a trader using a referral code: `volumeUsd`, `discountsUsd`, and `affiliateRewardsUsd` |
| `AffiliateTraderStatsByHour` | Hourly net trader flow for an affiliate: `tradersGained`, `tradersLost`, and `tradersNet` |
**New query resolvers.**
These are custom server-extension resolvers, not standard entity queries. Call them by name with a `where` argument:
| Resolver | Input fields | What it returns |
| -------- | ------------ | --------------- |
| `affiliateStats` | `affiliate` (required), `from?`, `to?` | Time-windowed volume, trade count, rebates, and trader flow for an affiliate, with optional period comparison |
| `traderReferralStats` | `trader` (required), `from?`, `to?` | Time-windowed volume and discounts for a trader using a referral code, with optional period comparison |
Both resolvers align timestamps to hourly buckets and choose a bucket size automatically based on the requested window length.
**Example queries.**
```graphql
# Affiliate dashboard: volume, rebates, and trader flow for a 7-day window
query AffiliateStats($affiliate: String!) {
affiliateStats(where: { affiliate: $affiliate, from: 1743292800, to: 1743897600 }) {
affiliate
from
to
bucketSizeSeconds
hasComparison
summary {
volumeUsd
volumeUsdDelta
rebatesUsd
rebatesUsdDelta
tradersNet
tradersNetDelta
}
points {
timestamp
volumeUsd
rebatesUsd
tradersGained
tradersLost
tradersNet
}
}
}
```
```graphql
# Trader dashboard: volume and discounts earned through a referral code
query TraderReferralStats($trader: String!) {
traderReferralStats(where: { trader: $trader, from: 1743292800, to: 1743897600 }) {
trader
from
to
bucketSizeSeconds
summary {
volumeUsd
discountsUsd
}
points {
timestamp
volumeUsd
discountsUsd
}
}
}
```
### 2026-03-10 - Staking power and프로젝트로 돌아가기