bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 16쪽
ts. Returns `{ acceptablePrice: indexPrice, acceptablePriceDeltaBps: 0n, priceDelta: 0n }` when `sizeDeltaUsd` is `0` or `indexPrice` is `0n`.
```typescript
const { acceptablePrice, acceptablePriceDeltaBps, priceDelta } = getAcceptablePriceByPriceImpact({
isIncrease: true,
isLong: true,
indexPrice: 1800n * 10n ** 30n,
sizeDeltaUsd: 10000n * 10n ** 30n,
priceImpactDeltaUsd: -50n * 10n ** 30n, // -$50 price impact
});
// acceptablePrice is slightly below indexPrice (worse for a long)
// acceptablePriceDeltaBps is the basis-point deviation from indexPrice
```
### getDefaultAcceptablePriceImpactBps
```typescript
getDefaultAcceptablePriceImpactBps(p: {
isIncrease: boolean;
isLong: boolean;
indexPrice: bigint;
sizeDeltaUsd: bigint;
priceImpactDeltaUsd: bigint;
acceptablePriceImapctBuffer?: number; // default: 30 (0.3%)
}): bigint
```
Returns the recommended acceptable price impact in basis points for a given trade, including a safety buffer. The default buffer is `30` basis points (0.3%).
When `priceImpactDeltaUsd` is positive (favorable price impact), the function returns only the buffer. When it's negative, the function converts the impact to basis points and adds the buffer on top.
:::note
The parameter name `acceptablePriceImapctBuffer` contains a typo (`Imapct` instead of `Impact`). This matches the source code exactly and must be used as-is.
:::
```typescript
const acceptableBps = getDefaultAcceptablePriceImpactBps({
isIncrease: true,
isLong: true,
indexPrice: 1800n * 10n ** 30n,
sizeDeltaUsd: 10000n * 10n ** 30n,
priceImpactDeltaUsd: -50n * 10n ** 30n,
// acceptablePriceImapctBuffer: 30 // 30 bps buffer (default)
});
// Returns: |priceImpactBps| + 30
```
### API data fetching
The prices module includes a utility for fetching OHLCV candle data from the GMX API. The public interface is the `fetchOhlcv` method on the [`GmxApiSdk`](../../../v2/readme.md) V2 client.
#### `fetchOhlcv` via `GmxApiSdk`
```typescript
const apiSdk = new GmxApiSdk({ chainId: 42161 });
const candles: OhlcvCandle[] = await apiSdk.fetchOhlcv({
symbol: "BTC/USD",
timeframe: "1h",
limit: 100,
});
```
The method sends a GET request to the `/prices/ohlcv` endpoint with the provided query parameters.
#### `OhlcvParams`
```typescript
type OhlcvParams = {
symbol: string; // Trading pair, for example "BTC/USD"
timeframe: string; // Candle interval, for example "1h", "4h", "1d"
limit?: number; // Maximum number of candles to return
since?: number; // Unix timestamp to start from
};
```
#### `OhlcvCandle`
Each candle in the returned array has this shape:
```typescript
type OhlcvCandle = {
timestamp: number;
open: string;
high: string;
low: string;
close: string;
};
```
The `open`, `high`, `low`, and `close` values are returned as strings.
:::note
The underlying `fetchApiOhlcv` function in `utils/prices/api` is not re-exported from `@gmx-io/sdk/utils/prices`. Use `GmxApiSdk.fetchOhlcv()` instead. The `OhlcvCandle` and `OhlcvParams` types are also available from `@gmx-io/sdk/types/prices`.
:::
---
## referrals
This module exports referral-code helpers and referral-related data types.
## Runtime exports
- `MAX_REFERRAL_CODE_LENGTH`
- `decodeReferralCode`
- `encodeReferralCode`
## Re-exported types
- `UserReferralInfo`
- `RebateDistributionType`
- `RebateDistribution`
- `CodeOwnershipInfo`
- `ReferralCodeStats`
- `AffiliateTotalStats`
- `TraderReferralTotalStats`
- `TierInfo`
- `ReferralsStats`
- `TotalReferralsStats`
```typescript
```
---
## sidecarOrders
This module is a type-only re-export for sidecar stop-loss, take-profit, and limit-order entry shapes.
## Exports
- `GroupPrefix`
- `EntryField`
- `InitialEntry`
- `SidecarOrderEntryBase`
- `SidecarSlTpOrderEntry`
- `SidecarSlTpOrderEntryValid`
- `SidecarLimitOrderEntry`
- `SidecarLimitOrderEntryValid`
- `SidecarOrderEntry`
- `SidecarOrderEntryGroupBase`
- `SidecarOrderEntryGroup`
```typescript
```
---
## findReachableTokens
This module provides functionality to find all tokens that can be reached from each token in a markets graph through swap operations, respecting maximum path length constraints.
## Methods
The `findReachableTokens` function is exported from `@gmx-io/sdk/utils/swap`.
### findReachableTokens
```typescript
findReachableTokens(graph: MarketsGraph): Record<string, string[]>
```
Performs a breadth-first search from every token in `graph` and returns a map of `tokenAddress → reachableTokenAddresses[]`. The search stops at `MAX_EDGE_PATH_LENGTH` hops (currently `3`). Each token's own address is always included in its reachable set.
For most SDK use cases, prefer `findAllReachableTokens(chainId, from)` from `@gmx-io/sdk/utils/swap`, which provides an O(1) lookup using precomputed data. Use `findReachableTokens` directly when you've built a custom `MarketsGraph` with `buildMarketsAdjacencyGraph`.
```typescript
// Build a custom graph (for example, to exclude certain markets)
const filteredMarketsMap = Object.fromEntries(
Object.entries(MARKETS[42161]).filter(([addr]) => addr !== excludedMarketAddress)
);
const graph = buildMarketsAdjacencyGraph(filteredMarketsMap);
// Compute reachability for all tokens in the custom graph
const reachableTokens = findReachableTokens(graph);
// reachableTokens[wethAddress] — all tokens reachable from WETH in ≤3 hops
// including wethAddress itself
```
---
## findSwapPathsBetweenTokens
This module computes all valid intermediate-token sequences for swapping between any two tokens in a `MarketsGraph`. The result is a precomputed lookup table that swap routing uses to enumerate candidate routes.
## Methods
This module exports a single function that builds a full swap-path lookup table from a markets graph.
### findSwapPathsBetweenTokens
```typescript
findSwapPathsBetweenTokens(graph: MarketsGraph): SwapPaths
```
Runs a breadth-first search from every token in `graph` to every other token and returns a `SwapPaths` map. Each entry in the map is an array of intermediate-token paths: the sequence of tokens the swap passes through between the source and destination. A direct swap with no intermediate hops is represented as an empty array `[]`.
The search is bounded by `MAX_EDGE_PATH_LENGTH = 3`, which limits the total number of market edges (hops) in any path. An intermediate-token list therefore contains at most 2 addresses.
Tokens with no reachable targets are omitted from the result.
#### Path pruning rules
`findSwapPathsBetweenTokens` applies two pruning rules during the search to discard routes that would almost always produce a loss:
1. **Single-market A → B → A loop.** If the path visits token `X`, then `Y`, then `X` again, and there is only one market between `X` and `Y`, the path is pruned. With a single market, the two legs incur price impact twice on the same pool, guaranteeing a net loss.
2. **Consecutive same-token visit.** If the last two tokens in the path are identical, the path is pruned as a degenerate loop.
Same-token swaps (for example, ETH → ETH) are valid when multiple markets connect that token to itself and the path includes at least one intermediate token.
#### Return type
```typescript
type SwapPaths = {
[fromToken: string]: {
[toToken: string]: string[][]; // array of intermediate-token sequences
};
};
```
Each `string[]` entry is one candidate route described by its intermediate tokens. For a direct single-hop swap, the entry is `[]`. For a two-hop swap through USDC, the entry is `["0xUSDC"]`.
#### Example
```typescript
const graph = buildMarketsAdjacencyGraph(MARKETS[42161]);
const swapPaths = findSwapPathsBetweenTokens(graph);
// Direct swap ETH → USDC and indirect via BTC
// swapPaths[wethAddress][usdcAddress] might be:
// [[], ["0xBTC..."]]
// ^ ^
// | two-hop: ETH → BTC → USDC
// direct: ETH → USDC
const routes = swapPaths[wethAddress]?.[usdcAddress] ?? [];
for (const intermediates of routes) {
if (intermediates.length === 0) {
console.log("Direct swap");
} else {
console.log("Via:", intermediates.join(" → "));
}
}
```
:::note
`findSwapPathsBetweenTokens` returns the raw graph-level paths (intermediate tokens only). To evaluate which path gives the best output for a specific swap amount, pass these paths to `getBestSwapPath` from [`utils/swap/swapRouting`](./swapRouting.md), which applies live market data to score each route.
:::
:::note
For most use cases, use the pre-computed constants from [`utils/swap/preparedSwapData`](./preparedSwapData.md) instead: `TOKEN_SWAP_PATHS`, `MARKETS_ADJACENCY_GRAPH`, and `REACHABLE_TOKENS` are built from `findSwapPathsBetweenTokens` at module load time and are optimized for repeated lookups.
:::
---
## preparedSwapData
This module provides pre-computed swap data structures for efficient token swapping operations across different chains. It contains adjacency graphs, swap paths, and reachable token mappings that are built at module initialization time from the static `MARKETS` configuration.
These constants are exported from `@gmx-io/sdk/utils/swap` (not as a separate sub-path).
## Constants
Three pre-computed constants are available, each keyed by chain ID.
### MARKETS_ADJACENCY_GRAPH
`MARKETS_ADJACENCY_GRAPH: { [chainId: number]: MarketsGraph }`
Pre-computed adjacency graph for each chain representing connections between tokens through shared markets. Built once at module load from `MARKETS`.
```typescript
const arbitrumGraph = MARKETS_ADJACENCY_GRAPH[42161];
const wethConnections = arbitrumGraph["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"];
```
### TOKEN_SWAP_PATHS
`TOKEN_SWAP_PATHS: { [chainId: number]: SwapPaths }`
Pre-computed swap paths between all reachable token pairs for each chain. Built once at module load from `MARKETS_ADJACENCY_GRAPH`.
```typescript
const arbitrumSwapPaths = TOKEN_SWAP_PATHS[42161];
const wethAddress = "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1";
const usdcAddress = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831";
const swapPath = arbitrumSwapPaths[wethAddress]?.[usdcAddress];
```
### REACHABLE_TOKENS
`REACHABLE_TOKENS: { [chainId: number]: { [token: string]: string[] } }`
Mapping of token addresses to all other tokens they can be reached from through swaps on each chain. Built once at module load.
```typescript
const reachableFromWeth = REACHABLE_TOKENS[42161]["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"];
```
---
## swap
This module provides utilities for calculating swap statistics and values in the GMX protocol. It includes functions for computing swap fees, price impact, and other swap-related metrics.
## Methods
The `@gmx-io/sdk/utils/swap` module re-exports all functions from its sub-modules. The table below maps each function group to its documentation page.
| Sub-module | Description |
| ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
| [`swapPath`](./swapPath.md) | Path discovery: `createFindSwapPath`, `getWrappedAddress` |
| [`swapValues`](./swapValues.md) | Amount calculation: `getSwapAmountsByFromValue`, `getSwapAmountsByToValue`, `getSwapPathComparator` |
| [`swapStats`](./swapStats.md) | Fee and price impact stats per swap step |
| [`swapRouting`](./swapRouting.md) | Route selection: `getBestSwapPath`, naive pre-selection |
| [`findSwapPathsBetweenTokens`](./findSwapPathsBetweenTokens.md) | Graph traversal for all token-pair paths |
| [`findReachableTokens`](./findReachableTokens.md) | Reachability analysis from a source token |
| [`preparedSwapData`](./preparedSwapData.md) | Pre-computed constants: `MARKETS_ADJACENCY_GRAPH`, `TOKEN_SWAP_PATHS`, `REACHABLE_TOKENS` |
---
## swapPath
This module provides utilities for finding optimal swap paths between tokens in the GMX protocol. It handles path discovery, liquidity analysis, and gas cost estimation to determine the most efficient routes for token swaps.
## Methods
The swapPath module exports a utility for address normalization and the main factory for building swap-path finders. Import any function directly from `@gmx-io/sdk/utils/swap`.
### getWrappedAddress
```typescript
getWrappedAddress(chainId: number, address: string | undefined): string | undefined
```
Converts a token address to its wrapped equivalent for the chain (for example, native ETH → WETH). Returns `undefined` when `address` is `undefined`.
```typescript
const wrappedAddress = getWrappedAddress(42161, nativeTokenAddress);
// Returns WETH address for Arbitrum
```
### createFindSwapPath
```typescript
createFindSwapPath(params: {
chainId: number;
fromTokenAddress: string | undefined;
toTokenAddress: string | undefined;
marketsInfoData: MarketsInfoData | undefined;
gasEstimationParams?: {
gasPrice: bigint;
gasLimits: GasLimitsConfig;
tokensData: TokensData;
};
swapPricingType: SwapPricingType | undefined;
disabledMarkets?: string[];
manualPath?: string[];
}): FindSwapPath
```
Creates a closure that finds the best swap path between two tokens. Call it once with the current market data, then call the returned `FindSwapPath` function for each input amount or sorting preference you want to evaluate.
The returned `FindSwapPath` function has the signature:
```typescript
(usdIn: bigint, opts?: { order?: ("liquidity" | "length")[] }) => SwapPathStats | undefined;
```
Results are cached per `(usdIn, order)` combination.
**Routing logic:**
- When `manualPath` is provided, the closure uses it directly and skips automatic routing.
- When `opts.order` is provided or `usdIn === 0n`, the closure uses the max-liquidity path (optionally filtered to shortest paths when `order[0] === "length"`).
- Otherwise, the closure runs the full two-phase routing: naive pre-selection followed by accurate scoring via `getBestSwapPath`.
When `marketsInfoData` is `undefined`, the returned function always returns `undefined`.
In addition to any markets you pass in `disabledMarkets`, the SDK automatically excludes markets listed in the `DISABLED_SWAP_ROUTE_MARKETS` configuration (from `@gmx-io/sdk/configs/markets`). These are markets that are unsuitable for swap routing regardless of caller context.
When `swapPricingType` is `SwapPricingType.AtomicSwap`, markets unavailable for Express Trading are also automatically added to the disabled set.
:::note
The parameter is `swapPricingType: SwapPricingType` (an enum), not `isExpressFeeSwap: boolean` as earlier documentation stated.
:::
The returned `SwapPathStats` contains:
| Field | Type | Description |
| ------------------------------ | ------------- | ------------------------------------------- |
| `swapPath` | `string[]` | Market addresses in hop order |
| `swapSteps` | `SwapStats[]` | Per-hop stats (fees, price impact, amounts) |
| `tokenInAddress` | `string` | Input token address |
| `tokenOutAddress` | `string` | Output token address |
| `usdOut` | `bigint` | Estimated USD output (30-decimal) |
| `amountOut` | `bigint` | Estimated output token amount |
| `totalSwapFeeUsd` | `bigint` | Total fees in USD across all hops |
| `totalSwapPriceImpactDeltaUsd` | `bigint` | Total price impact in USD |
| `totalFeesDeltaUsd` | `bigint` | Combined fees and price impact |
```typescript
const findSwapPath = createFindSwapPath({
chainId: 42161,
fromTokenAddress: wethAddress,
toTokenAddress: usdcAddress,
marketsInfoData,
gasEstimationParams: {
gasPrice: 1000000000n,
gasLimits,
tokensData,
},
swapPricingType: SwapPricingType.Swap,
});
// Find best path for a $1000 swap
const result = findSwapPath(1000n * 10n ** 30n);
if (result) {
console.log("Market path:", result.swapPath);
console.log("USD out:", result.usdOut);
console.log("Total fees:", result.totalFeesDeltaUsd);
}
// Find highest-liquidity path (useful for showing available capacity)
const liquidityPath = findSwapPath(0n, { order: ["liquidity"] });
```
---
## swapRouting
This module provides utilities for finding optimal swap routes between tokens in GMX markets. It includes functions for creating swap estimators, finding best swap paths, and working with market adjacency graphs to determine the most efficient routes for token swaps.
## Methods
The `swapRouting` module exports two categories of functions: **estimator factories** that produce closures used to score and compare routes, and **path selection utilities** that use those estimators to find the best route through the market graph.
### Estimator factories
These functions return closures (estimators) rather than results. You create them once per session with the current market data, then call them repeatedly during path evaluation.
#### createSwapEstimator
```typescript
createSwapEstimator(marketsInfoData: MarketsInfoData, swapPricingType: SwapPricingType): SwapEstimator
```
Creates an accurate swap estimator that computes the exact USD output for a `MarketEdge` and a USD input. It applies price impact and checks liquidity/capacity limits. Returns `{ usdOut: 0n }` for disabled markets or when the swap would exceed available liquidity or capacity.
Use this estimator with `getBestSwapPath` for the final route selection pass.
```typescript
const estimator = createSwapEstimator(marketsInfoData, SwapPricingType.Swap);
// Evaluate a single edge: USDC → WETH via a specific market
const edge = { marketAddress: "0xMarketAddress", from: "0xUSDC", to: "0xWETH" };
const { usdOut } = estimator(edge, 1000n * 10n ** 30n); // 1000 USD in
```
:::note
The second parameter is `swapPricingType` (a `SwapPricingType` enum), not `isAtomicSwap` as earlier documentation stated. The swap pricing type determines whether price impact uses the standard swap formula or the two-step atomic swap formula.
:::
#### createMarketEdgeLiquidityGetter
```typescript
createMarketEdgeLiquidityGetter(marketsInfoData: MarketsInfoData): MarketEdgeLiquidityGetter
```
Creates a function that returns the available USD liquidity for the output token pool of a `MarketEdge`. Returns `0n` for disabled markets.
Use this with `getMaxLiquidityMarketSwapPathFromTokenSwapPaths` and `getMaxLiquidityMarketForTokenEdge` to find the highest-capacity route.
```typescript
const getLiquidity = createMarketEdgeLiquidityGetter(marketsInfoData);
const edge = { marketAddress: "0xMarketAddress", from: "0xUSDC", to: "0xWETH" };
const availableLiquidity = getLiquidity(edge); // bigint in USD (30 decimals)
```
#### createNaiveSwapEstimator
```typescript
createNaiveSwapEstimator(marketsInfoData: MarketsInfoData, swapPricingType: SwapPricingType): NaiveSwapEstimator
```
Creates a fast swap estimator for use in the path pre-selection phase. Instead of returning `usdOut` as a `bigint`, it returns `swapYield` as a plain `number` ratio (for example, `0.998` means 0.2% slippage). Returns `{ swapYield: 0 }` when capacity, liquidity, or output is zero.
Use this with `getNaiveBestMarketSwapPathsFromTokenSwapPaths` to quickly narrow down the top candidate paths before running the accurate estimator.
```typescript
const naiveEstimator = createNaiveSwapEstimator(marketsInfoData, SwapPricingType.Swap);
const edge = { marketAddress: "0xMarketAddress", from: "0xUSDC", to: "0xWETH" };
const { swapYield } = naiveEstimator(edge, 1000n * 10n ** 30n);
// swapYield > 1.0 means favorable swap (output exceeds input in USD terms)
// swapYield < 1.0 means unfavorable swap (price impact)
```
:::note
`swapYield` is a ratio: `usdOut / usdIn`. A value of `1.1` means the output is 10% larger than the input; `0.9` means 10% less.
:::
#### createNaiveNetworkEstimator
```typescript
createNaiveNetworkEstimator(config: {
gasLimits: GasLimitsConfig;
tokensData: TokensData;
gasPrice: bigint;
chainId: number;
}): NaiveNetworkEstimator
```
Creates a network cost estimator that penalizes swap routes by their estimated execution fee. The returned estimator takes `(usdIn, swapsCount)` and returns `{ networkYield, usdOut }` where `networkYield` is the fraction of input USD retained after gas costs.
If the e프로젝트로 돌아가기