GMX 백서

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

there is a nonzero remainder (checked via `mulmod`), the result rounds away from zero by adding `1n`. Default is `false`. ```typescript bigMath.mulDiv(100n, 3n, 2n); // 150n bigMath.mulDiv(100n, 3n, 7n, true); // 43n (rounds up from 42.857...) ``` ### max ```typescript max(first: bigint, ...rest: bigint[]): bigint ``` Returns the largest value from the provided `bigint` arguments. ```typescript bigMath.max(10n, 25n, 5n, 100n); // 100n bigMath.max(42n); // 42n ``` ### min ```typescript min(first: bigint, ...rest: bigint[]): bigint ``` Returns the smallest value from the provided `bigint` arguments. ```typescript bigMath.min(10n, 25n, 5n, 100n); // 5n bigMath.min(42n); // 42n ``` ### avg ```typescript avg(...values: (bigint | undefined)[]): bigint | undefined ``` Computes the average of the provided `bigint` values, ignoring `undefined` entries. Returns `undefined` if no valid values are provided (truncates fractional result using integer division). ```typescript bigMath.avg(10n, 20n, 30n); // 20n bigMath.avg(10n, undefined, 30n); // 20n (undefined ignored) bigMath.avg(undefined, undefined); // undefined ``` ### divRound ```typescript divRound(x: bigint, y: bigint): bigint ``` Divides `x` by `y`, rounding to the nearest integer. Rounds up when the remainder is more than half the divisor. ```typescript bigMath.divRound(7n, 3n); // 2n (remainder 1, less than half of 3) bigMath.divRound(8n, 3n); // 3n (remainder 2, more than half of 3) ``` ### divRoundUp ```typescript divRoundUp(x: bigint, y: bigint): bigint ``` Divides `x` by `y`, always rounding up (ceiling division). Equivalent to `(x + y - 1n) / y`. ```typescript bigMath.divRoundUp(7n, 3n); // 3n (ceiling of 2.33...) bigMath.divRoundUp(6n, 3n); // 2n (exact, no rounding) ``` ### mulmod ```typescript mulmod(x: bigint, y: bigint, m: bigint): bigint ``` Returns `(x * y) % m` — the remainder of the product when divided by the modulus `m`. Used internally by `mulDiv` to check for nonzero remainders. ```typescript bigMath.mulmod(7n, 8n, 10n); // 6n (56 % 10) bigMath.mulmod(5n, 4n, 10n); // 0n (20 % 10) ``` ### clamp ```typescript clamp(value: bigint, min: bigint, max: bigint): bigint ``` Constrains `value` to the `[min, max]` range (inclusive), returning `min` if below or `max` if above. ```typescript bigMath.clamp(50n, 0n, 100n); // 50n (within range) bigMath.clamp(-5n, 0n, 100n); // 0n (below min) bigMath.clamp(150n, 0n, 100n); // 100n (above max) ``` --- ## buildUrl This module exports the URL builder used by the SDK's HTTP helpers. ## Exports - `buildUrl(baseUrl, path, query?)` ```typescript const url = buildUrl("https://example.com/api", "/orders", { account: "0x1234" }); ``` --- ## chains(Utils) This module is a type-only re-export for chain configuration shapes used by the SDK. ## Exports - `ContractsChainConfig` - `SourceChainConfig` ```typescript ``` For concrete chain IDs and helpers, use [`configs/chains`](../configs/chains.md). --- ## common This module exports small shared helpers used across the SDK. ## Exports - `sleep(ms, abortSignal?)` ```typescript ``` --- ## errors This module exposes helpers for extracting and decoding transaction errors, especially viem and GMX custom errors. ## Functions ### `extractErrorDataFromViemError` ```typescript extractErrorDataFromViemError(error: any): string | undefined ``` Walks a viem error object and returns the first raw revert-data payload it can find. ```typescript const data = extractErrorDataFromViemError(error); ``` ### `tryDecodeCustomError` ```typescript tryDecodeCustomError(reasonBytes: string): ParsedCustomError | undefined ``` Attempts to decode a GMX custom error directly from raw revert bytes. ```typescript const decoded = tryDecodeCustomError("0x08c379a0..."); ``` ### `decodeErrorFromViemError` ```typescript decodeErrorFromViemError(error: any): ParsedCustomError | undefined ``` Combines raw-data extraction and GMX custom-error decoding in one step. ```typescript const decoded = decodeErrorFromViemError(error); ``` ### `parseError` ```typescript parseError(error: ErrorLike | string | undefined, errorDepth = 0): ErrorData | undefined ``` Normalizes nested transaction errors into a structured object with context, decoded contract error details, and user-error classification. ```typescript const parsed = parseError(error); console.log(parsed?.contractError, parsed?.errorMessage); ``` ## Related - [`configs/contracts`](../configs/contracts.md) — ABI-backed contract context - [`utils/orders`](./orders.md) — order helpers that may surface decoded execution errors --- ## estimateOraclePriceCount This module provides utilities for estimating the number of oracle prices required for various GMX protocol operations. These functions help calculate gas costs and oracle price requirements for deposits, withdrawals, orders, shifts, and GLV operations. ## Methods Each function returns a `bigint` representing the number of oracle price signatures required for that operation type. Import any function directly from `@gmx-io/sdk/utils/fees`. ### estimateDepositOraclePriceCount ```typescript estimateDepositOraclePriceCount(swapsCount: number | bigint): bigint ``` Estimates the number of oracle prices required for a deposit operation. Returns `3n + swapsCount`. ```typescript const priceCount = estimateDepositOraclePriceCount(2); console.log(priceCount); // 5n ``` ### estimateWithdrawalOraclePriceCount ```typescript estimateWithdrawalOraclePriceCount(swapsCount: bigint): bigint ``` Estimates the number of oracle prices required for a withdrawal operation. Returns `3n + swapsCount`. ```typescript const priceCount = estimateWithdrawalOraclePriceCount(1n); console.log(priceCount); // 4n ``` ### estimateOrderOraclePriceCount ```typescript estimateOrderOraclePriceCount(swapsCount: number): bigint ``` Estimates the number of oracle prices required for an order operation. Returns `3n + swapsCount`. ```typescript const priceCount = estimateOrderOraclePriceCount(0); console.log(priceCount); // 3n ``` ### estimateShiftOraclePriceCount ```typescript estimateShiftOraclePriceCount(): bigint ``` Estimates the number of oracle prices required for a shift operation. Always returns `4n`. ```typescript const priceCount = estimateShiftOraclePriceCount(); console.log(priceCount); // 4n ``` ### estimateGlvDepositOraclePriceCount ```typescript estimateGlvDepositOraclePriceCount(marketCount: bigint, swapsCount?: bigint): bigint ``` Estimates the number of oracle prices required for a GLV deposit operation. Returns `2n + marketCount + swapsCount`. `swapsCount` defaults to `0n`. ```typescript const priceCount = estimateGlvDepositOraclePriceCount(3n, 1n); console.log(priceCount); // 6n ``` ### estimateGlvWithdrawalOraclePriceCount ```typescript estimateGlvWithdrawalOraclePriceCount(marketCount: bigint, swapsCount?: bigint): bigint ``` Estimates the number of oracle prices required for a GLV withdrawal operation. Returns `2n + marketCount + swapsCount`. `swapsCount` defaults to `0n`. ```typescript const priceCount = estimateGlvWithdrawalOraclePriceCount(2n); console.log(priceCount); // 4n ``` --- ## executionFee This module provides utilities for calculating execution fees and estimating gas limits for various GMX protocol operations. It handles fee calculations for orders, deposits, withdrawals, and batch operations while considering network-specific gas costs and limits. ## Methods The `executionFee` module exports two categories of functions: **fee calculation** functions that convert a gas limit into a token amount the user must pay, and **gas estimation** functions that compute the gas limit for each operation type. ### Fee calculation #### getExecutionFee ```typescript getExecutionFee( chainId: number, gasLimits: GasLimitsConfig, tokensData: TokensData, estimatedGasLimit: bigint, gasPrice: bigint, oraclePriceCount: bigint, numberOfParts?: number ): ExecutionFee | undefined ``` Converts an estimated gas limit into a full `ExecutionFee` object. Internally it applies the `estimatedFeeMultiplierFactor` from `GasLimitsConfig` and adds per-oracle-price overhead before multiplying by `gasPrice`. Returns `undefined` if the native token is not found in `tokensData`. The returned `ExecutionFee` contains: | Field | Type | Description | | ---------------- | --------- | ----------------------------------------------------------- | | `feeUsd` | `bigint` | Total fee in USD (30-decimal precision) | | `feeTokenAmount` | `bigint` | Total fee in native token units | | `feeToken` | `Token` | Native token data | | `gasLimit` | `bigint` | Adjusted gas limit (after multiplier) | | `isFeeHigh` | `boolean` | `true` when fee exceeds the chain's high-fee threshold | | `isFeeVeryHigh` | `boolean` | `true` when fee exceeds the chain's excessive-fee threshold | ```typescript const executionFee = getExecutionFee( 42161, // Arbitrum gasLimits, tokensData, 500000n, // estimated gas for the operation 1000000000n, // gas price in wei 2n // number of oracle prices required ); if (executionFee) { console.log("Fee USD:", executionFee.feeUsd); console.log("Fee token amount:", executionFee.feeTokenAmount); if (executionFee.isFeeVeryHigh) { console.warn("Execution fee is excessively high"); } else if (executionFee.isFeeHigh) { console.warn("Execution fee is high"); } } ``` #### estimateRelayerGasLimit ```typescript estimateRelayerGasLimit(params: { gasLimits: GasLimitsConfig; tokenPermitsCount: number; feeSwapsCount: number; feeExternalCallsGasLimit: bigint; oraclePriceCount: number; transactionPayloadGasLimit: bigint; l1GasLimit: bigint; }): bigint ``` Estimates the total gas limit for a relayer-submitted Express Trading transaction. The total is the sum of: per-permit overhead, per-fee-swap overhead, per-oracle-price overhead, external calls gas limit, the transaction payload gas limit, and the L1 gas buffer. ```typescript const gasLimit = estimateRelayerGasLimit({ gasLimits, tokenPermitsCount: 1, feeSwapsCount: 1, // 1 swap needed to convert payment token to relay fee token feeExternalCallsGasLimit: 0n, oraclePriceCount: 3, transactionPayloadGasLimit: 200000n, l1GasLimit: 0n, // non-zero only for L1-anchored chains }); ``` #### approximateL1GasBuffer ```typescript approximateL1GasBuffer(params: { l1Reference: L1ExpressOrderGasReference; sizeOfData: bigint; }): bigint ``` Estimates the L1 gas buffer for an Express Trading transaction by logarithmically scaling the reference gas limit based on data size. The formula is: ``` result = round(l1Reference.gasLimit × log(sizeOfData) / log(l1Reference.sizeOfData)) ``` Falls back to `l1Reference.gasLimit` if the logarithm produces a non-finite value (for example, when `sizeOfData` is `0n`). ```typescript const l1GasBuffer = approximateL1GasBuffer({ l1Reference: { gasLimit: 100000n, sizeOfData: 1000n, // reference data size in bytes }, sizeOfData: 1500n, // actual data size for this transaction }); ``` #### estimateBatchGasLimit ```typescript estimateBatchGasLimit(params: { gasLimits: GasLimitsConfig; createOrdersCount: number; updateOrdersCount: number; cancelOrdersCount: number; externalCallsGasLimit: bigint; isGmxAccount: boolean; }): bigint ``` Estimates the gas limit for a batch of order operations. Adds a `gmxAccountCollateralGasLimit` overhead when `isGmxAccount` is `true`. ```typescript const batchGasLimit = estimateBatchGasLimit({ gasLimits, createOrdersCount: 2, updateOrdersCount: 0, cancelOrdersCount: 1, externalCallsGasLimit: 0n, isGmxAccount: false, }); ``` #### estimateBatchMinGasPaymentTokenAmount ```typescript estimateBatchMinGasPaymentTokenAmount(params: { chainId: ContractsChainId; gasPaymentToken: TokenData; isGmxAccount: boolean; relayFeeToken: TokenData; gasPrice: bigint; gasLimits: GasLimitsConfig; l1Reference: L1ExpressOrderGasReference | undefined; tokensData: TokensData; createOrdersCount?: number; // default: 1 updateOrdersCount?: number; // default: 0 cancelOrdersCount?: number; // default: 0 executionFeeAmount?: bigint; // pass to override the estimated execution fee }): bigint ``` Estimates the minimum amount of `gasPaymentToken` the user must hold to cover a batch Express Trading transaction — including the relayer fee, batch gas limit, and execution fee. Converts the total from the relay fee token denomination to the payment token denomination. :::note `chainId` must be a `ContractsChainId` (a supported chain ID literal), not a generic `number`. ::: ```typescript const minPayment = estimateBatchMinGasPaymentTokenAmount({ chainId: 42161, // ContractsChainId for Arbitrum gasPaymentToken: usdcToken, isGmxAccount: false, relayFeeToken: wethToken, gasPrice: 1000000000n, gasLimits, l1Reference: undefined, tokensData, createOrdersCount: 2, updateOrdersCount: 0, cancelOrdersCount: 1, }); ``` ### Gas estimation These functions mirror their on-chain counterparts (`Copy from contract` in the source). They compute the gas limit for specific operation types by combining the base limit from `GasLimitsConfig` with per-swap and callback overheads. #### estimateExecuteIncreaseOrderGasLimit ```typescript estimateExecuteIncreaseOrderGasLimit( gasLimits: GasLimitsConfig, order: { swapsCount?: number; callbackGasLimit?: bigint } ): bigint ``` Estimates gas for a Market Increase or Limit Increase order. `swapsCount` defaults to `0`. ```typescript const gasLimit = estimateExecuteIncreaseOrderGasLimit(gasLimits, { swapsCount: 1, // number of token swaps along the collateral path callbackGasLimit: 0n, }); ``` #### estimateExecuteDecreaseOrderGasLimit ```typescript estimateExecuteDecreaseOrderGasLimit( gasLimits: GasLimitsConfig, order: { swapsCount: number; callbackGasLimit?: bigint; decreaseSwapType?: DecreasePositionSwapType; } ): bigint ``` Estimates gas for a Market Decrease, Limit Decrease, Stop-Loss, or Take-Profit order. When `decreaseSwapType` is not `NoSwap`, one additional swap is added to `swapsCount`. ```typescript const gasLimit = estimateExecuteDecreaseOrderGasLimit(gasLimits, { swapsCount: 0, decreaseSwapType: DecreasePositionSwapType.SwapCollateralTokenToPnlToken, }); ``` #### estimateExecuteSwapOrderGasLimit ```typescript estimateExecuteSwapOrderGasLimit( gasLimits: GasLimitsConfig, order: { swapsCount: number; callbackGasLimit?: bigint } ): bigint ``` Estimates gas for a Market Swap or Limit Swap order. ```typescript const gasLimit = estimateExecuteSwapOrderGasLimit(gasLimits, { swapsCount: 2, // number of market hops in the swap path callbackGasLimit: 0n, }); ``` #### estimateExecuteDepositGasLimit ```typescript estimateExecuteDepositGasLimit( gasLimits: GasLimitsConfig, deposit: { swapsCount?: number | bigint; callbackGasLimit?: bigint } ): bigint ``` Estimates gas for a GM token deposit (not a position increase). `swapsCount` is the total number of input-token swaps required before the deposit — for example, `2` when depositing USDC into an ETH/USDC market that accepts only the long and short tokens individually. :::note This function is for GM pool deposits only. For position increases (Market Increase / Limit Increase), use `estimateExecuteIncreaseOrderGasLimit`. ::: ```typescript const gasLimit = estimateExecuteDepositGasLimit(gasLimits, { swapsCount: 2, // total token swaps needed before the deposit callbackGasLimit: 0n, }); ``` #### estimateExecuteGlvDepositGasLimit ```typescript estimateExecuteGlvDepositGasLimit( gasLimits: GasLimitsConfig, params: { isMarketTokenDeposit: boolean; marketsCount: bigint; swapsCount: bigint; } ): bigint ``` Estimates gas for a GLV deposit. When `isMarketTokenDeposit` is `true`, the user deposits GM tokens directly and no deposit or swap gas is added — only the GLV base gas and per-market overhead. When `false`, the base GM deposit gas and swap gas are added on top. ```typescript // Deposit raw tokens (not GM tokens) into a GLV vault across 5 markets with 1 input swap const gasLimit = estimateExecuteGlvDepositGasLimit(gasLimits, { isMarketTokenDeposit: false, marketsCount: 5n, swapsCount: 1n, }); ``` #### estimateExecuteGlvWithdrawalGasLimit ```typescript estimateExecuteGlvWithdrawalGasLimit( gasLimits: GasLimitsConfig, params: { marketsCount: bigint; swapsCount: bigint } ): bigint ``` Estimates gas for a GLV withdrawal. Both `marketsCount` and `swapsCount` affect the result. ```typescript const gasLimit = estimateExecuteGlvWithdrawalGasLimit(gasLimits, { marketsCount: 5n, swapsCount: 1n, }); ``` #### estimateExecuteWithdrawalGasLimit ```typescript estimateExecuteWithdrawalGasLimit( gasLimits: GasLimitsConfig, withdrawal: { callbackGasLimit?: bigint; swapsCount?: bigint } ): bigint ``` Estimates gas for a GM token withdrawal (not a position decrease). `swapsCount` defaults to `0n`. :::note This function is for GM pool withdrawals only. For position decreases, use `estimateExecuteDecreaseOrderGasLimit`. ::: ```typescript const gasLimit = estimateExecuteWithdrawalGasLimit(gasLimits, { swapsCount: 1n, // token swaps performed after the withdrawal callbackGasLimit: 0n, }); ``` #### estimateExecuteShiftGasLimit ```typescript estimateExecuteShiftGasLimit( gasLimits: GasLimitsConfig, shift: { callbackGasLimit?: bigint } ): bigint ``` Estimates gas for a GM pool shift (moving liquidity from one market to another without withdrawing). ```typescript const gasLimit = estimateExecuteShiftGasLimit(gasLimits, { callbackGasLimit: 0n, }); ``` --- ## fees(Fees) This module provides utilities for calculating various fees in the GMX protocol, including swap fees, position fees, funding fees, borrowing fees, and price impact calculations. It also includes helper functions for working with fee items and swap statistics. ## Methods The `fees` module exports fee calculation functions for three categories of on-chain costs: swap fees, position fees (including referral discounts), and holding costs (funding fee and borrow fee). It also exports helper utilities for working with `FeeItem` objects. ### Swap and position fees #### getSwapFee ```typescript getSwapFee( marketInfo: MarketInfo, swapAmount: bigint, balanceWasImproved: boolean, swapPricingType: SwapPricingType ): bigint ``` Calculates the swap fee for a token amount. The fee factor depends on `swapPricingType`: - `SwapPricingType.AtomicSwap` — uses `atomicSwapFeeFactor` - `SwapPricingType.Withdrawal` — uses `withdrawalFeeFactorBalanceWasImproved` or `withdrawalFeeFactorBalanceWasNotImproved` - All other types (standard swaps) — uses `swapFeeFactorForBalanceWasImproved` or `swapFeeFactorForBalanceWasNotImproved` :::note The fourth parameter is `swapPricingType: SwapPricingType` (an enum), not `isAtomicSwap: boolean` as earlier documentation stated. ::: ```typescript const swapFee = getSwapFee( marketInfo, 1000n * 10n ** 18n, // 1000 USDC (18 decimals) true, // swap improves pool balance SwapPricingType.Swap ); ``` #### getPositionFee ```typescript getPositionFee( marketInfo: MarketInfo, sizeDeltaUsd: bigint, balanceWasImproved: boolean, referralInfo: { totalRebateFactor: bigint; discountFactor: bigint } | undefined, uiFeeFactor?: bigint ): { positionFeeUsd: bigint; discountUsd: bigint; totalRebateUsd: bigint; uiFeeUsd: bigint; } ``` Calculates the position fee for a size change. When `referralInfo` is provided, the rebate and discount are calculated and deducted from `positionFeeUsd`. ```typescript const { positionFeeUsd, discountUsd, totalRebateUsd, uiFeeUsd } = getPositionFee( marketInfo, 10000n * 10n ** 30n, // $10,000 size delta (30-decimal precision) false, { totalRebateFactor: 5000n, discountFactor: 3000n }, // rebate factors in basis points (PRECISION-scaled) 100n // UI fee factor ); ``` ### Funding fee #### getFundingFactorPerPeriod ```typescript getFundingFactorPerPeriod(marketInfo: Market
프로젝트로 돌아가기