bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 17쪽
xecution fee cannot be computed (for example, missing token price data), it returns `{ networkYield: 1.0, usdOut: usdIn }` as a safe fallback.
```typescript
const networkEstimator = createNaiveNetworkEstimator({
gasLimits,
tokensData,
gasPrice: 100000000n, // 0.1 gwei
chainId: 42161, // Arbitrum
});
// How much USD remains after 2 swaps, accounting for execution fee?
const { networkYield, usdOut } = networkEstimator(1000n * 10n ** 30n, 2);
// networkYield ≈ 0.997 if execution fee is ~$3
```
### Path selection utilities
#### getBestSwapPath
```typescript
getBestSwapPath(params: {
routes: MarketEdge[][];
usdIn: bigint;
estimator: SwapEstimator;
networkEstimator?: NaiveNetworkEstimator;
}): MarketEdge[] | undefined
```
Evaluates every route in `routes` by chaining the `estimator` across each edge and returns the route with the highest `usdOut`. When `networkEstimator` is provided, it adjusts the final USD output for execution fee before comparing routes.
Returns `undefined` only when `routes` is empty. If all routes produce zero output (for example, all paths are out of liquidity), it returns the first route.
```typescript
createSwapEstimator,
createNaiveNetworkEstimator,
getBestSwapPath,
marketRouteToMarketEdges,
} from "@gmx-io/sdk/utils/swap";
const estimator = createSwapEstimator(marketsInfoData, SwapPricingType.Swap);
const networkEstimator = createNaiveNetworkEstimator({ gasLimits, tokensData, gasPrice, chainId: 42161 });
// Convert market address paths to MarketEdge arrays
const routes = marketPaths.map((path) => marketRouteToMarketEdges(path, fromTokenAddress, marketsInfoData));
const bestRoute = getBestSwapPath({ routes, usdIn, estimator, networkEstimator });
```
#### getNaiveBestMarketSwapPathsFromTokenSwapPaths
```typescript
getNaiveBestMarketSwapPathsFromTokenSwapPaths(params: {
graph: MarketsGraph;
tokenSwapPaths: string[][];
usdIn: bigint;
tokenInAddress: string;
tokenOutAddress: string;
estimator: NaiveSwapEstimator;
topPathsCount?: number; // default: 3
networkEstimator?: NaiveNetworkEstimator;
}): string[][]
```
Evaluates token-level swap paths using the naive estimator and returns the top market paths by swap yield. The default `topPathsCount` is `3`.
For each token-level hop, it independently selects the best market using `getBestMarketForTokenEdge`, then accumulates the path's total yield. Paths with zero yield on any hop are discarded. When `networkEstimator` is provided, it adjusts yields to account for execution fee when comparing against the current top paths.
```typescript
createNaiveSwapEstimator,
createNaiveNetworkEstimator,
getNaiveBestMarketSwapPathsFromTokenSwapPaths,
getTokenSwapPathsForTokenPairPrebuilt,
getMarketAdjacencyGraph,
} from "@gmx-io/sdk/utils/swap";
const chainId = 42161; // Arbitrum
const graph = getMarketAdjacencyGraph(chainId);
const tokenSwapPaths = getTokenSwapPathsForTokenPairPrebuilt(chainId, wethAddress, usdcAddress);
const naiveEstimator = createNaiveSwapEstimator(marketsInfoData, SwapPricingType.Swap);
const networkEstimator = createNaiveNetworkEstimator({ gasLimits, tokensData, gasPrice, chainId });
const topMarketPaths = getNaiveBestMarketSwapPathsFromTokenSwapPaths({
graph,
tokenSwapPaths,
usdIn: 1000n * 10n ** 30n,
tokenInAddress: wethAddress,
tokenOutAddress: usdcAddress,
estimator: naiveEstimator,
topPathsCount: 3,
networkEstimator,
});
// Returns up to 3 arrays of market addresses, sorted by estimated yield
```
#### getMarketsForTokenPair
```typescript
getMarketsForTokenPair(graph: MarketsGraph, tokenAAddress: string, tokenBAddress: string): string[]
```
Looks up the market addresses that support a direct swap between `tokenAAddress` and `tokenBAddress`. The lookup is symmetric — it checks both `graph[A][B]` and `graph[B][A]`. Returns an empty array if no market connects the pair.
```typescript
const graph = getMarketAdjacencyGraph(42161);
const markets = getMarketsForTokenPair(graph, wethAddress, usdcAddress);
// markets: ["0xETH-USD-MarketAddress", ...]
```
#### getBestMarketForTokenEdge
```typescript
getBestMarketForTokenEdge(params: {
marketAddresses: string[];
usdIn: bigint;
tokenInAddress: string;
tokenOutAddress: string;
estimator: NaiveSwapEstimator;
marketPath?: string[];
calculatedCache?: Record<string, number>;
}): { marketAddress: string; swapYield: number } | undefined
```
From a list of candidate markets, selects the one with the highest `swapYield` for the given token edge. Markets already present in `marketPath` are skipped to prevent routing through the same market twice. Returns `undefined` if all candidates have zero yield.
The optional `calculatedCache` avoids recomputing yields for markets that have already been evaluated in the current routing pass.
```typescript
const best = getBestMarketForTokenEdge({
marketAddresses: ["0xMarket1", "0xMarket2"],
usdIn: 500n * 10n ** 30n,
tokenInAddress: wethAddress,
tokenOutAddress: usdcAddress,
estimator: naiveEstimator,
});
if (best) {
// best.marketAddress — address of the best market
// best.swapYield — ratio, for example 0.998 for 0.2% slippage
}
```
#### marketRouteToMarketEdges
```typescript
marketRouteToMarketEdges(marketPath: string[], from: string, marketsInfoData: MarketsInfoData): MarketEdge[]
```
Converts a sequence of market addresses into a sequence of `MarketEdge` objects. For each market, it determines `from` and `to` token addresses by inspecting the market's `longTokenAddress` and `shortTokenAddress` and comparing with the current input token.
```typescript
// Convert a 2-hop path [ETH-USD market, USDC-BTC market] into edges
const edges = marketRouteToMarketEdges(["0xETHUSDMarket", "0xUSDCBTCMarket"], wethAddress, marketsInfoData);
// edges[0]: { marketAddress: "0xETHUSDMarket", from: wethAddress, to: usdcAddress }
// edges[1]: { marketAddress: "0xUSDCBTCMarket", from: usdcAddress, to: wbtcAddress }
```
#### getTokenSwapPathsForTokenPair
```typescript
getTokenSwapPathsForTokenPair(tokenSwapPaths: SwapPaths, tokenAAddress: string, tokenBAddress: string): string[][]
```
Retrieves all intermediate token paths between `tokenAAddress` and `tokenBAddress` from a `SwapPaths` data structure. The lookup is symmetric — if only `B → A` paths exist, they are reversed to produce `A → B` paths.
Each returned path is a list of intermediate token addresses (not including the start and end tokens).
```typescript
// All intermediate-token paths from WETH to USDC
const paths = getTokenSwapPathsForTokenPair(tokenSwapPaths, wethAddress, usdcAddress);
// paths: [[], ["0xWBTC"], ["0xLINK", "0xWBTC"]] (direct, 1-hop, 2-hop)
```
#### getTokenSwapPathsForTokenPairPrebuilt
```typescript
getTokenSwapPathsForTokenPairPrebuilt(chainId: number, from: string, to: string): string[][]
```
Convenience wrapper that retrieves precomputed token swap paths for a chain without requiring you to load the `SwapPaths` data separately. Internally delegates to `getTokenSwapPathsForTokenPair` using the prebuilt `TOKEN_SWAP_PATHS` for the chain.
```typescript
const paths = getTokenSwapPathsForTokenPairPrebuilt(42161, wethAddress, usdcAddress);
```
#### getMarketAdjacencyGraph
```typescript
getMarketAdjacencyGraph(chainId: number): MarketsGraph
```
Returns the prebuilt market adjacency graph for a chain. The graph maps `tokenA → tokenB → marketAddress[]`, enabling O(1) market lookups for any token pair.
```typescript
const graph = getMarketAdjacencyGraph(42161); // Arbitrum
// graph["0xWETH"]["0xUSDC"] → ["0xETH-USD-MarketAddress"]
```
#### findAllReachableTokens
```typescript
findAllReachableTokens(chainId: number, from: string): string[]
```
Returns all token addresses reachable from `from` via at most `MAX_EDGE_PATH_LENGTH` hops (currently 3) on the given chain. This uses precomputed reachability data for O(1) lookup.
```typescript
const reachable = findAllReachableTokens(42161, wethAddress);
// reachable: ["0xUSDC", "0xWBTC", "0xARB", ...]
```
#### getMaxLiquidityMarketSwapPathFromTokenSwapPaths
```typescript
getMaxLiquidityMarketSwapPathFromTokenSwapPaths(params: {
graph: MarketsGraph;
tokenSwapPaths: string[][];
tokenInAddress: string;
tokenOutAddress: string;
getLiquidity: MarketEdgeLiquidityGetter;
}): { path: string[]; liquidity: bigint } | undefined
```
Finds the swap path with the greatest bottleneck liquidity across all candidate paths. For a multi-hop path, liquidity is the minimum available liquidity across all hops — the path's capacity is limited by its weakest link.
Returns `undefined` if no valid path exists.
```typescript
createMarketEdgeLiquidityGetter,
getMaxLiquidityMarketSwapPathFromTokenSwapPaths,
getTokenSwapPathsForTokenPairPrebuilt,
getMarketAdjacencyGraph,
} from "@gmx-io/sdk/utils/swap";
const chainId = 42161;
const graph = getMarketAdjacencyGraph(chainId);
const tokenSwapPaths = getTokenSwapPathsForTokenPairPrebuilt(chainId, wethAddress, usdcAddress);
const getLiquidity = createMarketEdgeLiquidityGetter(marketsInfoData);
const result = getMaxLiquidityMarketSwapPathFromTokenSwapPaths({
graph,
tokenSwapPaths,
tokenInAddress: wethAddress,
tokenOutAddress: usdcAddress,
getLiquidity,
});
if (result) {
// result.path — array of market addresses
// result.liquidity — minimum available liquidity across all hops (bigint, USD 30-decimal)
}
```
#### getMaxLiquidityMarketForTokenEdge
```typescript
getMaxLiquidityMarketForTokenEdge(params: {
markets: string[];
tokenInAddress: string;
tokenOutAddress: string;
getLiquidity: MarketEdgeLiquidityGetter;
}): { marketAddress: string; liquidity: bigint }
```
From a list of candidate markets for a single token edge, selects the one with the most available output-side liquidity. Always returns a result (using the first market as a fallback if all have zero liquidity).
```typescript
const best = getMaxLiquidityMarketForTokenEdge({
markets: ["0xMarket1", "0xMarket2"],
tokenInAddress: wethAddress,
tokenOutAddress: usdcAddress,
getLiquidity,
});
// best.marketAddress — market with most liquidity
// best.liquidity — available USD liquidity (bigint, 30 decimals)
```
---
## swapStats
This module provides utilities for calculating swap statistics, capacity, and liquidity for token swaps within GMX markets. It includes functions for analyzing swap paths, calculating fees and price impacts, and determining available liquidity.
## Methods
The swapStats module exports functions for computing pool capacity, simulating swap paths, and calculating per-step swap statistics. Import any function directly from `@gmx-io/sdk/utils/swap`. When passing `swapPricingType`, use the `SwapPricingType` enum imported from `@gmx-io/sdk/utils/orders`.
### getSwapCapacityUsd
```typescript
getSwapCapacityUsd(marketInfo: MarketInfo, isLong: boolean): bigint
```
Returns the remaining swap capacity in USD for the specified pool side: `convertToUsd(maxPoolAmount - poolAmount, token.decimals, getMidPrice(token.prices))`.
```typescript
const longCapacity = getSwapCapacityUsd(marketInfo, true); // long pool remaining capacity
const shortCapacity = getSwapCapacityUsd(marketInfo, false); // short pool remaining capacity
```
### getSwapPathOutputAddresses
```typescript
getSwapPathOutputAddresses(p: {
marketsInfoData: MarketsInfoData;
initialCollateralAddress: string;
swapPath: string[];
wrappedNativeTokenAddress: string;
shouldUnwrapNativeToken: boolean;
isIncrease: boolean;
}): { outTokenAddress: string | undefined; outMarketAddress: string | undefined }
```
Determines the output token and market addresses for a given swap path by walking the path and following opposite-collateral pointers at each step.
When `swapPath` is empty: for increase operations the `initialCollateralAddress` is returned as-is (increase targets are always ERC-20); for decrease operations the address is returned, or `NATIVE_TOKEN_ADDRESS` if `shouldUnwrapNativeToken` and the token is the wrapped native token.
When any market in the path is not found, both fields are `undefined`.
```typescript
const { outTokenAddress, outMarketAddress } = getSwapPathOutputAddresses({
marketsInfoData,
initialCollateralAddress: wethAddress,
swapPath: [ethUsdcMarketAddress],
wrappedNativeTokenAddress: wethAddress,
shouldUnwrapNativeToken: true,
isIncrease: false,
});
// outTokenAddress: NATIVE_TOKEN_ADDRESS (unwrapped ETH for decrease)
// outMarketAddress: ethUsdcMarketAddress
```
### getSwapPathStats
```typescript
getSwapPathStats(p: {
marketsInfoData: MarketsInfoData;
swapPath: string[];
initialCollateralAddress: string;
wrappedNativeTokenAddress: string;
usdIn: bigint;
shouldUnwrapNativeToken: boolean;
shouldApplyPriceImpact: boolean;
swapPricingType: SwapPricingType;
}): SwapPathStats | undefined
```
Simulates a multi-step swap along `swapPath` and returns aggregate statistics. Returns `undefined` when `swapPath` is empty or any market in the path is not found.
The `SwapPathStats` return type:
| Field | Type | Description |
| ------------------------------ | --------------------- | ------------------------------------------------ |
| `swapPath` | `string[]` | Market addresses traversed |
| `swapSteps` | `SwapStats[]` | Per-step statistics |
| `targetMarketAddress` | `string \| undefined` | Last market in path |
| `tokenInAddress` | `string` | Initial collateral address |
| `tokenOutAddress` | `string` | Final output token address |
| `usdOut` | `bigint` | Output value in USD (30-decimal) |
| `amountOut` | `bigint` | Output token amount (token decimals) |
| `totalSwapFeeUsd` | `bigint` | Sum of fees across all steps |
| `totalSwapPriceImpactDeltaUsd` | `bigint` | Sum of price impacts across all steps |
| `totalFeesDeltaUsd` | `bigint` | `totalSwapPriceImpactDeltaUsd - totalSwapFeeUsd` |
```typescript
const pathStats = getSwapPathStats({
marketsInfoData,
swapPath: [ethUsdcMarketAddress],
initialCollateralAddress: wethAddress,
wrappedNativeTokenAddress: wethAddress,
usdIn: 1000n * 10n ** 30n, // $1000 (30-decimal)
shouldUnwrapNativeToken: false,
shouldApplyPriceImpact: true,
swapPricingType: SwapPricingType.Swap,
});
if (pathStats) {
console.log("Total fee USD:", pathStats.totalSwapFeeUsd);
console.log("Amount out:", pathStats.amountOut);
console.log("USD out:", pathStats.usdOut);
}
```
### getSwapStats
```typescript
getSwapStats(p: {
marketInfo: MarketInfo;
tokenInAddress: string;
tokenOutAddress: string;
usdIn: bigint;
shouldApplyPriceImpact: boolean;
swapPricingType: SwapPricingType;
}): SwapStats
```
Computes detailed statistics for a single swap step. Uses `tokenIn.prices.minPrice` for `amountIn` conversion and `tokenOut.prices.maxPrice` for `amountOut` conversion.
When `getPriceImpactForSwap` throws (market out of capacity), returns a zero-output `SwapStats` with `isOutLiquidity: true` and `isOutCapacity` set based on whether the pool capacity is exceeded.
The `SwapStats` return type:
| Field | Type | Description |
| --------------------- | ---------------------- | ------------------------------------------ |
| `marketAddress` | `string` | Market being swapped through |
| `tokenInAddress` | `string` | Input token address |
| `tokenOutAddress` | `string` | Output token address |
| `isWrap` | `boolean` | `tokenInAddress === NATIVE_TOKEN_ADDRESS` |
| `isUnwrap` | `boolean` | `tokenOutAddress === NATIVE_TOKEN_ADDRESS` |
| `isOutLiquidity` | `boolean \| undefined` | Output exceeds available liquidity |
| `isOutCapacity` | `boolean \| undefined` | Input exceeds pool capacity |
| `amountIn` | `bigint` | Input token amount |
| `amountInAfterFees` | `bigint` | Input amount after fee deduction |
| `usdIn` | `bigint` | Input USD value (30-decimal) |
| `swapFeeAmount` | `bigint` | Fee in input token units |
| `swapFeeUsd` | `bigint` | Fee in USD (30-decimal) |
| `priceImpactDeltaUsd` | `bigint` | Capped price impact (30-decimal) |
| `amountOut` | `bigint` | Output token amount |
| `usdOut` | `bigint` | Output USD value (30-decimal) |
```typescript
const swapStats = getSwapStats({
marketInfo,
tokenInAddress: wethAddress,
tokenOutAddress: usdcAddress,
usdIn: 1000n * 10n ** 30n, // $1000 (30-decimal)
shouldApplyPriceImpact: true,
swapPricingType: SwapPricingType.Swap,
});
console.log("Swap fee:", swapStats.swapFeeUsd);
console.log("Price impact:", swapStats.priceImpactDeltaUsd);
console.log("Amount out:", swapStats.amountOut);
console.log("Out of liquidity:", swapStats.isOutLiquidity);
```
### getMaxSwapPathLiquidity
```typescript
getMaxSwapPathLiquidity(p: {
marketsInfoData: MarketsInfoData;
swapPath: string[];
initialCollateralAddress: string;
}): bigint
```
Returns the minimum available output liquidity across all steps in the swap path — the bottleneck that limits the maximum swap size. Returns `0n` when `swapPath` is empty or any market in the path is not found.
```typescript
const maxLiquidity = getMaxSwapPathLiquidity({
marketsInfoData,
swapPath: [ethUsdcMarketAddress],
initialCollateralAddress: wethAddress,
});
// Compare against desired swap size before submitting
if (maxLiquidity < desiredUsdIn) {
console.warn("Swap exceeds available liquidity");
}
```
---
## swapValues
This module provides utilities for calculating swap amounts and values for token exchanges in the GMX protocol. It handles both internal GMX swaps and external swap integrations, supporting limit orders and market orders with various optimization strategies.
## Methods
The module exports three functions for computing swap amounts and sorting swap routes.
### getSwapAmountsByFromValue
```typescript
getSwapAmountsByFromValue(p: {
tokenIn: TokenData;
tokenOut: TokenData;
amountIn: bigint;
triggerRatio?: TokensRatio;
isLimit: boolean;
swapOptimizationOrder?: SwapOptimizationOrderArray;
allowedSwapSlippageBps?: bigint;
uiFeeFactor: bigint;
marketsInfoData: MarketsInfoData | undefined;
chainId: number;
externalSwapQuoteParams: ExternalSwapQuoteParams | undefined;
findSwapPath: FindSwapPath;
allowSameTokenSwap: boolean;
}): SwapAmounts
```
Calculates `SwapAmounts` for a given input token amount. The returned `SwapAmounts` contains:
| Field | Type | Description |
| ----------------- | ------------------------------- | --------------------------------------- |
| `amountIn` | `bigint` | Input token amount |
| `usdIn` | `bigint` | Input value in USD (30-decimal) |
| `amountOut` | `bigint` | Expected output token amount |
| `usdOut` | `bigint` | Expected output value in USD |
| `priceIn` | `bigint` | Input token price used |
| `priceOut` | `bigint` | Output token price used |
| `minOutputAmount` | `bigint` | Minimum acceptable output amount |
| `swapStrategy` | `SwapStrategyForIncreaseOrders` | Internal/external swap strategy details |
For limit orders (`isLimit: true`), `triggerRatio` is required to compute the target output; without it the function returns zero-output amounts.
For wrap/unwrap operations, no swap path is needed and amounts are returned directly.
```typescript
const swapAmounts = getSwapAmountsByFromValue({
tokenIn: wethToken,
tokenOut: usdcToken,
amountIn: 1n * 10n ** 18n, // 1 WETH
isLimit: false,
uiFeeFactor: 0n,
marketsInfoData,
chainId: 42161,
externalSwapQuoteParams: undefined,
findSwapPath: myFindSwapPath,
allowSameTokenSwap: false,
});
console.log(swapAmounts.amountOut); // Expected USDC output
console.log(swapAmounts.minOutputAmount); // Minimum USDC (after fees)
```
### getSwapAmountsByToValue
```typescript
getSwapAmountsByToValue(p: {
tokenIn: TokenData;
tokenOut: TokenData;
amountOut: bigint;
triggerRatio?: TokensRatio;
isLimit: boolean;
swapOptimizationOrder?: SwapOptimizationOrderArray;
allowedSwapSlippageBps?: bigint;
uiFeeFactor: bigint;
marketsInfoData: MarketsInfoData | undefined;
chainId: number;
externalSwapQuoteParams: ExternalSwapQuoteParams | undefined;
findSwapPath: FindSwapPath;
allowSameTokenSwap: boolean;
}): SwapAmounts
```
Calculates `SwapAmounts` for a desired output token amou프로젝트로 돌아가기