bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 8쪽
Record<string, Address>>;
```
A complete mapping of chain IDs to contract addresses for all GMX protocol contracts.
`CONTRACTS` covers five chain IDs:
| Chain | Chain ID | Type |
| ---------------- | -------- | --------------------- |
| Arbitrum | `42161` | Production |
| Avalanche | `43114` | Production |
| MegaETH | `4326` | Production |
| Avalanche Fuji | `43113` | Development / testnet |
| Arbitrum Sepolia | `421614` | Development / testnet |
Contract categories vary by chain. Production chains Arbitrum and Avalanche include both V1 contracts (Vault, GLP, staking trackers) and V2 Synthetics contracts (DataStore, ExchangeRouter, SimulationRouter, SyntheticsReader, GLV router, and Multichain routers). MegaETH and the testnet chains include V2 Synthetics contracts only, with V1 slots set to `zeroAddress`.
```typescript
// Get the DataStore address on Arbitrum
const dataStoreAddress = CONTRACTS[42161].DataStore;
// Returns: "0xFD70de6b91282D8017aA4E741e9Ae325CAb992d8"
// Get the ExchangeRouter address on Avalanche
const exchangeRouterAddress = CONTRACTS[43114].ExchangeRouter;
// Returns: "0xc002Db96E682FFF6675966F959677285a0C45Efa"
// Iterate all production chains
for (const chainId of CONTRACTS_CHAIN_IDS) {
const router = CONTRACTS[chainId].ExchangeRouter;
console.log(`ExchangeRouter on ${chainId}: ${router}`);
}
```
:::tip
Prefer `getContract` over direct `CONTRACTS` indexing in application code. It provides a typed lookup and throws a descriptive error if the chain ID or contract name is not found, making integration bugs easier to diagnose.
:::
## Types
### `ContractName`
```typescript
type ContractName = ExtractContractNames<typeof CONTRACTS>;
// resolves to: "DataStore" | "ExchangeRouter" | "SyntheticsReader" | "Vault" | ...
```
A union of every contract key name defined across all chains in `CONTRACTS`. The type is derived automatically from the `CONTRACTS` object, so it stays in sync with the source without manual maintenance.
```typescript
// Valid: "DataStore" is a key in CONTRACTS
const name: ContractName = "DataStore";
// Also valid
const names: ContractName[] = ["ExchangeRouter", "SimulationRouter", "SyntheticsReader", "GlvRouter"];
```
`ContractName` includes all contract keys from all chains, including V1-only contracts (such as `"Vault"`, `"GlpManager"`) and V2-only contracts (such as `"DataStore"`, `"GlvRouter"`). Some contracts are set to `zeroAddress` on chains where they are not deployed — use `getContract` to retrieve the address and check the result before use if the contract may not be active on a given chain.
## Methods
### `getContract`
```typescript
function getContract(chainId: ContractsChainId, name: ContractName): Address;
```
Retrieves a specific contract address for a given chain ID and contract name.
#### Parameters
| Parameter | Type | Description |
| --------- | ------------------ | ---------------------------------------------------------------------- |
| `chainId` | `ContractsChainId` | The numeric chain ID (42161, 43114, 4326, 43113, or 421614) |
| `name` | `ContractName` | The contract name key (for example, `"DataStore"`, `"ExchangeRouter"`) |
#### Returns
`Address` — the checksummed hex address string for the contract on the given chain.
:::warning
`getContract` throws an `Error` if `chainId` is not in `CONTRACTS` or if `name` is not found for that chain. Always call with a valid `ContractsChainId` value.
:::
```typescript
// Get DataStore on Arbitrum
const dataStoreAddress = getContract(ARBITRUM, "DataStore");
// Returns: "0xFD70de6b91282D8017aA4E741e9Ae325CAb992d8"
// Get ExchangeRouter on Avalanche
const exchangeRouterAddress = getContract(AVALANCHE, "ExchangeRouter");
// Returns: "0xc002Db96E682FFF6675966F959677285a0C45Efa"
// Use with a dynamic chain ID (validated at runtime)
function lookupContract(chainId: number, name: ContractName): Address | null {
try {
return getContract(chainId as ContractsChainId, name);
} catch {
return null;
}
}
```
### `tryGetContract`
```typescript
function tryGetContract(chainId: ContractsChainId, name: ContractName): Address | undefined;
```
Returns the same address as `getContract`, or `undefined` when the chain or contract name is not configured. Use it for optional capabilities such as `SimulationRouter` without implementing your own `try`/`catch` wrapper.
```typescript
const simulationRouter = tryGetContract(ARBITRUM, "SimulationRouter");
if (simulationRouter) {
console.log(`SimulationRouter: ${simulationRouter}`);
}
```
## Related
- [`chains`](./chains.md) — chain IDs, `ContractsChainId`, `ContractsChainIdProduction`
- [SDK v1 Getting Started](../../readme.mdx)
---
## dataStore
This module is the SDK's public registry of GMX `DataStore` key constants and key-builder helpers.
## What it exports
- Static hashed keys such as `MIN_COLLATERAL_USD_KEY`, `MAX_AUTO_CANCEL_ORDERS_KEY`, `MAX_COLLATERAL_SUM_KEY`, `MIN_FUNDING_INCREASE_RATE_PER_SECOND`, `USE_OPEN_INTEREST_IN_TOKENS_FOR_BALANCE`, `VIRTUAL_INVENTORY_FOR_POSITIONS_IN_TOKENS_KEY`, and `REQUEST_EXPIRATION_TIME_KEY`
- Dynamic key builders such as `positionImpactFactorKey`, `swapFeeFactorKey`, `poolAmountKey`, `maxCollateralSumKey`, `minFundingIncreaseRatePerSecondKey`, `virtualInventoryForPositionsInTokensKey`, `accountOrderListKey`, `uiFeeFactorKey`, `hashedPositionKey`, and `claimTermsKey`
```typescript
MAX_COLLATERAL_SUM_KEY,
MAX_AUTO_CANCEL_ORDERS_KEY,
maxCollateralSumKey,
minFundingFactorPerSecondKey,
minFundingIncreaseRatePerSecondKey,
positionImpactFactorKey,
poolAmountKey,
uiFeeFactorKey,
virtualInventoryForPositionsInTokensKey,
} from "@gmx-io/sdk/configs/dataStore";
```
Funding bounds are side-specific: `minFundingFactorPerSecondKey(market, isLong)` and `maxFundingFactorPerSecondKey(market, isLong)` include the position side in the derived key.
Use this module when you need to read or derive raw `DataStore` keys for multicalls or contract debugging. The entrypoint is large by design because it mirrors the on-chain key layout.
---
## express
This module exports constants and helpers for Express Trading, subaccounts, and relay flows.
## Exports
This module provides constants and helper functions for Express Trading integrations.
### Constants
- `DEFAULT_SUBACCOUNT_EXPIRY_DURATION` -- default One-Click Trading session length (7 days)
- `DEFAULT_SUBACCOUNT_MAX_ALLOWED_COUNT` -- maximum allowed subaccount count (90)
- `DEFAULT_PERMIT_DEADLINE_DURATION` -- default ERC-20 permit deadline (1 hour)
- `DEFAULT_EXPRESS_ORDER_DEADLINE_DURATION` -- default express order deadline (1 hour)
- `EXPRESS_EXTRA_EXECUTION_FEE_BUFFER_BPS` -- extra execution fee buffer in basis points (1000 bps)
```typescript
```
### Helper functions
#### `getGasPaymentTokens`
```typescript
getGasPaymentTokens(chainId: number): string[]
```
Returns the list of token addresses accepted for gas payment on the given chain. For example, on Arbitrum this returns the addresses of USDC, WETH, and USDT.
#### `getDefaultGasPaymentToken`
```typescript
getDefaultGasPaymentToken(chainId: number): string
```
Returns the default gas payment token address for the given chain. For active chains, this is the first token in the gas payment list: USDC on Arbitrum and Avalanche, and USDM on MegaETH.
#### `getRelayerFeeToken`
```typescript
getRelayerFeeToken(chainId: number): Token
```
Returns the wrapped native token for the given chain. The relayer fee is denominated in this token.
```typescript
const gasTokens = getGasPaymentTokens(42161); // Arbitrum gas payment token addresses
const defaultToken = getDefaultGasPaymentToken(42161); // USDC address on Arbitrum
```
Use this module only if your integration exposes express or subaccount flows directly.
---
## factors
This module provides constants for various impact thresholds, slippage limits, and basis point calculations used throughout the GMX protocol. These factors help determine when to show warnings to users and set default acceptable limits for trading operations.
## Constants
The following constants are exported from `@gmx-io/sdk/configs/factors`. All numeric values represent basis points unless otherwise noted.
- `USD_DECIMALS: number` — Number of decimal places for USD values (30)
```typescript
const oneDollar = 10n ** BigInt(USD_DECIMALS);
```
- `BASIS_POINTS_DIVISOR: number` — Divisor for basis points calculations (10000)
```typescript
const percentage = (basisPoints / BASIS_POINTS_DIVISOR) * 100;
```
- `BASIS_POINTS_DIVISOR_BIGINT: bigint` — BigInt version of the basis points divisor (10000n)
```typescript
const percentageBigInt = (basisPointsBigInt * 100n) / BASIS_POINTS_DIVISOR_BIGINT;
```
- `BASIS_POINTS_DECIMALS: number` — Number of decimal places for basis points (4)
```typescript
const formattedBps = basisPoints.toFixed(BASIS_POINTS_DECIMALS);
```
- `HIGH_PRICE_IMPACT_BPS: number` — Threshold for high price impact warning (80 basis points = 0.8%)
```typescript
if (priceImpactBps > HIGH_PRICE_IMPACT_BPS) {
console.warn("High price impact detected");
}
```
- `HIGH_COLLATERAL_IMPACT_BPS: number` — Threshold for high collateral impact warning (2500 basis points = 25%)
```typescript
if (collateralImpactBps > HIGH_COLLATERAL_IMPACT_BPS) {
console.warn("High collateral impact");
}
```
- `HIGH_SWAP_IMPACT_BPS: number` — Threshold for high swap impact warning (50 basis points = 0.5%)
```typescript
const showSwapWarning = swapImpactBps > HIGH_SWAP_IMPACT_BPS;
```
- `DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER: number` — Default buffer for acceptable price impact (30 basis points = 0.3%)
```typescript
const maxAcceptableImpact = priceImpact + DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER;
```
- `HIGH_ALLOWED_SWAP_SLIPPAGE_BPS: number` — Threshold for high swap slippage (20 basis points = 0.2%)
```typescript
if (slippageBps > HIGH_ALLOWED_SWAP_SLIPPAGE_BPS) {
console.warn("High slippage tolerance");
}
```
- `DEFAULT_ALLOWED_SWAP_SLIPPAGE_BPS: bigint` — Default allowed swap slippage (100 basis points = 1%)
```typescript
const slippageTolerance = DEFAULT_ALLOWED_SWAP_SLIPPAGE_BPS;
```
---
## fees
This module exposes shared fee configuration constants and residual gas helpers used by order and Express Trading flows.
## Constants
### Residual gas defaults
These constants define the default USD bounds the SDK keeps available for future network fees after a max-value action.
- `DEFAULT_MIN_RESIDUAL_GAS_USD_NUMBER` — `20`
- `DEFAULT_MIN_RESIDUAL_GAS_USD` — `20` USD with 30-decimal precision
- `DEFAULT_MAX_RESIDUAL_GAS_USD` — `40` USD with 30-decimal precision
- `RESIDUAL_GAS_AMOUNT_MULTIPLIER` — `20n`
## Functions
### `getResidualGasUsd`
```typescript
getResidualGasUsd(chainId: ContractsChainId): { min: bigint; max: bigint }
```
Returns the residual gas balance bounds for a contracts chain. Most chains use the default `20` to `40` USD range. MegaETH uses a smaller `1` to `2` USD range because its execution fees are sub-cent and the global default would lock much more balance than needed.
```typescript
const residualGas = getResidualGasUsd(MEGAETH);
console.log(residualGas.min); // 1 USD with 30-decimal precision
console.log(residualGas.max); // 2 USD with 30-decimal precision
```
---
## gasLimits
This module exports the SDK's static gas-limit defaults.
## Exports
- `StaticGasLimitsConfig` — the shape of the per-chain static gas-limit map
- `GAS_LIMITS_STATIC_CONFIG` — static per-chain gas limits used alongside dynamically fetched datastore values
```typescript
console.log(GAS_LIMITS_STATIC_CONFIG[42161]);
```
---
## markets
This module provides market configuration data for the GMX protocol across different blockchain networks. It contains predefined market configurations including token addresses and swap limits for trading pairs on supported chains.
## Types
The `markets` module exports the following TypeScript types.
### MarketConfig
Configuration for a single market, keyed by market token address in the `MARKETS` map.
```typescript
type MarketConfig = {
marketTokenAddress: string;
indexTokenAddress: string;
longTokenAddress: string;
shortTokenAddress: string;
};
```
### MarketsConfigMap
A mapping from market token address to `MarketConfig`.
```typescript
type MarketsConfigMap = Record<string, MarketConfig>;
```
### MarketLabel
A template literal type for market label strings in the format `"SYMBOL/USD [LONG-SHORT]"`.
```typescript
type MarketLabel = `${string}/USD [${string}-${string}]`;
```
```typescript
const label: MarketLabel = "BTC/USD [WBTC.e-USDC]";
```
## Constants
### SWAP_GRAPH_MAX_MARKETS_PER_TOKEN
`SWAP_GRAPH_MAX_MARKETS_PER_TOKEN: number`
Maximum number of markets per token considered when building the swap graph. Value: `5`.
```typescript
console.log(SWAP_GRAPH_MAX_MARKETS_PER_TOKEN); // 5
```
### MARKETS
`MARKETS: Record<ContractsChainId, MarketsConfigMap>`
Complete market configuration mapping for all supported chains, keyed first by chain ID and then by market token address.
```typescript
// Get all markets for Arbitrum
const arbitrumMarkets = MARKETS[ARBITRUM];
// Get a specific market configuration
const btcUsdMarket = MARKETS[ARBITRUM]["0x47c031236e19d024b42f8AE6780E44A573170703"];
console.log(btcUsdMarket.indexTokenAddress); // BTC index token address
```
### DISABLED_SWAP_ROUTE_MARKETS
`DISABLED_SWAP_ROUTE_MARKETS: Partial<Record<ContractsChainId, string[]>>`
Markets excluded from swap path routing (collateral swaps and express fee swaps). GM token buying and selling for these markets is unaffected — only routing through them is blocked. On Arbitrum, this currently excludes the ATOM/USD, OP/USD, EIGEN/USD, and APE/USD markets.
```typescript
const disabledOnArbitrum = DISABLED_SWAP_ROUTE_MARKETS[ARBITRUM] ?? [];
console.log(disabledOnArbitrum);
// ["0x248C35760068cE009a13076D573ed3497A47bCD4", "0x4fDd333FF9cA409df583f306B6F5a7fFdE790739", ...]
```
## Methods
The `markets` module exports the following functions for looking up market configuration by chain, address, or label.
### getMarketsByChainId
`getMarketsByChainId(chainId: ContractsChainId): Record<string, MarketConfig>`
Returns all market configs for a chain. Throws if the chain ID has no configured markets.
```typescript
const markets = getMarketsByChainId(ARBITRUM);
for (const [address, config] of Object.entries(markets)) {
console.log(address, config.indexTokenAddress);
}
```
### getMarketByLabel
`getMarketByLabel(chainId: ContractsChainId, label: MarketLabel): MarketConfig`
Retrieves a market configuration by its human-readable label. Throws if the label is invalid or no matching market is found.
```typescript
const market = getMarketByLabel(ARBITRUM, "BTC/USD [WBTC.e-USDC]");
console.log(market.marketTokenAddress);
```
### fixTokenSymbolFromMarketLabel
`fixTokenSymbolFromMarketLabel(chainId: ContractsChainId, symbol: string): string`
Normalizes a raw token symbol extracted from a market label to match the token configuration format. For example, on Arbitrum `"WBTC"` maps to `"BTC"` and `"ETH"` maps to `"WETH"`.
```typescript
console.log(fixTokenSymbolFromMarketLabel(ARBITRUM, "WBTC")); // "BTC"
console.log(fixTokenSymbolFromMarketLabel(ARBITRUM, "ETH")); // "WETH"
```
### isMarketTokenAddress
`isMarketTokenAddress(chainId: number, marketTokenAddress: string): boolean`
Returns `true` if the given address is a known market token address on the specified chain.
```typescript
isMarketTokenAddress(ARBITRUM, "0x47c031236e19d024b42f8AE6780E44A573170703"); // true
isMarketTokenAddress(ARBITRUM, "0x0000000000000000000000000000000000000000"); // false
```
### getTokenAddressByMarket
`getTokenAddressByMarket(chainId: number, marketTokenAddress: string, tokenType: "long" | "short" | "index"): string`
Returns the address of the long, short, or index token for a market. For `"index"`, returns the native token address where applicable.
```typescript
const longTokenAddress = getTokenAddressByMarket(ARBITRUM, "0x47c031236e19d024b42f8AE6780E44A573170703", "long");
```
### getMarketIndexToken
`getMarketIndexToken(chainId: number, marketTokenAddress: string): Token`
Returns the `Token` object for a market's index token.
### getTokenSymbolByMarket
`getTokenSymbolByMarket(chainId: number, marketTokenAddress: string, tokenType: "long" | "short" | "index"): string`
Returns the symbol of the long, short, or index token for a market.
### getIsSpotOnlyMarket
`getIsSpotOnlyMarket(chainId: number, marketTokenAddress: string): boolean`
Returns `true` if the market is a spot-only market (index token address is `zeroAddress`, meaning no perpetuals).
### getMarketIsSameCollaterals
`getMarketIsSameCollaterals(chainId: number, marketTokenAddress: string): boolean`
Returns `true` if the market uses the same token for both long and short collateral (single-sided collateral market).
---
## multichain
This module exports chain guards used by the SDK's multichain funding logic.
## Exports
- `isSettlementChain(chainId)` — narrows a chain ID to `SettlementChainId`
- `isSourceChain(chainId, settlementChainId)` — checks whether a source chain is valid for a settlement chain
- `isSourceChainForAnySettlementChain(chainId)` — checks whether a chain is a valid source chain anywhere in the SDK
```typescript
```
---
## oracleKeeper
This module provides utilities for retrieving Oracle Keeper URLs for different blockchain networks supported by the GMX protocol. Oracle Keepers are responsible for providing price feeds and other critical data to the GMX smart contracts.
## Methods
Both functions throw an `Error` if `chainId` is not one of the supported chains: `ARBITRUM`, `AVALANCHE`, `MEGAETH`, `AVALANCHE_FUJI`, or `ARBITRUM_SEPOLIA`.
### getOracleKeeperUrl
```typescript
getOracleKeeperUrl(chainId: number): string
```
Returns the primary Oracle Keeper URL for the chain. Throws if `chainId` is not supported.
```typescript
const url = getOracleKeeperUrl(ARBITRUM);
// "https://arbitrum-api.gmxinfra.io"
```
### getOracleKeeperFallbackUrls
```typescript
getOracleKeeperFallbackUrls(chainId: number): string[]
```
Returns an ordered list of fallback Oracle Keeper URLs for the chain. Use these when the primary URL is unavailable. Throws if `chainId` is not supported.
```typescript
const fallbackUrls = getOracleKeeperFallbackUrls(ARBITRUM);
// ["https://arbitrum-api-fallback.gmxinfra.io", "https://arbitrum-api-fallback.gmxinfra2.io"]
```
---
## tokens
This module provides comprehensive token configuration and utilities for the GMX protocol across different blockchain networks. It includes token definitions, mappings, and helper functions for working with tokens in both V1 and V2 versions of the protocol.
## Constants
The constants section covers three categories: special stub addresses, pre-built token data maps, and color mappings. Import any constant directly from `@gmx-io/sdk/configs/tokens`.
### Special addresses
- `NATIVE_TOKEN_ADDRESS: string` — The zero address (`"0x0000000000000000000000000000000000000000"`) used to represent native tokens such as ETH and AVAX.
- `GM_STUB_ADDRESS: string` — Stub address used internally to represent GM (liquidity pool) tokens: `"<GM-ADDRESS>"`.
- `GLV_STUB_ADDRESS: string` — Stub address used internally to represent GLV (liquidity vault) tokens: `"<GLV-ADDRESS>"`.
```typescript
console.log(NATIVE_TOKEN_ADDRESS); // "0x0000000000000000000000000000000000000000"
```
### Token data maps (pre-built)
These objects are populated at module initialization time from the static `TOKENS` array. Prefer the getter functions below over accessing these maps directly.
- `TOKENS: { [chainId: number]: Token[] }` — Raw token array for each chain, used as the source of truth.
- `TOKENS_MAP: { [chainId: number]: { [address: string]: Token } }` — Tokens keyed by address per chain.
- `V1_TOKENS: { [chainId: number]: Token[] }` — V1-available tokens per chain.
- `V2_TOKENS: { [chainId: number]: Token[] }프로젝트로 돌아가기