GMX 백서

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

in the impact pools and by configured values. - Negative price impact may be capped by configured values. - If negative price impact is capped, the additional amount is kept in the claimable collateral pool. Claim it manually using `ExchangeRouter.claimCollateral`. - Positive funding fees must be manually claimed using `ExchangeRouter.claimFundingFees`. - Affiliate rewards must be manually claimed using `ExchangeRouter.claimAffiliateRewards`. - Markets or features may be disabled. - Execution continues even if a callback reverts. - Ensure callbacks have sufficient gas. - Subaccounts can create, update, and cancel any order for an account. - Subaccounts can spend WNT and collateral from the account. - UI fees can be changed. - Referral discounts can be changed. - Funds for blacklisted addresses are kept within the protocol. - The index token is not always the long token. - Fee rates change depending on whether there is a positive or negative impact. ### Deposits These items apply to deposit integrations. - Consider PnL factor when estimating GM price. - Handle deposit cancellations. - Ensure only handlers with the `CONTROLLER` role can call the `afterDepositExecution` and `afterDepositCancellation` callback functions. - Ensure only the correct deposit execution can call callback functions. - Consider markets with the same long and short token — swaps aren't supported for these markets. - Consider positive and negative price impact. - There is a request cancellation period for a configured delay during which deposit requests can't be cancelled. - Output amounts are subject to price impact and fees. - Deposits aren't allowed above the `MAX_PNL_FACTOR_FOR_DEPOSITS`. - The first deposit in any market must go to the `RECEIVER_FOR_FIRST_DEPOSIT`. ### Withdrawals These items apply to withdrawal integrations. - Two minimum outputs must be used for withdrawals. - Handle withdrawal cancellations. - Ensure only handlers with the `CONTROLLER` role can call the `afterWithdrawalExecution` and `afterWithdrawalCancellation` callback functions. - Ensure only the correct withdrawal execution can call callback functions. - Consider markets with the same long and short token — swaps aren't supported for these markets. - Consider positive and negative price impact. - There is a request cancellation period for a configured delay during which withdrawal requests can't be cancelled. - Output amounts are subject to price impact and fees. - Withdrawals aren't allowed above the `MAX_PNL_FACTOR_FOR_WITHDRAWALS`. ### Orders These items apply to order integrations. - Handle order cancellations. - Liquidations and ADLs can trigger the saved callback contract. - Orders can become frozen. - Ensure only handlers with the `CONTROLLER` role can call the `afterOrderExecution`, `afterOrderCancellation`, and `afterOrderFrozen` callback functions. - Ensure only the correct order execution can call callback functions. - Consider markets with the same long and short token — swaps aren't supported for these markets. - Consider positive and negative price impact. - Saved callback contracts can be changed. - There is a request cancellation period for a configured delay during which order requests can't be cancelled. - Output amounts are subject to price impact and fees. - The position impact pool is distributed to liquidity providers over time. - If computing price impact, consult the virtual inventory. - Trader PnL is capped above the `MAX_PNL_FACTOR_FOR_TRADERS`. - Negative price impact can be capped on position decreases. - Decrease order `sizeDelta` and `collateralDelta` are auto-updated if they exceed what the position can handle. - Consider `willPositionCollateralBeSufficient` validation. - Consider `decreasePositionSwapTypes`. - Consider the minimum collateral amount. - Referrals are still paid out during liquidation. - It is possible for positions to have zero collateral. - Positions with zero size can't exist. --- ## Overview Docs for the GMX contracts. This section focuses on the contracts most integrations interact with directly, not an exhaustive page for every deployed contract. ## Important notes Review these points before integrating with the contracts. :::warning See the [Known issues](./known-issues.md) page for the full list of known issues and integration considerations. These docs provide an overview. Check the actual contract code for the exact implementation and for any edge cases when building an application or integration. Contracts such as readers and events may not be audited. Check the scopes of the audits for more information, and take extra caution when using or depending on these contracts. Subscribe to the channels on the [Updates and Support](../updates-support.md) page for important contract update notifications. ::: ## How it works The protocol separates concerns across four contract categories (bank, data storage, logic, and event contracts) to enable upgrades without fund migration. Most user actions follow a two-phase execution model where the user submits a request and a keeper executes it with oracle prices. For a detailed explanation of the architecture and keeper network, see [Architecture](./architecture.md). The [contracts repo](https://github.com/gmx-io/gmx-synthetics/tree/updates) provides the production-branch source code. The [test](https://github.com/gmx-io/gmx-synthetics/tree/updates/test) folder contains examples for interacting with the contracts. ## Deployments Key contract addresses for active chains (Arbitrum, Avalanche, MegaETH), legacy Botanix deployments, and testnets are listed on the [Contract addresses](./addresses.md) page. The full deployment list with all 130+ contracts per chain is in the [gmx-synthetics docs folder](https://github.com/gmx-io/gmx-synthetics/tree/updates/docs). The machine-readable `contracts.json` currently covers mainnet deployments, while testnet deployments are published in the per-network markdown files in that folder. ### Testnet The Arbitrum Sepolia deployment is typically the most current testnet. See [Contract addresses — Testnet](./addresses.md#testnet) for key testnet addresses. For a frontend that connects to testnet, see the [Testnet frontend](../frontend-integration.md#testnet-frontend) section. ## Reading values You can read on-chain values using three contracts: - [Reader](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/reader/Reader.sol) - [GlvReader](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/reader/GlvReader.sol) - [DataStore](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/data/DataStore.sol) The `Reader` contract provides convenience functions for retrieving information such as markets and positions lists. Most integrations only need a small set of entry points: - `ExchangeRouter` for creating orders, deposits, withdrawals, and shifts - `GlvRouter` for GLV-specific deposits and withdrawals - `Reader` for GM markets, positions, and pricing data - `GlvReader` for GLV-specific reads The wider protocol architecture includes many additional handlers, vaults, storage contracts, and utility contracts. See [Architecture](./architecture.md) for how those pieces fit together. For delegated trading, gasless relay flows, and GMX Account cross-chain routers, see [Advanced entry points](./advanced-entrypoints.md). You can also retrieve additional information using the `DataStore` and `Keys` contracts. The [test](https://github.com/gmx-io/gmx-synthetics/tree/updates/test) folder contains `DataStore` usage examples, and the [keys](https://github.com/gmx-io/gmx-synthetics/blob/updates/utils/keys.ts) file shows how to construct keys for `DataStore` reads. To retrieve multiple values in a single query, use a [Multicall contract](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/mock/Multicall3.sol). See [Contract addresses](./addresses.md) for the `Multicall3` address on each chain. For detailed function references, see the [Reader](./reader.md) and [GLV Reader](./glv-reader.md) pages. For retrieving prices, see the [Oracle API](../rest-api/oracle-prices.mdx) docs. For token compatibility, known limitations, and integration considerations, see the [Known issues](./known-issues.md) page. --- ## Reader The Reader contract provides convenience functions for retrieving information such as markets, positions, and pricing data. This page focuses on the most commonly used read helpers. For the full public surface, see [`Reader.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/reader/Reader.sol). Examples below assume you already have contract instances such as `reader`, `dataStore`, and `referralStorage`, plus any required market or price structs. ## Market list Use `Reader.getMarkets` to retrieve a paginated list of all markets. Each market is represented by a `Market.Props` struct. ### Reader.getMarkets ```solidity function getMarkets(DataStore dataStore, uint256 start, uint256 end) external view returns (Market.Props[] memory) ``` **Example (TypeScript / ethers):** ```typescript const markets = await reader.getMarkets(dataStore.address, 0, 20); ``` **Parameters:** | Parameter | Type | Description | | ----------- | --------- | --------------------------------- | | `dataStore` | `address` | Address of the DataStore contract | | `start` | `uint256` | Start index for pagination | | `end` | `uint256` | End index for pagination | **Returns:** Array of `Market.Props`. ### Market.Props | Field | Type | Description | | ------------- | --------- | -------------------------------------------------------------------- | | `marketToken` | `address` | Address of the GM token for this market | | `indexToken` | `address` | Address of the index token (for example, ETH for the ETH/USD market) | | `longToken` | `address` | Address of the long collateral token | | `shortToken` | `address` | Address of the short collateral token | ## Detailed market list Use `Reader.getMarketInfoList` to retrieve markets with additional runtime data including borrowing rates, funding rates, and whether the market is disabled. ### Reader.getMarketInfoList ```solidity function getMarketInfoList( DataStore dataStore, MarketUtils.MarketPrices[] memory marketPricesList, uint256 start, uint256 end ) external view returns (ReaderUtils.MarketInfo[] memory) ``` **Example (TypeScript / ethers):** ```typescript const marketInfoList = await reader.getMarketInfoList(dataStore.address, marketPricesList, 0, 20); ``` **Parameters:** | Parameter | Type | Description | | ------------------ | ---------------------------- | ------------------------------------------------------------------------------ | | `dataStore` | `address` | Address of the DataStore contract | | `marketPricesList` | `MarketUtils.MarketPrices[]` | Current prices for each market, in the same order as the markets being queried | | `start` | `uint256` | Start index for pagination | | `end` | `uint256` | End index for pagination | **Returns:** Array of `ReaderUtils.MarketInfo`, which includes the market props, borrowing rates, funding rates, and a flag indicating whether the market is disabled. ### MarketUtils.MarketPrices | Field | Type | Description | | ----------------- | ------------- | --------------------------------------- | | `indexTokenPrice` | `Price.Props` | Current price range for the index token | | `longTokenPrice` | `Price.Props` | Current price range for the long token | | `shortTokenPrice` | `Price.Props` | Current price range for the short token | ### Price.Props | Field | Type | Description | | ----- | --------- | ------------------- | | `min` | `uint256` | Minimum (bid) price | | `max` | `uint256` | Maximum (ask) price | ### Price and amount encoding Reader pricing helpers (for example `getMarketTokenPrice`, `getSwapAmountOut`, `getDepositAmountOut`, `getWithdrawalAmountOut`) share two encoding conventions for the values you pass in. **Token amounts** use each token's **native** decimals — the same decimals the ERC-20 reports on-chain. Use each deposit or swap token's own decimals; do not substitute the index token's decimals. **Prices** stored in `Price.Props.min` / `Price.Props.max` are encoded as: ``` priceValue = usdPrice * 10^(30 - tokenDecimals) ``` This is the form produced by the oracle providers and consumed directly by the Reader. Common examples for a `$1` price: | Token | Decimals | Encoded price for $1 | | ------------------ | -------- | -------------------- | | USDC, USDT | 6 | `1 * 10^24` | | WBTC, WBTC.e | 8 | `1 * 10^22` | | TAO | 9 | `1 * 10^21` | | WETH, most ERC-20s | 18 | `1 * 10^12` | The invariant is `tokenAmount * priceValue = usdValue * 10^30`, so the raw token amount never needs a unit adjustment when multiplied by the encoded price. :::danger Common mistake Do **not** pass prices as `usdPrice * 10^30` (pure 30-decimal USD). That form is only correct for a hypothetical 0-decimal token — it is not the encoding used anywhere in the protocol. Anti-example — for USDC (6 decimals) at $1: | Form | Value | Correct? | | ------------------------ | -------------- | -------------------------------- | | `usdPrice * 10^30` | `1 * 10^30` | ❌ 10^6× too large | | `usdPrice * 10^(30 − 6)` | `1 * 10^24` | ✅ | Passing pure 30-decimal USD inflates each token's internal USD value by `10^tokenDecimals`. Since the Reader also uses the same prices to compute the pool value, `getDepositAmountOut` returns a ratio of two wrong numbers — typically thousands of times larger than the expected GM amount. ::: :::warning Synthetic index markets can mix decimals across the index, long, and short tokens. The `TAO/USD` GM market, for example, is backed by WBTC.e (8 decimals) as the long token and USDC (6 decimals) as the short token, while the index token TAO itself has 9 decimals and is never deposited. Always apply each token's own decimals when encoding its price and scaling its amount — reusing the index token's decimals for a deposit amount is a common source of off-by-10^n errors (for the TAO/USD market, off by a factor of `10^3` against USDC). ::: **Worked example — USDC-only deposit into the `TAO/USD` market** (TAO at `$420`, WBTC.e at `$60,000`, USDC at `$1`): ```typescript const prices = { // TAO index token — 9 decimals indexTokenPrice: { min: 420n * 10n ** 21n, max: 420n * 10n ** 21n, }, // WBTC.e long token — 8 decimals longTokenPrice: { min: 60_000n * 10n ** 22n, max: 60_000n * 10n ** 22n, }, // USDC short token — 6 decimals shortTokenPrice: { min: 1n * 10n ** 24n, max: 1n * 10n ** 24n, }, }; const longTokenAmount = 0n; // not depositing the long token const shortTokenAmount = 1_070_000n; // 1.07 USDC (6 decimals) — NOT 1.07 * 10^9 ``` The return value from `getDepositAmountOut` (and any other helper that returns a GM amount) is a raw `uint256` at 18 decimals. Divide by `10^18` for human-readable display. ## Getting GM token price Use `Reader.getMarketTokenPrice` to retrieve a GM token price for the supplied market, token prices, PnL factor type, and min/max direction. The call also returns detailed pool information: pool value, PnL, token amounts, borrowing fees, and the impact pool. Use this method when you need direct GMX Reader valuation for a specific block and supplied price context, or when a Chainlink Data Feed is not available. For external protocol integrations that only need a standard oracle interface, prefer Chainlink Data Feeds where available. For the integration decision tree, see [Getting GM and GLV token prices](../gm-glv-prices.md). ### Reader.getMarketTokenPrice ```solidity function getMarketTokenPrice( DataStore dataStore, Market.Props memory market, Price.Props memory indexTokenPrice, Price.Props memory longTokenPrice, Price.Props memory shortTokenPrice, bytes32 pnlFactorType, bool maximize ) external view returns (int256, MarketPoolValueInfo.Props memory) ``` **Example (TypeScript / ethers):** ```typescript const [gmPrice, poolInfo] = await reader.getMarketTokenPrice( dataStore.address, market, indexTokenPrice, longTokenPrice, shortTokenPrice, pnlFactorType, true ); ``` **Parameters:** | Parameter | Type | Description | | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dataStore` | `address` | Address of the DataStore contract | | `market` | `Market.Props` | Market data struct (see [Market list](#market-list)) | | `indexTokenPrice` | `Price.Props` | Current price range for the index token | | `longTokenPrice` | `Price.Props` | Current price range for the long token | | `shortTokenPrice` | `Price.Props` | Current price range for the short token | | `pnlFactorType` | `bytes32` | Which PnL factor cap to apply. Use `Keys.MAX_PNL_FACTOR_FOR_TRADERS` for trading contexts, `Keys.MAX_PNL_FACTOR_FOR_DEPOSITS` for deposit simulation, or `Keys.MAX_PNL_FACTOR_FOR_WITHDRAWALS` for withdrawal simulation. | | `maximize` | `bool` | Pass `true` to use maximum prices (gives the higher GM token price), `false` to use minimum prices | **Returns:** A tuple of `(int256 price, MarketPoolValueInfo.Props poolInfo)` where `price` is the GM token price and `poolInfo` contains pool value, PnL, token amounts, borrowing fees, and the impact pool balance. ## Position list Use `Reader.getAccountPositions` to retrieve all open positions for a given account. The function returns raw position data without fee or pricing calculations. ### Reader.getAccountPositions ```solidity function getAccountPositions( DataStore dataStore, address account, uint256 start, uint256 end ) external view returns (Position.Props[] memory) ``` **Example (TypeScript / ethers):** ```typescript const positions = await reader.getAccountPositions(dataStore.address, account.address, 0, 20); ``` **Parameters:** | Parameter | Type | Description | | ----------- | --------- | --------------------------------------------- | | `dataStore` | `address` | Address of the DataStore contract | | `account` | `address` | The account address to retrieve positions for | | `start` | `uint256` | Start index for pagination | | `end` | `uint256` | End index for pagination | **Returns:** Array of `Position.Props`, each containing the raw position state (size, collateral, entry price, and so on). ## Detailed position list Use `Reader.getAccountPositionInfoList` to retrieve all open positions for a given account with full fee and pricing context. This function uses the account address and market list directly rather than position keys. :::note `Reader.getAccountPositionInfoList` uses an account plus market list rather than explicit `positionKeys`. If you need to query specific keys directly, use `Reader.getPositionInfoList`. ::: ### Reader.getAccountPositionInfoList ```solidity function getAccountPositionInfoList( DataStore dataStore, IReferralStorage referralStorage, address account, address[] memory markets, MarketUtils.MarketPrices[] memory marketPrices, address uiFeeReceiver, uint256 start, uint256 end ) external view returns (ReaderPositionUtils.PositionInfo[] memory) ``` **Example (TypeScript / ethers):** ```typescript const positionInfoList = await reader.getAccountPositionInfoList( dataStore.address, referralStorage.address, account.address, markets, marketPrices, ethers.constants.AddressZero, 0, 20 ); ``` **Parameters:** | Parameter | Type | Description | | ----------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `dataStore` | `address` | Address of the DataStore contract | | `referralStorage` | `address` | Address of the ReferralStorage contract | | `account` | `address` | The account address to retrieve p
프로젝트로 돌아가기