bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 22쪽
ithdrawal
```typescript
const depositTxHash = await sdk.executeSameChainDeposit(signer, {
tokenAddress: arbitrumUsdc.address,
amount: 1_000_000n,
account,
});
const bridgeOutParams = sdk.buildSameChainWithdrawBridgeOutParams({
tokenAddress: arbitrumUsdc.address,
amount: 500_000n,
});
const withdrawTxHash = await sdk.executeSameChainWithdraw(signer, {
bridgeOutParams,
});
```
### Cross-chain deposit
```typescript
await sdk.executeErc20Approve(sourceSigner, {
tokenAddress: baseUsdc.address,
spender: baseUsdc.stargate,
amount: 1_000_000n,
});
const deposit = await sdk.executeCrossChainDeposit(sourceSigner, {
srcChainId: SOURCE_BASE_MAINNET,
account,
tokenSymbol: baseUsdc.symbol,
amount: 1_000_000n,
});
```
### Cross-chain withdrawal
```typescript
const bridgeOutParams = sdk.buildCrossChainWithdrawBridgeOutParams({
tokenAddress: arbitrumUsdc.address,
amount: 500_000n,
dstChainId: SOURCE_BASE_MAINNET,
stargateAddress: arbitrumUsdc.stargate,
slippageBps: 5,
});
const submitted = await sdk.executeCrossChainWithdraw(signer, {
srcChainId: SOURCE_BASE_MAINNET,
account,
bridgeOutParams,
});
const status = await sdk.getCrossChainWithdrawStatus(submitted.requestId);
```
### Manual cross-chain withdrawal
```typescript
const prepared = await sdk.prepareCrossChainWithdraw({
srcChainId: SOURCE_BASE_MAINNET,
account,
bridgeOutParams,
});
const signature = await sdk.signCrossChainWithdraw(prepared, signer);
const submitted = await sdk.submitCrossChainWithdraw({
srcChainId: SOURCE_BASE_MAINNET,
account,
signature,
bridgeOutParams,
relayParamsPayload: prepared.payload.relayParams,
relayerFeeTokenAddress: prepared.payload.gasPaymentParams.relayerFeeTokenAddress,
relayerFeeAmount: prepared.payload.gasPaymentParams.relayerFeeAmount,
requestId: prepared.requestId,
});
```
## Type reference
Use these tables as a compact reference for the public transaction types used by the examples above.
### PrepareOrderRequest
| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `kind` | `"increase" \| "decrease" \| "swap"` | Yes | |
| `symbol` | `string` | Yes | Market symbol, for example, `"ETH/USD [WETH-USDC]"` |
| `direction` | `"long" \| "short"` | For increase/decrease | |
| `orderType` | `"market" \| "limit" \| "stop-market" \| "take-profit" \| "stop-loss" \| "twap"` | Yes | |
| `size` | `bigint` | Yes | USD value with 30 decimals for positions; token decimals for swaps |
| `triggerPrice` | `bigint` | For limit/conditional | SDK/API input uses 30-decimal USD precision. Raw contract/order data stores the converted contract price: `price30 / 10 ** indexTokenDecimals`. |
| `slippage` | `number` | No | Basis points |
| `collateralToken` | `string` | No | Token symbol for position collateral |
| `collateralToPay` | `{ amount: bigint, token: string }` | For increase/swap | Token amount in native decimals |
| `receiveToken` | `string` | For swap/decrease | Token symbol to receive |
| `keepLeverage` | `boolean` | No | For decrease — withdraw collateral proportionally |
| `manualSwapPath` | `string[]` | No | Override auto swap path with market addresses |
| `acceptablePriceImpactBps` | `bigint` | No | Acceptable price impact in basis points |
| `executionFeeBufferBps` | `number` | No | Execution fee buffer in basis points |
| `uiFeeReceiver` | `string` | No | UI fee receiver address; for TWAP orders, the API copies it to every part |
| `twapConfig` | `{ duration: number, parts: number, frequency?: number }` | For TWAP | `parts` must be a safe integer from 2 through 30, and `duration` is in seconds. The published type exposes `frequency`, but the production API derives the schedule from `duration` and `parts`. |
| `tpsl` | `Array<{ type, triggerPrice, size? }>` | No | TP/SL sidecar orders (increase only) |
| `gasPaymentToken` | `string` | No | Token for gas payment |
| `referralCode` | `string` | No | Human-readable referral code or encoded `bytes32`; human-readable codes support letters, digits, and underscores, up to 20 characters |
| `mode` | `"express" \| "classic"` | Yes | |
| `from` | `string` | Yes | Main account or order owner address; also the transaction sender in Classic Trading |
| `subaccountAddress` | `string` | No | Express Trading subaccount address; pass it with `subaccountApproval` |
| `subaccountApproval` | `object` | No | Express Trading approval payload; required when `subaccountAddress` is set |
### PrepareOrderResponse
| Field | Type | Description |
|-------|------|-------------|
| `requestId` | `string` | Request identifier used for signing, submission, and status polling |
| `idempotencyKey` | `string?` | Idempotency key returned by the API, when available |
| `payloadType` | `"transaction" \| "typed-data"` | Whether the prepared payload is a classic transaction or EIP-712 typed data |
| `mode` | `"express" \| "classic"` | Transaction mode requested during preparation |
| `payload` | `Record<string, any>` | Prepared transaction or typed-data payload |
| `estimates` | `OrderEstimates?` | Fee, impact, and acceptable-price estimates |
| `expiresAt` | `number?` | Unix timestamp when the prepared payload expires |
| `warnings` | `string[]?` | Non-blocking API warnings for the prepared order |
| `validationWarnings` | `OrderValidationWarning[]?` | Structured capacity warnings such as `INSUFFICIENT_LIQUIDITY` or `TRADING_CAPACITY_UNAVAILABLE` |
| `traceId` | `string?` | API trace identifier for support and debugging |
### SubmitOrderResponse
| Field | Type | Description |
|-------|------|-------------|
| `requestId` | `string` | Request identifier |
| `status` | `string` | See status values above |
| `txHash` | `string?` | Relay transaction hash |
| `taskId` | `string?` | GMX Relay task identifier, when relay submission creates one |
| `error` | `{ code, message }?` | Error details |
| `traceId` | `string?` | API trace identifier for support and debugging |
### OrderEstimates
Returned in `prepared.estimates`:
| Field | Type | Description |
|-------|------|-------------|
| `sizeDeltaUsd` | `bigint` | Effective position size delta after full-close adjustment (30 decimals); it can differ from the requested size |
| `executionFeeAmount` | `bigint` | Execution fee in gas token |
| `positionFeeUsd` | `bigint` | Position fee (30 decimals) |
| `acceptablePrice` | `bigint` | Worst acceptable execution price (30 decimals) |
| `positionPriceImpactDeltaUsd` | `bigint` | Position price impact (30 decimals) |
| `swapPriceImpactDeltaUsd` | `bigint` | Swap price impact (30 decimals) |
| `borrowingFeeUsd` | `bigint` | Borrowing fee (30 decimals) |
| `fundingFeeUsd` | `bigint` | Funding fee (30 decimals) |
| `tradingCapacity` | `TradingCapacity?` | Capacity used to validate the requested market side, when available |
### Prepare-order errors
`parsePrepareOrderError(error)` parses a caught `HttpError` with status `400` into a `PrepareOrderError`. `isPrepareOrderError(value)` validates an already deserialized unknown value. Both helpers are exported from `@gmx-io/sdk/v2`.
```typescript
async function prepare(request: PrepareOrderRequest) {
try {
return await sdk.prepareOrder(request);
} catch (error) {
const prepareError = parsePrepareOrderError(error);
if (prepareError?.code === "INSUFFICIENT_LIQUIDITY") {
console.log(prepareError.details.availableLiquidity);
console.log(prepareError.details.requestedSizeUsd);
}
throw error;
}
}
```
The prepare runtime can also return `INSUFFICIENT_COLLATERAL` when the remaining collateral would fall below the on-chain minimum, including for an individual TWAP part. This code isn't yet declared in the exported `PrepareOrderError` union, so handle it as a raw `400` application error until the public type is aligned.
### OrderStatusResponse
| Field | Type | Description |
|-------|------|-------------|
| `requestId` | `string` | Request identifier |
| `status` | `string` | See status values above |
| `txHash` | `string?` | Relay transaction hash |
| `createdTxnHash` | `string?` | On-chain order creation tx |
| `executionTxnHash` | `string?` | On-chain execution tx |
| `orderKeys` | `string[]?` | Created order keys |
| `cancellationReason` | `string?` | Why the order was cancelled |
| `taskId` | `string?` | GMX Relay task identifier, when available |
| `error` | `{ code, message }?` | Error details |
| `createdAt` | `string?` | API creation timestamp |
| `updatedAt` | `string?` | API update timestamp |
| `traceId` | `string?` | API trace identifier for support and debugging |
---
## Getting Started
Use SDK v2 when you want HTTP-backed GMX data or API-relayed order workflows without wiring RPC, oracle, or Subsquid connections yourself.
Install the shared SDK package first:
```bash
npm install @gmx-io/sdk
```
Then import the client from the `v2` subpath:
```typescript
const apiSdk = new GmxApiSdk({ chainId: 42161 }); // Arbitrum
const markets = await apiSdk.fetchMarkets();
const marketsInfo = await apiSdk.fetchMarketsInfo();
const marketsConfig = await apiSdk.fetchMarketsConfig();
const marketsValues = await apiSdk.fetchMarketsValues();
const tickers = await apiSdk.fetchMarketsTickers({
symbols: ["BTC/USD [BTC-USDC]"],
});
const tokens = await apiSdk.fetchTokens();
const tokensData = await apiSdk.fetchTokensData();
const pairs = await apiSdk.fetchPairs();
const rates = await apiSdk.fetchRates({ period: "7d" });
const apy = await apiSdk.fetchApy({ period: "7d" });
const annualized = await apiSdk.fetchPerformanceAnnualized({
period: "30d",
});
const snapshots = await apiSdk.fetchPerformanceSnapshots({
period: "30d",
});
const positions = await apiSdk.fetchPositionsInfo({
address: "0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33",
includeRelatedOrders: true,
});
const orders = await apiSdk.fetchOrders({
address: "0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33",
});
const trades = await apiSdk.fetchTrades({
address: "0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33",
limit: 20,
});
const jitLiquidity = await apiSdk.fetchJitLiquidityInfo({ apiVersion: "v2" });
const candles = await apiSdk.fetchOhlcv({
symbol: "BTC",
timeframe: "1h",
limit: 100,
});
```
`GmxApiSdk` calls the GMX API directly — no RPC endpoint, oracle URL, or Subsquid URL required. It supports active mainnet integrations on Arbitrum, Avalanche, and MegaETH, plus Arbitrum Sepolia for testing. The constructor throws for unsupported chains.
If your app switches chains dynamically, prefer `isApiSupported(chainId)`, `getApiUrl(chainId)`, and `getApiFallbackUrls(chainId)` from `@gmx-io/sdk/configs/api` instead of hardcoding API hosts.
### GMX API deployment
The GMX API deployment exposes independent peer base URLs such as `https://{chain}.gmxapi.io/v1` and `https://{chain}.gmxapi.ai/v1`. `GmxApiSdk` builds an `HttpClientWithFallback` from the primary URL returned by `getApiUrl(chainId)` and any peers configured by `getApiFallbackUrls(chainId)`.
Fallback lists are configuration, not a fixed SDK guarantee. In the current published `latest`, `2.2.1`, the packaged list is empty for every chain, so `HttpClientWithFallback` runs against a single host unless you supply the peer. If your integration requires peer failover, pass the second host explicitly and monitor both in your own HTTP layer.
Arbitrum Sepolia uses a separate test host returned by `getApiUrl(421614)`. Test hosts can change, so use the exported helper instead of hardcoding the URL.
`@gmx-io/sdk/v2` is an import path inside the `@gmx-io/sdk` package, not a separate npm package.
If you're using CommonJS, require the v2 client from the `v2` subpath:
```javascript
const { GmxApiSdk } = require("@gmx-io/sdk/v2");
const apiSdk = new GmxApiSdk({ chainId: 42161 });
```
TypeScript subpath resolution is supported for `@gmx-io/sdk/v2` and the SDK's utility, config, ABI, and type-only entrypoints.
## What SDK v2 covers today
| Workflow | Status | Notes |
| -------- | ------ | ----- |
| Read market catalogs, configuration, values, tickers, trading capacity, and token data over HTTP | ✅ | Available through `fetchMarkets()`, `fetchMarketsInfo()`, `fetchMarketsConfig()`, `fetchMarketsValues()`, `fetchMarketsTickers()`, `getTradingCapacity()`, `fetchTokens()`, and `fetchTokensData()` |
| Read pairs, rates, APY, performance, GM pool yield/PnL analytics, and GM LP fee earnings over HTTP | ✅ | Available through `fetchPairs()`, `fetchRates()`, `fetchApy()`, `fetchPerformanceAnnualized()`, `fetchPerformanceSnapshots()`, `fetchGmPoolYieldPnl()`, and `fetchGmUserEarnings()` |
| Read one account's positions and orders over HTTP | ✅ | Available through `fetchPositionsInfo()` and `fetchOrders()` |
| Read trade history over HTTP | ✅ | Available through `fetchTrades()` and `searchTrades()` |
| Read OHLCV candles over HTTP | ✅ | Available through `fetchOhlcv()` |
| Read protocol buyback stats over HTTP | ✅ | Available through `fetchBuybackWeeklyStats()` |
| Read protocol-wide stats over HTTP | ✅ | Available through the standalone `fetchApiProtocolStatsSummary()`, `fetchApiProtocolStatsTimeseries()`, and `fetchApiProtocolStatsSources()` exports. See [Protocol stats helpers](#protocol-stats-helpers) |
| Read JIT liquidity over HTTP | ✅ | Available through `fetchJitLiquidityInfo()` |
| Read staking power over HTTP | ✅ | Available through `fetchStakingPower()` |
| Read USDC and USDG conversion routes, fee tiers, quotes, and orders over HTTP | ✅ | Available on Arbitrum through `fetchTransitRoutes()`, `fetchTransitFeeTier()`, `fetchTransitAuthorization()`, `fetchTransitQuote()`, `fetchTransitOrder()`, and `fetchTransitOrders()` |
| Read deposit whitelists and the USDG launch boost rate over HTTP | ✅ | Available through `fetchWhitelists()` and `fetchUsdgBoostApr()` |
| Read wallet balances and allowances over HTTP | ✅ | Available through `fetchWalletBalances()` and `fetchAllowances()` |
| Build approval transaction calldata | ✅ | Available through `buildApproveTransaction()`, `buildErc20ApproveTxn()`, and `executeErc20Approve()` |
| GMX Account deposits and withdrawals | ✅ | Available through same-chain deposit/withdraw helpers and cross-chain deposit/withdraw helpers |
| Submit, edit, cancel, or track orders | ✅ | Signed order intents are posted to the GMX API, which submits express orders through GMX Relay. [SDK v1](../v1/readme.mdx) and direct contracts remain available for integrations that prefer RPC. |
| One-click-trading subaccount helpers | ✅ | Available through `generateSubaccount()`, `activateSubaccount()`, `refreshSubaccountState()`, `clearSubaccount()`, `fetchSubaccountStatus()`, `prepareSubaccountApproval()`, and `signSubaccountApproval()` |
See [Order Examples](./examples.md) for runnable code showing how to open, close, edit, cancel, and track orders, including TP/SL, TWAP, classic mode, and one-click trading flows.
Use [SDK Overview](../overview.md) if you want a quick capability comparison before wiring an integration.
## Methods
`GmxApiSdk` exposes the following methods. All of them call the GMX API directly -- no RPC, oracle, or Subsquid connection is required.
| Method | Parameters | Returns | Notes |
| ------ | ---------- | ------- | ----- |
| `fetchMarkets()` | -- | `MarketWithTiers[]` | Market catalog data from `/markets` |
| `fetchMarketsInfo()` | -- | `RawMarketInfo[]` | Market definitions and pricing from `/markets/info` |
| `fetchMarketsConfig()` | -- | `RawMarketConfig[]` | Slower-changing market configuration from `/markets/config` |
| `fetchMarketsValues()` | -- | `RawMarketValues[]` | Frequently changing market state from `/markets/values`; each row includes its least-recent component timestamp in `updatedAt` |
| `fetchMarketsTickers(params?)` | `addresses?: string[]`, `symbols?: string[]` | `MarketTickerWithCapacity[]` | Filterable market tickers from `/markets/tickers`, each optionally carrying JIT-aware `capacityLong`/`capacityShort` |
| `getTradingCapacity(params)` | `symbol: string`, `direction: "long" \| "short"` | `TradingCapacity` | Validated capacity for one market side from `/markets/trading-capacity` |
| `fetchTokens()` | -- | `Token[]` | Static token catalog from `/tokens` |
| `fetchTokensData()` | -- | `TokenData[]` | Token metadata and current prices from `/tokens/info` |
| `fetchPairs()` | -- | `Pair[]` | Pair-level summary data from `/pairs` |
| `fetchRates(params?)` | `period?: ApiParameterPeriod`, `averageBy?: "1d" \| "7d" \| "30d"`, `address?: string` | `MarketRates[]` | Hourly funding and borrowing rate snapshots from `/rates`. For near-live rates, use `/markets/info` or `fetchMarketsInfo()` instead |
| `fetchApy(params?)` | `period?: ApiParameterPeriod` | `ApyResponse` | Market and GLV APY data from `/apy` |
| `fetchPerformanceAnnualized(params?)` | `period?: ApiParameterPeriod`, `address?: string` | `PerformanceAnnualized[]` | Annualized performance summaries from `/performance/annualized` |
| `fetchPerformanceSnapshots(params?)` | `period?: ApiParameterPeriod`, `address?: string` | `PerformanceSnapshots[]` | Historical performance snapshot series from `/performance/snapshots` |
| `fetchGmPoolYieldPnl(params?)` | `pools?: string[]`, `period?: ApiParameterPeriod`, `includeComponents?: boolean` | `GmPoolsYieldPnlResponse` | Fee-only APY plus trader-perspective PnL per GM pool from `/yield/gm-pools` |
| `fetchGmUserEarnings(params)` | `account: string` | `GmUserEarningsResponse` | Lifetime and 7-day fee earnings (`lifetimeFeeUsd`, `recent7dFeeUsd`, 30-decimal USD strings) for each GM pool an LP account has held, from `/yield/gm-user-earnings`. Only GM held in the wallet on this chain counts; GM in a GMX Account or bridged to another chain doesn't |
| `fetchPositionsInfo(params)` | `address: string`, `includeRelatedOrders?: boolean` | `ApiPositionInfo[]` | Position objects for an address; optionally includes related orders |
| `fetchOrders(params)` | `address: string` | `ApiOrderInfo[]` | Active order objects for an address |
| `fetchTrades(params)` | `address: string`, `symbol?: string`, `marketAddress?: string`, `since?: number`, `until?: number`, `actions?: TradeEventName[]`, `limit?: number`, `cursor?: string` | `TradesListResponse` | Account trade history from `/trades`. `since` and `until` are Unix timestamps in whole seconds; the API returns `400` for fractional or millisecond values |
| `searchTrades(params)` | `address?: string`, `forAllAccounts?: boolean`, `fromTimestamp?: number`, `toTimestamp?: number`, `marketsDirections?: MarketDirectionFilter[]`, `orderEventCombinations?: OrderEventCombination[]`, `showDebugValues?: boolean`, `limit?: number`, `cursor?: string` | `TradesListResponse` | Advanced trade-history search from `/trades/search`. `fromTimestamp` and `toTimestamp` are also whole seconds |
| `fetchOhlcv(params)` | `symbol: string`, `timeframe: string`, `limit?: number`, `since?: number` | `OhlcvCandle[]` | OHLCV candle data from `/prices/ohlcv`. Pass a token symbol such as `"BTC"` or a full market symbol such as `"BTC/USD [BTC-USDC]"`; `"BTC/USD"` returns `400`. `since` and each candle's `timestamp` are in milliseconds |
| `fetchBuybackWeeklyStats()` | -- | `BuybackWeeklyStatsResponse` | Weekly (`weeks`) and monthly (`months`) buyback accrual data and a cumulative summary from `/buyback/weekly-stats` |
| `fetchJitLiquidityInfo(params?)` | `apiVersion?: "v1" \| "v2"` | `JitLiquidityMap` | JIT liquidity map from `/v2/jit/liquidity_info`. Pass `apiVersion: "v2"`: the legacy `/v1/jit/liquidity_info` route is no longer served. To size an increase, use `getTradingCapacity()` instead |
| `fetchStakingPower(params)` | `address: string` | `StakingPowerResponse` | Staking power, loyalty ratio, and reward share data for an address from `/staking/power` |
| `fetchTransitRoutes(params?)` | `filter?: string`, `feeTier?: TransitFeeTier` | `TransitRoute[]` | Paxos conversion routes, each with its `sourceChainId`, `destinationChainId`, `offerAsset`, `wantAsset`, and `minOrderSize`, from `/paxos/transit/routes`. The list isn't limited to USDC and USDG on Arbitrum: it also includes ot프로젝트로 돌아가기