GMX 백서

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

nt. Determines how much input is required to receive `amountOut`. Returns the same `SwapAmounts` structure as `getSwapAmountsByFromValue`. ```typescript const swapAmounts = getSwapAmountsByToValue({ tokenIn: wethToken, tokenOut: usdcToken, amountOut: 2000n * 10n ** 6n, // 2000 USDC isLimit: false, uiFeeFactor: 0n, marketsInfoData, chainId: 42161, externalSwapQuoteParams: undefined, findSwapPath: myFindSwapPath, allowSameTokenSwap: false, }); console.log(swapAmounts.amountIn); // Required WETH input ``` ### getSwapPathComparator ```typescript getSwapPathComparator(order?: SwapOptimizationOrderArray): (a: SwapRoute, b: SwapRoute) => number ``` Returns a comparator function for sorting `SwapRoute` objects. The sort criteria are applied in order: - `"liquidity"` — sort by `route.liquidity` descending (higher is better) - `"length"` — sort by `route.path.length` ascending (shorter is better) When `order` is `undefined` or empty, the comparator returns `0` for all pairs (stable, no-op sort). ```typescript const comparator = getSwapPathComparator(["liquidity", "length"]); const sorted = swapRoutes.sort(comparator); // sorted[0] — highest liquidity; ties broken by shortest path ``` --- ## time This module exports simple period-conversion helpers. ## Exports - `secondsFrom` - `secondsToPeriod` - `periodToSeconds` - `nowInSeconds` ```typescript ``` --- ## tokens(Utils) This module provides utilities for token price conversions, amount calculations, and token relationship operations in the GMX protocol. It handles conversions between USD values and token amounts, price formatting for contracts, and various token comparison utilities. ## Methods The `tokens` utility module exports functions for price format conversions, token amount calculations, token data lookups, relationship checks, and ratio utilities. ### Price conversions #### parseContractPrice ```typescript parseContractPrice(price: bigint, tokenDecimals: number): bigint ``` Converts a contract-format price (`price × 10^tokenDecimals`) to a 30-decimal SDK price (`price × 10^30`). Internally: `price × expandDecimals(1, tokenDecimals)`. ```typescript const sdkPrice = parseContractPrice(contractPrice, 18); ``` #### convertToContractPrice ```typescript convertToContractPrice(price: bigint, tokenDecimals: number): ContractPrice ``` Converts a 30-decimal SDK price to contract format by dividing by `10^tokenDecimals`. Order builders use this conversion for position order price fields such as `triggerPrice` and `acceptablePrice` before creating contract calldata. For example, a DOGE `$0.04` trigger price is `40000000000000000000000000000n` in SDK price format. Since DOGE has 8 decimals, the contract-format value is `400000000000000000000n`. ```typescript const contractPrice = convertToContractPrice(1800n * 10n ** 30n, 18); ``` #### convertToContractTokenPrices ```typescript convertToContractTokenPrices(prices: TokenPrices, tokenDecimals: number): { min: ContractPrice; max: ContractPrice } ``` Converts both `minPrice` and `maxPrice` from 30-decimal SDK format to contract format. ```typescript const contractPrices = convertToContractTokenPrices({ minPrice: 1800n * 10n ** 30n, maxPrice: 1802n * 10n ** 30n }, 18); ``` #### getMidPrice ```typescript getMidPrice(prices: TokenPrices): bigint ``` Returns `(minPrice + maxPrice) / 2`. ```typescript const midPrice = getMidPrice({ minPrice: 1800n * 10n ** 30n, maxPrice: 1802n * 10n ** 30n }); ``` ### Token amount conversions #### convertToTokenAmount ```typescript convertToTokenAmount( usd: bigint | undefined, tokenDecimals: number | undefined, price: bigint | undefined ): bigint | undefined ``` Converts a USD value (30-decimal) to a token amount. Returns `undefined` when any argument is `undefined` or `price <= 0`. ```typescript const wethAmount = convertToTokenAmount( 1000n * 10n ** 30n, // $1000 USD 18, // WETH decimals 1800n * 10n ** 30n // WETH price ); // ≈ 0.556 WETH in 18-decimal units ``` #### convertToUsd ```typescript convertToUsd( tokenAmount: bigint | undefined, tokenDecimals: number | undefined, price: bigint | undefined ): bigint | undefined ``` Converts a token amount to USD (30-decimal). Returns `undefined` when any argument is `undefined`. ```typescript const usdValue = convertToUsd( 5n * 10n ** 17n, // 0.5 WETH 18, 1800n * 10n ** 30n // WETH price ); // $900 as 30-decimal bigint ``` #### convertBetweenTokens ```typescript convertBetweenTokens( tokenAmount: bigint | undefined, fromToken: TokenData | undefined, toToken: TokenData | undefined, maximize: boolean ): bigint | undefined ``` Converts `tokenAmount` of `fromToken` to an equivalent amount of `toToken`. Returns `tokenAmount` directly when the two tokens are equivalent. When `maximize` is `true`, uses `fromToken.prices.maxPrice` and `toToken.prices.minPrice` (maximizes value received). When `false`, uses `fromToken.prices.minPrice` and `toToken.prices.maxPrice` (minimizes value received, conservative estimate). ```typescript // Estimate how much USDC you get for 1 WETH (maximize=false → conservative) const usdcAmount = convertBetweenTokens(1n * 10n ** 18n, wethTokenData, usdcTokenData, false); ``` ### Token data lookups #### getTokenData ```typescript getTokenData( tokensData?: TokensData, address?: string, convertTo?: "wrapped" | "native" ): TokenData | undefined ``` Looks up a token by address in `tokensData`. When `convertTo` is provided, follows the token's `wrappedAddress` or `nativeTokenAddress` pointer before returning. ```typescript const wethData = getTokenData(tokensData, nativeEthAddress, "wrapped"); const nativeData = getTokenData(tokensData, wethAddress, "native"); ``` #### getGmToken ```typescript getGmToken(chainId: ContractsChainId, marketTokenAddress: string): Token ``` Returns a `Token` for a GM pool token by cloning the GM stub token and replacing its address with `marketTokenAddress`. ```typescript const gmToken = getGmToken(42161, marketTokenAddress); ``` #### getGlvToken ```typescript getGlvToken(chainId: ContractsChainId, glvTokenAddress: string): Token ``` Returns a `Token` for a GLV vault token by cloning the GLV stub token and replacing its address with `glvTokenAddress`. ```typescript const glvToken = getGlvToken(42161, glvTokenAddress); ``` ### Token relationship checks #### getIsEquivalentTokens ```typescript getIsEquivalentTokens(token1: Token, token2: Token): boolean ``` Returns `true` when the tokens are interchangeable: same address, a native/wrapped pair, or two synthetic tokens with the same symbol. ```typescript getIsEquivalentTokens(nativeEthToken, wethToken); // true ``` #### getIsWrap / getIsUnwrap / getIsStake / getIsUnstake ```typescript getIsWrap(token1: Token, token2: Token): boolean getIsUnwrap(token1: Token, token2: Token): boolean getIsStake(token1: Token, token2: Token): boolean getIsUnstake(token1: Token, token2: Token): boolean ``` Classify a token-pair operation as wrap (native → wrapped), unwrap (wrapped → native), stake (native or wrapped → staking token), or unstake (staking token → wrapped). Used by swap routing to short-circuit path selection for these special cases. ```typescript getIsWrap(nativeEthToken, wethToken); // true getIsUnwrap(wethToken, nativeEthToken); // true ``` ### Ratio utilities #### getTokensRatioByPrice ```typescript getTokensRatioByPrice(p: { fromToken: Token; toToken: Token; fromPrice: bigint; toPrice: bigint; }): TokensRatio ``` Computes a `TokensRatio` (exchange rate and which token is "largest") from two prices. ```typescript const ratio = getTokensRatioByPrice({ fromToken: wethToken, toToken: usdcToken, fromPrice: 1800n * 10n ** 30n, toPrice: 1n * 10n ** 30n, }); ``` #### getTokensRatioByAmounts ```typescript getTokensRatioByAmounts(p: { fromToken: Token; toToken: Token; fromTokenAmount: bigint; toTokenAmount: bigint; }): TokensRatio ``` Computes a `TokensRatio` from two token amounts. ```typescript const ratio = getTokensRatioByAmounts({ fromToken: wethToken, toToken: usdcToken, fromTokenAmount: 1n * 10n ** 18n, toTokenAmount: 1800n * 10n ** 6n, }); ``` #### getTokensRatioByMinOutputAmountAndTriggerPrice ```typescript getTokensRatioByMinOutputAmountAndTriggerPrice(p: { fromToken: Token; toToken: Token; fromTokenAmount: bigint; toTokenAmount: bigint; triggerPrice: bigint; minOutputAmount: bigint; }): TokensRatioAndSlippage ``` Extends `getTokensRatioByAmounts` to also compute the allowed slippage in basis points based on the trigger price and minimum output amount. ```typescript const ratioAndSlippage = getTokensRatioByMinOutputAmountAndTriggerPrice({ fromToken: wethToken, toToken: usdcToken, fromTokenAmount: 1n * 10n ** 18n, toTokenAmount: 1800n * 10n ** 6n, triggerPrice: 1800n * 10n ** 30n, minOutputAmount: 1790n * 10n ** 6n, // 1790 USDC minimum }); ``` #### getAmountByRatio ```typescript getAmountByRatio(p: { fromToken: Token; toToken: Token; fromTokenAmount: bigint; ratio: bigint; shouldInvertRatio?: boolean; allowedSwapSlippageBps?: bigint; }): bigint ``` Converts `fromTokenAmount` to a target-token amount using a pre-computed `TokensRatio.ratio`. Pass `allowedSwapSlippageBps` to reduce the output by a slippage tolerance. ```typescript const usdcOut = getAmountByRatio({ fromToken: wethToken, toToken: usdcToken, fromTokenAmount: 1n * 10n ** 18n, ratio: triggerRatio.ratio, shouldInvertRatio: triggerRatio.largestToken.address === usdcToken.address, allowedSwapSlippageBps: 50n, // 0.5% slippage }); ``` --- ## decrease This module provides utilities for calculating decrease position amounts, fees, and next position values when closing or reducing trading positions. It handles complex calculations including PnL realization, fee deductions, collateral adjustments, and swap requirements. ## Methods The decrease trade module exports functions for computing position close amounts, determining full-close conditions, calculating collateral costs, and projecting the next position state. Import any function directly from `@gmx-io/sdk/utils/trade`. ### getDecreasePositionAmounts ```typescript getDecreasePositionAmounts(p: { marketInfo: MarketInfo; collateralToken: TokenData; isLong: boolean; position: PositionInfoLoaded | undefined; closeSizeUsd: bigint; keepLeverage: boolean; triggerPrice?: bigint; fixedAcceptablePriceImpactBps?: bigint; acceptablePriceImpactBuffer?: number; userReferralInfo: UserReferralInfo | undefined; minCollateralUsd: bigint; minPositionSizeUsd: bigint; uiFeeFactor: bigint; isLimit?: boolean; limitPrice?: bigint; triggerOrderType?: DecreasePositionAmounts["triggerOrderType"]; isSetAcceptablePriceImpactEnabled: boolean; receiveToken?: TokenData; }): DecreasePositionAmounts ``` Computes a complete `DecreasePositionAmounts` result for a Market Decrease, Limit Decrease, Stop-Loss, or Take-Profit order. The result includes all pricing, fee, PnL, collateral, and receive-amount fields needed to build the on-chain order. When `position` is `undefined` or has zero size, only the fee and price fields are computed; amounts relating to PnL and collateral are left at zero. When `receiveToken` is omitted, it defaults to `collateralToken`. ```typescript const decreaseAmounts = getDecreasePositionAmounts({ marketInfo, collateralToken: usdcToken, isLong: true, position: currentPosition, closeSizeUsd: 1000n * 10n ** 30n, // close $1000 of position keepLeverage: false, userReferralInfo: undefined, minCollateralUsd: 5000n * 10n ** 30n, minPositionSizeUsd: 1000n * 10n ** 30n, uiFeeFactor: 0n, isSetAcceptablePriceImpactEnabled: true, }); console.log("Receive token amount:", decreaseAmounts.receiveTokenAmount); console.log("Receive USD:", decreaseAmounts.receiveUsd); console.log("Realized PnL:", decreaseAmounts.realizedPnl); console.log("Position fee:", decreaseAmounts.positionFeeUsd); console.log("Acceptable price:", decreaseAmounts.acceptablePrice); ``` ### getIsFullClose ```typescript getIsFullClose(p: { position: PositionInfoLoaded; sizeDeltaUsd: bigint; indexPrice: bigint; remainingCollateralUsd: bigint; minCollateralUsd: bigint; minPositionSizeUsd: bigint; }): boolean ``` Returns `true` when the decrease must be treated as a full close. This happens when: - The remaining position size would be `< $1` after the decrease, or - A loss would leave the remaining collateral below the minimum factor threshold, and the remaining collateral + PnL is below `minCollateralUsd` or the remaining size is below `minPositionSizeUsd`. ```typescript const isFullClose = getIsFullClose({ position: currentPosition, sizeDeltaUsd: 500n * 10n ** 30n, indexPrice: currentPosition.markPrice, remainingCollateralUsd: 100n * 10n ** 30n, minCollateralUsd: 5000n * 10n ** 30n, minPositionSizeUsd: 1000n * 10n ** 30n, }); ``` ### getMinCollateralUsdForLeverage ```typescript getMinCollateralUsdForLeverage(position: PositionInfoLoaded, openInterestDelta: bigint): bigint ``` Returns the minimum collateral required to keep the current position's leverage within the market's allowed range, given an open interest change. ```typescript const minCollateral = getMinCollateralUsdForLeverage( currentPosition, -1000n * 10n ** 30n // OI decreasing by $1000 ); ``` ### payForCollateralCost ```typescript payForCollateralCost(p: { initialCostUsd: bigint; collateralToken: TokenData; collateralPrice: bigint; outputAmount: bigint; remainingCollateralAmount: bigint; }): { outputAmount: bigint; remainingCollateralAmount: bigint; paidOutputAmount: bigint; paidRemainingCollateralAmount: bigint; } ``` Deducts `initialCostUsd` from `outputAmount` first, then from `remainingCollateralAmount`. Returns the updated balances and the amounts paid from each source. ```typescript const result = payForCollateralCost({ initialCostUsd: 100n * 10n ** 30n, collateralToken: usdcToken, collateralPrice: 1n * 10n ** 30n, // $1 per USDC outputAmount: 50_000_000n, // 50 USDC (6 decimals) remainingCollateralAmount: 1_000_000_000n, }); // result.paidOutputAmount — deducted from output // result.paidRemainingCollateralAmount — deducted from remaining collateral ``` ### estimateCollateralCost ```typescript estimateCollateralCost(baseUsd: bigint, collateralToken: TokenData, collateralPrice: bigint): { amount: bigint; usd: bigint; } ``` Converts `baseUsd` to the collateral token's amount using `collateralToken.prices.minPrice`, then converts back to USD using `collateralPrice`. Used to estimate costs denominated in the collateral token. ```typescript const { amount, usd } = estimateCollateralCost( 50n * 10n ** 30n, // $50 usdcToken, 1n * 10n ** 30n // $1 per USDC ); // amount: token units of the cost // usd: cost in USD at collateralPrice ``` ### getTotalFeesUsdForDecrease ```typescript getTotalFeesUsdForDecrease(p: { positionFeeUsd: bigint; borrowingFeeUsd: bigint; fundingFeeUsd: bigint; swapProfitFeeUsd: bigint; swapUiFeeUsd: bigint; uiFeeUsd: bigint; pnlUsd: bigint; totalPendingImpactDeltaUsd: bigint; }): bigint ``` Returns the total cost that must be covered by the position's output. Only negative contributions are counted: a negative `pnlUsd` (loss) and a negative `totalPendingImpactDeltaUsd` (adverse price impact) are added as absolute values. ```typescript const totalCost = getTotalFeesUsdForDecrease({ positionFeeUsd: 10n * 10n ** 30n, borrowingFeeUsd: 5n * 10n ** 30n, fundingFeeUsd: 2n * 10n ** 30n, swapProfitFeeUsd: 1n * 10n ** 30n, swapUiFeeUsd: 0n, uiFeeUsd: 0n, pnlUsd: -10n * 10n ** 30n, // $10 loss is added to total cost totalPendingImpactDeltaUsd: -5n * 10n ** 30n, // negative impact is added }); // totalCost = 10 + 5 + 2 + 1 + 10 + 5 = $33 ``` ### getNextPositionValuesForDecreaseTrade ```typescript getNextPositionValuesForDecreaseTrade(p: { existingPosition?: PositionInfo; marketInfo: MarketInfo; collateralToken: TokenData; sizeDeltaUsd: bigint; sizeDeltaInTokens: bigint; realizedPnl: bigint; estimatedPnl: bigint; collateralDeltaUsd: bigint; collateralDeltaAmount: bigint; payedRemainingCollateralUsd: bigint; payedRemainingCollateralAmount: bigint; proportionalPendingImpactDeltaUsd: bigint; showPnlInLeverage: boolean; isLong: boolean; minCollateralUsd: bigint; userReferralInfo: UserReferralInfo | undefined; }): NextPositionValues ``` Computes the projected position state after a decrease: remaining size, collateral, leverage, PnL percentage, and liquidation price. Use this to populate UI previews before order submission. ```typescript const nextValues = getNextPositionValuesForDecreaseTrade({ existingPosition: currentPosition, marketInfo, collateralToken: usdcToken, sizeDeltaUsd: decreaseAmounts.sizeDeltaUsd, sizeDeltaInTokens: decreaseAmounts.sizeDeltaInTokens, realizedPnl: decreaseAmounts.realizedPnl, estimatedPnl: decreaseAmounts.estimatedPnl, collateralDeltaUsd: decreaseAmounts.collateralDeltaUsd, collateralDeltaAmount: decreaseAmounts.collateralDeltaAmount, payedRemainingCollateralUsd: decreaseAmounts.payedRemainingCollateralUsd, payedRemainingCollateralAmount: decreaseAmounts.payedRemainingCollateralAmount, proportionalPendingImpactDeltaUsd: decreaseAmounts.proportionalPendingImpactDeltaUsd, showPnlInLeverage: true, isLong: true, minCollateralUsd: 5000n * 10n ** 30n, userReferralInfo: undefined, }); console.log("Next size:", nextValues.nextSizeUsd); console.log("Next leverage:", nextValues.nextLeverage); console.log("Next liq price:", nextValues.nextLiqPrice); ``` --- ## increase This module provides utilities for calculating increase position amounts, prices, and next position values for GMX trading operations. It handles different trading strategies including leverage by size, leverage by collateral, and independent position management. ## Methods This module exports functions for computing the full set of amounts required to open or increase a leveraged position. All USD values use 30-decimal precision (`USD_DECIMALS = 30`). Leverage values use basis-point encoding (10,000 = 1x, so 20x = `200000n`). :::note All functions in this module are exported from `@gmx-io/sdk/utils/trade`. Import them individually as shown in each example. ::: ### getIncreasePositionAmounts ```typescript getIncreasePositionAmounts(params: IncreasePositionParams): IncreasePositionAmounts ``` Computes the complete set of amounts needed to open or increase a leveraged position. This is the primary function to call when constructing an increase order — it calculates size, collateral, fees (position fee, borrow fee, funding fee, UI fee), price impact, acceptable price, and any required collateral swap. The function supports three strategies: | Strategy | Input required | Description | | ------------------------ | --------------------------------------------------- | --------------------------------------------------------------------------------------- | | `"leverageByCollateral"` | `initialCollateralAmount` + `leverage` | User specifies how much collateral to deposit; size is derived from the leverage target | | `"leverageBySize"` | `indexTokenAmount` + `leverage` | User specifies position size in tokens; collateral is derived from the leverage target | | `"independent"` | `indexTokenAmount` and/or `initialCollateralAmount` | Size and collateral are set independently; leverage is computed from the result | The acceptable price is computed automatically. For limit orders, the default acceptable price impact buffer is 30 bps (0.3%) unless overridden by `fixedAcceptablePriceImpactBps` or `acceptablePriceImpactBuffer`. **Parameters:** | Parameter | Type | Required | Description | | ----------------------------------- | ---------------------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------- | | `marketInfo` | `MarketInfo` | Yes | Target marke
프로젝트로 돌아가기