GMX 백서

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

` — V2-available tokens per chain. - `SYNTHETIC_TOKENS: { [chainId: number]: Token[] }` — Synthetic tokens per chain. - `TOKENS_BY_SYMBOL_MAP: { [chainId: number]: { [symbol: string]: Token } }` — Tokens keyed by symbol per chain. - `WRAPPED_TOKENS_MAP: { [chainId: number]: Token }` — The wrapped native token per chain. - `NATIVE_TOKENS_MAP: { [chainId: number]: Token }` — The native token per chain. ```typescript const arbitrumTokens = TOKENS[ARBITRUM]; console.log(arbitrumTokens[0].symbol); // "ETH" ``` ### TOKEN_COLOR_MAP `TOKEN_COLOR_MAP: { [symbol: string]: string }` Color mappings for token symbols used in UI components. Covers crypto tokens and TradFi tokens such as commodities (for example, GOLD, SILVER, XAU, XAG), and includes a `default` fallback color. ```typescript console.log(TOKEN_COLOR_MAP.ETH); // "#6062a6" console.log(TOKEN_COLOR_MAP.BTC); // "#F7931A" console.log(TOKEN_COLOR_MAP.GOLD); // "#D69A00" console.log(TOKEN_COLOR_MAP.default); // "#6062a6" ``` ## Methods The tokens config module exports functions organized into two groups: lookup and validation helpers for retrieving token objects, and display/conversion utilities. Import any function directly from `@gmx-io/sdk/configs/tokens`. Chain ID constants (such as `ARBITRUM`) must be imported from `@gmx-io/sdk/configs/chains`. ### getSyntheticTokens ```typescript getSyntheticTokens(chainId: number): Token[] ``` Returns all synthetic tokens available on the specified chain. ```typescript const syntheticTokens = getSyntheticTokens(ARBITRUM); console.log(syntheticTokens.map((token) => token.symbol)); ``` ### getWrappedToken ```typescript getWrappedToken(chainId: number): Token ``` Returns the wrapped native token for the specified chain (for example, WETH on Arbitrum, WAVAX on Avalanche). ```typescript const wrappedToken = getWrappedToken(ARBITRUM); console.log(wrappedToken.symbol); // "WETH" ``` ### getNativeToken ```typescript getNativeToken(chainId: number): Token ``` Returns the native token for the specified chain. ```typescript const nativeToken = getNativeToken(ARBITRUM); console.log(nativeToken.symbol); // "ETH" ``` ### getTokens ```typescript getTokens(chainId: number): Token[] ``` Returns all tokens available on the specified chain. ```typescript const allTokens = getTokens(ARBITRUM); ``` ### getV1Tokens ```typescript getV1Tokens(chainId: number): Token[] ``` Returns tokens available in GMX V1 on the specified chain. ### getV2Tokens ```typescript getV2Tokens(chainId: number): Token[] ``` Returns tokens available in GMX V2 on the specified chain. ### getTokensMap ```typescript getTokensMap(chainId: number): { [address: string]: Token } ``` Returns a mapping of token addresses to token objects for the specified chain. ```typescript const tokensMap = getTokensMap(ARBITRUM); const ethToken = tokensMap["0x0000000000000000000000000000000000000000"]; console.log(ethToken.symbol); // "ETH" ``` ### getWhitelistedV1Tokens ```typescript getWhitelistedV1Tokens(chainId: number): Token[] ``` Returns whitelisted tokens for GMX V1 on the specified chain. Equivalent to `getV1Tokens`. ### getVisibleV1Tokens ```typescript getVisibleV1Tokens(chainId: number): Token[] ``` Returns visible V1 tokens (excluding wrapped tokens) for the specified chain. ### isValidToken ```typescript isValidToken(chainId: number, address: string): boolean ``` Returns `true` if the token address exists on the specified chain. Throws if the chain ID is not recognized. ```typescript const isValid = isValidToken(ARBITRUM, "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"); console.log(isValid); // true ``` ### isValidTokenSafe ```typescript isValidTokenSafe(chainId: number, address: string): boolean ``` Safely checks if a token address exists on the specified chain without throwing. ```typescript isValidTokenSafe(ARBITRUM, "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"); // true isValidTokenSafe(ARBITRUM, "0xinvalidaddress"); // false ``` ### getToken ```typescript getToken(chainId: number, address: string): Token ``` Returns the token object for the specified address. Throws if the chain or address is not recognized. ```typescript const wethToken = getToken(ARBITRUM, "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"); console.log(wethToken.symbol); // "WETH" ``` ### getTokenBySymbol ```typescript getTokenBySymbol(chainId: number, symbol: string, options?: { isSynthetic?: boolean; version?: "v1" | "v2"; symbolType?: "symbol" | "baseSymbol" }): Token ``` Returns the token object for the specified symbol. Throws if not found. ```typescript const ethToken = getTokenBySymbol(ARBITRUM, "ETH"); const syntheticBTC = getTokenBySymbol(ARBITRUM, "BTC", { isSynthetic: true }); ``` ### getTokenBySymbolSafe ```typescript getTokenBySymbolSafe(chainId: number, symbol: string, options?: { isSynthetic?: boolean; version?: "v1" | "v2"; symbolType?: "symbol" | "baseSymbol" }): Token | undefined ``` Like `getTokenBySymbol` but returns `undefined` instead of throwing when the token is not found. ```typescript const token = getTokenBySymbolSafe(ARBITRUM, "ETH"); // Token const missing = getTokenBySymbolSafe(ARBITRUM, "INVALID"); // undefined ``` ### convertTokenAddress ```typescript convertTokenAddress(chainId: number, address: string, convertTo?: "wrapped" | "native"): string ``` Converts between native and wrapped token addresses. ```typescript const wrappedAddress = convertTokenAddress(ARBITRUM, NATIVE_TOKEN_ADDRESS, "wrapped"); console.log(wrappedAddress); // "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1" const nativeAddress = convertTokenAddress(ARBITRUM, "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1", "native"); console.log(nativeAddress); // "0x0000000000000000000000000000000000000000" ``` ### getNormalizedTokenSymbol ```typescript getNormalizedTokenSymbol(tokenSymbol: string): string ``` Returns a normalized version of a token symbol by applying these rules in order: - `WBTC`, `WETH`, `WAVAX` → strip the leading `W` (for example, `WETH` → `ETH`) - `PBTC`, `STBTC` → return `"BTC"` - `XAUT` → return `"XAUT.v2"` - Symbols containing `.` → return the part before the dot (for example, `USDC.E` → `USDC`) - All other symbols → return as-is ```typescript console.log(getNormalizedTokenSymbol("WETH")); // "ETH" console.log(getNormalizedTokenSymbol("USDC.E")); // "USDC" console.log(getNormalizedTokenSymbol("PBTC")); // "BTC" ``` ### isChartAvailableForToken ```typescript isChartAvailableForToken(chainId: number, tokenSymbol: string): boolean ``` Returns `true` if chart data is available for the token on the specified chain. ### getPriceDecimals ```typescript getPriceDecimals(chainId: number, tokenSymbol?: string): number ``` Returns the number of decimal places to display for a token's price. Defaults to `2`. ```typescript console.log(getPriceDecimals(ARBITRUM, "ETH")); // 2 ``` ### isTokenInList ```typescript isTokenInList(token: Token, tokenList: Token[]): boolean ``` Returns `true` if the token exists in the given list (matched by address). ### isSimilarToken ```typescript isSimilarToken(tokenA: Token, tokenB: Token): boolean ``` Returns `true` if two tokens are similar. Two tokens are considered similar when they share the same address, or when their `symbol` and `baseSymbol` fields overlap (for example, WETH with `baseSymbol: "ETH"` is similar to a token with `symbol: "ETH"`). ### getTokenVisualMultiplier ```typescript getTokenVisualMultiplier(token: Token): string ``` Returns the visual multiplier string for a token, derived from `token.visualPrefix` or `token.visualMultiplier`. Returns an empty string if neither is set. ### getStableTokens ```typescript getStableTokens(chainId: number): Token[] ``` Returns all stable tokens on the specified chain (tokens with `isStable: true`). ### getCategoryTokenAddresses ```typescript getCategoryTokenAddresses(chainId: number, category: TokenCategory): string[] ``` Returns token addresses belonging to the specified category on a chain. ### createTokensMap ```typescript createTokensMap(tokens: Token[]): Record<string, Token> ``` Creates a token address-to-token map from an array of tokens. ```typescript const v1Tokens = getV1Tokens(ARBITRUM); const tokensMap = createTokensMap(v1Tokens); ``` ### isUsdBasedStableToken ```typescript isUsdBasedStableToken(token: Token): boolean ``` Returns `true` if the token is a USD-based stablecoin (USDC, USDC.E, USDT, DAI, USDC.SG). ```typescript const usdc = getTokenBySymbol(ARBITRUM, "USDC"); console.log(isUsdBasedStableToken(usdc)); // true ``` --- ## twap This module exports TWAP configuration defaults. ## Exports - `DEFAULT_TWAP_NUMBER_OF_PARTS` - `MIN_TWAP_NUMBER_OF_PARTS` - `MAX_TWAP_NUMBER_OF_PARTS` - `DEFAULT_TWAP_DURATION` ```typescript ``` Use these constants together with [`utils/twap`](../utils/twap.md). --- ## uniswapV3 This module exposes Uniswap v3 deployment metadata used by external-swap integrations. ## Exports - `UniswapV3Deployment` — deployment shape - `getUniswapV3Deployment(chainId)` - `hasUniswapV3Deployment(chainId)` ```typescript ``` --- ## venus This module exposes Venus deployment metadata used by integrations that need Venus token support. ## Exports - `VenusVTokenConfig` - `VenusDeployment` - `VENUS_EXCHANGE_RATE_DECIMALS` - `getVenusDeployment(chainId)` - `hasVenusDeployment(chainId)` ```typescript ``` --- ## Useful modules The GMX SDK exports constants, types, and utility functions that you can import directly without going through the `GmxSdk` class. These exports are organized into three top-level categories: - **`configs/`** — chain IDs, contract addresses, token metadata, market parameters, oracle keeper URLs, and fee factors - **`utils/`** — fee calculations, price impact, swap routing, position sizing, number formatting, error parsing, and other computation helpers - **`types/`** — type-only entrypoints for SDK configs, markets, tokens, orders, positions, fees, price candles, trade flows, referrals, TWAP, trade history, and Subsquid schema types Additional public utility subpaths are available for lower-level integrations, including `@gmx-io/sdk/utils/orderTransactions`, `@gmx-io/sdk/utils/express`, `@gmx-io/sdk/utils/subaccount`, `@gmx-io/sdk/utils/rpc`, `@gmx-io/sdk/utils/signer`, `@gmx-io/sdk/utils/metrics`, `@gmx-io/sdk/utils/multichain`, and `@gmx-io/sdk/utils/gas/*`. These are lower-level building blocks used by SDK v2 order, subaccount, GMX Account, and gas flows; prefer `GmxApiSdk` from `@gmx-io/sdk/v2` unless you need to compose those primitives directly. The SDK v2 [Order Examples](../../v2/examples.md) page documents the primary transaction request and response types that wrap these utilities. Use these exports to implement custom logic or to pre-compute values before passing them to SDK methods. Import any export directly from its module path, for example: ```typescript ``` See the sub-pages in this section for the API reference modules that are covered manually. Some low-level SDK v2 utility subpaths are intentionally documented through the SDK v2 guide until they need standalone reference pages. --- ## 24h types This type-only entrypoint exports candle data used by the SDK's 24-hour market views. ## Exports - `DayPriceCandle` ```typescript ``` --- ## chains types This type-only entrypoint exports chain configuration shapes. ## Exports - `ContractsChainConfig` — includes contract-chain metadata, execution fee settings, gas price settings, and optional `residualGasUsd` bounds. - `SourceChainConfig` ```typescript ``` --- ## fees types This type-only entrypoint exports fee and gas-limit model types. ## Exports - `ExecutionFee` - `FeeItem` - `SwapFeeItem` - `ExternalSwapFeeItem` - `GasLimitsConfig` - `L1ExpressOrderGasReference` ```typescript ``` --- ## markets types This type-only entrypoint exports the SDK's market and market-info model types. ## Exports - `PnlFactorType` - `MarketSdkConfig` - `Market` - `MarketPoolTokens` - `MarketInfo` - `RawOpenInterestValues` - `MarketValues` - `MarketConfig` - `MarketsData` - `RawMarketInfo` - `RawMarketConfig` - `RawMarketValues` - `RawMarketsInfoData` - `MarketsInfoData` - `MarketTokensAPRData` - `UserEarningsData` - `ContractMarketPrices` - `ClaimableFunding` - `ClaimableFundingData` - `TradingCapacityLimitingFactor` - `JitDataStatus` - `MarketDataStatus` - `TradingCapacity` - `GetTradingCapacityParams` - `MarketTicker` - `MarketTickerWithCapacity` - `LeverageTier` - `MarketWithTiers` ```typescript MarketInfo, MarketsInfoData, RawMarketConfig, RawMarketInfo, RawMarketValues, TradingCapacity, } from "@gmx-io/sdk/types/markets"; ``` `RawMarketConfig` contains the slower-changing portion of a market response, including collateral limits, side-specific funding bounds, `minFundingIncreaseRatePerSecond`, `useOpenInterestInTokensForBalance`, and virtual token identifiers. `RawMarketValues` contains the frequently changing market values, including `virtualInventoryForPositionsInTokens`, plus `updatedAt: number | null`. `updatedAt` is Unix time in milliseconds and represents the least-recent component included in that values row. Treat `null` as an unknown freshness timestamp. `TradingCapacity` contains `availableLiquidity`, `baseAvailableLiquidity`, and `jitAvailableLiquidity` as `bigint`, plus `limitingFactor`, `jitDataStatus`, and `marketDataStatus`. `MarketTickerWithCapacity` extends `MarketTicker` with optional `capacityLong` and `capacityShort` values. `MarketInfo` also exposes optional USD- and token-denominated open interest split by long-token versus short-token collateral: `longInterestUsdUsingLongToken`, `longInterestUsdUsingShortToken`, `shortInterestUsdUsingLongToken`, `shortInterestUsdUsingShortToken`, and the corresponding four `...InTokens...` fields. These fields support the collateral-specific positive-PnL calculation and may be absent in older responses. --- ## orders types This type-only entrypoint exports order enums and enriched order model types. ## Exports - `OrderType` - `SwapOrderType` - `IncreaseOrderType` - `DecreaseOrderType` - `SwapPricingType` - `DecreasePositionSwapType` - `Order` - `SwapOrderInfo` - `PositionOrderInfo` - `TwapOrderInfo` - `OrderInfo` - `OrdersData` - `OrdersInfoData` - `OrderTxnType` - `OrderParams` - `ApiOrderInfo` ```typescript ``` --- ## positions types This type-only entrypoint exports raw and enriched position model types. ## Exports - `Position` - `PositionInfo` - `PositionInfoLoaded` - `RawPositionInfo` - `PositionsData` - `PositionsInfoData` - `ApiPositionInfo` ```typescript ``` `Position` includes `positionValueInUsd: bigint`, expressed with GMX's 30-decimal USD precision. Because `ApiPositionInfo` extends the raw position-info shape, API-backed position reads expose the same field as a `bigint`. --- ## prices types This type-only entrypoint exports OHLCV candle shapes and request params for the SDK's price candle API helpers. ## Exports - `OhlcvCandle` - `OhlcvParams` ```typescript ``` --- ## referrals types This type-only entrypoint exports the SDK's referral data shapes. ## Exports - `UserReferralInfo` - `RebateDistributionType` - `RebateDistribution` - `CodeOwnershipInfo` - `ReferralCodeStats` - `AffiliateTotalStats` - `TraderReferralTotalStats` - `TierInfo` - `ReferralsStats` - `TotalReferralsStats` ```typescript ``` --- ## sdk types This type-only entrypoint exports the v1 client config interface. ## Exports - `GmxSdkConfig` ```typescript ``` See [Getting Started](../../) for the currently documented `GmxSdkConfig` fields and initialization patterns. --- ## sidecarOrders types This type-only entrypoint exports sidecar stop-loss, take-profit, and limit-order entry types. ## Exports - `GroupPrefix` - `EntryField` - `InitialEntry` - `SidecarOrderEntryBase` - `SidecarSlTpOrderEntry` - `SidecarSlTpOrderEntryValid` - `SidecarLimitOrderEntry` - `SidecarLimitOrderEntryValid` - `SidecarOrderEntry` - `SidecarOrderEntryGroupBase` - `SidecarOrderEntryGroup` ```typescript ``` --- ## subsquid types This type-only entrypoint re-exports the generated GraphQL schema types from the SDK's Subsquid codegen. ## What it contains - GraphQL scalar helpers such as `Maybe`, `InputMaybe`, `Exact`, and `Scalars` - Generated entity types for the Subsquid schema - Generated connection, `WhereInput`, and `OrderByInput` types for paginated GraphQL queries ```typescript ``` This surface is generated and intentionally large. Use it when you need exact schema types for custom Subsquid queries. --- ## swap types This type-only entrypoint exports the swap-strategy model types used by the trade helpers. ## Exports - `NoSwapStrategy` - `ExternalSwapStrategy` - `InternalSwapStrategy` - `SwapStrategyForIncreaseOrders` - `SwapStrategyForSwapOrders` Both strategy unions contain only the no-swap, external-swap, and internal-swap variants. ```typescript ``` --- ## tokens types This type-only entrypoint exports token metadata, pricing, and balance model types. ## Exports - `ERC20Address` - `NativeTokenSupportedAddress` - `TokenAddressTypesMap` - `ContractPrice` - `TokenCategory` - `Token` - `TokenInfo` - `SignedTokenPermit` - `TokenPrices` - `TokenBalanceType` - `TokenAsyncData` - `TokenData` - `ProgressiveTokenData` - `TokensRatio` - `TokensRatioAndSlippage` - `InfoTokens` - `TokenBalancesData` - `TokenPricesData` - `TokensAllowanceData` - `TokensData` - `ProgressiveTokensData` ```typescript ``` --- ## trade types This type-only entrypoint exports the main trade calculation enums and result types. ## Exports - `TradeType` - `TradeMode` - `TriggerThresholdType` - `TradeFlags` - `SwapAmounts` - `IncreasePositionAmounts` - `DecreasePositionAmounts` - `DepositAmounts` - `WithdrawalAmounts` - `NextPositionValues` - `SwapStats` - `SwapPathStats` - `MarketEdge` - `SwapRoute` - `SwapPaths` - `SwapEstimator` - `NaiveSwapEstimator` - `NaiveNetworkEstimator` - `MarketEdgeLiquidityGetter` - `SwapOptimizationOrderArray` - `FindSwapPath` - `TradeFeesType` - `ExternalSwapAggregator` - `ExternalSwapQuote` - `ExternalSwapQuoteParams` - `ExternalSwapCalculationStrategy` - `ExternalSwapInputs` - `TradeFees` - `GmSwapFees` - `TradeSearchParams` ```typescript ``` --- ## tradeHistory types This type-only entrypoint exports the SDK's normalized trade-history action types. ## Exports - `TradeActionType` - `PositionTradeAction` - `SwapTradeAction` - `TradeAction` ```typescript ``` `SwapTradeAction` includes optional `swapFeeUsd?: bigint` and `swapImpactUsd?: bigint` fields for executed swap settlement details. --- ## twap types This type-only entrypoint exports TWAP timing and order-part parameter types. ## Exports - `TwapDuration` - `TwapOrderParams` - `TwapPartParams` ```typescript ``` --- ## LruCache This module exports a small in-memory least-recently-used cache. ## Exports - `LRUCache<T>` ```typescript const cache = new LRUCache<string>(100); ``` The class exposes `has`, `get`, `set`, `delete`, `getKeys`, and `clean`. --- ## abort This module exports abort-signal composition helpers. ## Exports - `combineAbortSignals(...signals)` ```typescript ``` --- ## bigmath This module provides mathematical utility functions for working with BigInt values, offering operations like absolute value, multiplication with division, min/max calculations, averaging, and various rounding strategies. ```typescript ``` ## Methods All methods are accessed through the `bigMath` object exported from `@gmx-io/sdk/utils/bigmath`. Import it once and call any method directly. ### abs ```typescript abs(x: bigint): bigint ``` Returns the absolute value of a `bigint`. ```typescript bigMath.abs(-100n); // 100n bigMath.abs(50n); // 50n ``` ### mulDiv ```typescript mulDiv(x: bigint, y: bigint, z: bigint, roundUpMagnitude?: boolean): bigint ``` Computes `(x * y) / z`. When `roundUpMagnitude` is `true` and
프로젝트로 돌아가기