GMX 백서

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

ccount key. - Improved subaccount approval handling so prepared approvals are refreshed when on-chain nonce, expiry, or action-count state makes the stored approval unusable. - Added quota safeguards for SDK-managed subaccount orders: empty approvals validate current subaccount status, near-exhausted action limits force a status refresh before prepare, and accepted relay submissions update cached action counts so approval refresh decisions stay consistent. - Preserved prepared subaccount approval metadata after failed structured submit responses so retries include the required approval payload. - Rejected mismatched caller-supplied `subaccountAddress` or `subaccountApproval.subaccount` when SDK-managed subaccount signing is active. ## 1.6.2 — June 9, 2026 This release adds SPCX market metadata and leverage handling. - Added Arbitrum SDK config entries for the SPCX/USD [WETH-USDC] market and SPCX token metadata. - Added generated market config and value keys needed by the SPCX market. - Added SPCX-specific leverage cap handling in market utilities so UI max leverage is capped at 10x when applicable. ## 1.6.1 — June 9, 2026 - Added `referralCode` to the SDK v2 `PrepareOrderRequest` type. - Hosted GMX API order prepare requests now accept `referralCode` for increase, decrease, swap, and TP/SL order payloads. The field can be a human-readable registered referral code or an already encoded `bytes32` value. - Human-readable referral codes are encoded by the API before signing and support letters, digits, and underscores, up to 20 characters. - Fixed referral code forwarding in SDK v2 order transaction requests so `referralCode` is included when preparing API-relayed orders. ## 1.6.0 — June 8, 2026 This release promotes the recent SDK v2 API, GMX Account, order, and helper surface from the alpha series into the stable `1.6.x` line. - Restored API peer fallback behavior in SDK API host config and related HTTP-backed reads. - Added `uiFeeReceiver` handling for TWAP UI fee receiver helpers. - Included the SDK v2 read, GMX Account, wallet, subaccount, and API-relayed order helpers introduced during the `1.5.0-alpha` series in the stable release line. ## 1.5.0-alpha-18 — May 20, 2026 - Added optional `uiFeeReceiver` support for API-driven order transaction helpers - Added GMX Account operation examples - Documented SDK v2 trade-history reads through `fetchTrades()` and `searchTrades()` - Documented SDK v2 one-click-trading lifecycle: `activateSubaccount()` signs owner approvals only when needed, `refreshSubaccountState()` updates tracked on-chain status, and synced subaccount orders use an empty approval with `signature: "0x"` while signing each order with the subaccount key. ## 1.5.0-alpha-17 — May 17, 2026 - Added public gas utility subpath exports under `@gmx-io/sdk/utils/gas/*`. - Expanded GMX Account helper coverage for SDK v2 integrations. ## 1.5.0-alpha-16 — May 16, 2026 - Added SDK v2 trade-history reads through `fetchTrades()` and `searchTrades()`. - Added SDK v2 JIT liquidity reads through `fetchJitLiquidityInfo()`. - Added SDK v2 GMX Account helpers for same-chain deposits and withdrawals, cross-chain deposits and withdrawals, bridge-out parameter building, ERC-20 approval building, and cross-chain withdrawal status polling. ## 1.5.0-alpha-15 — May 8, 2026 This release updates position valuation helpers, leverage-limit calculation, and package metadata for Release 110. - Removed the `@gmx-io/sdk/configs/marketHours` public config module. Max allowed leverage is now derived from live market fields instead of static market-hours sentinel values. - Added `getMaxAllowedLeverage({ minCollateralFactor, minCollateralFactorForLiquidation, positionFeeFactorForBalanceWasNotImproved })` to `@gmx-io/sdk/utils/markets`. - Added after-all-fees position fields and helpers: `netValueAfterAllFees`, `pnlAfterAllFees`, `pnlAfterAllFeesPercentage`, `getPositionNetValueAfterAllFees`, and `getPositionPnlAfterAllFees`. - Simplified `getPositionNetValue` and `getPositionPnlAfterFees` so they only account for collateral, PnL, borrowing fees, and funding fees. Use the after-all-fees helpers when you need price impact and closing fee effects included. - Added external swap support to `SwapStrategyForSwapOrders`. ## 1.5.0-alpha-14 — May 7, 2026 This release adds MegaETH market metadata and expands SDK trade-history data. - Added MEGA/USD market and token config entries for Arbitrum and MegaETH. - Added `swapFeeUsd` to transformed trade actions from `@gmx-io/sdk/utils/tradeHistory`. - Added `swapImpactUsd`, `totalImpactUsd`, `swapFeeUsd`, and `liquidationFeeAmount` to the SDK v1 trade-actions GraphQL selection. ## 1.5.0-alpha-13 — April 24, 2026 This release updates generated market and token metadata for new Arbitrum energy markets and includes a swap-routing fallback fix. - Added Arbitrum SDK config entries for WTIOIL/USD, BRENTOIL/USD, and NATGAS/USD markets and their synthetic index tokens. - Added `searchAliases` to token config metadata so integrations can expose alternate ticker search terms such as CL and BZ. - Added market-hours leverage config through `@gmx-io/sdk/configs/marketHours`, including `MARKET_HOURS_MARKETS` and `MarketHoursConfig`. - Fixed a swap-routing fallback case so route selection handles zero-output candidates correctly. ## 1.5.0-alpha-12 — April 24, 2026 This release updates API host configuration and adds helpers for restoring encrypted subaccount keys. - Updated the Arbitrum Sepolia API URL returned by `getApiUrl(421614)`. Test hosts can change between alpha releases, so integrations should use `getApiUrl(chainId)` instead of hardcoding the host. - `generateSubaccount(mainSigner)` now returns an AES-encrypted `privateKey` value. - Added `decryptSubaccountPrivateKey(encryptedPrivateKey, mainAccountAddress)` and `createSubaccountSignerFromConfig(encryptedPrivateKey, mainAccountAddress)` to `@gmx-io/sdk/utils/subaccount`. ## 1.5.0-alpha-11 — April 23, 2026 This release improves API peer handling and custom HTTP client injection for `GmxApiSdk`. - Exported `HttpClientWithFallback` and the `IHttp` type from `@gmx-io/sdk/v2`. - Added the `api` constructor option to `GmxApiSdk`, letting integrations inject a custom HTTP client instead of using the default `HttpClientWithFallback`. - `GmxApiSdk` uses the configured API peer list by default and can fail over between peer hosts for server or network errors. ## 1.5.0-alpha-10 — April 14, 2026 This release adds order submission, one-click-trading subaccounts, wallet helpers, and a signer abstraction to `GmxApiSdk`, and migrates the SDK's API hosts to the new peer-region deployment. - Added order submission, edit, and cancellation to `GmxApiSdk` in `@gmx-io/sdk/v2`. `executeExpressOrder(request, signer)` prepares, signs, and submits an order in one call via the GMX API and Gelato relay. Integrations that manage their own signing UX can use the manual `prepareOrder → signOrder → submitOrder` flow. `prepareEditOrder`, `prepareCancelOrder`, `prepareCollateral`, and `fetchOrderStatus` round out the order lifecycle. [SDK v1](./v1/readme.mdx) and direct contracts remain available for RPC-based integrations. - Added one-click-trading (1CT) subaccount support to `GmxApiSdk`. `generateSubaccount(mainSigner)` deterministically derives a subaccount from the main signer's signature, `activateSubaccount(mainSigner, { expiresInSeconds?, maxAllowedCount? })` signs a `SubaccountApproval` and stores it, and `clearSubaccount()` removes it. Once active, `executeExpressOrder` signs with the subaccount automatically. The lower-level helpers `fetchSubaccountStatus`, `prepareSubaccountApproval`, and `signSubaccountApproval` are also exposed, alongside `subaccountAddress`, `hasActiveSubaccount`, and `subaccountApprovalMessage` getters. - Added wallet helpers to `GmxApiSdk`: `fetchWalletBalances({ address })`, `fetchAllowances({ address, spender })`, and `buildApproveTransaction(params)` for building ERC-20 approval calldata. - Added a signer abstraction. `IAbstractSigner` is the interface `GmxApiSdk` methods accept for signing, and `PrivateKeySigner` is a built-in implementation for server-side integrations. Both are exported from `@gmx-io/sdk/v2`. - Migrated mainnet API base URLs in `@gmx-io/sdk/configs/api` to the new peer pair `https://{chain}.gmxapi.io/v1` and `https://{chain}.gmxapi.ai/v1` for Arbitrum, Avalanche, Botanix, and MegaETH. `getApiUrl(chainId)` returns the default peer, and `getApiFallbackUrls(chainId)` returns the additional peer list. ## 1.5.0-alpha-9 — March 25, 2026 This release expands `GmxApiSdk` with staking-power and buyback reads. - Added `fetchStakingPower(params)` to `GmxApiSdk` in `@gmx-io/sdk/v2`. This method wraps `/staking/power` and returns `StakingPowerResponse`. - Added `fetchBuybackWeeklyStats()` to `GmxApiSdk` in `@gmx-io/sdk/v2`. This method wraps `/buyback/weekly-stats` and returns `BuybackWeeklyStatsResponse`. - Added the matching `@gmx-io/sdk/v2` type exports for staking-power and buyback responses. ## 1.5.0-alpha-8 — March 11, 2026 This release expands the `GmxApiSdk` read surface to cover more GMX HTTP endpoints and exports the matching typed response helpers. - Added `fetchMarkets()`, `fetchMarketsTickers(params)`, `fetchTokens()`, `fetchPairs()`, `fetchRates(params)`, `fetchApy(params)`, `fetchPerformanceAnnualized(params)`, and `fetchPerformanceSnapshots(params)` to `GmxApiSdk` in `@gmx-io/sdk/v2`. - Added the matching `@gmx-io/sdk/v2` type exports for APY, market tickers, pairs, rates, and performance responses. ## 1.5.0-alpha-7 — March 9, 2026 This release improves TypeScript type resolution for projects that consume the SDK in CommonJS mode. - Added `typesVersions` mappings to `@gmx-io/sdk` so TypeScript resolves subpath types correctly when `moduleResolution` is set to `"node"` or `"node10"` in `tsconfig.json`. Projects using `"bundler"` or `"node16"` module resolution already resolve types through the `exports` field and are unaffected. - Covers the root client entrypoints (`@gmx-io/sdk`, `@gmx-io/sdk/v1`, `@gmx-io/sdk/v2`) as well as config, ABI, utility, prebuilt, and type-only subpaths. - No runtime SDK API methods changed in this release. The update is packaging and type-resolution focused. ## 1.5.0-alpha-6 — March 9, 2026 This release adds OHLCV reads to `GmxApiSdk` and renames address-filtered API SDK params to match the underlying GMX API. - Added `fetchOhlcv(params)` to `GmxApiSdk` in `@gmx-io/sdk/v2`. This method wraps `fetchApiOhlcv` and returns `OhlcvCandle[]` from `/prices/ohlcv`. - Renamed `fetchPositionsInfo(params)` and `fetchOrders(params)` params from `account` to `address`. The underlying `fetchApiPositionsInfo` and `fetchApiOrders` helpers now use `address` as well. - Added `OhlcvCandle` and `OhlcvParams` exports in `@gmx-io/sdk/v2`, plus the `@gmx-io/sdk/types/prices` subpath export for price candle types. ## 1.5.0-alpha-5 — February 28, 2026 This release fixes a potential negative pool amount edge case in position price impact calculations. - `getPriceImpactForPosition` in `@gmx-io/sdk/utils/fees` now accepts an optional `fallbackToZero` option. When enabled, negative pool amounts are clamped to zero instead of producing invalid results. - `getContractPositionDynamicFees` in `@gmx-io/sdk/utils/positions` uses `fallbackToZero: true` when calling `getPriceImpactForPosition` internally, preventing errors from negative pool states. ## 1.5.0-alpha-4 — February 13, 2026 This release adds five new synthetic markets on Arbitrum and expands the `GmxApiSdk` class with positions and orders support. - Added `fetchPositionsInfo(params)` and `fetchOrders(params)` methods to `GmxApiSdk` in `@gmx-io/sdk/v2`. These methods wrap `fetchApiPositionsInfo` and `fetchApiOrders` respectively. - Added five new Arbitrum markets: XAUT/USD [WBTC-USDC], LIT/USD [WETH-USDC], IP/USD [WBTC-USDC], CC/USD [WBTC-USDC], and MET/USD [WBTC-USDC]. All five index tokens are synthetic. - Added corresponding token configurations for XAUT, LIT (Lighter), IP (Story), CC (Canton), and MET (Meteora) on Arbitrum. ## 1.5.0-alpha-3 — February 13, 2026 This release introduces the `GmxApiSdk` client and adds GMX API support for positions, orders, and fee utilities. - Added `GmxApiSdk` class exported from `@gmx-io/sdk/v2`. Instantiate it with a `chainId` to call GMX API endpoints directly. Provides `fetchMarketsInfo()` and `fetchTokensData()` methods. Supported on Arbitrum, Avalanche, and Arbitrum Sepolia; throws at construction time for unsupported chains. - Added `getPositionInfo` utility to `@gmx-io/sdk/utils/positions`. Computes a comprehensive position summary (entry price, PnL, leverage, liquidation price, net value, fees) from a raw position and market data. - Added `getContractPositionDynamicFees` to `@gmx-io/sdk/utils/positions`. Calculates dynamic fees (borrowing, funding, closing) for a position given the current market fee state. - Added `fetchApiPositionsInfo` to `@gmx-io/sdk/utils/positions`. Fetches position data from the GMX API instead of on-chain multicalls (available on Arbitrum, Avalanche, and Arbitrum Sepolia). - Added `fetchApiOrders` to `@gmx-io/sdk/utils/orders`. Fetches order data from the GMX API. - Added `isApiSupported(chainId)` to `@gmx-io/sdk/configs/api`. Returns `true` for chains that have a GMX API endpoint (Arbitrum, Avalanche, and Arbitrum Sepolia). - Added `FLOAT_PRECISION_SQRT_DECIMALS` (15) and `FLOAT_PRECISION_SQRT` (`10n ** 15n`) constants to `@gmx-io/sdk/utils/numbers`. ## 1.5.0-alpha-2 — February 11, 2026 This release adds fee utilities and Solidity error decoding helpers. - Added `getMaxNegativeImpactBps` to `@gmx-io/sdk/utils/fees`. Converts a market's `maxPositionImpactFactorNegative` to basis points. - Added `tryDecodeCustomError`, `decodeErrorFromViemError`, and `extractErrorDataFromViemError` to `@gmx-io/sdk/utils/errors`. These functions decode custom Solidity errors from viem error objects using the GMX `CustomErrors` ABI. ## 1.3.1 — September 15, 2025 This release fixes order payload forwarding. - Fixed `dataList` not being forwarded to the on-chain order payload in `createIncreaseOrder`, `createDecreaseOrder`, and `createSwapOrder`. The `dataList` parameter (optional `string[]`) now defaults to `[]` when omitted. ## 1.3.0 — September 15, 2025 This release adds GMX v2.2 contract support and position impact fields. - Added support for GMX v2.2 contracts. Updated `SyntheticsReader` and `ClaimHandler` ABIs; added `SmartAccount` ABI. - Added `pendingImpactUsd` and `closePriceImpactDeltaUsd` fields to `PositionInfo`. - Added `nextPendingImpactDeltaUsd` and `potentialPriceImpactDiffUsd` fields to `NextPositionValues`. - Fixed position impact capping logic in `getNextPositionValuesForIncreaseTrade` to use `nextSizeUsd` instead of `sizeDeltaUsd`. ## 1.2.1 — August 25, 2025 This release fixes Botanix client initialization. - Fixed Botanix viem client initialization. Added Botanix to `BATCH_CONFIGS` (it was missing, which caused the default `PublicClient` to fail on Botanix). Changed batch config access to use optional chaining (`?.`) so an unsupported chain ID doesn't throw at client construction time. ## 1.2.0 — July 17, 2025 This release adds three new markets across Arbitrum and Avalanche. - Added market and token configurations for three new markets: PUMP/USD [WBTC-USDC] and ARB/USD [ARB-ARB] on Arbitrum, and PUMP/USD [WAVAX-USDC] on Avalanche. PUMP is a synthetic token. ## 1.1.0 — June 3, 2025 This release adds four new synthetic markets on Arbitrum. - Added market and token configurations for four new markets on Arbitrum: CRV/USD [WETH-USDC], XMR/USD [WBTC-USDC], MOODENG/USD [WBTC-USDC], and PI/USD [WBTC-USDC]. All four index tokens are synthetic. ## 1.0.5 — May 26, 2025 This release fixes `uiFeeReceiver` propagation in order creation. - Fixed `uiFeeReceiver` not being read from `sdk.config.settings.uiFeeReceiverAccount` in `createIncreaseOrder`, `createDecreaseOrder`, and `createSwapOrder`. Previously all three functions passed `zeroAddress` unconditionally. ## 1.0.3 — May 23, 2025 This release adds the `isTrigger` parameter and fixes order type forwarding in `createDecreaseOrder`. - Added `isTrigger` parameter to `orders.createDecreaseOrder`. When `true`, the order type is taken from `decreaseAmounts.triggerOrderType`; when `false` or omitted, the order type defaults to `Market Decrease`. - Fixed `orderType` not being forwarded correctly in `orders.createDecreaseOrder`. ## 1.0.0 — April 30, 2025 This is the initial stable release. It removes the deprecated `subgraphUrl` config key and adds dual ESM/CJS module support. - Removed `subgraphUrl` from `GmxSdkConfig`. Use `subsquidUrl` instead. - Added support for both ESM and CJS module formats. The package ships two builds: `build/esm/` and `build/cjs/`. - Changed the default module format from ESM to CJS. The `main` entry point resolves to `build/cjs/src/index.js`. --- ## SDK Overview The GMX SDK (`@gmx-io/sdk`) is a TypeScript library for integrating GMX perpetuals and spot trading into your application. It wraps the GMX smart contracts and data APIs into a typed interface, letting you read market data, compute fees, and submit orders without managing low-level contract calls directly. The SDK runs in Node.js (>=18) and browser environments. ## SDK v1 and v2 The SDK ships two clients. Choose based on your integration needs: Install both clients from the same package: `npm install @gmx-io/sdk`. The SDK v2 import path is `@gmx-io/sdk/v2`, but `@gmx-io/sdk/v2` is not a separate npm package. | | SDK v1 — `GmxSdk` | SDK v2 — `GmxApiSdk` | | ---------------- | -------------------------------------- | ---------------------------------------------- | | **Import** | `import { GmxSdk } from "@gmx-io/sdk"` | `import { GmxApiSdk } from "@gmx-io/sdk/v2"` | | **Requires** | RPC + Oracle URL + Subsquid URL | Chain ID only | | **Capabilities** | Full direct client (read + write) | HTTP client for reads, wallet helpers, subaccounts, and API-relayed order workflows | | **Status** | Maintenance only: no new features; to be removed in a future major version | Recommended for new integrations; expanding to cover the full SDK surface | :::note SDK v2 (`GmxApiSdk`) is under active development and will expand over time, replacing the need for direct RPC, oracle, and Subsquid connections. It wraps the [GMX API OpenAPI Reference](/docs/category/gmx-api-openapi-reference). ::: :::warning SDK v1 (`GmxSdk`) is being sunset. It receives no new features, and new capabilities such as JIT-aware trading capacity ship only in SDK v2. It will be removed in a future major version, so plan to migrate existing SDK v1 integrations to SDK v2. ::: - **[SDK v1 — Getting Started](./v1/readme.mdx)** — Full client for read and write operations - **[SDK v1 — Integration guide](./v1/integration-guide.md)** — End-to-end workflows and operational guidance - **[SDK v1 — Troubleshooting](./v1/troubleshooting.md)** — Receipt handling, duplicate-submit protection, stale reads, and simulation caveats - **[SDK v2 — Getting Started](./v2/readme.md)** — HTTP API client for TypeScript integrations - **[SDK v2 — Order Examples](./v2/examples.md)** — Creating, editing, cancelling, and tracking orders If you are starting a new integration, read the workflow page before the reference pages and build on SDK v2: HTTP-backed reads, wallet helpers, subaccount helpers, and API-relayed order submission. SDK v1 remains available for direct RPC-backed reads or writes until it is removed. ## Operational differences | Topic | SDK v1 — `GmxSdk` | SDK v2 — `GmxApiSdk` | |---|---|---| | Data sources | RPC, oracle, and Subsquid | GMX API | | Trade history | ✅ | ✅ | | Order submission, edit, and cancellation | ✅ Direct wallet transactions | ✅ Signed intents posted to the GMX API and submitted through GMX Relay for express orders | | Built-in HTTP peer failover | ❌ D
프로젝트로 돌아가기