bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 25쪽
- `deadline`: signature expiry
- `signature`: signed relay authorization
- `desChainId`: destination chain id expected by the signature
Relay signature validation supports ECDSA signatures from externally owned accounts, ERC-1271 signatures from deployed smart contract wallets, and EIP-6492-wrapped signatures from counterfactual smart contract wallets. The EIP-6492 path can deploy the counterfactual wallet through the configured `EIP6492Deployer` before validating its ERC-1271 signature.
### Integration notes
- Relay routers do not expose `multicall` or `sendTokens`; token movements for external calls must be declared through `externalCalls.sendTokens` and `externalCalls.sendAmounts`.
- Relay fees are paid from the main account, not the relayer.
- Both relay routers expose `createTwapOrder(...)`; the relay signature covers `twapCount` and `interval`.
- `SubaccountGelatoRelayRouter` additionally validates a `SubaccountApproval` signature and per-account nonce.
- External calls are rejected for subaccount relay orders.
For the exact implementation, see [`GelatoRelayRouter.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/router/relay/GelatoRelayRouter.sol), [`SubaccountGelatoRelayRouter.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/router/relay/SubaccountGelatoRelayRouter.sol), and [`IRelayUtils.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/router/relay/IRelayUtils.sol).
## Multichain routers
The multichain contracts power GMX Account flows and other cross-chain operations.
### Action routers
| Contract | Notable surface |
| --- | --- |
| `MultichainOrderRouter` | `batch`, `createOrder`, `updateOrder`, `cancelOrder`, `setTraderReferralCode`, `registerCode` |
| `MultichainGmRouter` | `createDeposit`, `createWithdrawal`, `createShift` |
| `MultichainGlvRouter` | `createGlvDeposit`, `createGlvWithdrawal` |
| `MultichainClaimsRouter` | `claimFundingFees`, `claimCollateral`, `claimAffiliateRewards` |
| `MultichainTransferRouter` | `bridgeIn`, `bridgeOut`, `transferOut` |
### Reader surface
`MultichainReader` is the cross-chain read helper. Its notable entry points are:
- `quoteReadFee(...)` to estimate the LayerZero read fee
- `sendReadRequests(...)` to dispatch read requests across configured chains
- `lzReceive(...)` to receive LayerZero read responses and forward them to the registered originator
### Integration notes
- Multichain action routers take both `account` and `srcChainId`, because the action may originate from a different chain than the settlement chain.
- GM and GLV multichain routers also take `TransferRequests` so funds can be routed into the correct vaults before the action is created.
- Claim routes send outputs into `MultichainVault` first, then record the transfer for the destination receiver.
- `MultichainTransferRouter.bridgeOutFromController(...)` is controller-only infrastructure for protocol-driven bridge-outs after execution, not a general user-facing entry point.
- `MultichainReader.quoteReadFee(...)` is a public read helper, but `sendReadRequests(...)` is controller-gated and intended for authorized originators rather than general end users.
- `lzReceive(...)` is part of the LayerZero receive path and not a normal end-user entry point.
For the exact implementation, see [`IMultichainOrderRouter.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/multichain/IMultichainOrderRouter.sol), [`IMultichainGmRouter.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/multichain/IMultichainGmRouter.sol), [`IMultichainGlvRouter.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/multichain/IMultichainGlvRouter.sol), [`IMultichainTransferRouter.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/multichain/IMultichainTransferRouter.sol), [`MultichainClaimsRouter.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/multichain/MultichainClaimsRouter.sol), and [`MultichainReader.sol`](https://github.com/gmx-io/gmx-synthetics/blob/updates/contracts/multichain/MultichainReader.sol).
## Next steps
- [Contract addresses](./addresses.md) for live deployments
- [Delegated trading integration](./delegated-trading.md) for end-to-end subaccount and relay patterns
- [ExchangeRouter](./exchange-router.md) for standard order, deposit, withdrawal, and shift flows
- [GlvRouter](./glv-router.md) for GLV request flows
- [Known issues](./known-issues.md) for integration caveats and operational risks
---
## Architecture
This page covers the GMX smart contract architecture, execution model, keeper network, and integration considerations. For contract function references, see [Reader](./reader.md), [ExchangeRouter](./exchange-router.md), and [GLV Reader](./glv-reader.md).
## Contract structure
The GMX protocol separates concerns across four contract categories. These categories describe the internal contract architecture, not the subset of contracts most integrations call directly day to day.
| Category | Role | Examples |
| --- | --- | --- |
| **Bank contracts** | Hold funds. Only these contracts custody tokens. | `Bank`, `StrictBank`, `MarketToken`, `DepositVault`, `OrderVault`, `WithdrawalVault`, `ShiftVault`, `GlvVault` |
| **Data storage** | Maintain all protocol state in a single store. | `DataStore`, `RoleStore`, `OracleStore` |
| **Logic contracts** | Stateless execution logic. Read from DataStore, compute results, emit events. | `ExchangeRouter`, `GlvRouter`, `Reader`, `GlvReader`, `OrderHandler`, `DepositHandler`, `WithdrawalHandler`, `ShiftHandler`, `LiquidationHandler`, `AdlHandler`, all `*Utils` contracts |
| **Event utilities** | Generalized event emission for indexing and monitoring. | `EventEmitter` |
This separation enables contract upgrades without migrating funds. When a logic contract is upgraded, a new version is deployed and granted the appropriate roles in `RoleStore`. The bank contracts and `DataStore` remain unchanged — no fund migration is required.
For most integrations, the main entry points are `ExchangeRouter` for writes and `Reader` / `GlvReader` for reads. `GlvRouter` handles GLV-specific operations (deposits, withdrawals). Many of the other contracts listed above are supporting handlers, storage contracts, or utilities used internally by those entry points.
Struct data is serialized into `DataStore` through `*StoreUtils` contracts (for example, `OrderStoreUtils`, `PositionStoreUtils`, `ShiftStoreUtils`, `MarketStoreUtils`, `GlvStoreUtils`), which allows new keys to be added to structs without requiring storage migration. Order and position lists are stored on-chain using `EnumerableSet` rather than relying on indexers, so interfaces and keepers can query accurate data without waiting for indexer sync delays.
:::warning
`RoleStore` and `DataStore` must not change after deployment. Replacing either requires migrating all funds and reconfiguring every dependent contract. New handlers and routers receive different addresses; integrations must support multiple handler versions temporarily during transitions.
:::
### Role-based access control
All privileged operations are gated through `RoleStore`, which maps addresses to roles using an `EnumerableSet`-backed store with a `roleCache` mapping for gas-efficient lookups. Handlers, keepers, and governance controllers each hold specific roles that authorize their actions. The `Config` contract applies most parameter changes through a `ConfigTimelockController` (extending OpenZeppelin's `TimelockController`) that enforces time delays on sensitive updates.
`RiskOracleConfig` provides a separate restricted path for risk-parameter updates. A config keeper controls which markets are enabled for this path, and the `RISK_ORACLE` role can update only the contract's fixed allowlist of price-impact, liquidity-cap, funding, collateral, and borrowing keys. Each update must pass the same configured range checks. Before changing a funding or borrowing key, the contract settles the market's accrued funding or cumulative borrowing factor using the previous value.
### EventEmitter
Rather than emitting events from each contract individually, the protocol routes all events through a shared `EventEmitter` contract. This provides a single address to monitor for all protocol activity. The `EventEmitter` uses three structured event types (`EventLog`, `EventLog1`, `EventLog2`) with different numbers of indexed topics for efficient filtering, plus raw `emitDataLog1` through `emitDataLog4` functions for general-purpose log emission.
For monitoring integration examples, see [Events](./events.md).
## Execution model
Most user actions follow a two-phase request-execution pattern:
```mermaid
sequenceDiagram
participant User
participant Contract as ExchangeRouter
participant Keeper as Order Keeper
participant Oracle as Oracle Keeper
participant Archive as Archive Node
User->>Contract: 1. createOrder(params)
Note over Contract: Request stored on-chain
Oracle->>Archive: Sign and publish prices
Keeper->>Archive: 2. Fetch signed prices
Keeper->>Contract: 3. executeOrder(key, oraclePrices)
Note over Contract: Validates prices, executes logic
Contract-->>User: Order filled or reverted
```
**Phase 1 — Request:** The user submits a transaction (via `ExchangeRouter`) that stores the request parameters on-chain — order type, size, collateral, acceptable price, and execution fee. No oracle prices are needed at this stage.
**Phase 2 — Execution:** A keeper observes the request, fetches signed oracle prices from archive nodes, and submits an execution transaction that bundles the prices with the request key. The contract validates the prices and executes the order atomically.
Execution uses a try/catch pattern in `OrderHandler.executeOrder`. If the error is a keeper issue (insufficient gas, missing oracle prices), the entire transaction reverts so that the user's request is not unnecessarily cancelled. For market orders, user-side errors (unmet conditions, insufficient funds) cancel the request and return funds. For limit and trigger orders, the order is frozen instead of cancelled to prevent gaming — see [Frozen orders](#frozen-orders) below.
This two-phase design prevents front-running: the user's intent is committed on-chain before oracle prices are included, so no actor can see the execution price before the request is recorded.
### Execution latency
The two-phase model introduces a brief delay between request and execution (typically a few seconds), during which the market price may move. The `acceptablePrice` parameter protects users — if the execution price exceeds their tolerance, the order is not fulfilled at that price.
### Simulations
You can dry-run actions before keeper execution by calling the latest-request simulation functions on `SimulationRouter` (for example, `simulateExecuteLatestOrder`, `simulateExecuteLatestDeposit`, `simulateExecuteLatestWithdrawal`, `simulateExecuteLatestShift`, and `simulateExecuteLatestJitOrder`) and the GLV simulation functions on `GlvRouter` (for example, `simulateExecuteLatestGlvDeposit` and `simulateExecuteLatestGlvWithdrawal`). These are public router entry points intended for preflight checks, while the actual execution functions live on keeper-gated handlers. Simulations use the `withSimulatedOraclePrices` modifier and revert with `EndOfOracleSimulation` on success (not failure). See [Simulations](./simulations.md) for details.
## Keeper network
Three components work together to execute orders:
### Oracle keepers
Oracle keepers fetch prices from oracle providers. The primary provider is `ChainlinkDataStreamProvider`, which sources prices from [Chainlink Data Streams](https://docs.chain.link/data-streams). Additional providers include `EdgeDataStreamProvider` and `StaticOracleProvider`. `StaticOracleProvider` reads stored minimum and maximum prices configured for a token through `Config.setStaticPriceForMarketIndexToken`. Each price report includes both a minimum price (`min`) and a maximum price (`max`), capturing the bid-ask spread. Prices are scaled so that multiplying a raw token amount — in the token's native decimals, unchanged — by the price produces the USD value at 30-decimal precision (`FLOAT_PRECISION = 10^30`):
```
fiatValue = tokenAmount * oraclePrice
tokenAmount = fiatValue / oraclePrice
```
Concretely, the encoded price is `usdPrice * 10^(30 - tokenDecimals)` — `$1` of USDC (6 decimals) becomes `1 * 10^24`, `$1` of WETH (18 decimals) becomes `1 * 10^12`. See the Reader's [Price and amount encoding](./reader.md#price-and-amount-encoding) for a worked example and common token scalings.
For providers that request a reference check, the protocol validates prices against Chainlink reference feeds using the `MAX_ORACLE_REF_PRICE_DEVIATION_FACTOR` parameter and rejects a price that deviates beyond the configured threshold. `StaticOracleProvider` explicitly skips this check. Not all tokens have a `ChainlinkPriceFeedProvider` configured as a reference price source.
The `Oracle` contract also retains each provider's raw minimum and maximum prices before provider-side spread reduction. Normal execution reads the adjusted primary price. ADL threshold calculations read the raw price so spread reduction can't narrow the price range used for the `MAX_PNL_FACTOR_FOR_ADL` check.
### Order keepers
Order keepers monitor the chain for pending requests (orders, deposits, withdrawals, shifts). When a request is detected, the keeper:
1. Fetches signed prices from the configured oracle providers.
2. Bundles the prices with the request key into an execution transaction.
3. Submits the transaction. The execution fee (paid by the user at request time) covers the keeper's gas cost.
If gas prices spike, the keeper may wait or the user can cancel the request after a cancellation period. Execution fees include a buffer to account for gas price volatility — any excess is refunded after execution.
On Arbitrum, Avalanche, and MegaETH, order keepers also cancel requests that stay pending too long. This covers Market Swap, Market Increase, and Market Decrease orders, GM deposits and withdrawals, shifts, and GLV deposits and withdrawals. A keeper cancels such a request once it has been pending for `requestExpirationTime` (300 seconds on these chains) plus a keeper buffer of about 60 seconds, so in practice about six minutes or more after the request was created or last updated. This timing is keeper behavior, not a protocol guarantee. The request's funds and execution fee are returned the same way as when the user cancels, and the keeper keeps no part of the execution fee. Limit, Stop Market, and TP/SL orders aren't cancelled this way. See [Cancelling requests](./exchange-router.md#cancelling-requests) for what integrators receive when this happens.
### Frozen orders
If an order cannot be fulfilled at execution time (for example, the order size exceeds available liquidity, or position constraints aren't met), the order is frozen rather than cancelled. This prevents gaming where a user could create a limit order with size greater than available pool liquidity, wait for the trigger price to be hit, then deposit into the pool to allow execution at a favorable price.
Frozen orders can be retried by dedicated frozen order keepers when conditions improve. Users can also call `updateOrder` to unfreeze and modify the order, or cancel it entirely.
## Integration considerations
### Contract versioning
Integrations must handle contract address changes during upgrades. When logic contracts are upgraded, new handler and router contracts are deployed at different addresses. During transition periods:
- Multiple handler versions may be active simultaneously.
- Callback contracts must whitelist both old and new handler addresses.
- Use configurable contract addresses rather than hardcoding them.
Subscribe to the channels in the [Updates and Support](../updates-support.md) page for contract update notifications.
### ETH and WETH handling
When the protocol needs to send ETH (for example, returning execution fee refunds), it first attempts a native ETH transfer with a configurable gas limit (`NATIVE_TOKEN_TRANSFER_GAS_LIMIT`). If the transfer fails (for example, the recipient contract lacks a `receive` function or doesn't have enough gas), the protocol wraps the ETH as WETH and sends that instead.
### First market deposit
The first deposit into a newly created market must set the receiver to `address(1)` and meet a minimum market token threshold (`MIN_MARKET_TOKENS_FOR_FIRST_DEPOSIT`). The minted market tokens are sent to `address(1)`, effectively locking them. This prevents manipulation of the market token price through rounding on the initial deposit. Subsequent deposits mint market tokens to the depositor normally.
### Token compatibility
The protocol is designed for standard ERC-20 tokens. The following token types are **not compatible**:
- **Rebasing tokens** — tokens that automatically adjust balances (for example, stETH in rebasing mode)
- **ERC-777 tokens** — tokens with transfer hooks that could enable reentrancy
- **Fee-on-transfer tokens** — tokens that deduct a fee on every transfer
- **Tokens with built-in burn mechanisms** — tokens where the supply decreases on transfer
### Token airdrops to GM holders
If airdropping tokens to GM token holders, the airdrop must be claimable by contracts (not just EOAs). Integrating protocols that hold GM tokens on behalf of users need to be able to claim and distribute the airdrop to their users.
## Known issues
For the full list of known issues, token compatibility constraints, and integration considerations, see the dedicated [Known issues](./known-issues.md) page.
## Next steps
- [Contract addresses](./addresses.md) — Deployment addresses for all supported chains.
- [ExchangeRouter](./exchange-router.md) — Create orders, deposits, withdrawals, and shifts.
- [GlvRouter](./glv-router.md) — Create GLV deposits and withdrawals.
- [Reader](./reader.md) — Query market, position, and pricing data.
- [GLV Reader](./glv-reader.md) — Query GLV vault data and pricing.
- [Advanced entry points](./advanced-entrypoints.md) — Delegated subaccount trading, relay router flows, and multichain routers.
- [Simulations](./simulations.md) — Dry-run actions before submitting on-chain.
- [Events](./events.md) — Monitor protocol activity through EventEmitter.
---
## Delegated trading integration
This page explains how to build delegated trading flows on GMX V2 using the subaccount and relay surfaces documented in [Advanced entry points](./advanced-entrypoints.md). It is intended for integrators who need an end-to-end implementation pattern, not just a function reference.
Use this guide when your application needs a model like:
- an account owner retains primary control of funds
- a delegated trader can place, update, and cancel orders
- delegated access expires automatically or is limited by action count
- your backend, relayer, or UI coordinates the signing flow
If you only need the raw contract surfaces, start with [Advanced entry points](./advanced-entrypoints.md). If you need read-path architecture and freshness guidance, also see the [API integration guide](../integration-guide.md) and [Reader](./reader.md).
## What GMX exposes
The delegated trading surface is built around:
- `SubaccountGelatoRelayRouter` for same-chain delegated order management (gasless, relay-based)
- `MultichainSubaccountRouter` for cross-chain delegated order management
- `DataStore` and `Keys` for delegated-access state such as expiry, action count, and integration id
A legacy `SubaccountRouter` contract is still deployed but is no longer used for order operations. The current GMX interface only calls it for wallet-based `removeSubaccount(...)` when the user is not going through the express flow. For new integrations, use `SubaccountGela프로젝트로 돌아가기