GMX 백서

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

efault viem transports use `retryCount: 0` | ✅ `HttpClientWithFallback` tries configured API peer hosts for server and network errors | | Built-in transaction receipt waiting | ❌ | Not applicable for API-relayed order submission; poll order status with the returned `requestId` | ## Available now - SDK v1 is in maintenance: it receives no new features and will be removed in a future major version. - SDK v2 exposes read methods such as `fetchMarketsInfo`, `fetchMarketsConfig`, `fetchMarketsValues`, `fetchMarkets`, `fetchMarketsTickers`, `getTradingCapacity`, `fetchTokensData`, `fetchTokens`, `fetchPairs`, `fetchRates`, `fetchApy`, `fetchPerformanceAnnualized`, `fetchPerformanceSnapshots`, `fetchGmPoolYieldPnl`, `fetchGmUserEarnings`, `fetchPositionsInfo`, `fetchOrders`, `fetchTrades`, `searchTrades`, `fetchOhlcv`, `fetchBuybackWeeklyStats`, `fetchJitLiquidityInfo`, `fetchStakingPower`, `fetchTransitRoutes`, `fetchTransitFeeTier`, `fetchTransitAuthorization`, `fetchTransitQuote`, `fetchTransitOrder`, `fetchTransitOrders`, `fetchWhitelists`, `fetchUsdgBoostApr`, `fetchWalletBalances`, and `fetchAllowances`. - `@gmx-io/sdk/v2` also exports standalone protocol-wide stats reads, `fetchApiProtocolStatsSummary`, `fetchApiProtocolStatsTimeseries`, and `fetchApiProtocolStatsSources`, which you call with an HTTP client built from `getStatsApiUrl()` in `@gmx-io/sdk/configs/api`. See [Protocol stats helpers](./v2/readme.md#protocol-stats-helpers). - SDK v2 also exposes approval helpers, order prepare/sign/submit/status methods, edit/cancel/collateral prepare methods, GMX Account deposit and withdrawal helpers, and subaccount helpers for one-click trading flows. - Use SDK v1 only if your integration needs direct RPC ownership or lower-level contract composition today, and plan its migration to SDK v2. ## Supported networks The SDK supports the following production networks: | Network | Chain ID | Status | | --------- | -------- | ------ | | Arbitrum | 42161 | Active | | Avalanche | 43114 | Active | | MegaETH | 4326 | Active | **Repository:** [github.com/gmx-io/gmx-interface/sdk](https://github.com/gmx-io/gmx-interface/tree/master/sdk) ## Installation Install the SDK using your preferred package manager: ```bash # npm npm install @gmx-io/sdk # yarn yarn add @gmx-io/sdk ``` Both SDK clients ship in this package. Import `GmxSdk` from `@gmx-io/sdk` and `GmxApiSdk` from `@gmx-io/sdk/v2`. The package supports both ESM and CommonJS. CommonJS consumers can use `require("@gmx-io/sdk")` for v1 and `require("@gmx-io/sdk/v2")` for v2. TypeScript subpath resolution is supported for the SDK's root, client, utility, config, ABI, and type-only entrypoints. :::note Use the [SDK changelog](./changelog.md) to review package-level changes before upgrading. ::: The SDK requires Node.js 18 or later. --- ## Examples Use this page for focused runnable snippets. If you want end-to-end trading flows or operational guidance, start with the [Integration guide](./integration-guide.md). ## Get funding fees This example shows how to fetch hourly funding fee rates for all markets using the GMX SDK. Funding fees are paid between long and short positions to keep open interest balanced — positive values mean a position receives funding, and negative values mean it pays. ### Prerequisites Initialize the SDK before running this example: ```typescript const sdk = new GmxSdk({ chainId: 42161, // Arbitrum rpcUrl: "https://arb1.arbitrum.io/rpc", oracleUrl: "https://arbitrum-api.gmxinfra.io", subsquidUrl: "https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql", }); ``` ### Fetch and format funding rates Call `sdk.markets.getMarketsInfo()` to retrieve live market data, then compute the per-period funding factor for each market: ```typescript const { marketsInfoData } = await sdk.markets.getMarketsInfo(); const fundingRates = Object.values(marketsInfoData ?? {}).map((market) => { // 3600n = 1 hour in seconds (BigInt required) const longHourly = getFundingFactorPerPeriod(market, true, 3600n); const shortHourly = getFundingFactorPerPeriod(market, false, 3600n); return { market: getMarketFullName(market), long: formatRatePercentage(longHourly, { displayDecimals: 2 }), short: formatRatePercentage(shortHourly, { displayDecimals: 2 }), }; }); console.table(fundingRates); // Example output: // [ // { market: "BTC/USD [WBTC-USDC]", long: "-0.01%", short: "+0.01%" }, // { market: "ETH/USD [WETH-USDC]", long: "+0.00%", short: "-0.00%" }, // ] ``` `getFundingFactorPerPeriod` returns a `bigint` representing the funding factor scaled to 30 decimal places. A negative value for a position side means that side pays funding for the period. `formatRatePercentage` converts the raw factor to a human-readable percentage string. :::note The `periodInSeconds` argument must be a `bigint` (for example, `3600n` for hourly rates). Passing a plain number will cause a TypeScript type error. ::: ### What the result tells you | Field | Type | Description | | -------- | -------- | ----------------------------------------------------------- | | `market` | `string` | Market name in `INDEX/USD [LONG-SHORT]` format | | `long` | `string` | Hourly funding rate for long positions (negative = paying) | | `short` | `string` | Hourly funding rate for short positions (negative = paying) | The sign convention is: negative means the position is paying funding to the counterpart side; positive means it is receiving funding. ### Related - [`getFundingFactorPerPeriod`](./exports/utils/fees/fees.md) — function reference and parameter details - [`formatRatePercentage`](./exports/utils/numbers.md) — number formatting utilities - [`getMarketFullName`](./exports/utils/markets.md) — market name formatting --- ## api This module exposes the SDK's GMX API endpoint lookup helpers. ## Functions All three helpers accept an optional `ApiEnvironment` value of `"production"` or `"test"`. They use `"production"` by default. ### `getApiUrl` ```typescript getApiUrl(chainId: number, environment?: ApiEnvironment): string | undefined ``` Returns the configured GMX API base URL as a string, or `undefined` when that chain does not have API support. ```typescript const apiUrl = getApiUrl(chainId); if (!apiUrl) { throw new Error(`GMX API is not configured for chain ${chainId}`); } ``` The returned value is an unversioned host. `GmxApiSdk` methods append paths such as `/v1/markets/info` or `/v2/jit/liquidity_info`. ### `getApiFallbackUrls` ```typescript getApiFallbackUrls(chainId: number, environment?: ApiEnvironment): string[] ``` Returns the additional GMX API base URLs configured for the requested chain and environment. The returned list can be empty. ```typescript const fallbackUrls = getApiFallbackUrls(chainId); ``` :::warning In `1.6.4` this returns an empty array for every chain in both the `production` and `test` environments. The packaged configuration currently ships no peer hosts, so peer rotation has to be supplied by your application. ::: GMX API production networks are deployed across separate `.gmxapi.io` and `.gmxapi.ai` hosts. If your integration requires peer rotation, pass the second host explicitly rather than relying on this helper. See [GMX API peer deployments](../../../../api/rest-api/fallback-urls.mdx#gmx-api-peer-deployments). ### `isApiSupported` ```typescript isApiSupported(chainId: number, environment?: ApiEnvironment): boolean ``` Returns `true` when `getApiUrl(chainId)` resolves to a GMX API endpoint. ```typescript if (!isApiSupported(chainId)) { throw new Error(`GMX API is not configured for chain ${chainId}`); } ``` :::note This helper reports package configuration; it does not check whether an endpoint is reachable or whether a deployment is still active. Verify network availability against the [GMX API peer deployments](../../../../api/rest-api/fallback-urls.mdx#gmx-api-peer-deployments) page before integrating. ::: --- ## batch This module exposes batching defaults used by the SDK's viem transports and paginated Subsquid helpers. ## Exports - `BATCH_CONFIGS` — per-chain viem batch settings for HTTP transport and client-side batching - `SUBSQUID_PAGINATION_LIMIT` — default page size used by paginated indexer helpers ```typescript ``` Use this module when you provide custom viem clients or build your own paginated Subsquid fetch loops. When you inject a custom viem `publicClient`, carry over `BATCH_CONFIGS[chainId].client` instead of relying on viem defaults. The SDK's batch config raises the client-side multicall calldata limit to `1024 * 1024` bytes; without it, large GMX multicalls may be split into many smaller RPC requests. --- ## chainIds This module exports the raw numeric chain ID constants used across the SDK, without the richer metadata from [`configs/chains`](./chains.md). ## Exports - Contracts chains: `ARBITRUM`, `AVALANCHE`, `MEGAETH` - Development contracts chains: `ARBITRUM_SEPOLIA`, `AVALANCHE_FUJI` - Source chains: `SOURCE_ETHEREUM_MAINNET`, `SOURCE_BASE_MAINNET`, `SOURCE_BSC_MAINNET`, `SOURCE_OPTIMISM_SEPOLIA`, `SOURCE_SEPOLIA` ```typescript console.log(ARBITRUM); // 42161 console.log(MEGAETH); // 4326 console.log(SOURCE_ETHEREUM_MAINNET); // 1 ``` --- ## chains This module provides chain configuration constants, types, and utilities for the GMX protocol. It includes chain IDs, names, gas configurations, execution fee settings, and helper functions for working with different blockchain networks supported by GMX. ## Types The `chains` module exports the following TypeScript types for working with chain identifiers and names. ### ContractsChainId Chain IDs where GMX contracts are deployed, including testnets. Equivalent to the union of all entries in `CONTRACTS_CHAIN_IDS_DEV` (42161, 43114, 4326, 43113, 421614). ```typescript // Arbitrum | Avalanche | MegaETH | Avalanche Fuji | Arbitrum Sepolia type ContractsChainId = (typeof CONTRACTS_CHAIN_IDS_DEV)[number]; ``` ### ContractsChainIdProduction Production-only chain IDs where GMX contracts are deployed, excluding testnets. Equivalent to the union of `CONTRACTS_CHAIN_IDS` (42161, 43114, 4326). ```typescript // Arbitrum | Avalanche | MegaETH type ContractsChainIdProduction = (typeof CONTRACTS_CHAIN_IDS)[number]; ``` ### SettlementChainId Chain IDs used for settlement operations, including testnets. Equivalent to the union of `SETTLEMENT_CHAIN_IDS_DEV` (42161, 43114, 421614, 43113). ```typescript // Arbitrum | Avalanche | Arbitrum Sepolia | Avalanche Fuji type SettlementChainId = (typeof SETTLEMENT_CHAIN_IDS_DEV)[number]; ``` ### SourceChainId Chain IDs from which assets can be bridged into GMX. Includes mainnet and testnet source chains as well as GMX settlement chains. ```typescript // SOURCE_OPTIMISM_SEPOLIA | SOURCE_SEPOLIA | SOURCE_BASE_MAINNET | SOURCE_BSC_MAINNET // | SOURCE_ETHEREUM_MAINNET | ARBITRUM_SEPOLIA | ARBITRUM | AVALANCHE | AVALANCHE_FUJI type SourceChainId = (typeof SOURCE_CHAIN_IDS)[number]; ``` ### AnyChainId Union of all supported chain IDs across contracts, settlement, and source chains. ```typescript type AnyChainId = ContractsChainId | SettlementChainId | SourceChainId; ``` ### ChainName Human-readable name for a supported chain. Returned by `getChainName()`. The value `"Unknown"` is returned for unrecognized chain IDs. ```typescript type ChainName = | "Arbitrum" | "Avalanche" | "Avalanche Fuji" | "Arbitrum Sepolia" | "Optimism Sepolia" | "Sepolia" | "Base" | "BNB" | "Ethereum" | "MegaETH" | "Unknown"; ``` ## Constants The module exports the following constants. ### Chain ID constants Numeric chain IDs for active, testnet, and legacy-supported networks. Import whichever you need; you rarely need all of them. ```typescript ARBITRUM, AVALANCHE, MEGAETH, AVALANCHE_FUJI, ARBITRUM_SEPOLIA, SOURCE_ETHEREUM_MAINNET, SOURCE_BASE_MAINNET, SOURCE_BSC_MAINNET, SOURCE_OPTIMISM_SEPOLIA, SOURCE_SEPOLIA, } from "@gmx-io/sdk/configs/chains"; console.log(ARBITRUM); // 42161 console.log(AVALANCHE); // 43114 console.log(MEGAETH); // 4326 console.log(AVALANCHE_FUJI); // 43113 console.log(ARBITRUM_SEPOLIA); // 421614 console.log(SOURCE_ETHEREUM_MAINNET); // 1 console.log(SOURCE_BASE_MAINNET); // 8453 console.log(SOURCE_BSC_MAINNET); // 56 console.log(SOURCE_OPTIMISM_SEPOLIA); // 11155420 console.log(SOURCE_SEPOLIA); // 11155111 ``` ### Chain ID arrays Readonly tuples of chain IDs grouped by role. Use these for validation or iteration instead of hardcoding values. - `CONTRACTS_CHAIN_IDS` — Production chains where GMX contracts are deployed: `[42161, 43114, 4326]` - `CONTRACTS_CHAIN_IDS_DEV` — All contracts chains including testnets: `[42161, 43114, 4326, 43113, 421614]` - `SETTLEMENT_CHAIN_IDS` — Production settlement chains: `[42161, 43114]` - `SETTLEMENT_CHAIN_IDS_DEV` — Settlement chains including testnets: `[42161, 43114, 421614, 43113]` - `SOURCE_CHAIN_IDS` — Source chains for cross-chain deposits ```typescript for (const chainId of CONTRACTS_CHAIN_IDS) { console.log(isContractsChain(chainId)); // true } ``` ### Other constants - `GMX_ACCOUNT_PSEUDO_CHAIN_ID: 0` — Pseudo chain ID used internally for the GMX Account feature. - `megaeth: Chain` — Viem `Chain` definition for the MegaETH network. Pass to `createPublicClient` when connecting to MegaETH. - `VIEM_CHAIN_BY_CHAIN_ID: Record<AnyChainId, Chain>` — Map of chain ID to viem `Chain` object for all supported chains. ```typescript // Use the pre-built MegaETH chain definition const megaClient = createPublicClient({ chain: megaeth, transport: http("https://mainnet.megaeth.com/rpc") }); // Or look up any chain by ID const arbitrumChain = VIEM_CHAIN_BY_CHAIN_ID[ARBITRUM]; ``` ## Methods The module exports functions for looking up chain metadata, validating chain IDs, and reading per-chain execution fee configuration. ### Chain identification #### getChainName `getChainName(chainId: number): ChainName` Returns the human-readable name for a chain ID. Returns `"Unknown"` for unrecognized IDs. ```typescript console.log(getChainName(ARBITRUM)); // "Arbitrum" console.log(getChainName(MEGAETH)); // "MegaETH" console.log(getChainName(99999)); // "Unknown" ``` #### getChainSlug `getChainSlug(chainId: number): ChainSlug` Returns the URL-friendly slug for a chain ID. Returns `"unknown"` for unrecognized IDs. ```typescript console.log(getChainSlug(ARBITRUM)); // "arbitrum" console.log(getChainSlug(AVALANCHE)); // "avalanche" ``` #### getChainIdBySlug `getChainIdBySlug(slug: string): AnyChainId | undefined` Returns the chain ID for a given slug, or `undefined` if not found. ```typescript console.log(getChainIdBySlug("arbitrum")); // 42161 console.log(getChainIdBySlug("unknown")); // undefined ``` #### getViemChain `getViemChain(chainId: number): Chain` Returns the viem `Chain` object for a chain ID. Use this when constructing a viem `PublicClient` or `WalletClient` for a dynamically selected chain. ```typescript const chain = getViemChain(ARBITRUM); const client = createPublicClient({ chain, transport: http("https://arb1.arbitrum.io/rpc") }); ``` ### Chain classification #### isContractsChain `isContractsChain(chainId: number, dev?: boolean): chainId is ContractsChainId` Returns `true` if the chain ID is one where GMX contracts are deployed. Pass `dev: true` to include testnet chains. ```typescript isContractsChain(ARBITRUM); // true isContractsChain(AVALANCHE_FUJI); // false (testnet excluded by default) isContractsChain(AVALANCHE_FUJI, true); // true (testnet included) ``` #### isTestnetChain `isTestnetChain(chainId: number): boolean` Returns `true` if the chain ID is a testnet. Matches Avalanche Fuji, Arbitrum Sepolia, Sepolia, and Optimism Sepolia. ```typescript isTestnetChain(ARBITRUM); // false isTestnetChain(ARBITRUM_SEPOLIA); // true ``` #### isChainDisabled `isChainDisabled(chainId: ContractsChainId): boolean` Returns `true` if the chain is disabled in the SDK configuration. ### Execution fee helpers These functions read per-chain execution fee configuration. Use them to validate or display fee estimates before submitting orders. #### getHighExecutionFee `getHighExecutionFee(chainId: number): number` Returns the "high fee" warning threshold in USD. Defaults to 5 for unknown chain IDs. ```typescript console.log(getHighExecutionFee(ARBITRUM)); // 5 ``` #### getExcessiveExecutionFee `getExcessiveExecutionFee(chainId: number): number` Returns the "excessive fee" threshold in USD. Defaults to 10 for unknown chain IDs. ```typescript console.log(getExcessiveExecutionFee(ARBITRUM)); // 10 ``` #### getExecutionFeeConfig `getExecutionFeeConfig(chainId: ContractsChainId): { shouldUseMaxPriorityFeePerGas: boolean; defaultBufferBps: number | undefined } | undefined` Returns the execution fee configuration for a chain, including whether to use `maxPriorityFeePerGas` and the default buffer basis points. #### getMaxFeePerGas `getMaxFeePerGas(chainId: ContractsChainId): bigint | undefined` Returns the EIP-1559 `maxFeePerGas` cap for a chain, or `undefined` if uncapped. #### getGasPricePremium `getGasPricePremium(chainId: ContractsChainId): bigint | undefined` Returns the gas price premium (in wei) added to execution fee calculations. #### getMaxPriorityFeePerGas `getMaxPriorityFeePerGas(chainId: ContractsChainId): bigint | undefined` Returns the `maxPriorityFeePerGas` value for a chain. #### getMinExecutionFeeUsd `getMinExecutionFeeUsd(chainId: ContractsChainId): bigint | undefined` Returns the configured minimum execution fee in USD equivalent (30-decimal precision), or `undefined` when the selected chain does not define one. #### getResidualGasUsdConfig `getResidualGasUsdConfig(chainId: ContractsChainId): { min: number; max: number } | undefined` Returns chain-specific residual gas balance bounds in USD. MegaETH sets this to `{ min: 1, max: 2 }`; other chains return `undefined` and use the default residual gas bounds from `@gmx-io/sdk/configs/fees`. #### getGasPriceBuffer `getGasPriceBuffer(chainId: ContractsChainId | SourceChainId): bigint | undefined` Returns the gas price buffer in basis points for non-EIP-1559 transaction fee calculations. ### Chain metadata #### getChainNativeTokenSymbol `getChainNativeTokenSymbol(chainId: ContractsChainId): string` Returns the native token symbol for a chain (for example, `"ETH"` for Arbitrum and MegaETH or `"AVAX"` for Avalanche). #### getChainWrappedTokenSymbol `getChainWrappedTokenSymbol(chainId: ContractsChainId): string` Returns the wrapped native token symbol (for example, `"WETH"` or `"WAVAX"`). #### getChainDefaultCollateralSymbol `getChainDefaultCollateralSymbol(chainId: ContractsChainId): string` Returns the default collateral token symbol for a chain (for example, `"USDC.e"` for Arbitrum, `"USDC"` for Avalanche). #### getExplorerUrl `getExplorerUrl(chainId: number | "layerzero" | "layerzero-testnet"): string` Returns the block explorer base URL for a chain. Also accepts `"layerzero"` and `"layerzero-testnet"` as special values for cross-chain transaction lookup. ```typescript console.log(getExplorerUrl(ARBITRUM)); // "https://arbiscan.io/" console.log(getExplorerUrl("layerzero")); // "https://layerzeroscan.com/" ``` #### getTokenExplorerUrl `getTokenExplorerUrl(chainId: number, tokenAddress: string): string` Returns the full block explorer URL for a specific token address on a chain. ```typescript const url = getTokenExplorerUrl(ARBITRUM, "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"); // "https://arbiscan.io/token/0xaf88d065e77c8cC2239327C5EDb3A432268e5831" ``` --- ## contracts This module provides contract addresses for the GMX protocol across different blockchain networks. It includes addresses for V1, V2 (Synthetics), simulation, GLV, Multichain, Gelato relay, and external contracts, as well as typed lookup utilities. ## Constants ### `CONTRACTS` ```typescript const CONTRACTS: Record<ContractsChainId,
프로젝트로 돌아가기