GMX 백서

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

seconds. By default, the backend pulls source snapshots every `60` seconds, syncs daily rows every `10` minutes, and marks a source `stale` when its data lags by more than `900` seconds. Use `meta.sources[].lagSeconds` rather than response arrival time to measure freshness. - GMX API `GET /pairs/solana`, which aggregators read at `https://solana.gmxapi.io/v1/pairs`, serves a snapshot rebuilt every `60` seconds and caches the response for `60` seconds. It returns `503` instead of an empty list or a snapshot older than `15` minutes. - GMX API `GET /incentives/usdg/boost-apr` responses are cached for `1800` seconds, and `GET /whitelists` responses for `60` seconds per address. - The backend currently caches `prices`, `tokensData`, and `marketsInfo` for `1` second, `userReferralInfo` for `5` seconds, and `onchainSettings` for `60` seconds. - Avoid joining data from unrelated polls when you need one coherent snapshot. Prefer composite endpoints such as `/markets/info` or `fetchPositionsInfo({ includeRelatedOrders: true })`. ### Retries, timeouts, and fallback URLs - The current API server timeout is `60000` ms. - SDK v2 uses `HttpClientWithFallback` with the hosts in its configuration and any additional hosts supplied by your application. In the current published `latest`, `2.2.1`, the packaged fallback list is empty for every chain, so an SDK integration has no peer to fail over to until your application supplies the second host. You still own request retry timing, backoff, and user-facing recovery behavior. - Use the [Fallback URLs](./rest-api/fallback-urls.mdx) page for Oracle API market and oracle reads. - If you receive a timeout, network error, `429`, or `5xx`, retry with backoff and fail over where you have fallback endpoints. Don't fail over in the middle of an express order chain; see [Idempotency and race conditions](#idempotency-and-race-conditions). - `/v1/stats` on a non-Arbitrum `gmxapi.ai` host answers with a `308` redirect to `https://arbitrum.gmxapi.ai`. Follow redirects, or call an Arbitrum host directly. ### Surface-specific operational model - The Oracle API is deployed per chain on `https://{chain}-api.gmxinfra.io` primary hosts, uses endpoint-specific cache windows, and documents fallback URLs for some public reads. - The GMX API is deployed per chain across two independent peer base URLs (`https://{chain}.gmxapi.io/v1` and `https://{chain}.gmxapi.ai/v1`). Both are equal; there is no primary/secondary. Clients that hit the API directly can use either base URL or rotate across both for reads. The two peers are independent deployments that don't share order-transaction records, so an express order chain must stay on one host. The generated reference does not define your retry policy. - GraphQL is indexed data. Expect lag relative to live chain state. - SDK v1 mixes live RPC, oracle, and indexed reads. Default SDK-created HTTP transports disable retries. - SDK v2 is an HTTP client for reads and API-relayed order workflows. Its transport supports peer failover across configured hosts, but the packaged host list is empty in the current published `latest`, `2.2.1`, so your integration must supply the peer hosts and define its own application-level retry policy. With fallback hosts configured, SDK v2 `2.1.1` and later send an express order's submit and status calls to the host that served its prepare, without cross-host fallback. - Direct contracts give you the most control, but your app owns retry, nonce, gas, and receipt strategy. - Delegated trading flows run through `SubaccountGelatoRelayRouter` or `MultichainSubaccountRouter` and have their own session lifecycle — your integration owns subaccount authorization, expiry, action-count tracking, and relay-nonce handling. See [Delegated trading integration](./contracts/delegated-trading.md). ### Idempotency and race conditions - For SDK v2 and API-relayed order workflows, persist the `requestId` returned by prepare or submit calls and poll order status instead of resubmitting blindly. - Keep an express order's prepare, submit, and status calls on the GMX API host that served prepare. The `requestId` record exists only in that host's deployment, so a status call on the peer host returns `404`. If the host that served prepare returns a `5xx`, or `404` for status, don't send the same `requestId` to the peer host: prepare the order again. Before you prepare again after a submit attempt, check the account's orders so you don't place the same order twice. The same rule applies to GMX Account cross-chain withdrawal submit and status calls. - For direct generic-relay flows, persist the `taskId` returned by `POST /relay/submit` and poll `POST /relay/status`. Treat `unknown` as inconclusive rather than failed, and don't submit the same signed operation again merely because status is temporarily unavailable. The `/relay/*` routes are a stateless proxy that keeps no per-host record, so the host pinning above doesn't apply to them. - After a write, do not assume your first follow-up read will reflect final state. Submission, relay processing, keeper execution, and indexing can land at different times. - If you need "position plus linked orders" on one screen, prefer a single positions call with `includeRelatedOrders: true` over stitching data from independent polls. ## Next steps - Use [API Overview](./overview.md) to decide between the GMX API, Oracle API, GraphQL, contracts, and the SDK. - Use [Getting GM and GLV token prices](./gm-glv-prices.md) when you need to choose between Chainlink Data Feeds, direct Reader calls, and API or SDK data for GM/GLV valuation. - Use the [Oracle API](/docs/category/oracle-api) for public market, price, and liquidity endpoints. - Use the generated [GMX API OpenAPI Reference](/docs/category/gmx-api-openapi-reference) for endpoint-level request and response schemas. - Use [Troubleshooting](./troubleshooting.md) if your reads look stale, a query fails validation, or a write does not show up yet. - Use [SDK v2](../sdk/v2/readme.md) when your application needs API-relayed order flows. - Use [SDK v1](../sdk/v1/readme.mdx) when your application needs direct RPC-backed write flows such as creating or canceling orders. - Use [Delegated trading integration](./contracts/delegated-trading.md) when you need subaccount-based, gasless, or one-click order flows on behalf of a user. --- ## API Overview GMX exposes several integration points for developers, integrators, and AI agents building on the protocol. Start with the integration surface that matches your task instead of trying to use one API for everything. For AI agent frameworks with pre-built trading skills, see [AI Agents](../ai-agents/overview.md). ## Available APIs GMX offers four integration points depending on the type of data or action you need. ### HTTP APIs GMX provides two HTTP API surfaces. The GMX API is under active development and will become the primary HTTP integration point. Use the GMX API for app-level HTTP integrations, account data, order data, trading-capacity and GM-pool analytics, and API-relayed workflows. Use the Oracle API for stable read-only oracle, market, liquidity, and APY snapshots served from chain-specific `gmxinfra.io` hosts. | | GMX API — [OpenAPI Reference](/docs/category/gmx-api-openapi-reference) | Oracle API — [endpoint docs](/docs/category/oracle-api) | | ------------- | ----------------------------------------------------------------------- | ------------------------------------------------------- | | **Base URLs** | `https://{chain}.gmxapi.io/v1` and `https://{chain}.gmxapi.ai/v1` — two independent peer regions per chain. Use either; clients integrating directly should treat both as equal. | `https://{chain}-api.gmxinfra.io` primary hosts with documented fallback URLs | | **Data** | Markets, tickers, JIT-aware trading capacity, tokens, positions, orders, trades, rates, APY, GM-pool yield and trader PnL, GM LP fee earnings for one wallet, performance, 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, protocol-wide stats across networks and GMX versions, JIT liquidity, risk-oracle market lists, GMX Account, subaccounts, order transaction workflows, and generic relay submission and status. | Oracle prices, markets, liquidity | | **Status** | Expanding | Stable | The `/v1` path in the `gmxapi.io` and `gmxapi.ai` base URLs is part of the GMX API deployment path. In these docs, **Oracle API** refers to the chain-specific HTTP endpoints on `gmxinfra.io`. The generic `POST /relay/submit` and `POST /relay/status` endpoints are a low-level, operation-agnostic GMX Relay surface. They don't replace `/orders/txns/*`: current SDK v2 order workflows continue to use the order transaction endpoints, which also submit Express Trading orders through GMX Relay. ### Other integration points - **[Contracts](/docs/category/contracts)** — Interact directly with ExchangeRouter, Reader, and GlvReader contracts on-chain. - **[GraphQL](./graphql.mdx)** — Historical on-chain data via Subsquid endpoints. - **Integration pair feed** — Public pair-summary endpoints for exchange and aggregator listings: `https://gmx-integration-cg.vercel.app/api/arbitrum/pairs` and `https://gmx-integration-cg.vercel.app/api/avalanche/pairs`. For GMX on Solana, the pair feed is `https://solana.gmxapi.io/v1/pairs`, the only path that host serves. Treat these as a narrow pair feed, not a general-purpose API. ## Start here - **[Integration guide](./integration-guide.md)** — "I want to do X" workflows, cache and retry guidance, and when to use the GMX API, Oracle API, GraphQL, or the SDK - **[Getting GM and GLV token prices](./gm-glv-prices.md)** — How to choose between Chainlink Data Feeds, Reader contracts, and API/SDK data for GM/GLV valuation - **[Troubleshooting](./troubleshooting.md)** — What to do when reads look stale, validation fails, or write-path state does not appear yet - **[GMX API OpenAPI Reference](/docs/category/gmx-api-openapi-reference)** — Generated endpoint schemas for the current GMX API surface - **[Oracle API](/docs/category/oracle-api)** — Manual docs for prices, markets, liquidity, and fallback URLs ## TypeScript SDK The [`@gmx-io/sdk`](../sdk/overview.md) package provides a high-level TypeScript interface that wraps these APIs. It ships two clients: **SDK v1** (`GmxSdk`) for direct RPC-backed reads and writes, and **SDK v2** (`GmxApiSdk`) for HTTP-backed reads, wallet helpers, subaccount helpers, GMX Account helpers, and API-relayed order workflows. The current SDK v2 surface covers markets, tickers, JIT-aware trading capacity, tokens, pairs, rates, APY, GM-pool yield and trader PnL, GM LP fee earnings, performance, positions, orders, trades, OHLCV, buyback stats, JIT liquidity, staking power, wallet balances, allowances, approval transaction building, GMX Account deposits and withdrawals, and signed order submission. For protocol-wide stats, `@gmx-io/sdk/v2` also exports the standalone `fetchApiProtocolStatsSummary()`, `fetchApiProtocolStatsTimeseries()`, and `fetchApiProtocolStatsSources()` functions, and `@gmx-io/sdk/configs/api` exports `getStatsApiUrl()`. See the [SDK docs](../sdk/overview.md) for details. The generated GMX API reference is generated from the OpenAPI spec and is the best source for raw HTTP schemas. The SDK pages are the best source for typed client method names, bigint parsing, signing helpers, and end-to-end TypeScript workflows. ## Supported networks GMX V2 is active on the following networks. - Arbitrum One - Avalanche C-Chain - MegaETH Not every API surface is available on every deployed network. Check the specific GMX API, Oracle API, GraphQL, or SDK page you plan to use before wiring a production integration. For contract and API update announcements, see [Updates and Support](./updates-support.md). ## AI agent integration GMX's oracle-based pricing and two-phase execution model make it well-suited for autonomous trading agents. For pre-built agent plugins that bundle SDK references, API endpoints, contract addresses, and order specifications, see the [AI Agents](../ai-agents/overview.md) section. This documentation site also generates LLM-friendly bundles at [`llms.txt`](https://docs.gmx.io/llms.txt) and [`llms-full.txt`](https://docs.gmx.io/llms-full.txt) for direct model consumption. --- ## Troubleshooting Use this page when API reads do not match what you expect. Most issues fall into one of four buckets: invalid request parameters, stale snapshots, using the wrong surface for the job, or expecting immediate read-after-write consistency. ## `400 Bad Request` Both read endpoints and order preparation return `400` for requests that can't be accepted. Common read cases: - `/orders` and `/positions` require a valid account address. - `/markets/tickers` validates `addresses` and `symbols` filters. - `/markets/trading-capacity` requires a valid `symbol` and a `direction` of `long` or `short`. - `/rates` validates `period` and `averageBy`. - `/apy`, `/yield/gm-pools`, and `/performance/*` validate their filters. `/yield/gm-pools` rejects malformed pool addresses. - `/yield/gm-user-earnings` requires a valid `account` address. - `/trades` `since` and `until`, and `/trades/search` `fromTimestamp` and `toTimestamp`, must be whole Unix seconds from `0` to `2147483647`. A fractional or millisecond value returns `Invalid since timestamp: whole seconds expected` (with the field's name). - `/stats/*` rejects an unknown `networks`, `versions`, or `metric` value, and a `from` or `to` that isn't whole Unix seconds. Repeat a list parameter for each value (`networks=arbitrum&networks=avalanche`); a comma-separated list is rejected. A filter that matches no configured source, such as `networks=megaeth&versions=v1`, returns `No configured source matches the requested networks and versions`. For schema validation failures, such as a missing required parameter or a value outside an enum, the `message` field is an object keyed by parameter name instead of a string. `POST /orders/txns/prepare` can also return an application error: - `INSUFFICIENT_LIQUIDITY` means a Market Increase exceeds current JIT-aware trading capacity. Reduce the requested size or refresh capacity before preparing again. A resting increase can return the same code in `validationWarnings` instead because liquidity will be checked again when it triggers. - `INSUFFICIENT_COLLATERAL` means collateral remaining after fees would be below the on-chain minimum. Add collateral or change the order. For TWAP increases, every part must satisfy the minimum. `validationWarnings` are non-blocking, but clients need to surface them before signing. If you receive a blocking `400`, validate the query or change the order inputs before retrying; repeating the unchanged request won't succeed. ## `503 Service Unavailable` A `503` from the GMX API means the request couldn't be served at that moment. Unlike a `400`, the same request can succeed later, so retry with backoff. - `/yield/gm-user-earnings` returns `503` while earnings data is warming up on a deployment, or on a deployment where it isn't available. - `/stats/*` returns `503` on a deployment that doesn't serve protocol stats. The production hosts route `/v1/stats` to the Arbitrum deployment; if you still get a `503`, call an Arbitrum host directly. - `/pairs/solana` returns `503` on a deployment that doesn't compute the GMX on Solana pair feed, and while its snapshot is still being built or is older than 15 minutes. Only the Arbitrum deployment computes it, and aggregators read it at `https://solana.gmxapi.io/v1/pairs`. - `POST /orders/txns/prepare` and other routes return `503` when the request runs past the `60` second server timeout. - A `503` whose body has `code: "BACKEND_UNAVAILABLE"` means the request reached a GMX API pool that doesn't serve that route. Retry, and if it persists, report it with the `X-Trace-Id` response header. For the earnings, stats, and Solana pair feed cases, the response body is the generic `{"message":"Internal Server Error"}`, so use the route and the `X-Trace-Id` header, not the message, to tell the cases apart. ## A value looks stale Start by checking whether you are reading from a cached or indexed surface. - Use Oracle API `/markets/info` when you need near-live market state. - Use Oracle API `/markets` when a `10` second cache window is acceptable. - Use GraphQL for historical activity, not for the latest write-path state. - Use a single composite read where possible instead of stitching unrelated polls together. For GMX API market values, inspect each `/v1/markets/values` row's `updatedAt` field. It is a Unix timestamp in milliseconds and uses the older timestamp from the main market-values refresh and the `virtualInventoryForPositionsInTokens` refresh. A `null` value means at least one component has no successful refresh timestamp. The default backend pulls market values every `5` seconds and marks a row stale for monitoring after `15` seconds. This threshold does not evict the row: - A total pull failure preserves the previous values and timestamps, which continue to age. - A market-specific failed refresh can preserve the previous values while setting `updatedAt` to `null`. - Disabled markets are excluded from backend values-staleness accounting. Compare `updatedAt` with a freshness limit appropriate for your application. Don't treat an HTTP `200` response as proof that every value came from the latest pull. For GMX API protocol stats (`/stats/*`), check the response metadata before trusting a total: - `meta.completeness` is `partial` when any source in scope isn't `fresh`. Stale sources still count toward the sums. - `meta.sources[]` reports each source's `health` (`fresh`, `stale`, or `missing`), `lagSeconds`, and `lastError`. A source becomes `stale` when its data lags by more than `900` seconds. - Timeseries points with `provisional: true` cover days that can still change. - `tvl.poolsValuedAt` and `tvl.valuedAt` report when TVL was valued. For `/yield/gm-user-earnings`, `window.endTimestamp` reports when the earnings were calculated. If you need one coherent account snapshot, prefer one positions call with `includeRelatedOrders: true` over multiple loosely coordinated reads. ## A write succeeded, but the API still does not show it That is usually a surface mismatch or an operation that hasn't reached a final state. - SDK v2 and GMX API `/orders/txns/*` endpoints prepare, submit, and track signed order intents. Persist their `requestId` and poll order status on the same GMX API host that served prepare. The `gmxapi.io` and `gmxapi.ai` peers don't share order records, so status on the other peer returns `404` with the message `Transaction not found`. Don't fail over to the peer for that `requestId`; prepare the order again if the original host can't continue the chain. See [Idempotency and race conditions](./integration-guide.md#idempotency-and-race-conditions). - The low-level GMX Relay surface accepts already-built relay-router calldata through `POST /relay/submit`. Persist the returned `taskId` and poll it through `POST /relay/status`. - SDK v1 and direct contracts submit transactions from your wallet or backend RPC client. Wait for the transaction receipt, then poll the read surface you care about. Generic relay statuses are `pending`, `executed`, `reverted`, `failed`, and `unknown`. Treat `unknown` as inconclusive rather than failed: keep the operation pending until your own timeout, and don't resubmit the same signed calldata blindly. A `404` immediately after an accepted submission can also be transient while status becomes readable. For a reverted relay operation, inspect `reason` and the top-level `revertData` when present. `revertData` contains public on-chain revert bytes and can be decoded by the client. If su
프로젝트로 돌아가기