bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 37쪽
a five-day delay, protecting traders from outsized impact during volatile periods.
## Risks
:::warning
Smart contracts carry inherent risk. The team mitigates risks through testing, audits, and bug bounties, but vulnerabilities in smart contract code are always possible. For details on contract operation, see [Contracts](./api/contracts/overview.md).
:::
A non-exhaustive list of risks:
- **Smart contract risks:** Vulnerabilities in smart contract code despite testing and audits.
- **Counterparty risks:** The GLV / GM pool is the counterparty to traders. If traders profit, that profit comes from the value of the GLV / GM pool.
- **Token risks:** Bridged tokens depend on the security of the bridge, and pegged tokens carry the risk of depegging.
- **Open interest imbalance:** While funding fees and price impact incentivize balanced long and short open interest, positions may not always be balanced. For example, if long positions are balanced against high-leverage short positions and a sudden price spike occurs, the short positions could be liquidated, temporarily creating an imbalance.
- **GLV shift exploitation:** The GLV shift feature rebalances liquidity between markets based on utilization. An attacker could temporarily inflate utilization in a low-utilization market to trigger a shift, then reverse the position. Position fees and price impact are configured to make this costly.
- **GLV illiquid GM tokens:** GM tokens in a GLV can become illiquid due to high PnL factor or high reserved USD. Users could deposit illiquid GM tokens into a GLV and withdraw liquidity from a different market, leaving the GLV holding illiquid tokens. The `glvMaxMarketTokenBalanceUsd` and `glvMaxMarketTokenBalanceAmount` parameters limit exposure to risky markets.
- **GLV negative market value:** If the value of a GM market within a GLV becomes negative, the GLV may be unusable until that market's value recovers.
### Hedging open interest imbalance
For liquidity providers that hedge the difference between long and short open interest, the relevant comparison method depends on the on-chain `useOpenInterestInTokensForBalance` setting. This is a protocol-wide setting stored once per chain in the `DataStore`, not a per-market parameter, so the same comparison method applies to every market. When this setting is enabled, the protocol compares the long and short `openInterestInTokens` values multiplied by the current index token price (notional value). When it is disabled, the protocol compares the `openInterest` USD values recorded at position entry. Funding rates, borrow fees, and price impact calculations all use whichever method this setting selects to determine open interest balance, so LP hedges should match the same approach.
## Next steps
- [Trade on GMX](./trading/overview.md) — Open leveraged positions using pool liquidity.
- [Contracts](./api/contracts/overview.md) — Review smart contract details.
- [GLV / GM pools app](https://app.gmx.io/#/pools) — Start providing liquidity.
---
## Referrals(Docs)
Get fee discounts and earn rewards through the GMX referral program.
## How it works
The GMX referral program lets you earn rewards when traders you refer open or close positions on GMX V2. To participate as an affiliate, create a referral code and share your referral link.
To create a referral code:
1. Go to the [Referrals](https://app.gmx.io/#/referrals) page.
2. Select the **Affiliates** tab.
3. Enter a referral code using letters (A–Z, a–z), digits (0–9), or underscores. Codes are case-sensitive and can be up to 20 characters long.
4. Submit the transaction to register the code on-chain.
:::note
Arbitrum is the leader chain for new referral-code validation. This validation applies to new code registrations; existing referral codes remain valid on their registered chains, and referral discounts and rewards continue to apply on supported chains. New codes are validated by `ReferralCodeValidator`; when a code is registered on Arbitrum, it becomes valid there immediately and is propagated to follower chains through LayerZero. If you start registration from a follower chain, the request is forwarded to Arbitrum, and the code becomes valid on that follower chain after validation has propagated back. Register on Arbitrum for the fastest and least ambiguous setup.
:::
Once your code is registered, copy your referral link from the Referrals page. The link format is:
```text
https://app.gmx.io/trade/?ref=your-code
```
Older links in the `https://app.gmx.io/#/trade/?ref=your-code` format still work and redirect to the new format with the referral code intact.
Share this link on any platform. When a trader opens the link, your referral code is stored in their browser. The code is written to the contract the first time they create an order with a registered and valid code. From that point on, the trader receives a fee discount and you earn rewards, unless the trader later qualifies for a GMX-managed protocol code as described below.
The referral program is subject to change as determined by GMX token holders. The full [referral terms](https://gmx.io/#/referral-terms) are available on the GMX website.
## Affiliate rewards
With the standard public referral tiers, affiliates earn 5% to 15% of referred traders' opening and closing fees for leverage trading. Traders using the code receive a 5% or 10% discount on those fees.
| Tier | Trader discount | Affiliate reward |
| ---- | --------------- | ---------------- |
| 1 | 5% | 5% |
| 2 | 10% | 10% |
| 3 | 10% | 15% |
Rewards and discounts don't apply to borrow fees or funding fees.
Tier 3 affiliates receive their 15% reward in the market's collateral token.
## Tiers
The referral program uses a tier system to prevent gaming through self-referrals, ensuring affiliates receive rewards for the traders they brought to the platform.
Anyone can create a Tier 1 code. To upgrade to standard Tier 2 or Tier 3, your account must meet the following weekly thresholds:
| Tier | Active users | Combined volume |
| ---- | ------------ | --------------- |
| 2 | 15+ | $5M+ |
| 3 | 30+ | $25M+ |
If your account meets these criteria, send a DM to [@GMXPartners](https://t.me/GMXPartners) to request an upgrade. Wallet providers and other protocols are also eligible for standard Tier 2 and Tier 3 rewards.
Additional partner tiers, including Tier 4, may be assigned by GMX Partners case-by-case for selected top affiliates. These tiers don't have public weekly qualification thresholds and aren't available through the standard upgrade criteria above.
### esGMX rewards
Tier 3 affiliates previously received a weekly esGMX bonus via the fee distributor, capped at 5,000 [esGMX tokens](./tokenomics/rewards.md#escrowed-gmx) per week. This distribution ended on February 4, 2026.
If you received esGMX through the referral program before it ended, you can still vest it using the Affiliate vault. To access it, open the vesting modal from the esGMX card on the [Earn](https://app.gmx.io/#/earn) page and select the Affiliate vault tab. Unlike standard vesting, the Affiliate vault doesn't require a paired GMX or GLP deposit.
## Claiming rewards
Rewards in the referral program work differently depending on whether you're a trader receiving discounts or an affiliate earning rewards.
### V2
Traders receive fee discounts automatically. The discount is deducted from the position fee at trade execution.
Affiliates accumulate rewards on every trade made by their referred traders. Rewards accrue per market in the collateral token of each market. You can claim them at any time from the [Referrals](https://app.gmx.io/#/referrals) page using the "Claimable rebates" card.
When claiming, you can optionally enable "Swap all rewards into one asset" to consolidate your rewards into a single token before receiving them. Available target tokens are:
- **Arbitrum:** GMX, USDC, WETH, BTC
- **Avalanche:** USDC, WAVAX, BTC
This swap is routed through an external aggregator (KyberSwap), not through GMX pools. The default allowed slippage is 3% and includes price impact and fees — unlike GMX native swaps where slippage and price impact are separate. You can adjust the slippage in the claim modal. If a swap route is unavailable for a particular reward token, the claim modal displays a warning.
### V1 (historical)
V1 trading is no longer active. No new V1 referral rewards are earned. Historically, V1 rewards and discounts were distributed as airdrops — ETH on Arbitrum and AVAX on Avalanche — every Wednesday. Your past V1 distribution history remains viewable on the [Referrals](https://app.gmx.io/#/referrals) page, labeled "V1 airdrop."
## Protocol-assigned referral codes {#protocol-referral-codes}
Protocol-assigned referral codes give qualifying traders a fee discount without requiring a referral-code application.
Traders reaching $50M in lifetime volume on Arbitrum receive an automatic 5% fee discount. At $250M in lifetime volume on Arbitrum, that increases to 10%. No referral code application is needed; GMX assigns the discount code automatically.
GMX can also assign protocol-owned referral codes after certain milestones to preserve trader discounts while no longer assigning affiliate rewards for that trader.
| Code | When it can be assigned | Trader discount | Affiliate reward |
| ---- | ----------------------- | --------------- | ---------------- |
| `EARNED_TRADER_DISCOUNT_5` | Organic VIP referral tier: trader reaches $50M lifetime volume on Arbitrum without a higher eligible protocol code | 5% | 0% |
| `EARNED_TRADER_DISCOUNT_10` | Organic VIP referral tier: trader reaches $250M lifetime volume on Arbitrum without a higher eligible protocol code | 10% | 0% |
| `DIRECT_GMX_DISCOUNT_5` | Trader graduates from a Tier 1 referral code | 5% | 0% |
| `DIRECT_GMX_DISCOUNT_10` | Trader graduates from a Tier 2 or Tier 3 referral code | 10% | 0% |
Organic VIP referral tiers are based on the trader's Arbitrum lifetime volume. Referral-code graduation applies per trader once either limit is reached, and the limits are the same for every tier: 12 months assigned to the code, or $20,000 in affiliate rewards generated for that referrer. The original tier only determines the resulting protocol code:
| Original referral tier | Protocol code after graduation |
| ---------------------- | ------------------------------ |
| Tier 1 | `DIRECT_GMX_DISCOUNT_5` |
| Tier 2 or Tier 3 | `DIRECT_GMX_DISCOUNT_10` |
When a trader graduates, their trader discount is preserved, but new affiliate rewards for that trader stop accruing to the previous referrer.
If the active referral code shown on the Referrals page is one of these GMX protocol codes, the interface explains whether it was assigned because of an organic volume threshold or because a previous referral code reached the graduation threshold.
## Transferring a referral code
To transfer ownership of a referral code to a new address, you interact directly with the `ReferralStorage` contract through a block explorer. There's no frontend UI for this action.
:::warning
Transferring a referral code is permanent. Once transferred, you lose ownership and only the new owner can transfer it further. There is no way to reclaim the code without the new owner's cooperation. Verify the destination address carefully before submitting.
:::
The `ReferralStorage` contract addresses are:
- **Arbitrum:** [`0xe6fab3F0c7199b0d34d7FbE83394fc0e0D06e99d`](https://arbiscan.io/address/0xe6fab3F0c7199b0d34d7FbE83394fc0e0D06e99d#writeContract)
- **Avalanche:** [`0x827ed045002ecdabeb6e2b0d1604cf5fc3d322f8`](https://snowtrace.io/address/0x827ed045002ecdabeb6e2b0d1604cf5fc3d322f8#writeContract)
- **MegaETH:** [`0xAd917849372eaEF498E982F90bA6459a43ecbd31`](https://megaeth.blockscout.com/address/0xAd917849372eaEF498E982F90bA6459a43ecbd31)
To transfer a code on a given network:
1. Convert your referral code to its `bytes32` encoding using a tool like [DEVoven](https://www.devoven.com/converting/string-to-bytes32) with the "Append Zeros" option checked. For example, the code `code` encodes to `0x636f646500000000000000000000000000000000000000000000000000000000`.
2. Open the `ReferralStorage` contract link for your network from the list above.
3. Go to the "Write Contract" tab.
4. Connect the wallet that currently owns the referral code.
5. Expand the `setCodeOwner` function. Enter the `bytes32` value from step 1 in the `_code` field and the destination wallet address in the `_newAccount` field.
6. Submit the transaction by clicking "Write."
---
## Getting Started(V1)
:::warning
SDK v1 is being sunset: it receives no new features and will be removed in a future major version. Build new integrations on [SDK v2](../v2/readme.md).
:::
The full SDK v1 client (`GmxSdk`) exposes these top-level modules:
- **`markets`** — fetch market definitions, pricing, and daily volumes
- **`tokens`** — fetch token metadata and balances
- **`positions`** — read open positions for an account
- **`orders`** — read active orders and submit new ones (long, short, swap, cancel)
- **`trades`** — fetch historical trade activity
- **`accounts`** — read governance delegate data
- **`oracle`** — read raw oracle markets, tokens, and tickers from the configured oracle URL
- **`utils`** — fee estimation, price impact, and other calculation helpers
## Before you start
To use `GmxSdk`, you need the following:
- An RPC endpoint for your target chain
- A GMX oracle keeper URL — see [Oracle Prices](../../api/rest-api/oracle-prices.mdx)
- A Subsquid GraphQL URL — see [GraphQL](../../api/graphql.mdx)
- A viem `WalletClient` for write operations. For read-only use, you can omit the wallet client, but you still configure the RPC, oracle, and Subsquid URLs.
## Initialization
The following example shows the minimum setup to initialize the SDK and fetch positions for an account on Arbitrum mainnet.
```typescript
// 1. Create the SDK instance
const sdk = new GmxSdk({
chainId: 42161, // Arbitrum
rpcUrl: "https://arb1.arbitrum.io/rpc",
oracleUrl: "https://arbitrum-api.gmxinfra.io",
subsquidUrl: "https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql",
});
// 2. Set the account you want to query
sdk.setAccount("0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33");
// 3. Fetch market and token data (required for most queries)
const { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();
// 4. Fetch open positions for the account
const { positionsData } = await sdk.positions.getPositions({
marketsData: marketsInfoData,
tokensData,
});
console.log(positionsData);
```
The SDK doesn't require a wallet client for read-only operations. To submit orders, pass a viem `WalletClient`:
```typescript
const account = privateKeyToAccount("0x...your-private-key");
const walletClient = createWalletClient({
account,
chain: arbitrum,
transport: http("https://arb1.arbitrum.io/rpc"),
});
const sdk = new GmxSdk({
chainId: 42161,
rpcUrl: "https://arb1.arbitrum.io/rpc",
oracleUrl: "https://arbitrum-api.gmxinfra.io",
subsquidUrl: "https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql",
walletClient,
});
```
If you're using CommonJS, require the v1 client from the package root:
```javascript
const { GmxSdk } = require("@gmx-io/sdk");
const sdk = new GmxSdk({
chainId: 42161,
rpcUrl: "https://arb1.arbitrum.io/rpc",
oracleUrl: "https://arbitrum-api.gmxinfra.io",
subsquidUrl: "https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql",
});
```
:::tip
If you're using wagmi in a React application, pass `useWalletClient().data` as the `walletClient` parameter after the wallet connects.
:::
## Common workflows
If you want exact "I want to do X" steps, start with the [Integration guide](./integration-guide.md):
- Read positions, active orders, and recent trades for one account
- Submit a `Market Increase` order with `orders.long()`
- Cancel active orders by on-chain order key
- Understand the SDK's simulation, retry, timeout, and eventual-consistency behavior
- Debug duplicate submits, missing receipts, stale reads, and cancel/replace races in [Troubleshooting](./troubleshooting.md)
## API Reference
The SDK groups methods into modules, each accessed as a property on the `GmxSdk` instance. All methods are async.
### Read methods
#### `sdk.markets`
| Method | Parameters | Returns | Notes |
| ----------------------------- | --------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------- |
| `getMarkets(offset?, limit?)` | `offset: bigint = 0n`, `limit: bigint = 300n` | `{ marketsData?, marketsAddresses?, error? }` | Builds the listed market set from oracle market configs plus on-chain reader data |
| `getMarketsInfo()` | — | `{ marketsInfoData?, tokensData?, pricesUpdatedAt? }` | Fetches full market details, underlying token prices, and pool values; it does not expose GM or GLV token prices as first-class fields |
| `getDailyVolumes()` | — | `Record<string, bigint> \| undefined` | Returns a map of market address → daily volume in USD (30-decimal precision) |
For GM/GLV token price selection, see [Getting GM and GLV token prices](../../api/gm-glv-prices.md).
#### `sdk.tokens`
| Method | Parameters | Returns | Notes |
| ----------------- | ---------- | --------------------------------- | -------------------------------------------------------------------------------- |
| `getTokensData()` | — | `{ tokensData, pricesUpdatedAt }` | Fetches token metadata and current prices for all tokens on the configured chain |
#### `sdk.positions`
| Method | Parameters | Returns | Notes |
| ----------------- | ------------------------------------------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `getPositions(p)` | `marketsData`, `tokensData`, `start?: number`, `end?: number` | `{ positionsData? }` | Requires an account set via `sdk.setAccount()`. `start`/`end` are pagination offsets (default 0/1000) |
| `getPositionsInfo(p)` | `marketsInfoData`, `tokensData`, `showPnlInLeverage` | `PositionsInfoData` | Builds enriched position summaries with fees, leverage, liquidation price, and referral context |
| `getPositionsConstants()` | — | `{ minCollateralUsd, minPositionSizeUsd, maxAutoCancelOrders }` | Reads and caches position-related DataStore constants |
| `getMaxAutoCancelOrders(p?)` | `positionOrders?`, `draftOrdersCount?` | `{ warning, autoCancelOrdersLimit }` | Calculates whether another auto-cancel order can be added for a position |
#### `sdk.orders`
| Method | Parameters | Returns | Notes |
| -------------- | -------------------------------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------ |
| `getOrders(p)` | `marketsInfoData`, `tokensData`, `account?`, `orderTypesFilter?`, `marketsDirectionsFilter?` | `{ count, ordersInfoData }` | Returns all active orders for the account; supports filtering by order type and market direction |
#### `sdk.trades`
| Method | Parameters | Returns | Notes |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | --------------------------------------------------------- |
| `getTradeHistory(p)` | `pageSize`, `pageIndex`, `marketsInfoData?`, `tokensData?`, `fromTxTimestamp?`, `toTxTimestamp?`, `marketsDirectionsFilter?`, `orderEventCombinations?`, `forAllAccounts?` | `Promise<TradeAction[]>` | Fetches paginated trade history from the Subsquid indexer |
#### `sdk.accounts`
| Method | Parameters | Returns | Notes |
| ----------------프로젝트로 돌아가기