bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 14쪽
splaying large round numbers like total liquidity.
```typescript
formatBigUsd(expandDecimals(999_999_999_999, USD_DECIMALS)); // "$999,999,999,999"
```
#### formatDeltaUsd
```typescript
formatDeltaUsd(
deltaUsd?: bigint,
percentage?: bigint,
opts?: { fallbackToZero?: boolean; showPlusForZero?: boolean; hidePercentage?: boolean }
): string | undefined
```
Formats a signed USD change with an optional percentage label. Returns `undefined` if `deltaUsd` is not a `bigint` and `fallbackToZero` is not set.
```typescript
const delta = expandDecimals(150, USD_DECIMALS);
const pct = expandDecimals(5, 2); // 5% expressed in basis points
formatDeltaUsd(delta, pct); // "+$150.00 (+5.00%)"
formatDeltaUsd(-delta, pct); // "-$150.00 (+5.00%)"
formatDeltaUsd(delta, pct, { hidePercentage: true }); // "+$150.00"
```
#### formatPercentage
```typescript
formatPercentage(
percentage?: bigint,
opts?: {
fallbackToZero?: boolean;
signed?: boolean;
displayDecimals?: number;
bps?: boolean;
showPlus?: boolean;
}
): string | undefined
```
Formats a percentage value. When `bps` is `true` (the default), treats the input as a basis-point-scaled value with 2 decimal places of precision. When `bps` is `false`, treats the input as `PERCENT_PRECISION_DECIMALS`-scaled (28 decimal places).
```typescript
// Input in basis points (bps = true by default)
formatPercentage(525n); // "5.25%"
formatPercentage(525n, { signed: true }); // "+5.25%"
formatPercentage(525n, { displayDecimals: 1 }); // "5.3%"
formatPercentage(undefined, { fallbackToZero: true }); // "0.00%"
```
#### formatRatePercentage
```typescript
formatRatePercentage(rate?: bigint, opts?: { displayDecimals?: number; signed?: boolean }): string
```
Formats a `PRECISION`-scaled rate as a percentage. The `signed` option defaults to `true`, so the result includes `+` or `-` by default. Returns `"-"` if `rate` is not a `bigint`.
```typescript
const rate = expandDecimals(5, 28); // 0.05 PRECISION-scaled (5%)
formatRatePercentage(rate); // "+5.0000%"
formatRatePercentage(rate, { signed: false }); // "5.0000%"
formatRatePercentage(rate, { displayDecimals: 2 }); // "+5.00%"
formatRatePercentage(undefined); // "-"
```
#### formatUsdPrice
```typescript
formatUsdPrice(price?: bigint, opts?: Parameters<typeof formatUsd>[1]): string | undefined
```
Formats a USD price with dynamic decimal precision based on price magnitude (via `calculateDisplayDecimals`). Returns `undefined` for `undefined` input, and `"NA"` for negative prices.
```typescript
formatUsdPrice(expandDecimals(2500, USD_DECIMALS)); // "$2,500.00"
formatUsdPrice(expandDecimals(1, 27)); // "$0.001000" (more decimals for small prices)
formatUsdPrice(undefined); // undefined
formatUsdPrice(-expandDecimals(1, USD_DECIMALS)); // "NA"
```
#### formatPercentageDisplay
```typescript
formatPercentageDisplay(percentage: number, hideThreshold?: number): string
```
Formats a plain JavaScript `number` as a percentage string. Returns an empty string if the value is below `hideThreshold`.
```typescript
formatPercentageDisplay(5.25); // "5.25%"
formatPercentageDisplay(0.5, 1); // "" (hidden, 0.5 < 1)
formatPercentageDisplay(1.0, 1); // "1%" (returned, 1.0 is not < 1)
```
#### formatAmountHuman
```typescript
formatAmountHuman(
amount: BigNumberish | undefined,
tokenDecimals: number,
showDollar?: boolean,
displayDecimals?: number
): string
```
Formats a scaled `bigint` amount as a compact human-readable string using `k`, `m`, or `b` suffixes. Returns `"..."` if `amount` is `undefined`. Default `displayDecimals` is `1`.
```typescript
formatAmountHuman(expandDecimals(1_500_000, 18), 18); // "1.5m"
formatAmountHuman(expandDecimals(2_500_000_000, 18), 18, true); // "$2.5b"
formatAmountHuman(expandDecimals(750, 18), 18); // "750.0"
formatAmountHuman(undefined, 18); // "..."
```
#### formatTokenAmount
```typescript
formatTokenAmount(
amount?: bigint,
tokenDecimals?: number,
symbol?: string,
opts?: {
showAllSignificant?: boolean;
displayDecimals?: number;
fallbackToZero?: boolean;
useCommas?: boolean;
minThreshold?: string;
maxThreshold?: string;
displayPlus?: boolean;
isStable?: boolean;
}
): string | undefined
```
Formats a token amount with an optional symbol. Automatically selects `displayDecimals` based on value magnitude using `calculateDisplayDecimals` unless you override it. Returns `undefined` if input is invalid and `fallbackToZero` is not set.
```typescript
const amount = expandDecimals(1234, 18);
formatTokenAmount(amount, 18, "ETH"); // "1,234.0000 ETH"
formatTokenAmount(amount, 18, "ETH", { isStable: true }); // "1,234.00 ETH"
formatTokenAmount(amount, 18, "ETH", { displayPlus: true }); // "+1,234.0000 ETH"
formatTokenAmount(undefined, 18, "ETH"); // undefined
formatTokenAmount(undefined, 18, "ETH", { fallbackToZero: true }); // "0.0000 ETH"
```
#### formatTokenAmountWithUsd
```typescript
formatTokenAmountWithUsd(
tokenAmount?: bigint,
usdAmount?: bigint,
tokenSymbol?: string,
tokenDecimals?: number,
opts?: { fallbackToZero?: boolean; displayDecimals?: number; displayPlus?: boolean; isStable?: boolean }
): string | undefined
```
Formats a token amount followed by its USD equivalent in parentheses. Returns `undefined` if any required argument is missing and `fallbackToZero` is not set.
```typescript
formatTokenAmountWithUsd(expandDecimals(1, 18), expandDecimals(2500, USD_DECIMALS), "ETH", 18); // "1.0000 ETH ($2,500.00)"
```
#### formatBalanceAmount
```typescript
formatBalanceAmount(
amount: bigint,
tokenDecimals: number,
tokenSymbol?: string,
opts?: { showZero?: boolean; toExponential?: boolean; isStable?: boolean; signed?: boolean }
): string
```
Formats a balance with dynamic decimal precision. Returns `"-"` for zero by default. Switches to exponential notation for values below `1e-8` when `toExponential` is `true` (the default).
```typescript
formatBalanceAmount(expandDecimals(123, 15), 18, "ETH"); // "0.000123 ETH"
formatBalanceAmount(0n, 18, "ETH"); // "-"
formatBalanceAmount(0n, 18, "ETH", { showZero: true }); // "0.0000 ETH"
```
#### formatFactor
```typescript
formatFactor(factor: bigint): string
```
Formats a `PRECISION`-scaled factor as a human-readable string with the minimum decimal places needed to represent the value. For factors larger than `PRECISION * 1000`, it returns the integer quotient.
```typescript
formatFactor(expandDecimals(15, 29)); // "1.5"
formatFactor(expandDecimals(2, 30)); // "2"
formatFactor(0n); // "0"
```
#### numberWithCommas
```typescript
numberWithCommas(x: BigNumberish, opts?: { showDollar?: boolean }): string
```
Adds comma thousand-separators to a number string. Returns `"..."` if the input is `undefined` or `null`.
```typescript
numberWithCommas(1234567); // "1,234,567"
numberWithCommas(1234567.89); // "1,234,567.89"
numberWithCommas(1234567, { showDollar: true }); // "$1,234,567"
```
#### calculateDisplayDecimals
```typescript
calculateDisplayDecimals(
price?: bigint,
decimals?: number,
visualMultiplier?: number,
isStable?: boolean
): number
```
Determines the appropriate number of decimal places to display for a price, based on its magnitude. Defaults to `USD_DECIMALS` (30) for `decimals`. Returns `2` for `undefined` or `0n` inputs. Stable tokens use a different scale that favors more decimal places at smaller values.
```typescript
calculateDisplayDecimals(expandDecimals(2500, USD_DECIMALS)); // 2 (price >= 1000)
calculateDisplayDecimals(expandDecimals(50, USD_DECIMALS)); // 4 (price >= 1)
calculateDisplayDecimals(expandDecimals(1, 27)); // 6 (price >= 0.01)
calculateDisplayDecimals(undefined); // 2 (default)
```
#### getPlusOrMinusSymbol
```typescript
getPlusOrMinusSymbol(value?: bigint, opts?: { showPlusForZero?: boolean }): string
```
Returns `"+"` for positive values, `"-"` for negative values, and `""` for zero. Pass `showPlusForZero: true` to return `"+"` for zero.
```typescript
getPlusOrMinusSymbol(100n); // "+"
getPlusOrMinusSymbol(-100n); // "-"
getPlusOrMinusSymbol(0n); // ""
getPlusOrMinusSymbol(0n, { showPlusForZero: true }); // "+"
getPlusOrMinusSymbol(undefined); // ""
```
### Object serialization
The SDK serializes `bigint` values to JSON-safe objects using a `{ type: "bigint", value: "..." }` envelope. Use these functions when you need to store or transmit SDK state as JSON.
#### serializeBigIntsInObject
```typescript
serializeBigIntsInObject<T extends object>(obj: T): SerializedBigIntsInObject<T>
```
Recursively converts every `bigint` value in an object (or array) to `{ type: "bigint", value: string }`. Non-bigint values are passed through unchanged. The returned type reflects the transformation.
```typescript
const position = { size: 1000000000000000000000000000000n, symbol: "ETH" };
const serialized = serializeBigIntsInObject(position);
// { size: { type: "bigint", value: "1000000000000000000000000000000" }, symbol: "ETH" }
JSON.stringify(serialized); // works — no BigInt serialization error
```
#### deserializeBigIntsInObject
```typescript
deserializeBigIntsInObject<T extends object>(
obj: T,
opts?: { handleInts?: boolean }
): DeserializeBigIntInObject<T>
```
Reverses `serializeBigIntsInObject`, converting `{ type: "bigint", value: string }` envelopes back to native `bigint`. Also handles legacy `{ _type: "BigNumber", hex: string }` format. When `handleInts` is `true`, it also converts plain numeric strings to `bigint`.
```typescript
const stored = { size: { type: "bigint", value: "1000000000000000000000000000000" } };
const position = deserializeBigIntsInObject(stored);
// { size: 1000000000000000000000000000000n }
```
---
## objects
This module exports dictionary helpers used across the SDK.
## Exports
- `setByKey`
- `updateByKey`
- `getByKey`
- `deleteByKey`
- `objectKeysDeep`
- `toDict`
```typescript
```
---
## orders
This module provides utilities for working with GMX orders, including type checking functions, order information processing, and order classification helpers. It handles both swap orders and position orders, including TWAP (Time-Weighted Average Price) orders.
## Methods
This module exports type-check predicates, type-narrowing guards, and data-enrichment helpers for working with GMX orders. Import everything from `@gmx-io/sdk/utils/orders`.
### Order type classification
The following predicates check which broad category an `OrderType` enum value belongs to. Use these to branch logic without hardcoding enum integers.
| Function | Returns `true` for |
| ---------------------------- | ----------------------------------------------------- |
| `isMarketOrderType` | `MarketSwap`, `MarketIncrease`, `MarketDecrease` |
| `isLimitOrderType` | `LimitIncrease`, `LimitSwap`, `StopIncrease` |
| `isTriggerDecreaseOrderType` | `LimitDecrease`, `StopLossDecrease` |
| `isDecreaseOrderType` | `MarketDecrease`, `LimitDecrease`, `StopLossDecrease` |
| `isIncreaseOrderType` | `MarketIncrease`, `LimitIncrease`, `StopIncrease` |
| `isSwapOrderType` | `MarketSwap`, `LimitSwap` |
| `isLimitSwapOrderType` | `LimitSwap` only |
| `isLiquidationOrderType` | `Liquidation` only |
| `isStopLossOrderType` | `StopLossDecrease` only |
| `isLimitDecreaseOrderType` | `LimitDecrease` only |
| `isLimitIncreaseOrderType` | `LimitIncrease` only |
| `isStopIncreaseOrderType` | `StopIncrease` only |
:::note
`isLimitOrderType` includes `StopIncrease` (Stop Market Increase) in addition to `LimitIncrease` and `LimitSwap`. This matches the on-chain classification where stop market increase orders behave like limit orders — they execute when price reaches a trigger level.
:::
```typescript
isMarketOrderType,
isLimitOrderType,
isTriggerDecreaseOrderType,
isDecreaseOrderType,
isIncreaseOrderType,
isSwapOrderType,
isLiquidationOrderType,
} from "@gmx-io/sdk/utils/orders";
isMarketOrderType(OrderType.MarketIncrease); // true
isLimitOrderType(OrderType.LimitIncrease); // true
isLimitOrderType(OrderType.StopIncrease); // true — stop market is treated as limit
isTriggerDecreaseOrderType(OrderType.StopLossDecrease); // true
isDecreaseOrderType(OrderType.MarketDecrease); // true
isIncreaseOrderType(OrderType.LimitIncrease); // true
isSwapOrderType(OrderType.LimitSwap); // true
isLiquidationOrderType(OrderType.Liquidation); // true
```
### `isIncreaseOrderType`
```typescript
function isIncreaseOrderType(
orderType: OrderType
): orderType is OrderType.MarketIncrease | OrderType.LimitIncrease | OrderType.StopIncrease;
```
Type predicate that narrows `OrderType` to one of the three increase variants. Use this in conditional branches where the TypeScript compiler must know the narrowed type.
```typescript
function handleOrder(orderType: OrderType) {
if (isIncreaseOrderType(orderType)) {
// orderType is now typed as MarketIncrease | LimitIncrease | StopIncrease
return buildIncreaseParams(orderType);
}
}
```
### OrderInfo type guards
These functions accept an `OrderInfo` object (enriched order) and narrow its type to a more specific variant. `OrderInfo` is a union of `SwapOrderInfo`, `PositionOrderInfo`, and `TwapOrderInfo`.
| Function | Narrows to |
| -------------------------------- | --------------------------------------------------------------------------------------- |
| `isSwapOrder(orderInfo)` | `SwapOrderInfo` — has `triggerRatio`, `initialCollateralToken`, `targetCollateralToken` |
| `isPositionOrder(orderInfo)` | `PositionOrderInfo` — has `acceptablePrice`, `triggerPrice`, `marketInfo`, `indexToken` |
| `isTwapOrder(orderInfo)` | `Extract<T, { isTwap: true }>` — has `orders[]`, `twapId`, `numberOfParts` |
| `isTwapSwapOrder(orderInfo)` | `TwapOrderInfo<SwapOrderInfo>` |
| `isTwapPositionOrder(orderInfo)` | `TwapOrderInfo<PositionOrderInfo>` |
```typescript
isSwapOrder,
isPositionOrder,
isTwapOrder,
isTwapSwapOrder,
isTwapPositionOrder,
} from "@gmx-io/sdk/utils/orders";
// Route order handling by type
function handleOrderInfo(orderInfo: OrderInfo) {
if (isTwapOrder(orderInfo)) {
// orderInfo.orders — array of individual sub-orders
console.log(`TWAP has ${orderInfo.orders.length} parts`);
} else if (isSwapOrder(orderInfo)) {
console.log("Swap trigger ratio:", orderInfo.triggerRatio);
} else if (isPositionOrder(orderInfo)) {
console.log("Acceptable price:", orderInfo.acceptablePrice);
}
}
```
### `getOrderKeys`
```typescript
function getOrderKeys(order: OrderInfo): string[];
```
Returns all on-chain order keys for an order. TWAP orders have one key per sub-order; regular orders have a single key. Use this when you need to cancel or update all parts of an order without special-casing TWAP.
```typescript
const keys = getOrderKeys(orderInfo);
// Regular order: ["0xabc..."]
// TWAP order with 4 parts: ["0xabc...", "0xdef...", "0x123...", "0x456..."]
```
### `getOrderInfo`
```typescript
function getOrderInfo(p: {
marketsInfoData: MarketsInfoData;
tokensData: TokensData;
wrappedNativeToken: Token;
order: Order;
}): OrderInfo | undefined;
```
Enriches a raw `Order` (as returned by the contract reader) into an `OrderInfo` with resolved token data, market info, computed swap path stats, trigger ratios, and parsed prices. Returns `undefined` if required tokens or market data are missing from the supplied data maps.
#### Parameters
| Parameter | Type | Description |
| -------------------- | ----------------- | ------------------------------------------------- |
| `marketsInfoData` | `MarketsInfoData` | Map of market address → `MarketInfo` |
| `tokensData` | `TokensData` | Map of token address → `TokenData` with prices |
| `wrappedNativeToken` | `Token` | Wrapped native token (for unwrap path resolution) |
| `order` | `Order` | Raw order object from contract |
:::warning
`getOrderInfo` returns `undefined` when any required lookup fails — for example, when the initial collateral token or target collateral token is not present in `tokensData`, or when the market is not in `marketsInfoData`. Always check the return value before accessing fields.
:::
```typescript
const orderInfo = getOrderInfo({
marketsInfoData,
tokensData,
wrappedNativeToken,
order: rawOrder,
});
if (!orderInfo) {
// Token or market data not loaded yet — retry when data is available
return;
}
console.log("Trigger price:", orderInfo.triggerPrice);
```
### `isVisibleOrder`
```typescript
function isVisibleOrder(orderType: OrderType): boolean;
```
Returns `true` if the order type is one that a user would see in a position or orders list. Returns `true` for all market orders, limit orders, limit swap orders, and trigger decrease orders. Returns `false` for `Liquidation` (which is a keeper action, not a user order).
```typescript
isVisibleOrder(OrderType.LimitIncrease); // true
isVisibleOrder(OrderType.MarketDecrease); // true
isVisibleOrder(OrderType.Liquidation); // false — liquidations are not user-visible
```
### `isOrderForPosition`
```typescript
function isOrderForPosition(order: OrderInfo, positionKey: string): order is PositionOrderInfo;
```
Returns `true` if the order belongs to the position identified by `positionKey`, and narrows the type to `PositionOrderInfo`. The collateral address check differs by order type: limit increase orders match on `targetCollateralToken`, while trigger decrease orders match on `initialCollateralTokenAddress`.
```typescript
const positionOrders = orders.filter((o) => isOrderForPosition(o, positionKey));
// positionOrders is now typed as PositionOrderInfo[]
```
### `isOrderForPositionByData`
```typescript
function isOrderForPositionByData(
order: OrderInfo,
params: {
account: string;
marketAddress: string;
collateralAddress: string;
isLong: boolean;
}
): order is PositionOrderInfo;
```
Same matching logic as `isOrderForPosition` but accepts explicit position data instead of a position key string. Use this when you have individual position fields rather than a composed key.
#### Parameters
| Parameter | Type | Description |
| ------------------- | ----------- | ------------------------- |
| `order` | `OrderInfo` | Enriched order to check |
| `account` | `string` | Trader account address |
| `marketAddress` | `string` | Market contract address |
| `collateralAddress` | `string` | Collateral token address |
| `isLong` | `boolean` | `true` for long positions |
```typescript
const isMatch = isOrderForPositionByData(orderInfo, {
account: "0x1234567890123456789012345678901234567890",
marketAddress: "0xFD70de6b91282D8017aA4E741e9Ae325CAb992d8",
collateralAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
isLong: true,
});
```
### `getOrderTradeboxKey`
```typescript
function getOrderTradeboxKey(order: OrderInfo): string;
```
Returns a stable string key for deduplicating orders by position in UI state. Position orders (including TWAP position orders) use the format `POSITION-{account}:{marketAddress}:{collateralAddress}:{isLong}`. Swap orders use `SWAP-{account}:{initialCollateralTokenAddress}:{targetCollateralToken.address}`.
```typescript
const key = getOrderTradeboxKey(orderInfo);
// Position order example:
// "POSITION-0x1234...5678:0xFD70...2d8:0x82aF...bab1:true"
// Swap order example:
// "SWAP-0x1234...5678:0x82aF...bab1:0xFF97...cf5"
```
### API data fetching
#### `fetchApiOrders`
```typescript
fetchApiOrders(ctx: { api: IHttp }, params: {
address: string;
}): Promise<ApiOrderInfo[]>
```
Fetches order data from the GMX API instead of on-chain multicalls. Available on chains where `isApiSupported(chainId)` returns `true` (Arbitrum, Avalanche, and Arbitrum Sepolia). The response is deserialized with `deserializeBigIntsInObject`.
```typescript
const apiSdk = new GmxApiSdk({ chainId: 42161 });
const orders = await fetchApiOrders(apiSdk.ctx, { address: "0x1234...5678" });
```
## Related
- [`utils/prices`](./prices.md) — `getOrderThresholdType`, trigger price logic
- [`utils/trade/increase`](./trade/increase.md) — building increase position order params
- [`utils/trade/decrease`](./trade/decrease.md) — bui프로젝트로 돌아가기