GMX 백서

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

Info, isLong: boolean, periodInSeconds: bigint): bigint ``` Returns the funding factor (PRECISION-scaled) accumulated over `periodInSeconds`. Negative values mean the position pays funding; positive values mean it receives funding. The paying side is determined by `marketInfo.longsPayShorts`. The receiving side's factor is scaled by `payingInterest / receivingInterest` to maintain balance. ```typescript const factor = getFundingFactorPerPeriod(marketInfo, true, 3600n); // 1 hour in seconds (bigint) // Negative: longs are paying funding this hour ``` #### getFundingFeeRateUsd ```typescript getFundingFeeRateUsd(marketInfo: MarketInfo, isLong: boolean, sizeInUsd: bigint, periodInSeconds: bigint): bigint ``` Returns the funding fee in USD for a position of `sizeInUsd` over `periodInSeconds`. Applies `getFundingFactorPerPeriod` to the size. ```typescript const fundingFeeUsd = getFundingFeeRateUsd( marketInfo, true, 10000n * 10n ** 30n, // $10,000 position 86400n // 24 hours (bigint) ); ``` ### Borrow fee #### getBorrowingFactorPerPeriod ```typescript getBorrowingFactorPerPeriod(marketInfo: MarketInfo, isLong: boolean, periodInSeconds: bigint): bigint ``` Returns the borrow factor (PRECISION-scaled) accumulated over `periodInSeconds`. Uses `borrowingFactorPerSecondForLongs` or `borrowingFactorPerSecondForShorts` from `marketInfo`. ```typescript const borrowFactor = getBorrowingFactorPerPeriod(marketInfo, false, 3600n); // short, 1 hour ``` #### getBorrowingFeeRateUsd ```typescript getBorrowingFeeRateUsd(marketInfo: MarketInfo, isLong: boolean, sizeInUsd: bigint, periodInSeconds: bigint): bigint ``` Returns the borrow fee in USD for a position of `sizeInUsd` over `periodInSeconds`. ```typescript const borrowFeeUsd = getBorrowingFeeRateUsd( marketInfo, false, 10000n * 10n ** 30n, // $10,000 position 86400n // 24 hours ); ``` ### FeeItem helpers #### getIsHighPriceImpact ```typescript getIsHighPriceImpact(positionPriceImpact?: FeeItem, swapPriceImpact?: FeeItem): boolean ``` Returns `true` when the combined price impact is negative and its absolute basis-point value is at or above `HIGH_PRICE_IMPACT_BPS` (80 bps = 0.8%). ```typescript const isHigh = getIsHighPriceImpact(positionPriceImpactFeeItem, swapPriceImpactFeeItem); if (isHigh) { // warn the user before submitting } ``` #### getFeeItem ```typescript getFeeItem( feeDeltaUsd?: bigint, basis?: bigint, opts?: { shouldRoundUp?: boolean } ): FeeItem | undefined ``` Creates a `FeeItem` from a USD delta and a USD basis. Returns `undefined` when `feeDeltaUsd` is `undefined`. When `basis` is `undefined` or `0`, `bps` and `precisePercentage` are set to `0n`. ```typescript const feeItem = getFeeItem( -100n * 10n ** 30n, // -$100 impact 10000n * 10n ** 30n // $10,000 basis ); // feeItem.bps ≈ -100n (1%) // feeItem.precisePercentage is PRECISION-scaled ``` #### getTotalFeeItem ```typescript getTotalFeeItem(feeItems: (FeeItem | undefined)[]): FeeItem ``` Sums a list of `FeeItem` objects. `undefined` entries are ignored. Always returns a `FeeItem` (never `undefined`), with all fields starting at `0n`. ```typescript const total = getTotalFeeItem([positionFeeItem, swapFeeItem, undefined]); // total.deltaUsd = sum of all non-undefined deltaUsd values ``` #### getTotalSwapVolumeFromSwapStats ```typescript getTotalSwapVolumeFromSwapStats(swapSteps?: SwapStats[]): bigint ``` Returns the sum of `usdIn` across all swap steps. Returns `0n` when `swapSteps` is `undefined` or empty. ```typescript const totalVolume = getTotalSwapVolumeFromSwapStats(swapPath); // totalVolume: sum of usdIn for each hop in the swap path ``` --- ## getNaiveEstimatedGasBySwapCount This module provides a utility function for calculating estimated gas costs based on the number of swaps in a transaction. ## Methods This module exports a single function, available from `@gmx-io/sdk/utils/fees`. ### getNaiveEstimatedGasBySwapCount ```typescript getNaiveEstimatedGasBySwapCount( singleSwap: GasLimitsConfig["singleSwap"], swapsCount: number ): bigint ``` Returns `singleSwap × swapsCount`. Use this to estimate the swap portion of an order's gas limit when building a quick pre-check or a UI estimate. Pass `gasLimits.singleSwap` as the first argument. ```typescript // 2-hop swap path: USDC → WETH → WBTC const swapGas = getNaiveEstimatedGasBySwapCount(gasLimits.singleSwap, 2); // swapGas = gasLimits.singleSwap * 2n ``` --- ## priceImpact This module provides utilities for calculating price impact in GMX protocol operations, including position trades and swaps. It handles price impact calculations based on pool imbalances, virtual inventories, and various impact factors. ## Methods This module exports functions for computing price impact in position and swap operations. Price impact measures how a trade shifts pool balance — moves that improve balance receive positive impact (a rebate), while moves that worsen balance receive negative impact (a cost). All USD values use 30-decimal precision (`USD_DECIMALS = 30`), meaning `1_000000000000000000000000000000n` represents $1. :::note All functions in this module are exported from `@gmx-io/sdk/utils/fees`. Import them individually as shown in each example. ::: ### getPriceImpactByAcceptablePrice ```typescript getPriceImpactByAcceptablePrice(p: { sizeDeltaUsd: bigint; acceptablePrice: bigint; indexPrice: bigint; isLong: boolean; isIncrease: boolean; }): { priceImpactDeltaUsd: bigint; priceImpactDeltaAmount: bigint; priceDelta: bigint; acceptablePriceDeltaBps: bigint; } ``` Computes the price impact implied by the difference between your acceptable price and the current index price. Use this to show users the cost of their slippage tolerance before order submission. | Parameter | Type | Description | | ----------------- | --------- | ------------------------------------------------------------ | | `sizeDeltaUsd` | `bigint` | Trade size in USD (30-decimal precision) | | `acceptablePrice` | `bigint` | Worst price the user accepts (30-decimal precision) | | `indexPrice` | `bigint` | Current mark price of the index token (30-decimal precision) | | `isLong` | `boolean` | `true` for long positions | | `isIncrease` | `boolean` | `true` when opening or increasing a position | ```typescript // ETH long increase: $1 size, acceptable price $1.95, mark price $2.00 const priceImpact = getPriceImpactByAcceptablePrice({ sizeDeltaUsd: 1_000000000000000000000000000000n, // $1 acceptablePrice: 1_950000000000000000000000000000n, // $1.95 indexPrice: 2_000000000000000000000000000000n, // $2.00 isLong: true, isIncrease: true, }); console.log(priceImpact.priceImpactDeltaUsd); // negative — user pays for slippage console.log(priceImpact.acceptablePriceDeltaBps); // basis-point difference from mark price ``` ### applySwapImpactWithCap ```typescript applySwapImpactWithCap( marketInfo: MarketInfo, token: TokenData, priceImpactDeltaUsd: bigint ): { impactDeltaAmount: bigint; cappedDiffUsd: bigint } ``` Converts a USD price impact value to a token amount for swap operations, capping positive impact at the available swap impact pool balance. Positive impact is paid out from the pool; negative impact is collected from the user. :::warning Throws if `token` is not a collateral token of the given market. Always pass a token that belongs to the market's long or short pool. ::: | Parameter | Type | Description | | --------------------- | ------------ | ---------------------------------------------------------------------------------- | | `marketInfo` | `MarketInfo` | Market containing the swap impact pool | | `token` | `TokenData` | Collateral token being swapped in or out | | `priceImpactDeltaUsd` | `bigint` | Raw price impact in USD (30-decimal precision); positive = rebate, negative = cost | ```typescript // Apply $0.50 positive impact, capped by the pool's available balance const result = applySwapImpactWithCap( marketInfo, usdcTokenData, 500000000000000000000000000000n // $0.50 impact ); console.log(result.impactDeltaAmount); // token amount credited or debited console.log(result.cappedDiffUsd); // USD value lost to pool cap (if any) ``` ### getCappedPositionImpactUsd ```typescript getCappedPositionImpactUsd( marketInfo: MarketInfo, sizeDeltaUsd: bigint, isLong: boolean, isIncrease: boolean, opts?: { fallbackToZero?: boolean; shouldCapNegativeImpact?: boolean } ): { priceImpactDeltaUsd: bigint; balanceWasImproved: boolean } ``` Computes position price impact bounded by the market's maximum impact factor. This is the main function to use when you need to show a user their estimated price impact before placing a position order. | Parameter | Type | Description | | ------------------------------ | ------------ | ----------------------------------------------------------- | | `marketInfo` | `MarketInfo` | Target market | | `sizeDeltaUsd` | `bigint` | Absolute position size change in USD (30-decimal precision) | | `isLong` | `boolean` | `true` for long positions | | `isIncrease` | `boolean` | `true` when opening or increasing; `false` when decreasing | | `opts.fallbackToZero` | `boolean` | Return zero instead of throwing when pool goes negative | | `opts.shouldCapNegativeImpact` | `boolean` | Also cap negative impact by the max impact factor | ```typescript // Estimate impact for a $1 long increase const impact = getCappedPositionImpactUsd( marketInfo, 1_000000000000000000000000000000n, // $1 true, // long true, // increase { fallbackToZero: true } ); console.log(impact.priceImpactDeltaUsd); // negative = cost, positive = rebate console.log(impact.balanceWasImproved); // true when trade improves pool balance ``` ### capPositionImpactUsdByMaxImpactPool ```typescript capPositionImpactUsdByMaxImpactPool( marketInfo: MarketInfo, positionImpactDeltaUsd: bigint ): bigint ``` Caps a positive position impact at the value of tokens available in the position impact pool. Negative values pass through unchanged. Call this before distributing a positive impact rebate to ensure the pool can cover it. | Parameter | Type | Description | | ------------------------ | ------------ | ------------------------------------------------- | | `marketInfo` | `MarketInfo` | Market containing the position impact pool | | `positionImpactDeltaUsd` | `bigint` | Raw positive impact in USD (30-decimal precision) | ```typescript const cappedImpact = capPositionImpactUsdByMaxImpactPool( marketInfo, 750000000000000000000000000000n // $0.75 raw impact ); console.log(cappedImpact); // at most the pool's available USD value ``` ### capPositionImpactUsdByMaxPriceImpactFactor ```typescript capPositionImpactUsdByMaxPriceImpactFactor( marketInfo: MarketInfo, sizeDeltaUsd: bigint, positionImpactDeltaUsd: bigint ): bigint ``` Caps position impact (positive or negative) at the market's configured maximum impact factor multiplied by the trade size. The effective cap is `abs(sizeDeltaUsd) × maxImpactFactor`. | Parameter | Type | Description | | ------------------------ | ------------ | -------------------------------------------------- | | `marketInfo` | `MarketInfo` | Market with configured max impact factors | | `sizeDeltaUsd` | `bigint` | Trade size in USD (signed; negative for decreases) | | `positionImpactDeltaUsd` | `bigint` | Raw impact in USD to cap | ```typescript const cappedImpact = capPositionImpactUsdByMaxPriceImpactFactor( marketInfo, 1_000000000000000000000000000000n, // $1 trade size -500000000000000000000000000000n // $0.50 raw negative impact ); console.log(cappedImpact); // bounded by maxNegativeImpactFactor × $1 ``` ### getMaxPositionImpactFactors ```typescript getMaxPositionImpactFactors( marketInfo: MarketInfo ): { maxPositiveImpactFactor: bigint; maxNegativeImpactFactor: bigint } ``` Returns the maximum position impact factors for a market. The positive cap is set to `min(maxPositiveImpactFactorPositive, maxNegativeImpactFactor)` to prevent excessive rebates. | Parameter | Type | Description | | ------------ | ------------ | ---------------------------------- | | `marketInfo` | `MarketInfo` | Market to read impact factors from | ```typescript const { maxPositiveImpactFactor, maxNegativeImpactFactor } = getMaxPositionImpactFactors(marketInfo); // Factors are scaled to 30 decimals — divide by 1e30 to get the decimal fraction console.log(maxPositiveImpactFactor); // bigint, 30-decimal precision console.log(maxNegativeImpactFactor); ``` ### getPriceImpactForPosition ```typescript getPriceImpactForPosition( marketInfo: MarketInfo, sizeDeltaUsd: bigint, isLong: boolean, opts?: { fallbackToZero?: boolean } ): { priceImpactDeltaUsd: bigint; balanceWasImproved: boolean } ``` Computes the uncapped price impact for a position trade based on the change in open interest. When the market has a non-zero virtual inventory, the function uses the more conservative of the real and virtual impact values. This is a building block used by `getCappedPositionImpactUsd`. | Parameter | Type | Description | | --------------------- | ------------ | ------------------------------------------------------------------ | | `marketInfo` | `MarketInfo` | Market with open interest and virtual inventory data | | `sizeDeltaUsd` | `bigint` | Signed size delta in USD — positive for longs, negative for shorts | | `isLong` | `boolean` | `true` for long positions | | `opts.fallbackToZero` | `boolean` | Return zero instead of throwing when pool goes negative | ```typescript const impact = getPriceImpactForPosition( marketInfo, 1_000000000000000000000000000000n, // $1 long increase true, { fallbackToZero: true } ); console.log(impact.priceImpactDeltaUsd); // uncapped impact in USD console.log(impact.balanceWasImproved); ``` ### getProportionalPendingImpactValues ```typescript getProportionalPendingImpactValues(p: { sizeInUsd: bigint; pendingImpactAmount: bigint; sizeDeltaUsd: bigint; indexToken: TokenData; }): { proportionalPendingImpactDeltaAmount: bigint; proportionalPendingImpactDeltaUsd: bigint; } ``` Splits a pending price impact proportionally when partially closing a position. Use this when a user closes part of a position that has an accrued impact amount. | Parameter | Type | Description | | --------------------- | ----------- | ------------------------------------------------ | | `sizeInUsd` | `bigint` | Full position size in USD (30-decimal precision) | | `pendingImpactAmount` | `bigint` | Accrued pending impact in index tokens | | `sizeDeltaUsd` | `bigint` | Size being closed in USD | | `indexToken` | `TokenData` | Index token with price data for USD conversion | ```typescript // Close $1 of a $5 position with 0.1 ETH pending impact const impact = getProportionalPendingImpactValues({ sizeInUsd: 5_000000000000000000000000000000n, // $5 full position pendingImpactAmount: 100000000000000000n, // 0.1 ETH sizeDeltaUsd: 1_000000000000000000000000000000n, // $1 being closed indexToken: ethTokenData, }); console.log(impact.proportionalPendingImpactDeltaAmount); // token amount for this close console.log(impact.proportionalPendingImpactDeltaUsd); // USD value of that amount ``` ### getPriceImpactForSwap ```typescript getPriceImpactForSwap( marketInfo: MarketInfo, tokenA: TokenData, tokenB: TokenData, usdDeltaTokenA: bigint, usdDeltaTokenB: bigint, opts?: { fallbackToZero?: boolean } ): { priceImpactDeltaUsd: bigint; balanceWasImproved: boolean } ``` Computes the uncapped price impact for a swap between two tokens in the same market pool. When the market has non-zero virtual inventory, the function uses the more conservative of the real and virtual impact values. :::warning Throws if either token is not a collateral token of the given market, or if both tokens map to the same pool side on a non-same-collateral market. ::: | Parameter | Type | Description | | --------------------- | ------------ | ----------------------------------------------------------------------------- | | `marketInfo` | `MarketInfo` | Market containing both tokens | | `tokenA` | `TokenData` | First swap token | | `tokenB` | `TokenData` | Second swap token | | `usdDeltaTokenA` | `bigint` | USD added to the pool for token A (positive = deposit, negative = withdrawal) | | `usdDeltaTokenB` | `bigint` | USD added to the pool for token B | | `opts.fallbackToZero` | `boolean` | Return zero instead of throwing on pool underflow | ```typescript // Swap $1 USDC in, $1 WETH out const impact = getPriceImpactForSwap( marketInfo, usdcTokenData, wethTokenData, 1_000000000000000000000000000000n, // +$1 USDC into pool -1_000000000000000000000000000000n, // -$1 WETH from pool { fallbackToZero: true } ); console.log(impact.priceImpactDeltaUsd); // negative = user pays, positive = user receives console.log(impact.balanceWasImproved); ``` ### getNextPoolAmountsParams ```typescript getNextPoolAmountsParams(p: { longToken: TokenData; shortToken: TokenData; longPoolAmount: bigint; shortPoolAmount: bigint; longDeltaUsd: bigint; shortDeltaUsd: bigint; }): { longPoolUsd: bigint; shortPoolUsd: bigint; nextLongPoolUsd: bigint; nextShortPoolUsd: bigint; } ``` Converts current pool token amounts to USD and applies deltas to produce the next-state pool values. This is a helper used by `getPriceImpactForSwap` and `getPriceImpactUsd`. | Parameter | Type | Description | | ----------------- | ----------- | -------------------------------------------------- | | `longToken` | `TokenData` | Long-side collateral token with price data | | `shortToken` | `TokenData` | Short-side collateral token with price data | | `longPoolAmount` | `bigint` | Current long pool amount in token units | | `shortPoolAmount` | `bigint` | Current short pool amount in token units | | `longDeltaUsd` | `bigint` | USD change to the long pool (30-decimal precision) | | `shortDeltaUsd` | `bigint` | USD change to the short pool | ```typescript const poolParams = getNextPoolAmountsParams({ longToken: wethTokenData, shortToken: usdcTokenData, longPoolAmount: 1_000000000000000000n, // 1 WETH shortPoolAmount: 2_000000000000000000n, // 2 USDC (6-decimal token, adjust per token.decimals) longDeltaUsd: 500000000000000000000000000000n, // +$0.50 into long pool shortDeltaUsd: -250000000000000000000000000000n, // -$0.25 from short pool }); console.log(poolParams.longPoolUsd); // current long pool in USD console.log(poolParams.nextLongPoolUsd); // long pool after delta ``` ### getPriceImpactUsd ```typescript getPriceImpactUsd(p: { currentLongUsd: bigint; currentShortUsd: bigint; nextLongUsd: bigint; nextShortUsd: bigint; factorPositive: bigint; factorNegative: bigint; exponentFactorPositive: bigint; exponentFactorNegative: bigint; fallbackToZero?: boolean; }): { priceImpactDeltaUsd: bigint; balanceWasImproved: boolean } ``` Core price impact calculation. Compares the current and next pool state to determine whether the trade improves or worsens balance, then applies the appropriate factor and exponent. Uses separate exponent factors for positive and negative impact paths. See the [GMX synthetics SwapPricingUtils contract](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/pricing/SwapPricingUtils.sol) for the matching on-chain implementation. | Parameter | Type | Description | | ------------------------ | --------- | ------------------------------------------------------------- | | `currentLongUsd` | `bigint` | Current long-side USD value | | `currentShortUsd` | `bigint` | Current short-side USD value | | `nextLongUsd` | `bigint` | Post-trade long-side USD value | | `nextShortUsd` | `bigint` | Post-trade short-side USD value | | `factorPositive` | `bigint` | Impact factor when balance improves (30-decimal fraction) | | `factorNegative` | `bigint` | Impact factor when balance worsens | | `exponentFactorPositive` | `bigint` | Exponent applied to positive-impact calculations (30-decimal) | | `exponentFactorNegative` | `bigint` | Exponent appli
프로젝트로 돌아가기