GMX 백서

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

sZero, market: marketToken.address, glv: glvToken.address, longTokenSwapPath: [], shortTokenSwapPath: [], }, minLongTokenAmount, minShortTokenAmount, shouldUnwrapNativeToken: false, executionFee, callbackGasLimit: 0, dataList: [], }, ]), ], { value: executionFee } ); ``` **Parameters:** | Parameter | Type | Description | | --------- | --------------------------------------------------- | ---------------------------------------------- | | `params` | `IGlvWithdrawalUtils.CreateGlvWithdrawalParams` | Struct containing GLV withdrawal configuration | **Returns:** `bytes32` -- the key that identifies this GLV withdrawal request. ### CreateGlvWithdrawalParams The GLV token amount to withdraw is not part of `CreateGlvWithdrawalParams`. It is set by the amount sent to the `GlvVault` in the preceding `sendTokens` call. | Field | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `addresses` | Group of address fields listed in [CreateGlvWithdrawalParamsAddresses](#createglvwithdrawalparamsaddresses). | | `minLongTokenAmount` | Minimum output amount of long token after swapping through `longTokenSwapPath`. For example, if WETH is swapped to BTC, this specifies the minimum BTC amount. | | `minShortTokenAmount` | Minimum output amount of short token after swapping through `shortTokenSwapPath`. | | `shouldUnwrapNativeToken` | Whether to unwrap the native token on output. For example, if the output token is WETH and this is `true`, the contract converts WETH to ETH before sending. | | `executionFee` | Amount of native token (for example, ETH on Arbitrum) included as the execution fee. This is the maximum fee keepers can use to execute the withdrawal. Any excess is returned to the withdrawal account. See [Execution Fee](./fees.md#execution-fee) for details. | | `callbackGasLimit` | Gas limit passed to the callback contract on withdrawal execution or cancellation. | | `dataList` | Array of additional `bytes32` data. Pass an empty array if no extra data is needed. | ### CreateGlvWithdrawalParamsAddresses | Field | Description | | -------------------- | ------------------------------------------------------------------------ | | `receiver` | Address that receives the withdrawn tokens. | | `callbackContract` | Contract to call on withdrawal execution or cancellation. | | `uiFeeReceiver` | Address that receives the UI fee. | | `market` | GM market to withdraw from. Must be a market that the GLV vault supports.| | `glv` | Address of the GLV vault to withdraw from. | | `longTokenSwapPath` | Array of market addresses to swap the withdrawn long token through. | | `shortTokenSwapPath` | Array of market addresses to swap the withdrawn short token through. | ## Cancelling GLV requests You can cancel a pending GLV deposit or withdrawal if it hasn't been executed yet. Only the account that created the request can cancel it. On Arbitrum, Avalanche, and MegaETH, keepers also cancel GLV deposits and withdrawals that are still pending about 60 seconds after they become cancellable, so about six minutes or more after creation with `requestExpirationTime` at 300 seconds. This timing is keeper behavior, not a protocol guarantee. The `GlvDepositCancelled` or `GlvWithdrawalCancelled` event carries the reason `USER_INITIATED_CANCEL`, the same as a cancellation you send yourself. See [Cancelling requests](./exchange-router.md#cancelling-requests). ### GlvRouter.cancelGlvDeposit ```solidity function cancelGlvDeposit(bytes32 key) external ``` Cancels a pending GLV deposit. The deposited tokens and any unused execution fee are returned to the original account. **Parameters:** | Parameter | Type | Description | | --------- | --------- | -------------------------------------------- | | `key` | `bytes32` | Key of the GLV deposit request to cancel | ### GlvRouter.cancelGlvWithdrawal ```solidity function cancelGlvWithdrawal(bytes32 key) external ``` Cancels a pending GLV withdrawal. The GLV tokens and any unused execution fee are returned to the original account. **Parameters:** | Parameter | Type | Description | | --------- | --------- | ---------------------------------------------- | | `key` | `bytes32` | Key of the GLV withdrawal request to cancel | ## Simulating GLV execution You can dry-run GLV deposits and withdrawals before keeper execution. These simulation helpers are publicly callable on `GlvRouter`, but the real execution path remains keeper-only on `GlvDepositHandler.executeGlvDeposit` and `GlvWithdrawalHandler.executeGlvWithdrawal`. Like the simulation helpers on `ExchangeRouter`, these calls execute with supplied oracle prices and revert with `EndOfOracleSimulation` on success, so they are typically used through `eth_call` or `callStatic`-style preflight checks rather than as standalone state-changing transactions. ### GlvRouter.simulateExecuteGlvDeposit ```solidity function simulateExecuteGlvDeposit( bytes32 key, OracleUtils.SimulatePricesParams memory simulatedOracleParams ) ``` Simulates execution for a specific GLV deposit request key. ### GlvRouter.simulateExecuteLatestGlvDeposit ```solidity function simulateExecuteLatestGlvDeposit( OracleUtils.SimulatePricesParams memory simulatedOracleParams ) ``` Simulates execution for the latest created GLV deposit request. ### GlvRouter.simulateExecuteGlvWithdrawal ```solidity function simulateExecuteGlvWithdrawal( bytes32 key, OracleUtils.SimulatePricesParams memory simulatedOracleParams ) ``` Simulates execution for a specific GLV withdrawal request key. ### GlvRouter.simulateExecuteLatestGlvWithdrawal ```solidity function simulateExecuteLatestGlvWithdrawal( OracleUtils.SimulatePricesParams memory simulatedOracleParams ) ``` Simulates execution for the latest created GLV withdrawal request. ## External swaps before GLV actions `GlvRouter` also exposes `makeExternalCalls(...)` through its `ExternalHandler` integration. Use this when you need to perform an external swap or aggregator call before creating the GLV request, then refund any residual tokens back to the intended receivers. ## Next steps - [GLV Reader](./glv-reader.md) -- Query GLV vault data and pricing - [Simulations](./simulations.md) -- Dry-run GLV actions - [Contract addresses](./addresses.md) -- GlvRouter and GlvVault addresses per chain - [ExchangeRouter](./exchange-router.md) -- GM market operations --- ## Known issues This page is based on the known issues section of the [gmx-synthetics repository](https://github.com/gmx-io/gmx-synthetics/blob/updates/README.md#known-issues), with corrections and additions. It is intended for integrators, auditors, and developers building on top of the GMX contracts. ## Tokens These constraints apply to tokens used with the protocol. - Collateral tokens must be whitelisted with a configured `TOKEN_TRANSFER_GAS_LIMIT`. - Rebasing tokens, tokens that change balance on transfer, tokens with burns, tokens with callbacks (for example, ERC-777 tokens), and similar non-standard tokens are not compatible with the system and must not be whitelisted. ## Keepers These items describe known keeper behavior and limitations. - Order keepers can use prices from different timestamps for limit orders with a swap, which leads to different output amounts. - Order keepers are expected to validate whether a transaction will revert before sending it, to minimize gas wastage. - Order keepers may cause requests to be cancelled instead of executed by executing the request with insufficient gas. - If an execution transaction requires a large amount of gas close to the maximum block gas limit, it may be possible to stuff blocks to prevent the transaction from being included. - On certain blockchains, the keeper can control the `tx.gasprice` used to execute a transaction, which affects the execution fee paid to the keeper. - A malicious user can intentionally unbalance a market to create high price impact, preventing order execution. This is expected to be costly and difficult to benefit from. ## Price impact These items describe known limitations of the price impact mechanism. - Price impact can be reduced by using positions and swaps across markets, chains, forks, and other protocols. Virtual inventory tracking partially mitigates this. - A user can reduce price impact by using high-leverage positions. The `MIN_COLLATERAL_FACTOR_FOR_OPEN_INTEREST_MULTIPLIER` value partially mitigates this. - Price impact calculations don't account for fees or the effects of the price impact itself. In most cases, the effect on the calculation is expected to be small. ## Market token price These items describe edge cases in market token pricing. - It is rare but possible for a pool's value to become negative. This can happen because the `impactPoolAmount` and pending PnL are subtracted from the worth of the tokens in the pool. - Due to the difference in positive and negative position price impact, virtual token amounts can build up in the position impact pool, which affects the pricing of market tokens. The position impact pool must be gradually distributed if needed. ## Virtual inventory Virtual inventory tracking has the following constraints. - Virtual inventory tracks the amount of tokens in pools. Tokens in each grouping must be the same type and have the same decimals — the long tokens across pools in the group must have the same decimals, and the short tokens across pools in the group must have the same decimals. For example, because USDC has 6 decimals and DAI has 18 decimals, markets like ETH-USDC and ETH-DAI must not be grouped. - Virtual IDs must be set before market creation or token whitelisting. If set after trading for the token or market has occurred, the tracking won't be accurate and may need to be adjusted. ## Blockchain These items cover blockchain-level risks and mitigations. - For L2s with sequencers, there is no contract validation to check if the L2 sequencer is active. Oracle keepers must stop signing prices if the sequencer stops producing blocks. When the sequencer resumes, oracle keepers must sign prices for the latest blocks using the latest fetched prices. - If an L2 sequencer is down, it may prevent deposits into positions to prevent liquidations. - For transactions that can be executed entirely using on-chain price feeds, it may be possible to take advantage of stale pricing due to price latency or the chain being down. On-chain price feeds must be temporary, and low-latency feeds must be used instead once all tokens are supported. - Block re-orgs could allow a user to retroactively cancel an order after it has been executed if price didn't move favorably for the user. Handle this case if using the contracts on chains where long re-orgs are possible. - Updating and cancellation of orders could be front-run to prevent order execution. This is not expected to be an issue if the probability of successful front-running is `<= 50%`. If the probability is higher than 50%, fees and price impact must be adjusted to ensure the strategy is not net profitable. Adjusting the UI fee or referral discount could similarly be used to cause order cancellations. - During downtime of the blockchain or oracle, orders may be executed at significantly different prices or may not execute if the order's acceptable price can't be fulfilled. - There is a dependency on the accuracy of the block timestamp because oracle prices are validated against this value. For blockchains where nodes have some control over the timestamp, set the `oracleTimestampAdjustment` to a value that makes manipulation of the timestamp unprofitable. ## GLV These items describe known risks specific to GLV vaults. - The GLV shift feature can be exploited by temporarily increasing the utilization in a market that typically has low utilization. Once the keeper executes the shift, the attacker can lower the utilization back to normal levels. Position fees and price impact must be configured to make this attack expensive enough to cover the GLV loss. - A GLV may contain GM markets that are above their maximum `pnlToPoolFactorForTraders`. If a GM market's `maxPnlFactorForDeposits` is higher than `maxPnlFactorForTraders`, the GM market is valued lower during deposits than it will be once traders have realized their capped profits. A malicious user may observe a GM market in this condition and deposit into the GLV to gain from the ADLs that follow. To avoid this, `maxPnlFactorForDeposits` must be less than or equal to `maxPnlFactorForTraders`. - It is technically possible for market value to become negative. In this case, the GLV is unusable until the market value becomes positive. - GM tokens could become illiquid due to high PnL factor or high reserved USD. Users can deposit illiquid GM tokens into a GLV and withdraw liquidity from a different market, leaving the GLV with illiquid tokens. The `glvMaxMarketTokenBalanceUsd` and `glvMaxMarketTokenBalanceAmount` parameters must account for the riskiness of a market to avoid accumulating too many GM tokens from a risky market. ## Factories This item describes a known behavior in market and GLV factory contracts. - When adding a market with the `MarketStoreUtils.set` function, the market receives a lookup where the market address can be obtained with the market salt. This lookup is not cleared on market deletion. The same applies to GLV. ## Notes These notes cover deployment, configuration, and upgrade procedures. ### Deployment These items cover the initial deployment verification process. - Use `scripts/verifyFallback.ts` to verify contracts. - One MarketToken contract needs to be verified using `npx hardhat verify`. After that, all MarketToken contracts are verified because the source code is the same. ### Configuration This item covers a key configuration parameter. - `MAX_ORACLE_REF_PRICE_DEVIATION_FACTOR` is a sanity check that helps guard against incorrect oracle decimal configuration or incorrect price feed configuration. Set this to a sufficiently high value to prevent reverts during times of high volatility. ### Upgrades These items describe considerations when upgrading contracts. - If new contracts lead to a difference in pricing (for example, of market tokens) between old and new contracts, disable the old contracts before enabling the new ones. - Notify external protocols that use the Reader contract or potentially outdated pricing calculations to use the latest contracts and calculations (for example, Chainlink price feeds for GM tokens). - Publish a best-effort changelog documenting important changes that integrations must be aware of (for example, if a field is added to a struct passed into a callback function). These changes may not be obvious to integrations. - If the contracts support equity synthetic markets, ensure that stock splits and similar changes can be handled. - Contracts with the `CONTROLLER` role have access to important functions such as setting DataStore values. Ensure that such contracts don't have generic functions that can be used to change important values. - Add tests for the different market types (for example, spot-only markets, single-token markets). - Don't modify the ordering of values in the `eventData` for callbacks unless strictly necessary, because callback contracts may reference values by a fixed index. - If a struct passed into callbacks is changed (for example, Deposit, Withdrawal, Order structs), callback contracts expecting the previous struct stop working. Highlight struct changes to integrations. - If the referral system is in use, the OrderHandler must be given access to update the referral code for traders. ## Integrations These items describe integration considerations for protocols building on the GMX contracts. ### General These general considerations apply to all integrations. - Deposits, withdrawals, and orders may be cancelled if the requirements specified in the request can't be fulfilled (for example, minimum output amount). Check where funds and gas refunds are sent on cancellation to ensure it matches expectations. - Decrease position orders can output two tokens instead of one if the decrease position swap fails. The output amount and collateral may also not be sufficient to cover fees, causing the order not to be executed. - If there is a large spread, opening or closing a position can significantly change the min and max price of the market token. This must not be manipulatable in a profitable way. - Changes in config values such as `FUNDING_FACTOR`, `THRESHOLD_FOR_STABLE_FUNDING`, `BORROWING_FACTOR`, `SKIP_BORROWING_FEE_FOR_SMALLER_SIDE`, and `BORROWING_FEE_RECEIVER_FACTOR` could lead to additional charges for users and changes in market token price. - If trader PnL is capped due to `MAX_PNL_FACTOR_FOR_TRADERS`, the percentage of profit paid out to traders may differ depending on the order in which positions are decreased or closed, because the cap is recalculated based on the current state of the pool. - Event data may be passed to callback contracts. The ordering of params in the `eventData` is kept unchanged where possible, so params can be accessed by index. For safety, validate the key of each param before use to confirm it matches the expected value. - Some parameters such as `order.sizeDelta` and `order.initialCollateralDeltaAmount` may be updated during execution. The updated values may not be passed to the callback contract. - Callback contracts may need to whitelist the DepositHandler, OrderHandler, or WithdrawalHandler. New versions of these handlers may be deployed as new code is added, and two handlers can temporarily exist at the same time (for example, OrderHandler(1), OrderHandler(2)). The callback contract must be able to whitelist and simultaneously accept callbacks from multiple handlers. - Instead of maintaining a separate whitelist for each handler type, validate the role of `msg.sender` in the RoleStore — for example, `RoleStore.hasRole(msg.sender, Role.CONTROLLER)`. This checks that `msg.sender` is a valid handler. - If the user can choose which ExchangeRouter to interact with, don't assume the callback params are a fixed format. During transitions between old and new contracts, callbacks for functions such as `afterOrderCancellation` could be in either format. If only a specific ExchangeRouter can trigger the callback, this is not an issue. - Addresses of contracts such as the ExchangeRouter, Oracle, or Reader change as new logic is added. - When contracts such as the ExchangeRouter, Oracle, or Reader are updated, effort is made to keep function parameters the same. However, this may not always be possible (for example, if a new order property requires changing the `ExchangeRouter.createOrder` params). - The RoleStore and DataStore for deployments must not change. If they are changed, a migration of funds from the previous contracts to the new contracts is likely needed. - While the code is structured to minimize the risk of [read-only reentrancy](https://officercia.mirror.xyz/DBzFiDuxmDOTQEbfXhvLdK0DXVpKu1Nkurk0Cqk3QKc), guard against this possibility. - Token airdrops may occur to accounts of GM token holders. Integrating contracts holding GM tokens must be able to claim these tokens, otherwise the tokens are locked. One approach is to allow claiming of tokens that aren't market tokens — check using the `Keys.MARKET_LIST` value. - ETH transfers are sent with `NATIVE_TOKEN_TRANSFER_GAS_LIMIT` for the gas limit. If the transfer fails due to insufficient gas or other errors, ETH is sent as WETH instead. - Accounts may receive ETH for ADLs or liquidations. If the account can't receive ETH, WETH is sent instead. - Positive price impact is capped by the amount of tokens
프로젝트로 돌아가기