GMX 백서

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 38쪽

---------------- | ------------------ | ---------- | --------------------------------------------------------------------- | | `getGovTokenDelegates(account?)` | `account?: string` | `string[]` | Returns the governance token delegates for the given account address; on chains without a configured GovToken it resolves to `[]` | #### `sdk.oracle` | Method | Parameters | Returns | Notes | | ------ | ---------- | ------- | ----- | | `getMarkets()` | — | `Promise<MarketSdkConfig[]>` | Fetches raw market configs from the configured oracle URL | | `getTokens()` | — | `Promise<TokensResponse>` | Fetches raw token configs from the configured oracle URL | | `getTickers()` | — | `Promise<TickersResponse>` | Fetches current oracle ticker data from `/prices/tickers` | ### Write methods Write methods submit transactions on-chain and require a `walletClient` and an account set via `sdk.setAccount()`. #### Quick order helpers (`sdk.orders`) The quick helpers automatically calculate swap paths, amounts, and fees from the current market state. You don't need to pre-fetch `marketsInfoData` or `tokensData` — the helpers fetch what they need unless you pass them directly. | Method | Key parameters | Notes | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `long(p)` | `payAmount` or `sizeAmount`, `marketAddress`, `payTokenAddress`, `collateralTokenAddress`, `allowedSlippageBps?`, `leverage?`, `limitPrice?` | Opens a long position; see [Usage Examples](#usage-examples) | | `short(p)` | Same as `long` | Opens a short position | | `swap(p)` | `fromAmount` or `toAmount`, `fromTokenAddress`, `toTokenAddress`, `allowedSlippageBps?`, `triggerPrice?` | Executes a token swap; set `triggerPrice` for a Limit Swap | #### Full order methods (`sdk.orders`) Full methods require pre-computed amounts (use the `utils` module or the calculation helpers in `@gmx-io/sdk/utils/trade`). | Method | Notes | | ----------------------------------- | ---------------------------------------------------------------------------------------- | | `createIncreaseOrder(p)` | Creates a Market Increase or Limit Increase order; see [Usage Examples](#usage-examples) | | `createDecreaseOrder(p)` | Creates a Market Decrease, Stop-Loss, or Take-Profit order | | `createSwapOrder(p)` | Creates a Market Swap or Limit Swap order | | `createWrapOrUnwrapOrder(p)` | Creates a wrap or unwrap transaction for native and wrapped tokens | | `cancelOrders(orderKeys: string[])` | Cancels one or more orders by their on-chain keys | ## Configuration Options Pass a `GmxSdkConfig` object to the `GmxSdk` constructor. The full interface is: ```typescript interface GmxSdkConfig { // Required chainId: number; // 42161 (Arbitrum), 43114 (Avalanche), 4326 (MegaETH), 43113 (Avalanche Fuji), or 421614 (Arbitrum Sepolia) rpcUrl: string; // RPC endpoint for the chain oracleUrl: string; // GMX oracle keeper URL subsquidUrl: string; // GMX Subsquid GraphQL URL // Optional — connection account?: string; // Wallet address; can also be set via sdk.setAccount() publicClient?: PublicClient; // Custom viem PublicClient; auto-created from rpcUrl if omitted walletClient?: WalletClient; // Viem WalletClient; required for write operations // Optional — overrides tokens?: Record<string, Partial<Token>>; // Override token metadata by address markets?: Record<string, Partial<MarketSdkConfig>>; // Override market config by address // Optional — fees settings?: { uiFeeReceiverAccount?: string; // Address that receives UI fees on orders you submit }; } ``` ### Network URLs Use the following endpoints for production networks: | Network | Oracle URL | Chain ID | Status | | --------- | ---------------------------------------------------- | -------- | ------ | | Arbitrum | <CopyUrl url="https://arbitrum-api.gmxinfra.io" /> | 42161 | Active | | Avalanche | <CopyUrl url="https://avalanche-api.gmxinfra.io" /> | 43114 | Active | | MegaETH | <CopyUrl url="https://megaeth-api.gmxinfra.io" /> | 4326 | Active | For Subsquid GraphQL endpoints per network, see [GraphQL](../../api/graphql.mdx). The Arbitrum endpoint is `https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql`. The table above lists production endpoints. The SDK also accepts Arbitrum Sepolia (`421614`) and Avalanche Fuji (`43113`) in `chainId` when you provide matching RPC, oracle, and Subsquid endpoints for those environments. Testnet infrastructure changes more often than production. If you already depend on the SDK config surface, prefer the exported lookup helpers over hardcoded hosts so chain-specific URLs stay aligned with the package version you ship. For the underlying contract ABIs and parameters the SDK wraps, see [Contracts](/docs/category/contracts). :::tip The SDK source exports `getOracleKeeperUrl(chainId)` from `@gmx-io/sdk/configs/oracleKeeper`. For read-only API branching, use `getApiUrl(chainId)` and `isApiSupported(chainId)` from `@gmx-io/sdk/configs/api` instead of hardcoding testnet API hosts. ::: ### Setting up custom viem clients By default, the SDK creates its own viem `PublicClient` from `rpcUrl`. If you create your own client, include the batching configuration to optimize multicall performance: :::warning If you inject a custom viem `publicClient` without `BATCH_CONFIGS`, large GMX multicalls may be split into many smaller requests. The SDK's batch config sets the client-side multicall calldata limit to `1024 * 1024` bytes; omitting it can cause unexpected request fan-out, rate limits, or browser-side transport failures on public RPC endpoints. ::: ```typescript const publicClient = createPublicClient({ chain: arbitrum, transport: http("https://arb1.arbitrum.io/rpc", { batch: BATCH_CONFIGS[42161].http, }), batch: BATCH_CONFIGS[42161].client, }); 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", publicClient, }); ``` If you supply your own transport as well, carry over both parts of the batch config: - `BATCH_CONFIGS[chainId].http` for the viem HTTP transport - `BATCH_CONFIGS[chainId].client` for client-side multicall batching ### Customizing token data To override default token properties, pass a `tokens` map keyed by token address: ```typescript 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", tokens: { "0x912CE59144191C1204E64559FE8253a0e49E6548": { name: "My Custom Name for ARB", }, }, }); ``` The `name` field for this token address uses your custom value throughout the SDK. ### Customizing market availability To hide specific markets from the SDK, set `isListed: false` in the `markets` override map: ```typescript 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", markets: { "0x47c031236e19d024b42f8AE6780E44A573170703": { isListed: false, }, }, }); ``` ## Usage Examples These examples show the most common integration workflows. All examples assume you've initialized `sdk` and called `sdk.setAccount()` as shown in [Initialization](#initialization). ### Quick order helpers For most use cases, use the quick helper methods. They automatically calculate swap paths, amounts, and execution fees from the current market state. You can optionally pass `marketsInfoData` and `tokensData` yourself to reduce API calls if you've already fetched them. **Open a long position on ETH/USD (WETH-USDC) using WETH as collateral:** ```typescript await sdk.orders.long({ payAmount: 100031302n, // Raw pay-token amount in the token's native decimals marketAddress: "0x70d95587d40A2caf56bd97485aB3Eec10Bee6336", // ETH/USD [WETH-USDC] payTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1", // WETH collateralTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", // USDC allowedSlippageBps: 125, // 1.25% slippage tolerance leverage: 50000n, // 5x leverage (basis points, 10000 = 1x) }); ``` **Swap ARB to LINK:** ```typescript await sdk.orders.swap({ fromAmount: 1000n, fromTokenAddress: "0x912CE59144191C1204E64559FE8253a0e49E6548", // ARB toTokenAddress: "0xf97f4df75117a78c1A5a0DBb814Af92458539FB4", // LINK allowedSlippageBps: 125, }); ``` :::tip Pass `payAmount` to specify your input amount. Pass `sizeAmount` instead to target a specific position size. The helper calculates the other value automatically. ::: #### Synthetic token addresses The `payTokenAddress` is the token you're depositing. The `collateralTokenAddress` is the token held as margin. Some markets use synthetic index tokens — for example, the BTC/USD [WBTC-USDC] market's index token is a synthetic BTC, so you pass the WBTC address (`0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f`) as `collateralTokenAddress`, not the synthetic address. ### Full order method Use `createIncreaseOrder` when you need precise control over order amounts, for example in automated strategies where you compute `increaseAmounts` yourself using `getIncreasePositionAmounts` from `@gmx-io/sdk/utils/trade`. ```typescript const { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo(); if (!marketsInfoData || !tokensData) { throw new Error("Failed to fetch market data"); } // ETH/USD [WETH-USDC] on Arbitrum const marketInfo = marketsInfoData["0x70d95587d40A2caf56bd97485aB3Eec10Bee6336"]; // USDC as collateral const collateralToken = tokensData["0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]; // Compute increaseAmounts with getIncreasePositionAmounts(). // That helper needs the full IncreasePositionParams input shown in: // /docs/sdk/v1/exports/utils/trade/increase const increaseAmounts: IncreasePositionAmounts = /* precomputed */; await sdk.orders.createIncreaseOrder({ marketsInfoData, tokensData, isLimit: false, isLong: true, marketAddress: marketInfo.marketTokenAddress, allowedSlippage: 50, collateralToken, collateralTokenAddress: collateralToken.address, receiveTokenAddress: collateralToken.address, fromToken: collateralToken, marketInfo, indexToken: marketInfo.indexToken, increaseAmounts, }); ``` :::note The `increaseAmounts` object has a complex structure including `swapStrategy`, price impact data, and fee components. Use `getIncreasePositionAmounts` from `@gmx-io/sdk/utils/trade` to compute it rather than constructing it manually. The complete low-level input shape is documented in [trade/increase](./exports/utils/trade/increase.md). ::: ## Operational notes Keep these behaviors in mind when you integrate SDK v1 into a production app: - Write methods return a transaction hash after submission. They do not wait for keeper execution or refetch the resulting order state for you. - The default viem HTTP clients created by `GmxSdk` disable transport retries. Add your own retry and backoff policy around safe read paths. - The SDK does not provide idempotency keys or client order IDs. Prevent duplicate submits in your UI while a transaction is pending. - Market increases and market swaps simulate before submit by default. Where configured, the SDK routes execution preflight through `SimulationRouter`; some non-market flows skip simulation in the current implementation. See the [Integration guide](./integration-guide.md#simulation-behavior) for the exact behavior. ### Next steps - Start with the [Integration guide](./integration-guide.md) for scenario-based walkthroughs - See [SDK Examples](./examples.md) for more complete integration patterns - See [Exports](./exports/exports.md) for utility functions available in the SDK --- ## Security This page covers general safety practices, audit reports, and the bug bounty program. ## General safety Exercise caution when interacting with any smart contract or blockchain application. Although the GMX team mitigates risk through rigorous testing, independent audits, and an active bug bounty program, smart contract code can contain vulnerabilities that remain undetected even after review. Keep the following points in mind: - [Phishing](https://en.wikipedia.org/wiki/Phishing) attacks and scams are prevalent in both traditional and blockchain contexts. - Blockchain-specific phishing techniques include tricking users into revealing private keys or seed phrases, or into signing malicious transactions. - Consider maintaining two separate wallets — one to store the majority of your holdings (a "cold" wallet with minimal dApp exposure), and a separate wallet for interacting with new or unfamiliar websites. - Before signing any transaction, verify the target contract address and review the operation being signed. Most wallets display the operation name and contract details to assist with this. - Only interact with the official GMX interface and verified contract addresses listed in the [contracts](./api/contracts/overview.md) page. ## Audits Audit reports for GMX V2 contracts are available in the [gmx-synthetics repository](https://github.com/gmx-io/gmx-synthetics/tree/updates/audits). The following firms have conducted audits: - **Guardian** — Primary auditor for GMX. Conducted 8 engagements between October 2022 and September 2023, totalling 88 person-weeks and resulting in the remediation or acknowledgement of 365 findings across the full severity range. Guardian continues to audit all smart contract updates, with additional engagements through 2024, 2025, and 2026 covering GLV, buybacks, pro tiers, gasless calls, cross-chain V2.2, fee automations, and subsequent protocol changes. - **ABDK** — Audited the GMX Synthetics contracts at a specific commit. - **Certora** — Audited GMX Synthetics (November 2023). - **Dedaub** — Audited GMX Synthetics. - **Sherlock** — Audited GMX Synthetics updates. ## Bug bounty GMX maintains an active bug bounty program covering all repositories under [github.com/gmx-io](https://github.com/gmx-io). Full program details, scope, and reward tiers are available on the [GMX Immunefi](https://immunefi.com/bounty/gmx/) page. --- ## GMX token GMX is the platform's utility and governance token. Staking GMX earns you a share of protocol fees — 27% of fees from leverage trading, liquidations, borrowing fees, and swaps are used to buy back GMX. Distribution of bought-back GMX is currently suspended; see [Staking](#staking) for details. For more on fee distribution, see [Fees](../trading/fees.md). GMX also grants [voting power](../governance/voting-power.md) in protocol governance. Escrowed GMX (esGMX) has historically been distributed as a staking and referral incentive. Learn more about esGMX on the [Rewards](./rewards.md) page. ## Token addresses - Arbitrum: [0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a](https://arbiscan.io/token/0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a) - Avalanche: [0x62edc0692BD897D2295872a9FFCac5425011c661](https://snowtrace.io/address/0x62edc0692BD897D2295872a9FFCac5425011c661) - Solana: [9wX6Qz1Y5YQe71dfnFYFfZYXZhKqjYKQwdqfrRkmYUSX](https://solscan.io/token/9wX6Qz1Y5YQe71dfnFYFfZYXZhKqjYKQwdqfrRkmYUSX) GMX can be bridged between Arbitrum and Avalanche using [Stargate](https://stargate.finance/bridge?srcChain=arbitrum&srcToken=0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a&dstChain=avalanche&dstToken=0x62edc0692BD897D2295872a9FFCac5425011c661). For bridging between other chains, you can use [Jumper Exchange](https://jumper.exchange/). ## Buying GMX You can buy GMX from the [Earn portfolio](https://app.gmx.io/#/earn/portfolio) page. ## Staking Staking GMX earns you a share of protocol fee buybacks. 27% of protocol fees are used to buy back GMX on the open market through a mechanism approved by the DAO [Tally vote](https://www.tally.xyz/gov/gmx/proposal/81921330482579592877925554009800798217173652653143694483196169672340561914053). :::note GMX staking rewards are suspended. Bought-back GMX accumulates in the Treasury and will be distributed to stakers when GMX reaches $90. Your share is based on [staking power](./rewards.md#staking-power), which accrues continuously based on the amount staked and the duration of staking. ::: You can stake GMX on the [Earn](https://app.gmx.io/#/earn) page. For programmatic access to staking power data, use the [`fetchStakingPower()`](../sdk/v2/readme.md#methods) method in SDK v2 or the GMX API `/staking/power` endpoint. ### Staked GMX token addresses After staking GMX, you receive a Staked GMX token. The balance of this token reflects your total staked amount, including any esGMX tokens. - Arbitrum: [0xd2D1162512F927a7e282Ef43a362659E4F2a728F](https://arbiscan.io/token/0xd2D1162512F927a7e282Ef43a362659E4F2a728F) - Avalanche: [0x4d268a7d4C16ceB5a606c173Bd974984343fea13](https://snowtrace.io/address/0x4d268a7d4C16ceB5a606c173Bd974984343fea13) ## Treasury The GMX treasury is funded by: - Fees from the GMX/ETH protocol-owned liquidity - 8.8% of V2 fees (10% is allocated to Chainlink, the treasury, and keeper costs, of which 1.2% goes to Chainlink) The treasury is held in multiple contracts: - DAO Treasury: [0x4bd1cdAab4254fC43ef6424653cA2375b4C94C0E](https://www.tally.xyz/gov/gmx/treasury) - POL Multisig: [0xc6378ddf536410c14666dc59bc92b5ebc0f2f79e](https://debank.com/profile/0xc6378ddf536410c14666dc59bc92b5ebc0f2f79e) - Governance Committee: [0x0263ad94023a5Df6d64f54BFEF089F1FBF8A4CA0](https://debank.com/profile/0x0263ad94023a5Df6d64f54BFEF089F1FBF8A4CA0) - Bond Protocol: [0xea8a734db4c7EA50C32B5db8a0Cb811707e8ACE3](https://debank.com/profile/0xea8a734db4c7EA50C32B5db8a0Cb811707e8ACE3) - GM Holdings: [0xe1f7c5209938780625e354dc546e28397f6ce174](https://debank.com/profile/0xe1f7c5209938780625e354dc546e28397f6ce174) - [0x68863dDE14303BcED249cA8ec6AF85d4694dea6A](https://debank.com/profile/0x68863dDE14303BcED249cA8ec6AF85d4694dea6A) - [0x0339740d92fb8BAf73bAB0E9eb9494bc0Df1CaFD](https://debank.com/profile/0x0339740d92fb8BAf73bAB0E9eb9494bc0Df1CaFD) - [0x2c247a44928d66041d9f7b11a69d7a84d25207ba](https://debank.com/profile/0x2c247a44928d66041d9f7b11a69d7a84d25207ba) The GMX DAO owns protocol-owned liquidity in the form of Uniswap V3 NFT LP tokens: - [0x4bd1cdAab4254fC43ef6424653cA2375b4C94C0E](https://arbiscan.io/token/0xc36442b4a4522e871399cd717abdd847ab11fe88?a=0x4bd1cdAab4254fC43ef6424653cA2375b4C94C0E#inventory) If required, the treasury may be used to pay for issues submitted through the [bug bounty](../security.md#bug-bounty). ## Token supply The supply of GMX can be viewed on the [Dashboard](https://app.gmx.io/#/dashboard). The increase in circulating supply varies depending on the number of tokens that are vested. The forecasted max supply is 13.25 million GMX tokens. Minting beyond this cap requires a governance vote approved by GMX token holders. ### Supply allocation - 6 million GMX: [XVIX](https://xvix.finance/) and [Gambit](https://gambit.financial/) migration. GMX was formed by a merger of the XVIX and Gambit communities. - 2 million GMX: Paired with ETH for liquidity on [Uniswap](https://app.uniswap.org/#/swap?inputCurrency=ETH&outputCurrency=0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a). - 2 million GMX: Reserved for vesting of [escrowed GMX](./rewards.md#escrowed-gmx) tokens. - 2 million GMX: For the treasury. - 1 million GMX: For integration incentives and community developers. - 250,000 GMX: Distributed to contributors linearly over 2 years. <details> <summary>Circulating supply calculation</summary> The supply displayed on the dashboard is the [total minted GMX tokens](https://arbiscan.io/token/0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a) minus the tokens held in [vesting](./rewards.md#escrowed-gmx),
프로젝트로 돌아가기