GMX 백서

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 2쪽

ese flows directly in your own order creation, storage, and claiming logic. #### UI fees 1. Choose the wallet address that should receive UI fees. 2. From that receiver address, call `ExchangeRouter.setUiFeeFactor(uiFeeFactor)`. The factor is a 30-decimal percentage and must not exceed `MAX_UI_FEE_FACTOR`. 3. When you create supported actions, pass that address as `uiFeeReceiver` in the action parameters. Supported actions include deposits, withdrawals, swap orders, increase and decrease position orders, GLV deposits and withdrawals, and shifts. 4. Claim accrued UI fees by calling `ExchangeRouter.claimUiFees(markets, tokens, receiver)` from the UI fee receiver address. See [Fees](./contracts/fees.md#ui-fee) and [ExchangeRouter UI fee configuration](./contracts/exchange-router.md#ui-fee-configuration) for the contract details. #### Referrals 1. Register and own the referral code on each network where you want to earn affiliate rewards. For new validator-gated codes, prefer registration on Arbitrum, which is the leader chain for referral-code validation. 2. If you create orders through SDK v2 or the hosted GMX API order prepare flow, pass the code as `referralCode` in the prepare request. The API accepts either the human-readable registered code or an already encoded `bytes32` value. Human-readable codes can contain letters, digits, and underscores, and can be up to 20 characters long. 3. If you create orders through direct contract calls, encode the referral code as `bytes32` before passing it to order creation. 4. Before applying a code for a trader, read `ReferralStorage.traderReferralCodes(trader)` and `ReferralStorage.codeOwners(referralCode)`. On-chain reads use the `bytes32`-encoded referral code. Where `ReferralCodeValidator` is active, also check `ReferralCodeValidator.isValid(referralCode)`. 5. If the trader has no on-chain referral code, `codeOwners(referralCode)` is not the zero address, and the code is valid where validator checks apply, pass the code when creating the trader's order. 6. Claim accrued affiliate rewards by calling `ExchangeRouter.claimAffiliateRewards(markets, tokens, receiver)` from the referral-code owner address. A referral code is valid for affiliate rewards only if it has a registered owner and, for new validator-gated codes, `ReferralCodeValidator.isValid(referralCode)` returns true. Existing pre-validator codes remain valid. In practice, the code is set on the first successful order transaction that includes a valid registered code for a trader with no existing referral code. After a trader has an on-chain referral code, later order transactions cannot replace it through the normal order referral assignment path. That path skips zero referral codes and does not overwrite an existing trader referral code. Changing an existing trader referral code is normally a separate user action that requires the user to sign a referral-code change transaction or relay message. Integrations should not bundle or disguise a referral-code change as part of any other action. GMX-maintained protocol services may still assign GMX-owned codes for organic volume discounts or referral graduation, such as `EARNED_TRADER_DISCOUNT_5`, `EARNED_TRADER_DISCOUNT_10`, `DIRECT_GMX_DISCOUNT_5`, and `DIRECT_GMX_DISCOUNT_10`; custom integrations should treat those as protocol-managed codes and should not try to overwrite them through normal order creation. Registered referral-code owners earn affiliate rewards on position fees only. Position fees are the fees charged on leveraged position size when a trader opens, closes, increases, or partially decreases a position; they do not include swap fees, deposit or withdrawal fees, borrowing fees, or funding fees. See [Referrals](../referrals.md) for the user-facing referral flow and tier details. #### One-Click Trading and delegated signing If your integration exposes One-Click Trading or another delegated trading flow, you must provide your own storage and session management. 1. Choose the delegated signer model: browser-local signer, backend-managed signer, or an externally controlled delegated wallet. 2. Create or identify the delegated signer address. 3. Have the main account authorize the delegated signer with expiry, maximum action count, delegated action type, and any integration id your flow uses. 4. Store delegated session metadata in your own origin or backend. Track at least the subaccount address, authorization status, expiry, remaining action count, nonce state for relay flows, and revocation state. 5. Submit delegated orders through the supported delegated trading routers, such as `SubaccountGelatoRelayRouter` for same-chain delegated order flow or `MultichainSubaccountRouter` for cross-chain delegated order flow. 6. Monitor expiry, action-count usage, nonce invalidation, order lifecycle, and revocation. Refresh or revoke delegated access when the session is no longer valid. Because browser storage is origin-scoped, a custom frontend or aggregator cannot reuse One-Click Trading state stored by the GMX Interface deployment. If your integration manages the delegated signer on a backend for bots, agents, or managed trading services, your backend becomes responsible for hot-key custody, session lifecycle, revocation, and monitoring. See [Delegated trading integration](./contracts/delegated-trading.md) for the subaccount and relay model. --- ## Getting GM and GLV token prices Use this page when you need a GM or GLV token price and need to choose the right integration surface. The best method depends on whether you need a standard oracle feed, direct GMX valuation for a specific block and price context, or off-chain display data. ## Quick answer | If you need | Use | Notes | | --- | --- | --- | | Current GLV display price | [Oracle API `/prices/tickers`](./rest-api/oracle-prices.mdx#tickers) | Use [`/tokens`](./rest-api/oracle-prices.mdx#tokens) to get the exact GLV symbol and address for the network | | Current GM market-token display price | Direct Reader call, or Chainlink Data Feed where available | GM market tokens are not exposed as first-class `GM [...]` Oracle API tickers | | Exact GMX GM valuation | [`Reader.getMarketTokenPrice`](./contracts/reader.md#getting-gm-token-price) | Requires supplied token prices, min/max handling, and the correct PnL factor context | | Exact GMX GLV valuation | [`GlvReader.getGlvTokenPrice`](./contracts/glv-reader.md#getting-glv-token-price) | Requires supplied token prices and min/max handling | | GLV composition or GM balances | [Oracle API `/glvs/info`](./rest-api/liquidity.mdx#glv-info) | Returns vault metadata, market exposure, GM balances, and GM balance values, not a `glvPrice` field | | External on-chain oracle integration | [Chainlink Data Feeds](https://data.chain.link/), where available | Best fit when a public GM or GLV feed exists for your chain and token | ## Overview GM and GLV are liquidity tokens, not simple underlying market tokens. - **GM tokens** represent shares of one GM market. Their value depends on pool value, borrowing fees, capped trader PnL, impact pools, total supply, and the token prices you pass into the valuation. - **GLV tokens** represent shares of a GLV vault. Their value is aggregated across the GM markets held by that vault. For the liquidity-provider mental model, see [Token pricing](../providing-liquidity.md#token-pricing). For contract-level lookups, see [Reader](./contracts/reader.md#getting-gm-token-price) and [GlvReader](./contracts/glv-reader.md#getting-glv-token-price). ## Chainlink Data Feeds Use Chainlink Data Feeds when your integration needs a standard oracle interface and a GM or GLV feed exists for the token you need. Check availability on [data.chain.link](https://data.chain.link/) for the chain and token address you plan to integrate. Feed availability can differ by chain and can change over time, so do not hardcode assumptions from this page. Data Feeds are the highest-level integration path for external protocols because they avoid reproducing GMX's internal valuation inputs. They may not match a same-block Reader valuation because the Reader calculation includes current pool state, capped pending PnL, borrowing fees, impact pools, and caller-supplied min/max token prices. ## Oracle API price endpoints Use Oracle API price endpoints when you need off-chain display prices for GLV ticker symbols supported by that network. These endpoints are public HTTP endpoints on `gmxinfra.io`; they are not on-chain oracle feeds and are not the same as direct Reader valuation. For current GLV prices, use [`/prices/tickers`](./rest-api/oracle-prices.mdx#tickers). The response includes token ticker objects with `tokenSymbol`, `tokenAddress`, `minPrice`, `maxPrice`, `timestamp`, and `updatedAt` fields. Use [`/tokens`](./rest-api/oracle-prices.mdx#tokens) to get the exact GLV symbol and address for the network, then use that `tokenSymbol` for ticker and candle lookups. For historical GLV display data, use [`/prices/candles`](./rest-api/oracle-prices.mdx#candlesticks) with the GLV `tokenSymbol`. These API endpoints are useful for off-chain UI and analytics. For external on-chain protocol integrations, prefer Chainlink Data Feeds where available. For exact GMX valuation at a specific block and price context, use the Reader contracts. ## GMX Reader contracts Use direct Reader calls when you need GMX's valuation formula for a specific block and supplied price context, or when a Chainlink Data Feed is not available for the token you need. Reader methods are not standalone oracles. They are deterministic contract valuation helpers. Your integration supplies the market data, encoded token prices, PnL factor type, and min/max direction. For direct calls, you usually need: - The `DataStore` contract address. - The `Reader` or `GlvReader` contract address. - The GM market or GLV token address. - The relevant `Price.Props` values for index, long, and short tokens. - The PnL factor context for GM token pricing. - Two calls when you need both min and max valuation. Contract addresses are listed in [Contract addresses](./contracts/addresses.md). The Reader parameter encoding is documented in [Price and amount encoding](./contracts/reader.md#price-and-amount-encoding). ## GM price example Use `Reader.getMarketTokenPrice` for a direct GM token valuation. The function returns one side of the valuation range, so call it with both `maximize=false` and `maximize=true` when you need min and max prices. ```typescript const market = await reader.getMarket(dataStoreAddress, marketAddress); const [gmPriceMin, poolInfoMin] = await reader.getMarketTokenPrice( dataStoreAddress, market, indexTokenPrice, longTokenPrice, shortTokenPrice, MAX_PNL_FACTOR_FOR_TRADERS, false ); const [gmPriceMax, poolInfoMax] = await reader.getMarketTokenPrice( dataStoreAddress, market, indexTokenPrice, longTokenPrice, shortTokenPrice, MAX_PNL_FACTOR_FOR_TRADERS, true ); ``` Use the `pnlFactorType` that matches your context: | Context | PnL factor type | | --- | --- | | Trading or general pool valuation | `Keys.MAX_PNL_FACTOR_FOR_TRADERS` | | Deposit simulation | `Keys.MAX_PNL_FACTOR_FOR_DEPOSITS` | | Withdrawal simulation | `Keys.MAX_PNL_FACTOR_FOR_WITHDRAWALS` | ## GLV price example Use `GlvReader.getGlvTokenPrice` for a direct GLV token valuation. The market address list and `indexTokenPrices` array must use the same order. ```typescript const glvInfo = await glvReader.getGlvInfo(dataStoreAddress, glvAddress); const marketAddresses = glvInfo.markets; const indexTokenPrices = marketAddresses.map((marketAddress) => { return indexTokenPricesByMarket[marketAddress]; }); const [glvPriceMin, glvValueMin, totalSupply] = await glvReader.getGlvTokenPrice( dataStoreAddress, marketAddresses, indexTokenPrices, longTokenPrice, shortTokenPrice, glvAddress, false ); const [glvPriceMax, glvValueMax] = await glvReader.getGlvTokenPrice( dataStoreAddress, marketAddresses, indexTokenPrices, longTokenPrice, shortTokenPrice, glvAddress, true ); ``` GLV markets in the same vault share the same long and short token pair. Pass one `longTokenPrice` and one `shortTokenPrice`, plus the index token price for each underlying GM market. ## Precision and decimals GM and GLV tokens use 18 decimals. The price returned by `Reader.getMarketTokenPrice` or `GlvReader.getGlvTokenPrice` is a 30-decimal USD price per full GM or GLV token. ```typescript const displayPrice = formatUnits(gmPriceMax, 30); ``` This return-value format is different from the input `Price.Props` format for underlying tokens. Input token prices use: ``` priceValue = usdPrice * 10^(30 - tokenDecimals) ``` For example, `$1` USDC with 6 token decimals is encoded as `1 * 10^24`, while `$1` WETH with 18 token decimals is encoded as `1 * 10^12`. Oracle API ticker and candle responses use their own endpoint response formats. Do not mix Oracle API ticker fields with Reader return values without applying the endpoint-specific scaling documented in [Oracle Prices](./rest-api/oracle-prices.mdx). ## Min and max price handling The `maximize` parameter selects one side of the valuation. - For GM, `maximize=true` uses the higher valuation path and `maximize=false` uses the lower valuation path. - For GLV, `maximize=true` and `maximize=false` select the high or low valuation across the underlying GM markets. - Each call returns one price, not a min/max pair. For price ranges, call the Reader twice and label the results explicitly in your integration. ## API and SDK limitations The Oracle API exposes current prices for supported token tickers through `/prices/tickers`, including configured GLV symbols on networks where those symbols are part of the API token list. Other API and SDK surfaces expose related GM and GLV data, but not every GM or GLV valuation as a first-class high-level field or method. - Oracle API `/prices/tickers` can expose configured GLV ticker prices for off-chain display. It does not expose every GM market token as a `GM [...]` ticker. - Oracle API `/markets/info` exposes market state such as token amounts, liquidity, open interest, funding, borrowing, disabled status, and the GM market token address. It does not expose a `gmPrice` field, and GM market tokens are not exposed as `GM [...]` tickers in `/prices/tickers`. - Oracle API `/glvs/info` is a GLV composition endpoint. It exposes GLV vault metadata, market exposure, GM balances, and balance values, but not a `glvPrice` field. Use `/prices/tickers` for current GLV display prices and `/tokens` for the exact GLV symbol. - SDK v1 `sdk.markets.getMarketsInfo()` returns `marketsInfoData`, `tokensData`, and pool values. It does not expose `getGmPrice()` or `getGlvPrice()` as high-level methods. - SDK v1 exports low-level ABIs that can be used for direct contract calls, but those are not the same as a high-level SDK price method. Use API or SDK data for off-chain displays when the exposed fields are sufficient. Use Chainlink Data Feeds where available for a standard oracle interface. Use direct Reader or GlvReader contract calls when you need the GMX valuation formula for a specific block and price context. --- ## Integration guide Use this page when you want exact integration steps. The hand-written API pages explain which surfaces exist and how they behave operationally. The GMX API OpenAPI reference is generated and is best used for endpoint schemas and response fields, not for workflow guidance. Use [Troubleshooting](./troubleshooting.md) when reads do not match expected state. ## Choose the right integration surface Start by choosing the narrowest surface that solves your problem. | Need | Recommended surface | Notes | | ---- | ------------------- | ----- | | Live oracle prices, market snapshots, liquidity, and APY | [Oracle API pages](/docs/category/oracle-api) | Stable public HTTP endpoints on `gmxinfra.io`. Use GMX API `/yield/gm-pools` when fee APY and trader PnL must use the same pool and time window. | | Read app-level HTTP data such as markets, tickers, JIT-aware trading capacity, tokens, pairs, rates, APY, GM-pool yield and trader PnL, performance, positions, orders, trades, OHLCV, wallet balances, allowances, buyback stats, JIT liquidity, risk-oracle market lists, staking power, USDG launch boost rates, deposit whitelists, or USDC and USDG conversion quotes | [SDK v2](../sdk/v2/readme.md), the generated GMX API reference, or direct GMX API HTTP calls | SDK v2 provides typed TypeScript helpers for its supported methods; use direct HTTP for routes not yet wrapped or generated | | Protocol-wide volume, fees, revenue, TVL, open interest, users, and trades across networks and GMX versions | Direct GMX API `GET /stats/summary`, `/stats/timeseries`, and `/stats/sources`, or the SDK v2 `fetchApiProtocolStats*` functions | Chain-agnostic and computed only by the Arbitrum deployment. See [Read protocol-wide stats](#read-protocol-wide-stats). | | LP fee earnings for one wallet's GM token holdings | GMX API `GET /yield/gm-user-earnings` or SDK v2 `fetchGmUserEarnings()` | Per chain and GM only. Use the GraphQL `glvUserEarnings` resolver for GLV vault earnings. See [Read GM LP fee earnings for one account](#read-gm-lp-fee-earnings-for-one-account). | | Historical trade and order activity | [SDK v2](../sdk/v2/readme.md), the generated GMX API reference, or [GraphQL](./graphql.mdx) | Use GMX API or SDK v2 for API-backed trade reads; use GraphQL for full indexed history and custom analytics | | Submit, edit, cancel, or track orders | [SDK v2](../sdk/v2/readme.md), [SDK v1](../sdk/v1/readme.mdx), or direct contract calls | SDK v2 posts signed order intents to the GMX API, which submits express orders through GMX Relay. SDK v1 and direct contracts remain available for RPC-owned flows | | Submit already-built relay-router calldata and track the relay operation | Direct GMX API `POST /relay/submit` and `POST /relay/status` | Low-level, operation-agnostic GMX Relay surface. Persist its `taskId`; it doesn't replace the SDK v2 `/orders/txns/*` workflow. | | Exchange or aggregator pair listings | Integration pair feed | Public GET endpoints at `https://gmx-integration-cg.vercel.app/api/arbitrum/pairs` and `https://gmx-integration-cg.vercel.app/api/avalanche/pairs`. For GMX on Solana, `GET https://solana.gmxapi.io/v1/pairs` returns the perpetual pairs in the GMX API `/pairs` format | | Delegated, gasless, or one-click order flows on behalf of a user | [Delegated trading integration](./contracts/delegated-trading.md) | Subaccount and relay pattern using `SubaccountGelatoRelayRouter` and `MultichainSubaccountRouter` | | GM or GLV token prices | [Getting GM and GLV token prices](./gm-glv-prices.md) | Explains when to use Chainlink Data Feeds, Reader calls, or API/SDK data for GM/GLV valuation | ## What is available now The current hand-written docs and checked-out code support the following split: | Surface | Read | Write | Description | | ------- | ---- | ----- | ----------- | | [GMX API OpenAPI Reference](/docs/category/gmx-api-openapi-reference) | ✅ | ✅ | Generated schema reference for the GMX API. Covers markets, JIT-aware trading capacity, tokens, positions, orders, trades, rates, APY, GM-pool yield and trader PnL, GM LP fee earnings, protocol-wide stats, performance, JIT liquidity, wallet balances, allowances, staking power, buyback stats, USDG launch boost rates, deposit whitelists, USDC and USDG conversion through Paxos on Arbitrum, the GMX on Solana pair feed, GMX Account, subaccount approval/status, order transaction flows, and generic relay submission/status. Deployed per chain across two independent peer base URLs: `https://{chain}.gmxapi.io/v1` and `https://{chain}.gmxapi.ai/v1`. | | [Oracle API](/docs/category/oracle-api) (`gmxinfra.io`) | ✅ | ❌ | Public market, price, liquidity, APY, and performance reads. Manual docs cover the stable public HTTP endpoi
프로젝트로 돌아가기