GMX 백서

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

ed to negative-impact calculations | | `fallbackToZero` | `boolean` | Return zero instead of throwing when pool goes negative | ```typescript // Long pool increases from $10 to $11, short stays at $8 — worsens imbalance const impact = getPriceImpactUsd({ currentLongUsd: 10_000000000000000000000000000000n, // $10 currentShortUsd: 8_000000000000000000000000000000n, // $8 nextLongUsd: 11_000000000000000000000000000000n, // $11 nextShortUsd: 8_000000000000000000000000000000n, // $8 (unchanged) factorPositive: 5000000000000000000000000n, // 0.0005% factor factorNegative: 5000000000000000000000000n, // 0.0005% factor exponentFactorPositive: 2_000000000000000000000000000000n, // exponent 2.0 exponentFactorNegative: 2_000000000000000000000000000000n, // exponent 2.0 fallbackToZero: true, }); console.log(impact.priceImpactDeltaUsd); // negative — trade worsens pool balance console.log(impact.balanceWasImproved); // false ``` ### calculateImpactForSameSideRebalance ```typescript calculateImpactForSameSideRebalance(p: { currentDiff: bigint; nextDiff: bigint; hasPositiveImpact: boolean; factor: bigint; exponentFactor: bigint; }): bigint ``` Computes impact when a trade stays on the same side of the pool imbalance — that is, the larger pool stays larger after the trade. Returns positive or negative `bigint` depending on `hasPositiveImpact`. See the [GMX PricingUtils contract](https://github.com/gmx-io/gmx-synthetics/blob/5fd9991ff2c37ae5f24f03bc9c132730b012ebf2/contracts/pricing/PricingUtils.sol) for the matching on-chain implementation. | Parameter | Type | Description | | ------------------- | --------- | ------------------------------------------------------------------------- | | `currentDiff` | `bigint` | Absolute difference between current long and short pools (30-decimal USD) | | `nextDiff` | `bigint` | Absolute difference between next long and short pools | | `hasPositiveImpact` | `boolean` | `true` when the trade reduces the imbalance | | `factor` | `bigint` | Impact factor (30-decimal fraction) | | `exponentFactor` | `bigint` | Exponent (30-decimal) | ```typescript // Imbalance narrows from $2 to $1.50 — positive impact const impact = calculateImpactForSameSideRebalance({ currentDiff: 2_000000000000000000000000000000n, // $2 imbalance nextDiff: 1_500000000000000000000000000000n, // $1.50 imbalance hasPositiveImpact: true, factor: 5000000000000000000000000n, // 0.0005% exponentFactor: 2_000000000000000000000000000000n, // 2.0 }); console.log(impact); // positive bigint rebate in USD (30-decimal) ``` ### calculateImpactForCrossoverRebalance ```typescript calculateImpactForCrossoverRebalance(p: { currentDiff: bigint; nextDiff: bigint; factorPositive: bigint; factorNegative: bigint; exponentFactorPositive: bigint; exponentFactorNegative: bigint; }): bigint ``` Computes impact when a trade crosses over the pool balance point — the previously larger side becomes the smaller side. This is a split calculation: the portion that moves the pool toward balance uses `factorPositive`; the portion past the balance point uses `factorNegative`. See the [GMX PricingUtils contract](https://github.com/gmx-io/gmx-synthetics/blob/5fd9991ff2c37ae5f24f03bc9c132730b012ebf2/contracts/pricing/PricingUtils.sol) for the matching on-chain implementation. | Parameter | Type | Description | | ------------------------ | -------- | ------------------------------------------------------------- | | `currentDiff` | `bigint` | Absolute imbalance before the trade (30-decimal USD) | | `nextDiff` | `bigint` | Absolute imbalance after the trade (now on the opposite side) | | `factorPositive` | `bigint` | Factor applied to the balance-improving portion | | `factorNegative` | `bigint` | Factor applied to the balance-worsening portion | | `exponentFactorPositive` | `bigint` | Exponent for the positive portion (30-decimal) | | `exponentFactorNegative` | `bigint` | Exponent for the negative portion | ```typescript // Imbalance of $1 crosses zero to -$0.50 on the other side const impact = calculateImpactForCrossoverRebalance({ currentDiff: 1_000000000000000000000000000000n, // $1 imbalance nextDiff: 500000000000000000000000000000n, // $0.50 imbalance, opposite side factorPositive: 5000000000000000000000000n, // 0.0005% factorNegative: 5000000000000000000000000n, // 0.0005% exponentFactorPositive: 2_000000000000000000000000000000n, // 2.0 exponentFactorNegative: 2_000000000000000000000000000000n, // 2.0 }); console.log(impact); // net impact bigint in USD (30-decimal), may be positive or negative ``` ### applyImpactFactor ```typescript applyImpactFactor(diff: bigint, factor: bigint, exponent: bigint): bigint ``` Low-level helper that raises `diff` to the power of `exponent` and multiplies by `factor`. Both `diff` and `exponent` are converted to floating-point for the exponentiation, then the result is converted back to a 30-decimal `bigint`. Returns `0n` if the intermediate value is not finite. | Parameter | Type | Description | | ---------- | -------- | ------------------------------------- | | `diff` | `bigint` | Pool imbalance value (30-decimal USD) | | `factor` | `bigint` | Impact factor (30-decimal fraction) | | `exponent` | `bigint` | Exponent (30-decimal) | ```typescript const result = applyImpactFactor( 1_000000000000000000000000000000n, // $1 imbalance 5000000000000000000000000n, // 0.0005% factor 2_000000000000000000000000000000n // exponent 2.0 ); console.log(result); // bigint result (30-decimal) ``` ### getCappedPriceImpactPercentageFromFees ```typescript getCappedPriceImpactPercentageFromFees(p: { fees: TradeFees | undefined; isSwap: boolean; }): bigint | undefined ``` Extracts the capped price impact percentage from an already-computed `TradeFees` object. Returns `swapPriceImpact.precisePercentage` for swaps or `positionNetPriceImpact.precisePercentage` for position trades. Returns `0n` when the relevant fee item is absent. | Parameter | Type | Description | | --------- | ------------------------ | ----------------------------------------------------------- | | `fees` | `TradeFees \| undefined` | Pre-computed trade fees object | | `isSwap` | `boolean` | `true` to read swap impact; `false` to read position impact | ```typescript // Read position price impact percentage from an existing TradeFees object const impactPercentage = getCappedPriceImpactPercentageFromFees({ fees: tradeFees, isSwap: false, }); // impactPercentage is a 30-decimal fraction — divide by 1e28 for a basis-point value console.log(impactPercentage); ``` ### getMaxNegativeImpactBps ```typescript getMaxNegativeImpactBps(marketInfo: MarketInfo): bigint ``` Converts a market's `maxPositionImpactFactorNegative` from a 30-decimal factor to basis points. Use this to display the maximum adverse price impact a user can experience in a given market. | Parameter | Type | Description | | ------------ | ------------ | ---------------------------------------------- | | `marketInfo` | `MarketInfo` | Market to read the negative impact factor from | ```typescript const maxNegImpactBps = getMaxNegativeImpactBps(marketInfo); // For example, 50n means 0.50% max negative price impact ``` --- ## graphqlFetcher This module exports the SDK's default GraphQL POST fetch helper. ## Exports - default export `graphqlFetcher<T>(endpoint, query, variables?)` ```typescript ``` It posts `{ query, variables }` to the target endpoint and returns the `data` field from the GraphQL response. --- ## hash This module exports low-level hashing helpers used for SDK key generation. ## Exports - `ZERO_DATA` - `hashData` - `hashString` - `hashDataMap` - `keccakString` ```typescript ``` --- ## indexers This module exports helper types and functions for building GraphQL filter bodies and paginating indexer reads. ## Exports - `GraphQlFilters` - `buildFiltersBody` - `queryPaginated` ```typescript ``` --- ## markets(Utils) This module provides utilities for working with GMX markets, including market naming, pricing, liquidity calculations, and PnL computations. It handles market metadata, pool calculations, leverage limits, and various market-related operations. ## Methods The `markets` utility module exports functions organized into six categories: display names, prices and PnL, liquidity and open interest, market classification, leverage, and data assembly. ### Market display names #### getMarketFullName `getMarketFullName(p: { longToken: Token; shortToken: Token; indexToken: Token; isSpotOnly: boolean }): string` Returns the full display name of a market combining the index name and pool name. ```typescript const fullName = getMarketFullName({ longToken: ethToken, shortToken: usdcToken, indexToken: ethToken, isSpotOnly: false, }); // "ETH/USD [ETH-USDC]" ``` #### getMarketIndexName `getMarketIndexName(p: ({ indexToken: Token } | { glvToken: Token }) & { isSpotOnly: boolean }): string` Returns the index name portion of a market name (for example, `"ETH/USD"` or `"SWAP-ONLY"`). #### getMarketBaseName `getMarketBaseName(p: ({ indexToken: Token } | { glvToken: Token }) & { isSpotOnly: boolean }): string` Returns the base token name from a market (for example, `"ETH"`). #### getMarketPoolName `getMarketPoolName(p: { longToken: Token; shortToken: Token }, separator?: string): string` Returns the pool name combining long and short token symbols. Default separator is `"-"`. ```typescript getMarketPoolName({ longToken: ethToken, shortToken: usdcToken }); // "ETH-USDC" getMarketPoolName({ longToken: ethToken, shortToken: usdcToken }, "/"); // "ETH/USDC" ``` #### getMarketAddressByName `getMarketAddressByName(marketsInfoData: MarketsInfoData, name: string): string | undefined` Looks up a market token address by its full name string (for example, `"ETH/USD [WETH-USDC]"`). Returns `undefined` if not found. ### Prices and PnL #### getContractMarketPrices `getContractMarketPrices(tokensData: TokensData, market: Market): ContractMarketPrices | undefined` Returns contract-formatted prices for market tokens, or `undefined` if token price data is missing. ```typescript const contractPrices = getContractMarketPrices(tokensData, market); if (contractPrices) { console.log(contractPrices.indexTokenPrice); } ``` #### getPriceForPnl `getPriceForPnl(prices: TokenPrices, isLong: boolean, maximize: boolean): bigint` Returns the appropriate price (min or max) for PnL calculations based on position direction. #### getMarketPnl `getMarketPnl(marketInfo: MarketInfo, isLong: boolean, forMaxPoolValue: boolean): bigint` Returns the aggregate PnL for the long or short side of a market. #### getPositiveMarketPnl `getPositiveMarketPnl(marketInfo: MarketInfo, isLong: boolean, forMaxPoolValue: boolean): bigint` Returns the sum of positive PnL calculated separately for positions using the long and short collateral tokens. Losses in one collateral bucket don't offset profits in the other. If the collateral-split fields are unavailable, the helper falls back to `getMarketPnl()`. #### getMarket24Stats `getMarket24Stats(dayPriceCandle: DayPriceCandle): { open24h, high24h, low24h, close24h, priceChange24h, priceChangePercent24hBps }` Computes 24-hour OHLC stats and price change in basis points from a day price candle. #### getMarketTicker `getMarketTicker(marketInfo: MarketInfo, dayPriceCandle: DayPriceCandle): MarketTicker` Returns a comprehensive market ticker including prices, open interest, liquidity, funding rates, and borrowing rates. ### Liquidity and open interest #### getPoolUsdWithoutPnl `getPoolUsdWithoutPnl(marketInfo: MarketInfo, isLong: boolean, priceType: "minPrice" | "maxPrice" | "midPrice"): bigint` Returns the USD value of the long or short pool excluding PnL. #### getCappedPoolPnl `getCappedPoolPnl(p: { marketInfo: MarketInfo; poolUsd: bigint; poolPnl: bigint; isLong: boolean }): bigint` Returns the pool PnL capped at the market's maximum allowed PnL ratio. #### getAvailableUsdLiquidityForCollateral `getAvailableUsdLiquidityForCollateral(marketInfo: MarketInfo, isLong: boolean): bigint` Returns available USD liquidity for collateral on the specified side. #### getReservedUsd `getReservedUsd(marketInfo: MarketInfo, isLong: boolean): bigint` Returns the reserved USD amount for the long or short side. #### getOpenInterestUsd `getOpenInterestUsd(marketInfo: MarketInfo, isLong: boolean): bigint` Returns the open interest in USD for the long or short side. #### getOpenInterestInTokens `getOpenInterestInTokens(marketInfo: MarketInfo, isLong: boolean): bigint` Returns the open interest in tokens for the long or short side. #### getOpenInterestForBalance `getOpenInterestForBalance(marketInfo: MarketInfo, isLong: boolean): bigint` Returns the open interest used for balance calculations. Uses token-denominated interest converted to USD when `useOpenInterestInTokensForBalance` is set. #### getOiUsdFromRawValues `getOiUsdFromRawValues(rawValues: { longInterestUsingLongToken, longInterestUsingShortToken, shortInterestUsingLongToken, shortInterestUsingShortToken }, marketDivisor: bigint): { longInterestUsd, shortInterestUsd }` Computes aggregate long/short USD open interest from raw on-chain split values, applying the market divisor. #### getOiInTokensFromRawValues `getOiInTokensFromRawValues(rawValues: {...}, marketDivisor: bigint): { longInterestInTokens, shortInterestInTokens }` Computes aggregate long/short token open interest from raw on-chain split values. ### Market classification and config #### getTokenPoolType `getTokenPoolType(marketInfo: { longToken: Token; shortToken: Token }, tokenAddress: string): "long" | "short" | undefined` Returns whether a token belongs to the `"long"` or `"short"` pool in a market. #### getMarketDivisor `getMarketDivisor({ longTokenAddress, shortTokenAddress }): bigint` Returns `2n` for single-collateral markets (same long/short token) and `1n` for two-token markets. #### getOppositeCollateral `getOppositeCollateral(marketInfo: MarketInfo, tokenAddress: string): Token | undefined` Returns the opposite collateral token for a given token in a market. #### getOppositeCollateralFromConfig `getOppositeCollateralFromConfig(marketConfig: ConfigMarketConfig, tokenAddress: string): string` Like `getOppositeCollateral` but works on the config object (addresses only, no hydrated token data). #### getIsMarketAvailableForExpressSwaps `getIsMarketAvailableForExpressSwaps(marketInfo: MarketInfo): boolean` Returns `true` if all three market tokens (index, long, short) have a price feed provider, enabling express swaps. ### Leverage #### getMaxLeverageByMinCollateralFactor `getMaxLeverageByMinCollateralFactor(minCollateralFactor: bigint | undefined): number` Returns the theoretical maximum leverage (as a basis-point integer) from the minimum collateral factor. #### getMaxAllowedLeverage ```typescript getMaxAllowedLeverage(params: { minCollateralFactor: bigint | undefined; minCollateralFactorForLiquidation: bigint | undefined; positionFeeFactorForBalanceWasNotImproved: bigint | undefined; }): number ``` Returns the maximum allowed leverage as a basis-point integer. The helper uses the market's opening collateral factor, liquidation collateral factor, and position fee factor, then rounds down to the nearest `5x` leverage step. If any required value is missing or zero, the helper returns `100x` (`100 * BASIS_POINTS_DIVISOR`) as the fallback cap. #### getMarketWithTiers `getMarketWithTiers(marketInfo: MarketInfo, constants: { minCollateralUsd, minPositionSizeUsd }): MarketWithTiers` Returns a `MarketWithTiers` object including leverage tiers and size limits, used for market listing displays. ### Market data assembly These functions assemble market data from raw on-chain responses. Typically used internally by the SDK client rather than called directly. #### composeRawMarketInfo `composeRawMarketInfo({ market, marketValues, marketConfig, marketsConstants }): RawMarketInfo` Merges on-chain market values, config, and constants into a `RawMarketInfo` record. #### composeRawMarketsInfoData `composeRawMarketsInfoData({ marketsAddresses, marketValues, marketConfigs, marketsConstants }): RawMarketsInfoData` Composes a full `RawMarketsInfoData` map for multiple markets. #### hydrateMarketInfo `hydrateMarketInfo({ chainId, rawMarketInfo, tokensData, claimableFundingData? }): MarketInfo | undefined` Hydrates a `RawMarketInfo` into a full `MarketInfo` by resolving token addresses to `Token` objects. Returns `undefined` if any token is missing from `tokensData`. #### composeFullMarketsInfoData `composeFullMarketsInfoData({ chainId, marketsAddresses, rawMarketsInfoData, tokensData, claimableFundingData? }): MarketsInfoData` Hydrates a full `RawMarketsInfoData` map into `MarketsInfoData`. ### API data fetching #### fetchApiMarketsTickers `fetchApiMarketsTickers(ctx: { api: IHttp }, params?: { addresses?: string[]; symbols?: string[] }): Promise<MarketTickerWithCapacity[]>` Fetches filterable market tickers. Each row may include parsed `capacityLong` and `capacityShort` values. #### parseTradingCapacity `parseTradingCapacity(raw: unknown): TradingCapacity | undefined` Parses and validates a trading-capacity response. Numeric capacity fields are returned as `bigint`; invalid shapes return `undefined`. #### fetchApiTradingCapacity `fetchApiTradingCapacity(ctx: { api: IHttp }, params: GetTradingCapacityParams): Promise<TradingCapacity>` Fetches validated capacity for `params.symbol` and `params.direction` from `/v1/markets/trading-capacity`. It throws if the response doesn't match `TradingCapacity`. #### fetchApiMarketsInfo `fetchApiMarketsInfo(ctx: { api: IHttp }): Promise<RawMarketInfo[]>` Fetches raw market info records from the GMX API. #### fetchApiTokensData `fetchApiTokensData(ctx: { api: IHttp }): Promise<TokenData[]>` Fetches token data from the GMX API. ### Multicall helpers These functions build and parse multicall requests for on-chain market data. They are used internally by the SDK. #### buildClaimableFundingDataRequest Builds a multicall request for claimable funding data for a given account and set of markets. #### buildMarketsValuesRequest Builds a multicall request for market values (pool amounts, open interest, PnL, and borrowing fees) for a set of markets. #### parseMarketsValuesResponse Parses the multicall response from `buildMarketsValuesRequest` into `MarketsValuesData`. #### buildMarketsConfigsRequest Builds a multicall request for market configurations (fees, impact factors, and borrowing rate parameters) for a set of markets. #### parseMarketsConfigsResponse Parses the multicall response from `buildMarketsConfigsRequest` into `MarketsConfigsData`. ### Hash key helpers (from `hashKeys.ts`) Used internally for building multicall key hashes. #### hashMarketConfigKeys `hashMarketConfigKeys(market: MarketConfigInput): MarketConfigKeysHash` #### hashMarketValuesKeys `hashMarketValuesKeys(market: MarketConfigInput): MarketValuesKeysHash` #### hashKinkModelKeys `hashKinkModelKeys(marketAddress: string): KinkModelKeysHash` --- ## numbers This module provides comprehensive utilities for handling numeric operations, formatting, and conversions in the GMX protocol. It includes functions for working with BigInt values, formatting currencies and percentages, handling decimal precision, and converting between different numeric representations. ## Types The `numbers` module exports union types used throughout the SDK for accepting flexible numeric input. | Type | Definition | Description | | -------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `Numeric` | `number \| bigint` | A value that is either a JavaScript `number` or a `bigint`. | | `BigNumber
프로젝트로 돌아가기